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 25KB

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