modified lib-jitsi-meet dev repo
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 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /* global require */
  2. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  3. const logger = require('jitsi-meet-logger').getLogger(__filename);
  4. const RTCBrowserType = require('../RTC/RTCBrowserType');
  5. import * as StatisticsEvents from '../../service/statistics/Events';
  6. /* Whether we support the browser we are running into for logging statistics */
  7. const browserSupported = RTCBrowserType.isChrome()
  8. || RTCBrowserType.isOpera() || RTCBrowserType.isFirefox()
  9. || RTCBrowserType.isNWJS() || RTCBrowserType.isElectron();
  10. /**
  11. * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
  12. * by RTCPeerConnection#getStats mapped by RTCBrowserType.
  13. */
  14. const KEYS_BY_BROWSER_TYPE = {};
  15. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  16. 'ssrc': 'ssrc',
  17. 'packetsReceived': 'packetsReceived',
  18. 'packetsLost': 'packetsLost',
  19. 'packetsSent': 'packetsSent',
  20. 'bytesReceived': 'bytesReceived',
  21. 'bytesSent': 'bytesSent'
  22. };
  23. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME] = {
  24. 'receiveBandwidth': 'googAvailableReceiveBandwidth',
  25. 'sendBandwidth': 'googAvailableSendBandwidth',
  26. 'remoteAddress': 'googRemoteAddress',
  27. 'transportType': 'googTransportType',
  28. 'localAddress': 'googLocalAddress',
  29. 'activeConnection': 'googActiveConnection',
  30. 'ssrc': 'ssrc',
  31. 'packetsReceived': 'packetsReceived',
  32. 'packetsSent': 'packetsSent',
  33. 'packetsLost': 'packetsLost',
  34. 'bytesReceived': 'bytesReceived',
  35. 'bytesSent': 'bytesSent',
  36. 'googFrameHeightReceived': 'googFrameHeightReceived',
  37. 'googFrameWidthReceived': 'googFrameWidthReceived',
  38. 'googFrameHeightSent': 'googFrameHeightSent',
  39. 'googFrameWidthSent': 'googFrameWidthSent',
  40. 'audioInputLevel': 'audioInputLevel',
  41. 'audioOutputLevel': 'audioOutputLevel'
  42. };
  43. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_OPERA]
  44. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  45. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_NWJS]
  46. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  47. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_ELECTRON]
  48. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  49. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_IEXPLORER]
  50. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  51. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_SAFARI]
  52. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  53. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_REACT_NATIVE]
  54. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  55. /**
  56. * Calculates packet lost percent using the number of lost packets and the
  57. * number of all packet.
  58. * @param lostPackets the number of lost packets
  59. * @param totalPackets the number of all packets.
  60. * @returns {number} packet loss percent
  61. */
  62. function calculatePacketLoss(lostPackets, totalPackets) {
  63. if (!totalPackets || totalPackets <= 0
  64. || !lostPackets || lostPackets <= 0) {
  65. return 0;
  66. }
  67. return Math.round((lostPackets / totalPackets) * 100);
  68. }
  69. /**
  70. * Holds "statistics" for a single SSRC.
  71. * @constructor
  72. */
  73. function SsrcStats() {
  74. this.loss = {};
  75. this.bitrate = {
  76. download: 0,
  77. upload: 0
  78. };
  79. this.resolution = {};
  80. }
  81. /**
  82. * Sets the "loss" object.
  83. * @param loss the value to set.
  84. */
  85. SsrcStats.prototype.setLoss = function(loss) {
  86. this.loss = loss || {};
  87. };
  88. /**
  89. * Sets resolution that belong to the ssrc represented by this instance.
  90. * @param resolution new resolution value to be set.
  91. */
  92. SsrcStats.prototype.setResolution = function(resolution) {
  93. this.resolution = resolution || {};
  94. };
  95. /**
  96. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  97. * the respective fields of the "bitrate" field of this object.
  98. * @param bitrate an object holding the values to add.
  99. */
  100. SsrcStats.prototype.addBitrate = function(bitrate) {
  101. this.bitrate.download += bitrate.download;
  102. this.bitrate.upload += bitrate.upload;
  103. };
  104. /**
  105. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  106. * represented by this instance.
  107. */
  108. SsrcStats.prototype.resetBitrate = function() {
  109. this.bitrate.download = 0;
  110. this.bitrate.upload = 0;
  111. };
  112. /**
  113. *
  114. */
  115. function ConferenceStats() {
  116. /**
  117. * The bandwidth
  118. * @type {{}}
  119. */
  120. this.bandwidth = {};
  121. /**
  122. * The bit rate
  123. * @type {{}}
  124. */
  125. this.bitrate = {};
  126. /**
  127. * The packet loss rate
  128. * @type {{}}
  129. */
  130. this.packetLoss = null;
  131. /**
  132. * Array with the transport information.
  133. * @type {Array}
  134. */
  135. this.transport = [];
  136. }
  137. /* eslint-disable max-params */
  138. /**
  139. * <tt>StatsCollector</tt> registers for stats updates of given
  140. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  141. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  142. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  143. * instance as an event source.
  144. *
  145. * @param peerconnection WebRTC PeerConnection object.
  146. * @param audioLevelsInterval
  147. * @param statsInterval stats refresh interval given in ms.
  148. * @param eventEmitter
  149. * @constructor
  150. */
  151. function StatsCollector(
  152. peerconnection,
  153. audioLevelsInterval,
  154. statsInterval,
  155. eventEmitter) {
  156. // StatsCollector depends entirely on the format of the reports returned by
  157. // RTCPeerConnection#getStats. Given that the value of
  158. // RTCBrowserType#getBrowserType() is very unlikely to change at runtime, it
  159. // makes sense to discover whether StatsCollector supports the executing
  160. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  161. // needlessly check a "static" condition multiple times very very often and
  162. // (2) the lack of support for the executing browser would be discovered and
  163. // reported multiple times very very often too late in the execution in some
  164. // totally unrelated callback.
  165. /**
  166. * The RTCBrowserType supported by this StatsCollector. In other words, the
  167. * RTCBrowserType of the browser which initialized this StatsCollector
  168. * instance.
  169. * @private
  170. */
  171. this._browserType = RTCBrowserType.getBrowserType();
  172. const keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  173. if (!keys) {
  174. // eslint-disable-next-line no-throw-literal
  175. throw `The browser type '${this._browserType}' isn't supported!`;
  176. }
  177. /**
  178. * The function which is to be used to retrieve the value associated in a
  179. * report returned by RTCPeerConnection#getStats with a LibJitsiMeet
  180. * browser-agnostic name/key.
  181. * @function
  182. * @private
  183. */
  184. this._getStatValue = this._defineGetStatValueMethod(keys);
  185. this.peerconnection = peerconnection;
  186. this.baselineAudioLevelsReport = null;
  187. this.currentAudioLevelsReport = null;
  188. this.currentStatsReport = null;
  189. this.previousStatsReport = null;
  190. this.audioLevelsIntervalId = null;
  191. this.eventEmitter = eventEmitter;
  192. this.conferenceStats = new ConferenceStats();
  193. // Updates stats interval
  194. this.audioLevelsIntervalMilis = audioLevelsInterval;
  195. this.statsIntervalId = null;
  196. this.statsIntervalMilis = statsInterval;
  197. // Map of ssrcs to SsrcStats
  198. this.ssrc2stats = {};
  199. }
  200. /* eslint-enable max-params */
  201. module.exports = StatsCollector;
  202. /**
  203. * Stops stats updates.
  204. */
  205. StatsCollector.prototype.stop = function() {
  206. if (this.audioLevelsIntervalId) {
  207. clearInterval(this.audioLevelsIntervalId);
  208. this.audioLevelsIntervalId = null;
  209. }
  210. if (this.statsIntervalId) {
  211. clearInterval(this.statsIntervalId);
  212. this.statsIntervalId = null;
  213. }
  214. };
  215. /**
  216. * Callback passed to <tt>getStats</tt> method.
  217. * @param error an error that occurred on <tt>getStats</tt> call.
  218. */
  219. StatsCollector.prototype.errorCallback = function(error) {
  220. GlobalOnErrorHandler.callErrorHandler(error);
  221. logger.error('Get stats error', error);
  222. this.stop();
  223. };
  224. /**
  225. * Starts stats updates.
  226. */
  227. StatsCollector.prototype.start = function(startAudioLevelStats) {
  228. const self = this;
  229. if (startAudioLevelStats) {
  230. this.audioLevelsIntervalId = setInterval(
  231. () => {
  232. // Interval updates
  233. self.peerconnection.getStats(
  234. report => {
  235. let results = null;
  236. if (!report || !report.result
  237. || typeof report.result !== 'function') {
  238. results = report;
  239. } else {
  240. results = report.result();
  241. }
  242. self.currentAudioLevelsReport = results;
  243. self.processAudioLevelReport();
  244. self.baselineAudioLevelsReport
  245. = self.currentAudioLevelsReport;
  246. },
  247. self.errorCallback
  248. );
  249. },
  250. self.audioLevelsIntervalMilis
  251. );
  252. }
  253. if (browserSupported) {
  254. this.statsIntervalId = setInterval(
  255. () => {
  256. // Interval updates
  257. self.peerconnection.getStats(
  258. report => {
  259. let results = null;
  260. if (!report || !report.result
  261. || typeof report.result !== 'function') {
  262. // firefox
  263. results = report;
  264. } else {
  265. // chrome
  266. results = report.result();
  267. }
  268. self.currentStatsReport = results;
  269. try {
  270. self.processStatsReport();
  271. } catch (e) {
  272. GlobalOnErrorHandler.callErrorHandler(e);
  273. logger.error(`Unsupported key:${e}`, e);
  274. }
  275. self.previousStatsReport = self.currentStatsReport;
  276. },
  277. self.errorCallback
  278. );
  279. },
  280. self.statsIntervalMilis
  281. );
  282. }
  283. };
  284. /**
  285. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  286. * gets the value from a specific report returned by RTCPeerConnection#getStats
  287. * associated with a LibJitsiMeet browser-agnostic name.
  288. *
  289. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  290. * names to RTCPeerConnection#getStats browser-specific keys
  291. */
  292. StatsCollector.prototype._defineGetStatValueMethod = function(keys) {
  293. // Define the function which converts a LibJitsiMeet browser-asnostic name
  294. // to a browser-specific key of a report returned by
  295. // RTCPeerConnection#getStats.
  296. const keyFromName = function(name) {
  297. const key = keys[name];
  298. if (key) {
  299. return key;
  300. }
  301. // eslint-disable-next-line no-throw-literal
  302. throw `The property '${name}' isn't supported!`;
  303. };
  304. // Define the function which retrieves the value from a specific report
  305. // returned by RTCPeerConnection#getStats associated with a given
  306. // browser-specific key.
  307. let itemStatByKey;
  308. switch (this._browserType) {
  309. case RTCBrowserType.RTC_BROWSER_CHROME:
  310. case RTCBrowserType.RTC_BROWSER_OPERA:
  311. case RTCBrowserType.RTC_BROWSER_NWJS:
  312. case RTCBrowserType.RTC_BROWSER_ELECTRON:
  313. // TODO What about other types of browser which are based on Chrome such
  314. // as NW.js? Every time we want to support a new type browser we have to
  315. // go and add more conditions (here and in multiple other places).
  316. // Cannot we do a feature detection instead of a browser type check? For
  317. // example, if item has a stat property of type function, then it's very
  318. // likely that whoever defined it wanted you to call it in order to
  319. // retrieve the value associated with a specific key.
  320. itemStatByKey = (item, key) => item.stat(key);
  321. break;
  322. case RTCBrowserType.RTC_BROWSER_REACT_NATIVE:
  323. // The implementation provided by react-native-webrtc follows the
  324. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  325. // Array in which each element is a key-value pair.
  326. itemStatByKey = function(item, key) {
  327. let value;
  328. item.values.some(pair => {
  329. if (pair.hasOwnProperty(key)) {
  330. value = pair[key];
  331. return true;
  332. }
  333. return false;
  334. });
  335. return value;
  336. };
  337. break;
  338. default:
  339. itemStatByKey = (item, key) => item[key];
  340. }
  341. // Compose the 2 functions defined above to get a function which retrieves
  342. // the value from a specific report returned by RTCPeerConnection#getStats
  343. // associated with a specific LibJitsiMeet browser-agnostic name.
  344. return function(item, name) {
  345. return itemStatByKey(item, keyFromName(name));
  346. };
  347. };
  348. /* eslint-disable no-continue */
  349. /**
  350. * Stats processing logic.
  351. */
  352. StatsCollector.prototype.processStatsReport = function() {
  353. if (!this.previousStatsReport) {
  354. return;
  355. }
  356. const getStatValue = this._getStatValue;
  357. /**
  358. *
  359. * @param report
  360. * @param name
  361. */
  362. function getNonNegativeStat(report, name) {
  363. let value = getStatValue(report, name);
  364. if (typeof value !== 'number') {
  365. value = Number(value);
  366. }
  367. if (isNaN(value)) {
  368. return 0;
  369. }
  370. return Math.max(0, value);
  371. }
  372. const byteSentStats = {};
  373. for (const idx in this.currentStatsReport) {
  374. if (!this.currentStatsReport.hasOwnProperty(idx)) {
  375. continue;
  376. }
  377. const now = this.currentStatsReport[idx];
  378. try {
  379. const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  380. const sendBandwidth = getStatValue(now, 'sendBandwidth');
  381. if (receiveBandwidth || sendBandwidth) {
  382. this.conferenceStats.bandwidth = {
  383. 'download': Math.round(receiveBandwidth / 1000),
  384. 'upload': Math.round(sendBandwidth / 1000)
  385. };
  386. }
  387. } catch (e) { /* not supported*/ }
  388. if (now.type === 'googCandidatePair') {
  389. let active, ip, localip, type;
  390. try {
  391. ip = getStatValue(now, 'remoteAddress');
  392. type = getStatValue(now, 'transportType');
  393. localip = getStatValue(now, 'localAddress');
  394. active = getStatValue(now, 'activeConnection');
  395. } catch (e) { /* not supported*/ }
  396. if (!ip || !type || !localip || active !== 'true') {
  397. continue;
  398. }
  399. // Save the address unless it has been saved already.
  400. const conferenceStatsTransport = this.conferenceStats.transport;
  401. if (!conferenceStatsTransport.some(
  402. t =>
  403. t.ip === ip
  404. && t.type === type
  405. && t.localip === localip)) {
  406. conferenceStatsTransport.push({ ip,
  407. type,
  408. localip });
  409. }
  410. continue;
  411. }
  412. if (now.type === 'candidatepair') {
  413. if (now.state === 'succeeded') {
  414. continue;
  415. }
  416. const local = this.currentStatsReport[now.localCandidateId];
  417. const remote = this.currentStatsReport[now.remoteCandidateId];
  418. this.conferenceStats.transport.push({
  419. ip: `${remote.ipAddress}:${remote.portNumber}`,
  420. type: local.transport,
  421. localip: `${local.ipAddress}:${local.portNumber}`
  422. });
  423. }
  424. if (now.type !== 'ssrc' && now.type !== 'outboundrtp'
  425. && now.type !== 'inboundrtp') {
  426. continue;
  427. }
  428. const before = this.previousStatsReport[idx];
  429. const ssrc = getStatValue(now, 'ssrc');
  430. if (!before || !ssrc) {
  431. continue;
  432. }
  433. const ssrcStats
  434. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
  435. let isDownloadStream = true;
  436. let key = 'packetsReceived';
  437. let packetsNow = getStatValue(now, key);
  438. if (typeof packetsNow === 'undefined'
  439. || packetsNow === null || packetsNow === '') {
  440. isDownloadStream = false;
  441. key = 'packetsSent';
  442. packetsNow = getStatValue(now, key);
  443. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  444. logger.warn('No packetsReceived nor packetsSent stat found');
  445. continue;
  446. }
  447. }
  448. if (!packetsNow || packetsNow < 0) {
  449. packetsNow = 0;
  450. }
  451. const packetsBefore = getNonNegativeStat(before, key);
  452. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  453. const packetsLostNow = getNonNegativeStat(now, 'packetsLost');
  454. const packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
  455. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  456. ssrcStats.setLoss({
  457. packetsTotal: packetsDiff + packetsLostDiff,
  458. packetsLost: packetsLostDiff,
  459. isDownloadStream
  460. });
  461. const bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
  462. const bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
  463. const bytesReceived
  464. = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  465. let bytesSent = 0;
  466. // TODO: clean this mess up!
  467. let nowBytesTransmitted = getStatValue(now, 'bytesSent');
  468. if (typeof nowBytesTransmitted === 'number'
  469. || typeof nowBytesTransmitted === 'string') {
  470. nowBytesTransmitted = Number(nowBytesTransmitted);
  471. if (!isNaN(nowBytesTransmitted)) {
  472. byteSentStats[ssrc] = nowBytesTransmitted;
  473. if (nowBytesTransmitted > 0) {
  474. bytesSent = nowBytesTransmitted
  475. - getStatValue(before, 'bytesSent');
  476. }
  477. }
  478. }
  479. bytesSent = Math.max(0, bytesSent);
  480. const timeMs = now.timestamp - before.timestamp;
  481. let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  482. if (timeMs > 0) {
  483. // TODO is there any reason to round here?
  484. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  485. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  486. }
  487. ssrcStats.addBitrate({
  488. 'download': bitrateReceivedKbps,
  489. 'upload': bitrateSentKbps
  490. });
  491. const resolution = { height: null,
  492. width: null };
  493. try {
  494. let height, width;
  495. if ((height = getStatValue(now, 'googFrameHeightReceived'))
  496. && (width = getStatValue(now, 'googFrameWidthReceived'))) {
  497. resolution.height = height;
  498. resolution.width = width;
  499. } else if ((height = getStatValue(now, 'googFrameHeightSent'))
  500. && (width = getStatValue(now, 'googFrameWidthSent'))) {
  501. resolution.height = height;
  502. resolution.width = width;
  503. }
  504. } catch (e) { /* not supported*/ }
  505. if (resolution.height && resolution.width) {
  506. ssrcStats.setResolution(resolution);
  507. } else {
  508. ssrcStats.setResolution(null);
  509. }
  510. }
  511. // process stats
  512. const totalPackets = {
  513. download: 0,
  514. upload: 0
  515. };
  516. const lostPackets = {
  517. download: 0,
  518. upload: 0
  519. };
  520. let bitrateDownload = 0;
  521. let bitrateUpload = 0;
  522. const resolutions = {};
  523. Object.keys(this.ssrc2stats).forEach(
  524. function(ssrc) {
  525. const ssrcStats = this.ssrc2stats[ssrc];
  526. // process packet loss stats
  527. const loss = ssrcStats.loss;
  528. const type = loss.isDownloadStream ? 'download' : 'upload';
  529. totalPackets[type] += loss.packetsTotal;
  530. lostPackets[type] += loss.packetsLost;
  531. // process bitrate stats
  532. bitrateDownload += ssrcStats.bitrate.download;
  533. bitrateUpload += ssrcStats.bitrate.upload;
  534. ssrcStats.resetBitrate();
  535. // collect resolutions
  536. resolutions[ssrc] = ssrcStats.resolution;
  537. },
  538. this
  539. );
  540. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, byteSentStats);
  541. this.conferenceStats.bitrate
  542. = { 'upload': bitrateUpload,
  543. 'download': bitrateDownload };
  544. this.conferenceStats.packetLoss = {
  545. total:
  546. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  547. totalPackets.download + totalPackets.upload),
  548. download:
  549. calculatePacketLoss(lostPackets.download, totalPackets.download),
  550. upload:
  551. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  552. };
  553. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  554. 'bandwidth': this.conferenceStats.bandwidth,
  555. 'bitrate': this.conferenceStats.bitrate,
  556. 'packetLoss': this.conferenceStats.packetLoss,
  557. 'resolution': resolutions,
  558. 'transport': this.conferenceStats.transport
  559. });
  560. this.conferenceStats.transport = [];
  561. };
  562. /**
  563. * Stats processing logic.
  564. */
  565. StatsCollector.prototype.processAudioLevelReport = function() {
  566. if (!this.baselineAudioLevelsReport) {
  567. return;
  568. }
  569. const getStatValue = this._getStatValue;
  570. for (const idx in this.currentAudioLevelsReport) {
  571. if (!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
  572. continue;
  573. }
  574. const now = this.currentAudioLevelsReport[idx];
  575. if (now.type !== 'ssrc') {
  576. continue;
  577. }
  578. const before = this.baselineAudioLevelsReport[idx];
  579. const ssrc = getStatValue(now, 'ssrc');
  580. if (!before) {
  581. logger.warn(`${ssrc} not enough data`);
  582. continue;
  583. }
  584. if (!ssrc) {
  585. if ((Date.now() - now.timestamp) < 3000) {
  586. logger.warn('No ssrc: ');
  587. }
  588. continue;
  589. }
  590. // Audio level
  591. let audioLevel;
  592. try {
  593. audioLevel
  594. = getStatValue(now, 'audioInputLevel')
  595. || getStatValue(now, 'audioOutputLevel');
  596. } catch (e) { /* not supported*/
  597. logger.warn('Audio Levels are not available in the statistics.');
  598. clearInterval(this.audioLevelsIntervalId);
  599. return;
  600. }
  601. if (audioLevel) {
  602. const isLocal = !getStatValue(now, 'packetsReceived');
  603. // TODO: Can't find specs about what this value really is, but it
  604. // seems to vary between 0 and around 32k.
  605. audioLevel = audioLevel / 32767;
  606. this.eventEmitter.emit(
  607. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel, isLocal);
  608. }
  609. }
  610. };
  611. /* eslint-enable no-continue */