Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

RTPStatsCollector.js 23KB

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