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

RTPStatsCollector.js 23KB

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