您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTPStatsCollector.js 22KB

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