You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTPStatsCollector.js 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. import { browsers } from '@jitsi/js-utils';
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import * as MediaType from '../../service/RTC/MediaType';
  4. import * as StatisticsEvents from '../../service/statistics/Events';
  5. import browser from '../browser';
  6. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  7. const logger = getLogger(__filename);
  8. /**
  9. * The lib-jitsi-meet browser-agnostic names of the browser-specific keys
  10. * reported by RTCPeerConnection#getStats mapped by browser.
  11. */
  12. const KEYS_BY_BROWSER_TYPE = {};
  13. KEYS_BY_BROWSER_TYPE[browsers.FIREFOX] = {
  14. 'ssrc': 'ssrc',
  15. 'packetsReceived': 'packetsReceived',
  16. 'packetsLost': 'packetsLost',
  17. 'packetsSent': 'packetsSent',
  18. 'bytesReceived': 'bytesReceived',
  19. 'bytesSent': 'bytesSent',
  20. 'framerateMean': 'framerateMean',
  21. 'ip': 'address',
  22. 'port': 'port',
  23. 'protocol': 'protocol'
  24. };
  25. KEYS_BY_BROWSER_TYPE[browsers.CHROME] = {
  26. 'receiveBandwidth': 'googAvailableReceiveBandwidth',
  27. 'sendBandwidth': 'googAvailableSendBandwidth',
  28. 'remoteAddress': 'googRemoteAddress',
  29. 'transportType': 'googTransportType',
  30. 'localAddress': 'googLocalAddress',
  31. 'activeConnection': 'googActiveConnection',
  32. 'ssrc': 'ssrc',
  33. 'packetsReceived': 'packetsReceived',
  34. 'packetsSent': 'packetsSent',
  35. 'packetsLost': 'packetsLost',
  36. 'bytesReceived': 'bytesReceived',
  37. 'bytesSent': 'bytesSent',
  38. 'googCodecName': 'googCodecName',
  39. 'googFrameHeightReceived': 'googFrameHeightReceived',
  40. 'googFrameWidthReceived': 'googFrameWidthReceived',
  41. 'googFrameHeightSent': 'googFrameHeightSent',
  42. 'googFrameWidthSent': 'googFrameWidthSent',
  43. 'googFrameRateReceived': 'googFrameRateReceived',
  44. 'googFrameRateSent': 'googFrameRateSent',
  45. 'audioInputLevel': 'audioInputLevel',
  46. 'audioOutputLevel': 'audioOutputLevel',
  47. 'currentRoundTripTime': 'googRtt',
  48. 'remoteCandidateType': 'googRemoteCandidateType',
  49. 'localCandidateType': 'googLocalCandidateType',
  50. 'ip': 'ip',
  51. 'port': 'port',
  52. 'protocol': 'protocol'
  53. };
  54. KEYS_BY_BROWSER_TYPE[browsers.REACT_NATIVE] = {
  55. 'packetsReceived': 'packetsReceived',
  56. 'packetsSent': 'packetsSent',
  57. 'bytesReceived': 'bytesReceived',
  58. 'bytesSent': 'bytesSent',
  59. 'frameWidth': 'frameWidth',
  60. 'frameHeight': 'frameHeight',
  61. 'framesPerSecond': 'framesPerSecond',
  62. 'ip': 'ip',
  63. 'port': 'port',
  64. 'protocol': 'protocol'
  65. };
  66. KEYS_BY_BROWSER_TYPE[browsers.OPERA]
  67. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  68. KEYS_BY_BROWSER_TYPE[browsers.NWJS]
  69. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  70. KEYS_BY_BROWSER_TYPE[browsers.ELECTRON]
  71. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  72. KEYS_BY_BROWSER_TYPE[browsers.SAFARI]
  73. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  74. /**
  75. * Calculates packet lost percent using the number of lost packets and the
  76. * number of all packet.
  77. * @param lostPackets the number of lost packets
  78. * @param totalPackets the number of all packets.
  79. * @returns {number} packet loss percent
  80. */
  81. function calculatePacketLoss(lostPackets, totalPackets) {
  82. if (!totalPackets || totalPackets <= 0
  83. || !lostPackets || lostPackets <= 0) {
  84. return 0;
  85. }
  86. return Math.round((lostPackets / totalPackets) * 100);
  87. }
  88. /**
  89. * Holds "statistics" for a single SSRC.
  90. * @constructor
  91. */
  92. function SsrcStats() {
  93. this.loss = {};
  94. this.bitrate = {
  95. download: 0,
  96. upload: 0
  97. };
  98. this.resolution = {};
  99. this.framerate = 0;
  100. this.codec = '';
  101. }
  102. /**
  103. * Sets the "loss" object.
  104. * @param loss the value to set.
  105. */
  106. SsrcStats.prototype.setLoss = function(loss) {
  107. this.loss = loss || {};
  108. };
  109. /**
  110. * Sets resolution that belong to the ssrc represented by this instance.
  111. * @param resolution new resolution value to be set.
  112. */
  113. SsrcStats.prototype.setResolution = function(resolution) {
  114. this.resolution = resolution || {};
  115. };
  116. /**
  117. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  118. * the respective fields of the "bitrate" field of this object.
  119. * @param bitrate an object holding the values to add.
  120. */
  121. SsrcStats.prototype.addBitrate = function(bitrate) {
  122. this.bitrate.download += bitrate.download;
  123. this.bitrate.upload += bitrate.upload;
  124. };
  125. /**
  126. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  127. * represented by this instance.
  128. */
  129. SsrcStats.prototype.resetBitrate = function() {
  130. this.bitrate.download = 0;
  131. this.bitrate.upload = 0;
  132. };
  133. /**
  134. * Sets the "framerate".
  135. * @param framerate the value to set.
  136. */
  137. SsrcStats.prototype.setFramerate = function(framerate) {
  138. this.framerate = framerate || 0;
  139. };
  140. SsrcStats.prototype.setCodec = function(codec) {
  141. this.codec = codec || '';
  142. };
  143. /**
  144. *
  145. */
  146. function ConferenceStats() {
  147. /**
  148. * The bandwidth
  149. * @type {{}}
  150. */
  151. this.bandwidth = {};
  152. /**
  153. * The bit rate
  154. * @type {{}}
  155. */
  156. this.bitrate = {};
  157. /**
  158. * The packet loss rate
  159. * @type {{}}
  160. */
  161. this.packetLoss = null;
  162. /**
  163. * Array with the transport information.
  164. * @type {Array}
  165. */
  166. this.transport = [];
  167. }
  168. /* eslint-disable max-params */
  169. /**
  170. * <tt>StatsCollector</tt> registers for stats updates of given
  171. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  172. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  173. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  174. * instance as an event source.
  175. *
  176. * @param peerconnection WebRTC PeerConnection object.
  177. * @param audioLevelsInterval
  178. * @param statsInterval stats refresh interval given in ms.
  179. * @param eventEmitter
  180. * @constructor
  181. */
  182. export default function StatsCollector(
  183. peerconnection,
  184. audioLevelsInterval,
  185. statsInterval,
  186. eventEmitter) {
  187. // StatsCollector depends entirely on the format of the reports returned by
  188. // RTCPeerConnection#getStats. Given that the value of
  189. // browser#getName() is very unlikely to change at runtime, it
  190. // makes sense to discover whether StatsCollector supports the executing
  191. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  192. // needlessly check a "static" condition multiple times very very often and
  193. // (2) the lack of support for the executing browser would be discovered and
  194. // reported multiple times very very often too late in the execution in some
  195. // totally unrelated callback.
  196. /**
  197. * The browser type supported by this StatsCollector. In other words, the
  198. * type of the browser which initialized this StatsCollector
  199. * instance.
  200. * @private
  201. */
  202. this._browserType = browser.getName();
  203. const keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  204. if (!keys) {
  205. throw new Error(`The browser type '${this._browserType}' isn't supported!`);
  206. }
  207. /**
  208. * Whether to use the Promise-based getStats API or not.
  209. * @type {boolean}
  210. */
  211. this._usesPromiseGetStats
  212. = browser.isWebKitBased() || browser.isFirefox() || browser.isReactNative();
  213. /**
  214. * The function which is to be used to retrieve the value associated in a
  215. * report returned by RTCPeerConnection#getStats with a lib-jitsi-meet
  216. * browser-agnostic name/key.
  217. *
  218. * @function
  219. * @private
  220. */
  221. this._getStatValue
  222. = this._usesPromiseGetStats
  223. ? this._defineNewGetStatValueMethod(keys)
  224. : this._defineGetStatValueMethod(keys);
  225. this.peerconnection = peerconnection;
  226. this.baselineAudioLevelsReport = null;
  227. this.currentAudioLevelsReport = null;
  228. this.currentStatsReport = null;
  229. this.previousStatsReport = null;
  230. this.audioLevelReportHistory = {};
  231. this.audioLevelsIntervalId = null;
  232. this.eventEmitter = eventEmitter;
  233. this.conferenceStats = new ConferenceStats();
  234. // Updates stats interval
  235. this.audioLevelsIntervalMilis = audioLevelsInterval;
  236. this.speakerList = [];
  237. this.statsIntervalId = null;
  238. this.statsIntervalMilis = statsInterval;
  239. /**
  240. * Maps SSRC numbers to {@link SsrcStats}.
  241. * @type {Map<number,SsrcStats}
  242. */
  243. this.ssrc2stats = new Map();
  244. }
  245. /**
  246. * Set the list of the remote speakers for which audio levels are to be calculated.
  247. *
  248. * @param {Array<string>} speakerList - Endpoint ids.
  249. * @returns {void}
  250. */
  251. StatsCollector.prototype.setSpeakerList = function(speakerList) {
  252. this.speakerList = speakerList;
  253. };
  254. /**
  255. * Stops stats updates.
  256. */
  257. StatsCollector.prototype.stop = function() {
  258. if (this.audioLevelsIntervalId) {
  259. clearInterval(this.audioLevelsIntervalId);
  260. this.audioLevelsIntervalId = null;
  261. }
  262. if (this.statsIntervalId) {
  263. clearInterval(this.statsIntervalId);
  264. this.statsIntervalId = null;
  265. }
  266. };
  267. /**
  268. * Callback passed to <tt>getStats</tt> method.
  269. * @param error an error that occurred on <tt>getStats</tt> call.
  270. */
  271. StatsCollector.prototype.errorCallback = function(error) {
  272. GlobalOnErrorHandler.callErrorHandler(error);
  273. logger.error('Get stats error', error);
  274. this.stop();
  275. };
  276. /**
  277. * Starts stats updates.
  278. */
  279. StatsCollector.prototype.start = function(startAudioLevelStats) {
  280. if (startAudioLevelStats) {
  281. if (browser.supportsReceiverStats()) {
  282. logger.info('Using RTCRtpSynchronizationSource for remote audio levels');
  283. }
  284. this.audioLevelsIntervalId = setInterval(
  285. () => {
  286. if (browser.supportsReceiverStats()) {
  287. const audioLevels = this.peerconnection.getAudioLevels(this.speakerList);
  288. for (const ssrc in audioLevels) {
  289. if (audioLevels.hasOwnProperty(ssrc)) {
  290. // Use a scaling factor of 2.5 to report the same
  291. // audio levels that getStats reports.
  292. const audioLevel = audioLevels[ssrc] * 2.5;
  293. this.eventEmitter.emit(
  294. StatisticsEvents.AUDIO_LEVEL,
  295. this.peerconnection,
  296. Number.parseInt(ssrc, 10),
  297. audioLevel,
  298. false /* isLocal */);
  299. }
  300. }
  301. } else {
  302. // Interval updates
  303. this.peerconnection.getStats(
  304. report => {
  305. let results = null;
  306. if (!report || !report.result
  307. || typeof report.result !== 'function') {
  308. results = report;
  309. } else {
  310. results = report.result();
  311. }
  312. this.currentAudioLevelsReport = results;
  313. if (this._usesPromiseGetStats) {
  314. this.processNewAudioLevelReport();
  315. } else {
  316. this.processAudioLevelReport();
  317. }
  318. this.baselineAudioLevelsReport
  319. = this.currentAudioLevelsReport;
  320. },
  321. error => this.errorCallback(error)
  322. );
  323. }
  324. },
  325. this.audioLevelsIntervalMilis
  326. );
  327. }
  328. const processStats = () => {
  329. // Interval updates
  330. this.peerconnection.getStats(
  331. report => {
  332. let results = null;
  333. if (!report || !report.result
  334. || typeof report.result !== 'function') {
  335. // firefox
  336. results = report;
  337. } else {
  338. // chrome
  339. results = report.result();
  340. }
  341. this.currentStatsReport = results;
  342. try {
  343. if (this._usesPromiseGetStats) {
  344. this.processNewStatsReport();
  345. } else {
  346. this.processStatsReport();
  347. }
  348. } catch (e) {
  349. GlobalOnErrorHandler.callErrorHandler(e);
  350. logger.error(`Unsupported key:${e}`, e);
  351. }
  352. this.previousStatsReport = this.currentStatsReport;
  353. },
  354. error => this.errorCallback(error)
  355. );
  356. };
  357. processStats();
  358. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  359. };
  360. /**
  361. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  362. * gets the value from a specific report returned by RTCPeerConnection#getStats
  363. * associated with a lib-jitsi-meet browser-agnostic name.
  364. *
  365. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  366. * names to RTCPeerConnection#getStats browser-specific keys
  367. */
  368. StatsCollector.prototype._defineGetStatValueMethod = function(keys) {
  369. // Define the function which converts a lib-jitsi-meet browser-asnostic name
  370. // to a browser-specific key of a report returned by
  371. // RTCPeerConnection#getStats.
  372. const keyFromName = function(name) {
  373. const key = keys[name];
  374. if (key) {
  375. return key;
  376. }
  377. throw new Error(`The property '${name}' isn't supported!`);
  378. };
  379. // Define the function which retrieves the value from a specific report
  380. // returned by RTCPeerConnection#getStats associated with a given
  381. // browser-specific key.
  382. let itemStatByKey;
  383. switch (this._browserType) {
  384. case browsers.CHROME:
  385. case browsers.OPERA:
  386. case browsers.NWJS:
  387. case browsers.ELECTRON:
  388. // TODO What about other types of browser which are based on Chrome such
  389. // as NW.js? Every time we want to support a new type browser we have to
  390. // go and add more conditions (here and in multiple other places).
  391. // Cannot we do a feature detection instead of a browser type check? For
  392. // example, if item has a stat property of type function, then it's very
  393. // likely that whoever defined it wanted you to call it in order to
  394. // retrieve the value associated with a specific key.
  395. itemStatByKey = (item, key) => item.stat(key);
  396. break;
  397. default:
  398. itemStatByKey = (item, key) => item[key];
  399. }
  400. // Compose the 2 functions defined above to get a function which retrieves
  401. // the value from a specific report returned by RTCPeerConnection#getStats
  402. // associated with a specific lib-jitsi-meet browser-agnostic name.
  403. return (item, name) => itemStatByKey(item, keyFromName(name));
  404. };
  405. /**
  406. * Obtains a stat value from given stat and converts it to a non-negative
  407. * number. If the value is either invalid or negative then 0 will be returned.
  408. * @param report
  409. * @param {string} name
  410. * @return {number}
  411. * @private
  412. */
  413. StatsCollector.prototype.getNonNegativeStat = function(report, name) {
  414. let value = this._getStatValue(report, name);
  415. if (typeof value !== 'number') {
  416. value = Number(value);
  417. }
  418. if (isNaN(value)) {
  419. return 0;
  420. }
  421. return Math.max(0, value);
  422. };
  423. /* eslint-disable no-continue */
  424. /**
  425. * Stats processing logic.
  426. */
  427. StatsCollector.prototype.processStatsReport = function() {
  428. if (!this.previousStatsReport) {
  429. return;
  430. }
  431. const getStatValue = this._getStatValue;
  432. const byteSentStats = {};
  433. for (const idx in this.currentStatsReport) {
  434. if (!this.currentStatsReport.hasOwnProperty(idx)) {
  435. continue;
  436. }
  437. const now = this.currentStatsReport[idx];
  438. // The browser API may return "undefined" values in the array
  439. if (!now) {
  440. continue;
  441. }
  442. try {
  443. const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  444. const sendBandwidth = getStatValue(now, 'sendBandwidth');
  445. if (receiveBandwidth || sendBandwidth) {
  446. this.conferenceStats.bandwidth = {
  447. 'download': Math.round(receiveBandwidth / 1000),
  448. 'upload': Math.round(sendBandwidth / 1000)
  449. };
  450. }
  451. } catch (e) { /* not supported*/ }
  452. if (now.type === 'googCandidatePair') {
  453. let active, ip, localCandidateType, localip,
  454. remoteCandidateType, rtt, type;
  455. try {
  456. active = getStatValue(now, 'activeConnection');
  457. if (!active) {
  458. continue;
  459. }
  460. ip = getStatValue(now, 'remoteAddress');
  461. type = getStatValue(now, 'transportType');
  462. localip = getStatValue(now, 'localAddress');
  463. localCandidateType = getStatValue(now, 'localCandidateType');
  464. remoteCandidateType = getStatValue(now, 'remoteCandidateType');
  465. rtt = this.getNonNegativeStat(now, 'currentRoundTripTime');
  466. } catch (e) { /* not supported*/ }
  467. if (!ip || !type || !localip || active !== 'true') {
  468. continue;
  469. }
  470. // Save the address unless it has been saved already.
  471. const conferenceStatsTransport = this.conferenceStats.transport;
  472. if (!conferenceStatsTransport.some(
  473. t =>
  474. t.ip === ip
  475. && t.type === type
  476. && t.localip === localip)) {
  477. conferenceStatsTransport.push({
  478. ip,
  479. type,
  480. localip,
  481. p2p: this.peerconnection.isP2P,
  482. localCandidateType,
  483. remoteCandidateType,
  484. rtt
  485. });
  486. }
  487. continue;
  488. }
  489. if (now.type === 'candidatepair') {
  490. // we need succeeded and selected pairs only
  491. if (now.state !== 'succeeded' || !now.selected) {
  492. continue;
  493. }
  494. const local = this.currentStatsReport[now.localCandidateId];
  495. const remote = this.currentStatsReport[now.remoteCandidateId];
  496. this.conferenceStats.transport.push({
  497. ip: `${remote.ipAddress}:${remote.portNumber}`,
  498. type: local.transport,
  499. localip: `${local.ipAddress}:${local.portNumber}`,
  500. p2p: this.peerconnection.isP2P,
  501. localCandidateType: local.candidateType,
  502. remoteCandidateType: remote.candidateType
  503. });
  504. }
  505. if (now.type !== 'ssrc' && now.type !== 'outboundrtp'
  506. && now.type !== 'inboundrtp' && now.type !== 'track') {
  507. continue;
  508. }
  509. const before = this.previousStatsReport[idx];
  510. let ssrc = this.getNonNegativeStat(now, 'ssrc');
  511. // If type="track", take the first SSRC from ssrcIds.
  512. if (now.type === 'track' && Array.isArray(now.ssrcIds)) {
  513. ssrc = Number(now.ssrcIds[0]);
  514. }
  515. if (!before || !ssrc) {
  516. continue;
  517. }
  518. // isRemote is available only in FF and is ignored in case of chrome
  519. // according to the spec
  520. // https://www.w3.org/TR/webrtc-stats/#dom-rtcrtpstreamstats-isremote
  521. // when isRemote is true indicates that the measurements were done at
  522. // the remote endpoint and reported in an RTCP RR/XR.
  523. // Fixes a problem where we are calculating local stats wrong adding
  524. // the sent bytes to the local download bitrate.
  525. // In new W3 stats spec, type="track" has a remoteSource boolean
  526. // property.
  527. if (now.isRemote === true || now.remoteSource === true) {
  528. continue;
  529. }
  530. let ssrcStats = this.ssrc2stats.get(ssrc);
  531. if (!ssrcStats) {
  532. ssrcStats = new SsrcStats();
  533. this.ssrc2stats.set(ssrc, ssrcStats);
  534. }
  535. let isDownloadStream = true;
  536. let key = 'packetsReceived';
  537. let packetsNow = getStatValue(now, key);
  538. if (typeof packetsNow === 'undefined'
  539. || packetsNow === null || packetsNow === '') {
  540. isDownloadStream = false;
  541. key = 'packetsSent';
  542. packetsNow = getStatValue(now, key);
  543. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  544. logger.warn('No packetsReceived nor packetsSent stat found');
  545. }
  546. }
  547. if (!packetsNow || packetsNow < 0) {
  548. packetsNow = 0;
  549. }
  550. const packetsBefore = this.getNonNegativeStat(before, key);
  551. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  552. const packetsLostNow
  553. = this.getNonNegativeStat(now, 'packetsLost');
  554. const packetsLostBefore
  555. = this.getNonNegativeStat(before, 'packetsLost');
  556. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  557. ssrcStats.setLoss({
  558. packetsTotal: packetsDiff + packetsLostDiff,
  559. packetsLost: packetsLostDiff,
  560. isDownloadStream
  561. });
  562. const bytesReceivedNow
  563. = this.getNonNegativeStat(now, 'bytesReceived');
  564. const bytesReceivedBefore
  565. = this.getNonNegativeStat(before, 'bytesReceived');
  566. const bytesReceived
  567. = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  568. let bytesSent = 0;
  569. // TODO: clean this mess up!
  570. let nowBytesTransmitted = getStatValue(now, 'bytesSent');
  571. if (typeof nowBytesTransmitted === 'number'
  572. || typeof nowBytesTransmitted === 'string') {
  573. nowBytesTransmitted = Number(nowBytesTransmitted);
  574. if (!isNaN(nowBytesTransmitted)) {
  575. byteSentStats[ssrc] = nowBytesTransmitted;
  576. if (nowBytesTransmitted > 0) {
  577. bytesSent = nowBytesTransmitted
  578. - getStatValue(before, 'bytesSent');
  579. }
  580. }
  581. }
  582. bytesSent = Math.max(0, bytesSent);
  583. const timeMs = now.timestamp - before.timestamp;
  584. let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  585. if (timeMs > 0) {
  586. // TODO is there any reason to round here?
  587. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  588. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  589. }
  590. ssrcStats.addBitrate({
  591. 'download': bitrateReceivedKbps,
  592. 'upload': bitrateSentKbps
  593. });
  594. const resolution = {
  595. height: null,
  596. width: null
  597. };
  598. try {
  599. let height, width;
  600. if ((height = getStatValue(now, 'googFrameHeightReceived'))
  601. && (width = getStatValue(now, 'googFrameWidthReceived'))) {
  602. resolution.height = height;
  603. resolution.width = width;
  604. } else if ((height = getStatValue(now, 'googFrameHeightSent'))
  605. && (width = getStatValue(now, 'googFrameWidthSent'))) {
  606. resolution.height = height;
  607. resolution.width = width;
  608. }
  609. } catch (e) { /* not supported*/ }
  610. // Tries to get frame rate
  611. let frameRate;
  612. try {
  613. frameRate = getStatValue(now, 'googFrameRateReceived')
  614. || getStatValue(now, 'googFrameRateSent') || 0;
  615. } catch (e) {
  616. // if it fails with previous properties(chrome),
  617. // let's try with another one (FF)
  618. try {
  619. frameRate = this.getNonNegativeStat(now, 'framerateMean');
  620. } catch (err) { /* not supported*/ }
  621. }
  622. ssrcStats.setFramerate(Math.round(frameRate || 0));
  623. if (resolution.height && resolution.width) {
  624. ssrcStats.setResolution(resolution);
  625. } else {
  626. ssrcStats.setResolution(null);
  627. }
  628. let codec;
  629. // Try to get the codec for later reporting.
  630. try {
  631. codec = getStatValue(now, 'googCodecName') || '';
  632. } catch (e) { /* not supported*/ }
  633. ssrcStats.setCodec(codec);
  634. }
  635. this.eventEmitter.emit(
  636. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  637. this._processAndEmitReport();
  638. };
  639. /**
  640. *
  641. */
  642. StatsCollector.prototype._processAndEmitReport = function() {
  643. // process stats
  644. const totalPackets = {
  645. download: 0,
  646. upload: 0
  647. };
  648. const lostPackets = {
  649. download: 0,
  650. upload: 0
  651. };
  652. let bitrateDownload = 0;
  653. let bitrateUpload = 0;
  654. const resolutions = {};
  655. const framerates = {};
  656. const codecs = {};
  657. let audioBitrateDownload = 0;
  658. let audioBitrateUpload = 0;
  659. let audioCodec;
  660. let videoBitrateDownload = 0;
  661. let videoBitrateUpload = 0;
  662. let videoCodec;
  663. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  664. // process packet loss stats
  665. const loss = ssrcStats.loss;
  666. const type = loss.isDownloadStream ? 'download' : 'upload';
  667. totalPackets[type] += loss.packetsTotal;
  668. lostPackets[type] += loss.packetsLost;
  669. // process bitrate stats
  670. bitrateDownload += ssrcStats.bitrate.download;
  671. bitrateUpload += ssrcStats.bitrate.upload;
  672. // collect resolutions and framerates
  673. const track = this.peerconnection.getTrackBySSRC(ssrc);
  674. if (track) {
  675. if (track.isAudioTrack()) {
  676. audioBitrateDownload += ssrcStats.bitrate.download;
  677. audioBitrateUpload += ssrcStats.bitrate.upload;
  678. audioCodec = ssrcStats.codec;
  679. } else {
  680. videoBitrateDownload += ssrcStats.bitrate.download;
  681. videoBitrateUpload += ssrcStats.bitrate.upload;
  682. videoCodec = ssrcStats.codec;
  683. }
  684. const participantId = track.getParticipantId();
  685. if (participantId) {
  686. const resolution = ssrcStats.resolution;
  687. if (resolution.width
  688. && resolution.height
  689. && resolution.width !== -1
  690. && resolution.height !== -1) {
  691. const userResolutions = resolutions[participantId] || {};
  692. userResolutions[ssrc] = resolution;
  693. resolutions[participantId] = userResolutions;
  694. }
  695. if (ssrcStats.framerate !== 0) {
  696. const userFramerates = framerates[participantId] || {};
  697. userFramerates[ssrc] = ssrcStats.framerate;
  698. framerates[participantId] = userFramerates;
  699. }
  700. if (audioCodec && videoCodec) {
  701. const codecDesc = {
  702. 'audio': audioCodec,
  703. 'video': videoCodec
  704. };
  705. const userCodecs = codecs[participantId] || {};
  706. userCodecs[ssrc] = codecDesc;
  707. codecs[participantId] = userCodecs;
  708. }
  709. } else {
  710. logger.error(`No participant ID returned by ${track}`);
  711. }
  712. }
  713. ssrcStats.resetBitrate();
  714. }
  715. this.conferenceStats.bitrate = {
  716. 'upload': bitrateUpload,
  717. 'download': bitrateDownload
  718. };
  719. this.conferenceStats.bitrate.audio = {
  720. 'upload': audioBitrateUpload,
  721. 'download': audioBitrateDownload
  722. };
  723. this.conferenceStats.bitrate.video = {
  724. 'upload': videoBitrateUpload,
  725. 'download': videoBitrateDownload
  726. };
  727. this.conferenceStats.packetLoss = {
  728. total:
  729. calculatePacketLoss(
  730. lostPackets.download + lostPackets.upload,
  731. totalPackets.download + totalPackets.upload),
  732. download:
  733. calculatePacketLoss(lostPackets.download, totalPackets.download),
  734. upload:
  735. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  736. };
  737. const avgAudioLevels = {};
  738. let localAvgAudioLevels;
  739. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  740. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  741. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  742. if (isLocal) {
  743. localAvgAudioLevels = avgAudioLevel;
  744. } else {
  745. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  746. if (track) {
  747. const participantId = track.getParticipantId();
  748. if (participantId) {
  749. avgAudioLevels[participantId] = avgAudioLevel;
  750. }
  751. }
  752. }
  753. });
  754. this.audioLevelReportHistory = {};
  755. this.eventEmitter.emit(
  756. StatisticsEvents.CONNECTION_STATS,
  757. this.peerconnection,
  758. {
  759. 'bandwidth': this.conferenceStats.bandwidth,
  760. 'bitrate': this.conferenceStats.bitrate,
  761. 'packetLoss': this.conferenceStats.packetLoss,
  762. 'resolution': resolutions,
  763. 'framerate': framerates,
  764. 'codec': codecs,
  765. 'transport': this.conferenceStats.transport,
  766. localAvgAudioLevels,
  767. avgAudioLevels
  768. });
  769. this.conferenceStats.transport = [];
  770. };
  771. /**
  772. * Stats processing logic.
  773. */
  774. StatsCollector.prototype.processAudioLevelReport = function() {
  775. if (!this.baselineAudioLevelsReport) {
  776. return;
  777. }
  778. const getStatValue = this._getStatValue;
  779. for (const idx in this.currentAudioLevelsReport) {
  780. if (!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
  781. continue;
  782. }
  783. const now = this.currentAudioLevelsReport[idx];
  784. if (now.type !== 'ssrc' && now.type !== 'track') {
  785. continue;
  786. }
  787. const before = this.baselineAudioLevelsReport[idx];
  788. let ssrc = this.getNonNegativeStat(now, 'ssrc');
  789. if (!ssrc && Array.isArray(now.ssrcIds)) {
  790. ssrc = Number(now.ssrcIds[0]);
  791. }
  792. if (!before) {
  793. logger.warn(`${ssrc} not enough data`);
  794. continue;
  795. }
  796. if (!ssrc) {
  797. if ((Date.now() - now.timestamp) < 3000) {
  798. logger.warn('No ssrc: ');
  799. }
  800. continue;
  801. }
  802. // Audio level
  803. let audioLevel;
  804. try {
  805. audioLevel
  806. = getStatValue(now, 'audioInputLevel')
  807. || getStatValue(now, 'audioOutputLevel');
  808. } catch (e) { /* not supported*/
  809. logger.warn('Audio Levels are not available in the statistics.');
  810. clearInterval(this.audioLevelsIntervalId);
  811. return;
  812. }
  813. if (audioLevel) {
  814. let isLocal;
  815. // If type="ssrc" (legacy) check whether they are received packets.
  816. if (now.type === 'ssrc') {
  817. isLocal = !getStatValue(now, 'packetsReceived');
  818. // If type="track", check remoteSource boolean property.
  819. } else {
  820. isLocal = !now.remoteSource;
  821. }
  822. // According to the W3C WebRTC Stats spec, audioLevel should be in
  823. // 0..1 range (0 == silence). However browsers don't behave that
  824. // way so we must convert it to 0..1.
  825. // TODO: Can't find specs about what this value really is, but it
  826. // seems to vary between 0 and around 32k.
  827. audioLevel = audioLevel / 32767;
  828. if (!(ssrc in this.audioLevelReportHistory)) {
  829. this.audioLevelReportHistory[ssrc] = {
  830. isLocal,
  831. data: []
  832. };
  833. }
  834. this.audioLevelReportHistory[ssrc].data.push(audioLevel);
  835. this.eventEmitter.emit(
  836. StatisticsEvents.AUDIO_LEVEL,
  837. this.peerconnection,
  838. ssrc,
  839. audioLevel,
  840. isLocal);
  841. }
  842. }
  843. };
  844. /* eslint-enable no-continue */
  845. /**
  846. * New promised based getStats report processing.
  847. * Tested with chrome, firefox and safari. Not switching it on for chrome as
  848. * frameRate stat is missing and calculating it using framesSent,
  849. * gives values double the values seen in webrtc-internals.
  850. * https://w3c.github.io/webrtc-stats/
  851. */
  852. /**
  853. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  854. * gets the value from a specific report returned by RTCPeerConnection#getStats
  855. * associated with a lib-jitsi-meet browser-agnostic name in case of using
  856. * Promised based getStats.
  857. *
  858. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  859. * names to RTCPeerConnection#getStats browser-specific keys
  860. */
  861. StatsCollector.prototype._defineNewGetStatValueMethod = function(keys) {
  862. // Define the function which converts a lib-jitsi-meet browser-asnostic name
  863. // to a browser-specific key of a report returned by
  864. // RTCPeerConnection#getStats.
  865. const keyFromName = function(name) {
  866. const key = keys[name];
  867. if (key) {
  868. return key;
  869. }
  870. throw new Error(`The property '${name}' isn't supported!`);
  871. };
  872. // Compose the 2 functions defined above to get a function which retrieves
  873. // the value from a specific report returned by RTCPeerConnection#getStats
  874. // associated with a specific lib-jitsi-meet browser-agnostic name.
  875. return (item, name) => item[keyFromName(name)];
  876. };
  877. /**
  878. * Converts the value to a non-negative number.
  879. * If the value is either invalid or negative then 0 will be returned.
  880. * @param {*} v
  881. * @return {number}
  882. * @private
  883. */
  884. StatsCollector.prototype.getNonNegativeValue = function(v) {
  885. let value = v;
  886. if (typeof value !== 'number') {
  887. value = Number(value);
  888. }
  889. if (isNaN(value)) {
  890. return 0;
  891. }
  892. return Math.max(0, value);
  893. };
  894. /**
  895. * Calculates bitrate between before and now using a supplied field name and its
  896. * value in the stats.
  897. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  898. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  899. * previous stats.
  900. * @param fieldName the field to use for calculations.
  901. * @return {number} the calculated bitrate between now and before.
  902. * @private
  903. */
  904. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  905. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  906. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  907. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  908. const timeMs = now.timestamp - before.timestamp;
  909. let bitrateKbps = 0;
  910. if (timeMs > 0) {
  911. // TODO is there any reason to round here?
  912. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  913. }
  914. return bitrateKbps;
  915. };
  916. /**
  917. * Stats processing new getStats logic.
  918. */
  919. StatsCollector.prototype.processNewStatsReport = function() {
  920. if (!this.previousStatsReport) {
  921. return;
  922. }
  923. const getStatValue = this._getStatValue;
  924. const byteSentStats = {};
  925. this.currentStatsReport.forEach(now => {
  926. // RTCIceCandidatePairStats
  927. // https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  928. if (now.type === 'candidate-pair'
  929. && now.nominated
  930. && now.state === 'succeeded') {
  931. const availableIncomingBitrate = now.availableIncomingBitrate;
  932. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  933. if (availableIncomingBitrate || availableOutgoingBitrate) {
  934. this.conferenceStats.bandwidth = {
  935. 'download': Math.round(availableIncomingBitrate / 1000),
  936. 'upload': Math.round(availableOutgoingBitrate / 1000)
  937. };
  938. }
  939. const remoteUsedCandidate
  940. = this.currentStatsReport.get(now.remoteCandidateId);
  941. const localUsedCandidate
  942. = this.currentStatsReport.get(now.localCandidateId);
  943. // RTCIceCandidateStats
  944. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  945. // safari currently does not provide ice candidates in stats
  946. if (remoteUsedCandidate && localUsedCandidate) {
  947. const remoteIpAddress = getStatValue(remoteUsedCandidate, 'ip');
  948. const remotePort = getStatValue(remoteUsedCandidate, 'port');
  949. const ip = `${remoteIpAddress}:${remotePort}`;
  950. const localIpAddress = getStatValue(localUsedCandidate, 'ip');
  951. const localPort = getStatValue(localUsedCandidate, 'port');
  952. const localIp = `${localIpAddress}:${localPort}`;
  953. const type = getStatValue(remoteUsedCandidate, 'protocol');
  954. // Save the address unless it has been saved already.
  955. const conferenceStatsTransport = this.conferenceStats.transport;
  956. if (!conferenceStatsTransport.some(
  957. t =>
  958. t.ip === ip
  959. && t.type === type
  960. && t.localip === localIp)) {
  961. conferenceStatsTransport.push({
  962. ip,
  963. type,
  964. localIp,
  965. p2p: this.peerconnection.isP2P,
  966. localCandidateType: localUsedCandidate.candidateType,
  967. remoteCandidateType: remoteUsedCandidate.candidateType,
  968. networkType: localUsedCandidate.networkType,
  969. rtt: now.currentRoundTripTime * 1000
  970. });
  971. }
  972. }
  973. // RTCReceivedRtpStreamStats
  974. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  975. // RTCSentRtpStreamStats
  976. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  977. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  978. const before = this.previousStatsReport.get(now.id);
  979. const ssrc = this.getNonNegativeValue(now.ssrc);
  980. if (!before || !ssrc) {
  981. return;
  982. }
  983. let ssrcStats = this.ssrc2stats.get(ssrc);
  984. if (!ssrcStats) {
  985. ssrcStats = new SsrcStats();
  986. this.ssrc2stats.set(ssrc, ssrcStats);
  987. }
  988. let isDownloadStream = true;
  989. let key = 'packetsReceived';
  990. if (now.type === 'outbound-rtp') {
  991. isDownloadStream = false;
  992. key = 'packetsSent';
  993. }
  994. let packetsNow = now[key];
  995. if (!packetsNow || packetsNow < 0) {
  996. packetsNow = 0;
  997. }
  998. const packetsBefore = this.getNonNegativeValue(before[key]);
  999. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  1000. const packetsLostNow
  1001. = this.getNonNegativeValue(now.packetsLost);
  1002. const packetsLostBefore
  1003. = this.getNonNegativeValue(before.packetsLost);
  1004. const packetsLostDiff
  1005. = Math.max(0, packetsLostNow - packetsLostBefore);
  1006. ssrcStats.setLoss({
  1007. packetsTotal: packetsDiff + packetsLostDiff,
  1008. packetsLost: packetsLostDiff,
  1009. isDownloadStream
  1010. });
  1011. const resolution = {
  1012. height: null,
  1013. width: null
  1014. };
  1015. try {
  1016. resolution.height = getStatValue(now, 'frameHeight');
  1017. resolution.width = getStatValue(now, 'frameWidth');
  1018. } catch (e) { /* not supported*/ }
  1019. // Tries to get frame rate
  1020. let frameRate;
  1021. try {
  1022. frameRate = getStatValue(now, 'framesPerSecond');
  1023. } catch (err) { /* not supported*/ }
  1024. ssrcStats.setFramerate(Math.round(frameRate || 0));
  1025. if (resolution.height && resolution.width) {
  1026. ssrcStats.setResolution(resolution);
  1027. } else {
  1028. ssrcStats.setResolution(null);
  1029. }
  1030. if (now.type === 'inbound-rtp') {
  1031. ssrcStats.addBitrate({
  1032. 'download': this._calculateBitrate(
  1033. now, before, 'bytesReceived'),
  1034. 'upload': 0
  1035. });
  1036. // RTCInboundRtpStreamStats
  1037. // https://w3c.github.io/webrtc-stats/#inboundrtpstats-dict*
  1038. // TODO: can we use framesDecoded for frame rate, available
  1039. // in chrome
  1040. } else {
  1041. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  1042. ssrcStats.addBitrate({
  1043. 'download': 0,
  1044. 'upload': this._calculateBitrate(
  1045. now, before, 'bytesSent')
  1046. });
  1047. // RTCOutboundRtpStreamStats
  1048. // https://w3c.github.io/webrtc-stats/#outboundrtpstats-dict*
  1049. // TODO: can we use framesEncoded for frame rate, available
  1050. // in chrome
  1051. }
  1052. // FF has framerateMean out of spec
  1053. const framerateMean = now.framerateMean;
  1054. if (framerateMean) {
  1055. ssrcStats.setFramerate(Math.round(framerateMean || 0));
  1056. }
  1057. let codec;
  1058. // Try to get the codec for later reporting.
  1059. try {
  1060. codec = this.currentStatsReport.get(now.codecId);
  1061. } catch (e) { /* not supported*/ }
  1062. if (codec) {
  1063. /**
  1064. * The mime type has the following form: video/VP8 or audio/ISAC,
  1065. * so we what to keep just the type after the '/', audio and video
  1066. * keys will be added on the processing side.
  1067. */
  1068. const codecShortType = codec.mimeType.split('/')[1];
  1069. codecShortType && ssrcStats.setCodec(codecShortType);
  1070. }
  1071. // track for resolution
  1072. // RTCVideoHandlerStats
  1073. // https://w3c.github.io/webrtc-stats/#vststats-dict*
  1074. // RTCMediaHandlerStats
  1075. // https://w3c.github.io/webrtc-stats/#mststats-dict*
  1076. } else if (now.type === 'track') {
  1077. const resolution = {
  1078. height: now.frameHeight,
  1079. width: now.frameWidth
  1080. };
  1081. // Tries to get frame rate
  1082. let frameRate = now.framesPerSecond;
  1083. if (!frameRate) {
  1084. // we need to calculate it
  1085. const before = this.previousStatsReport.get(now.id);
  1086. if (before) {
  1087. const timeMs = now.timestamp - before.timestamp;
  1088. if (timeMs > 0 && now.framesSent) {
  1089. const numberOfFramesSinceBefore
  1090. = now.framesSent - before.framesSent;
  1091. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  1092. }
  1093. }
  1094. if (!frameRate) {
  1095. return;
  1096. }
  1097. }
  1098. const trackIdentifier = now.trackIdentifier;
  1099. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  1100. if (!ssrc) {
  1101. return;
  1102. }
  1103. let ssrcStats = this.ssrc2stats.get(ssrc);
  1104. if (!ssrcStats) {
  1105. ssrcStats = new SsrcStats();
  1106. this.ssrc2stats.set(ssrc, ssrcStats);
  1107. }
  1108. ssrcStats.setFramerate(Math.round(frameRate || 0));
  1109. if (resolution.height && resolution.width) {
  1110. ssrcStats.setResolution(resolution);
  1111. } else {
  1112. ssrcStats.setResolution(null);
  1113. }
  1114. }
  1115. });
  1116. this.eventEmitter.emit(
  1117. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  1118. this._processAndEmitReport();
  1119. };
  1120. /**
  1121. * Stats processing logic.
  1122. */
  1123. StatsCollector.prototype.processNewAudioLevelReport = function() {
  1124. if (!this.baselineAudioLevelsReport) {
  1125. return;
  1126. }
  1127. this.currentAudioLevelsReport.forEach(now => {
  1128. if (now.type !== 'track') {
  1129. return;
  1130. }
  1131. // Audio level
  1132. const audioLevel = now.audioLevel;
  1133. if (!audioLevel) {
  1134. return;
  1135. }
  1136. const trackIdentifier = now.trackIdentifier;
  1137. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  1138. if (ssrc) {
  1139. const isLocal
  1140. = ssrc === this.peerconnection.getLocalSSRC(
  1141. this.peerconnection.getLocalTracks(MediaType.AUDIO));
  1142. this.eventEmitter.emit(
  1143. StatisticsEvents.AUDIO_LEVEL,
  1144. this.peerconnection,
  1145. ssrc,
  1146. audioLevel,
  1147. isLocal);
  1148. }
  1149. });
  1150. };
  1151. /**
  1152. * End new promised based getStats processing methods.
  1153. */