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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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 LibJitsiMeet browser-agnostic names of the browser-specific keys reported
  11. * 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 LibJitsiMeet
  190. * browser-agnostic name/key.
  191. * @function
  192. * @private
  193. */
  194. this._getStatValue = this._defineGetStatValueMethod(keys);
  195. this.peerconnection = peerconnection;
  196. this.baselineAudioLevelsReport = null;
  197. this.currentAudioLevelsReport = null;
  198. this.currentStatsReport = null;
  199. this.previousStatsReport = null;
  200. this.audioLevelsIntervalId = null;
  201. this.eventEmitter = eventEmitter;
  202. this.conferenceStats = new ConferenceStats();
  203. // Updates stats interval
  204. this.audioLevelsIntervalMilis = audioLevelsInterval;
  205. this.statsIntervalId = null;
  206. this.statsIntervalMilis = statsInterval;
  207. // Map of ssrcs to SsrcStats
  208. this.ssrc2stats = {};
  209. }
  210. /* eslint-enable max-params */
  211. /**
  212. * Stops stats updates.
  213. */
  214. StatsCollector.prototype.stop = function() {
  215. if (this.audioLevelsIntervalId) {
  216. clearInterval(this.audioLevelsIntervalId);
  217. this.audioLevelsIntervalId = null;
  218. }
  219. if (this.statsIntervalId) {
  220. clearInterval(this.statsIntervalId);
  221. this.statsIntervalId = null;
  222. }
  223. };
  224. /**
  225. * Callback passed to <tt>getStats</tt> method.
  226. * @param error an error that occurred on <tt>getStats</tt> call.
  227. */
  228. StatsCollector.prototype.errorCallback = function(error) {
  229. GlobalOnErrorHandler.callErrorHandler(error);
  230. logger.error('Get stats error', error);
  231. this.stop();
  232. };
  233. /**
  234. * Starts stats updates.
  235. */
  236. StatsCollector.prototype.start = function(startAudioLevelStats) {
  237. const self = this;
  238. if (startAudioLevelStats) {
  239. this.audioLevelsIntervalId = setInterval(
  240. () => {
  241. // Interval updates
  242. self.peerconnection.getStats(
  243. report => {
  244. let results = null;
  245. if (!report || !report.result
  246. || typeof report.result !== 'function') {
  247. results = report;
  248. } else {
  249. results = report.result();
  250. }
  251. self.currentAudioLevelsReport = results;
  252. self.processAudioLevelReport();
  253. self.baselineAudioLevelsReport
  254. = self.currentAudioLevelsReport;
  255. },
  256. self.errorCallback
  257. );
  258. },
  259. self.audioLevelsIntervalMilis
  260. );
  261. }
  262. if (browserSupported) {
  263. this.statsIntervalId = setInterval(
  264. () => {
  265. // Interval updates
  266. self.peerconnection.getStats(
  267. report => {
  268. let results = null;
  269. if (!report || !report.result
  270. || typeof report.result !== 'function') {
  271. // firefox
  272. results = report;
  273. } else {
  274. // chrome
  275. results = report.result();
  276. }
  277. self.currentStatsReport = results;
  278. try {
  279. self.processStatsReport();
  280. } catch (e) {
  281. GlobalOnErrorHandler.callErrorHandler(e);
  282. logger.error(`Unsupported key:${e}`, e);
  283. }
  284. self.previousStatsReport = self.currentStatsReport;
  285. },
  286. self.errorCallback
  287. );
  288. },
  289. self.statsIntervalMilis
  290. );
  291. }
  292. };
  293. /**
  294. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  295. * gets the value from a specific report returned by RTCPeerConnection#getStats
  296. * associated with a LibJitsiMeet browser-agnostic name.
  297. *
  298. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  299. * names to RTCPeerConnection#getStats browser-specific keys
  300. */
  301. StatsCollector.prototype._defineGetStatValueMethod = function(keys) {
  302. // Define the function which converts a LibJitsiMeet browser-asnostic name
  303. // to a browser-specific key of a report returned by
  304. // RTCPeerConnection#getStats.
  305. const keyFromName = function(name) {
  306. const key = keys[name];
  307. if (key) {
  308. return key;
  309. }
  310. // eslint-disable-next-line no-throw-literal
  311. throw `The property '${name}' isn't supported!`;
  312. };
  313. // Define the function which retrieves the value from a specific report
  314. // returned by RTCPeerConnection#getStats associated with a given
  315. // browser-specific key.
  316. let itemStatByKey;
  317. switch (this._browserType) {
  318. case RTCBrowserType.RTC_BROWSER_CHROME:
  319. case RTCBrowserType.RTC_BROWSER_OPERA:
  320. case RTCBrowserType.RTC_BROWSER_NWJS:
  321. case RTCBrowserType.RTC_BROWSER_ELECTRON:
  322. // TODO What about other types of browser which are based on Chrome such
  323. // as NW.js? Every time we want to support a new type browser we have to
  324. // go and add more conditions (here and in multiple other places).
  325. // Cannot we do a feature detection instead of a browser type check? For
  326. // example, if item has a stat property of type function, then it's very
  327. // likely that whoever defined it wanted you to call it in order to
  328. // retrieve the value associated with a specific key.
  329. itemStatByKey = (item, key) => item.stat(key);
  330. break;
  331. case RTCBrowserType.RTC_BROWSER_REACT_NATIVE:
  332. // The implementation provided by react-native-webrtc follows the
  333. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  334. // Array in which each element is a key-value pair.
  335. itemStatByKey = function(item, key) {
  336. let value;
  337. item.values.some(pair => {
  338. if (pair.hasOwnProperty(key)) {
  339. value = pair[key];
  340. return true;
  341. }
  342. return false;
  343. });
  344. return value;
  345. };
  346. break;
  347. default:
  348. itemStatByKey = (item, key) => item[key];
  349. }
  350. // Compose the 2 functions defined above to get a function which retrieves
  351. // the value from a specific report returned by RTCPeerConnection#getStats
  352. // associated with a specific LibJitsiMeet browser-agnostic name.
  353. return function(item, name) {
  354. return itemStatByKey(item, keyFromName(name));
  355. };
  356. };
  357. /* eslint-disable no-continue */
  358. /**
  359. * Stats processing logic.
  360. */
  361. StatsCollector.prototype.processStatsReport = function() {
  362. if (!this.previousStatsReport) {
  363. return;
  364. }
  365. const getStatValue = this._getStatValue;
  366. /**
  367. *
  368. * @param report
  369. * @param name
  370. */
  371. function getNonNegativeStat(report, name) {
  372. let value = getStatValue(report, name);
  373. if (typeof value !== 'number') {
  374. value = Number(value);
  375. }
  376. if (isNaN(value)) {
  377. return 0;
  378. }
  379. return Math.max(0, value);
  380. }
  381. const byteSentStats = {};
  382. for (const idx in this.currentStatsReport) {
  383. if (!this.currentStatsReport.hasOwnProperty(idx)) {
  384. continue;
  385. }
  386. const now = this.currentStatsReport[idx];
  387. // The browser API may return "undefined" values in the array
  388. if (!now) {
  389. continue;
  390. }
  391. try {
  392. const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  393. const sendBandwidth = getStatValue(now, 'sendBandwidth');
  394. if (receiveBandwidth || sendBandwidth) {
  395. this.conferenceStats.bandwidth = {
  396. 'download': Math.round(receiveBandwidth / 1000),
  397. 'upload': Math.round(sendBandwidth / 1000)
  398. };
  399. }
  400. } catch (e) { /* not supported*/ }
  401. if (now.type === 'googCandidatePair') {
  402. let active, ip, localip, type;
  403. try {
  404. ip = getStatValue(now, 'remoteAddress');
  405. type = getStatValue(now, 'transportType');
  406. localip = getStatValue(now, 'localAddress');
  407. active = getStatValue(now, 'activeConnection');
  408. } catch (e) { /* not supported*/ }
  409. if (!ip || !type || !localip || active !== 'true') {
  410. continue;
  411. }
  412. // Save the address unless it has been saved already.
  413. const conferenceStatsTransport = this.conferenceStats.transport;
  414. if (!conferenceStatsTransport.some(
  415. t =>
  416. t.ip === ip
  417. && t.type === type
  418. && t.localip === localip)) {
  419. conferenceStatsTransport.push({
  420. ip,
  421. type,
  422. localip,
  423. p2p: this.peerconnection.isP2P
  424. });
  425. }
  426. continue;
  427. }
  428. if (now.type === 'candidatepair') {
  429. // we need succeeded pairs only
  430. if (now.state !== 'succeeded') {
  431. continue;
  432. }
  433. const local = this.currentStatsReport[now.localCandidateId];
  434. const remote = this.currentStatsReport[now.remoteCandidateId];
  435. this.conferenceStats.transport.push({
  436. ip: `${remote.ipAddress}:${remote.portNumber}`,
  437. type: local.transport,
  438. localip: `${local.ipAddress}:${local.portNumber}`,
  439. p2p: this.peerconnection.isP2P
  440. });
  441. }
  442. if (now.type !== 'ssrc' && now.type !== 'outboundrtp'
  443. && now.type !== 'inboundrtp') {
  444. continue;
  445. }
  446. const before = this.previousStatsReport[idx];
  447. const ssrc = getStatValue(now, 'ssrc');
  448. if (!before || !ssrc) {
  449. continue;
  450. }
  451. // isRemote is available only in FF and is ignored in case of chrome
  452. // according to the spec
  453. // https://www.w3.org/TR/webrtc-stats/#dom-rtcrtpstreamstats-isremote
  454. // when isRemote is true indicates that the measurements were done at
  455. // the remote endpoint and reported in an RTCP RR/XR
  456. // Fixes a problem where we are calculating local stats wrong adding
  457. // the sent bytes to the local download bitrate
  458. if (now.isRemote === true) {
  459. continue;
  460. }
  461. const ssrcStats
  462. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
  463. let isDownloadStream = true;
  464. let key = 'packetsReceived';
  465. let packetsNow = getStatValue(now, key);
  466. if (typeof packetsNow === 'undefined'
  467. || packetsNow === null || packetsNow === '') {
  468. isDownloadStream = false;
  469. key = 'packetsSent';
  470. packetsNow = getStatValue(now, key);
  471. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  472. logger.warn('No packetsReceived nor packetsSent stat found');
  473. continue;
  474. }
  475. }
  476. if (!packetsNow || packetsNow < 0) {
  477. packetsNow = 0;
  478. }
  479. const packetsBefore = getNonNegativeStat(before, key);
  480. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  481. const packetsLostNow = getNonNegativeStat(now, 'packetsLost');
  482. const packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
  483. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  484. ssrcStats.setLoss({
  485. packetsTotal: packetsDiff + packetsLostDiff,
  486. packetsLost: packetsLostDiff,
  487. isDownloadStream
  488. });
  489. const bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
  490. const bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
  491. const bytesReceived
  492. = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  493. let bytesSent = 0;
  494. // TODO: clean this mess up!
  495. let nowBytesTransmitted = getStatValue(now, 'bytesSent');
  496. if (typeof nowBytesTransmitted === 'number'
  497. || typeof nowBytesTransmitted === 'string') {
  498. nowBytesTransmitted = Number(nowBytesTransmitted);
  499. if (!isNaN(nowBytesTransmitted)) {
  500. byteSentStats[ssrc] = nowBytesTransmitted;
  501. if (nowBytesTransmitted > 0) {
  502. bytesSent = nowBytesTransmitted
  503. - getStatValue(before, 'bytesSent');
  504. }
  505. }
  506. }
  507. bytesSent = Math.max(0, bytesSent);
  508. const timeMs = now.timestamp - before.timestamp;
  509. let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  510. if (timeMs > 0) {
  511. // TODO is there any reason to round here?
  512. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  513. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  514. }
  515. ssrcStats.addBitrate({
  516. 'download': bitrateReceivedKbps,
  517. 'upload': bitrateSentKbps
  518. });
  519. const resolution = { height: null,
  520. width: null };
  521. try {
  522. let height, width;
  523. if ((height = getStatValue(now, 'googFrameHeightReceived'))
  524. && (width = getStatValue(now, 'googFrameWidthReceived'))) {
  525. resolution.height = height;
  526. resolution.width = width;
  527. } else if ((height = getStatValue(now, 'googFrameHeightSent'))
  528. && (width = getStatValue(now, 'googFrameWidthSent'))) {
  529. resolution.height = height;
  530. resolution.width = width;
  531. }
  532. } catch (e) { /* not supported*/ }
  533. // Tries to get frame rate
  534. try {
  535. ssrcStats.setFramerate(
  536. getStatValue(now, 'googFrameRateReceived')
  537. || getStatValue(now, 'googFrameRateSent')
  538. || 0);
  539. } catch (e) {
  540. // if it fails with previous properties(chrome),
  541. // let's try with another one (FF)
  542. try {
  543. ssrcStats.setFramerate(Math.round(
  544. getNonNegativeStat(now, 'framerateMean')));
  545. } catch (err) { /* not supported*/ }
  546. }
  547. if (resolution.height && resolution.width) {
  548. ssrcStats.setResolution(resolution);
  549. } else {
  550. ssrcStats.setResolution(null);
  551. }
  552. }
  553. // process stats
  554. const totalPackets = {
  555. download: 0,
  556. upload: 0
  557. };
  558. const lostPackets = {
  559. download: 0,
  560. upload: 0
  561. };
  562. let bitrateDownload = 0;
  563. let bitrateUpload = 0;
  564. const resolutions = {};
  565. const framerates = {};
  566. Object.keys(this.ssrc2stats).forEach(
  567. function(ssrc) {
  568. const ssrcStats = this.ssrc2stats[ssrc];
  569. // process packet loss stats
  570. const loss = ssrcStats.loss;
  571. const type = loss.isDownloadStream ? 'download' : 'upload';
  572. totalPackets[type] += loss.packetsTotal;
  573. lostPackets[type] += loss.packetsLost;
  574. // process bitrate stats
  575. bitrateDownload += ssrcStats.bitrate.download;
  576. bitrateUpload += ssrcStats.bitrate.upload;
  577. ssrcStats.resetBitrate();
  578. // collect resolutions
  579. resolutions[ssrc] = ssrcStats.resolution;
  580. // collect framerates
  581. framerates[ssrc] = ssrcStats.framerate;
  582. },
  583. this
  584. );
  585. this.eventEmitter.emit(
  586. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  587. this.conferenceStats.bitrate
  588. = { 'upload': bitrateUpload,
  589. 'download': bitrateDownload };
  590. this.conferenceStats.packetLoss = {
  591. total:
  592. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  593. totalPackets.download + totalPackets.upload),
  594. download:
  595. calculatePacketLoss(lostPackets.download, totalPackets.download),
  596. upload:
  597. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  598. };
  599. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  600. 'bandwidth': this.conferenceStats.bandwidth,
  601. 'bitrate': this.conferenceStats.bitrate,
  602. 'packetLoss': this.conferenceStats.packetLoss,
  603. 'resolution': resolutions,
  604. 'framerate': framerates,
  605. 'transport': this.conferenceStats.transport
  606. });
  607. this.conferenceStats.transport = [];
  608. };
  609. /**
  610. * Stats processing logic.
  611. */
  612. StatsCollector.prototype.processAudioLevelReport = function() {
  613. if (!this.baselineAudioLevelsReport) {
  614. return;
  615. }
  616. const getStatValue = this._getStatValue;
  617. for (const idx in this.currentAudioLevelsReport) {
  618. if (!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
  619. continue;
  620. }
  621. const now = this.currentAudioLevelsReport[idx];
  622. if (now.type !== 'ssrc') {
  623. continue;
  624. }
  625. const before = this.baselineAudioLevelsReport[idx];
  626. const ssrc = getStatValue(now, 'ssrc');
  627. if (!before) {
  628. logger.warn(`${ssrc} not enough data`);
  629. continue;
  630. }
  631. if (!ssrc) {
  632. if ((Date.now() - now.timestamp) < 3000) {
  633. logger.warn('No ssrc: ');
  634. }
  635. continue;
  636. }
  637. // Audio level
  638. let audioLevel;
  639. try {
  640. audioLevel
  641. = getStatValue(now, 'audioInputLevel')
  642. || getStatValue(now, 'audioOutputLevel');
  643. } catch (e) { /* not supported*/
  644. logger.warn('Audio Levels are not available in the statistics.');
  645. clearInterval(this.audioLevelsIntervalId);
  646. return;
  647. }
  648. if (audioLevel) {
  649. const isLocal = !getStatValue(now, 'packetsReceived');
  650. // TODO: Can't find specs about what this value really is, but it
  651. // seems to vary between 0 and around 32k.
  652. audioLevel = audioLevel / 32767;
  653. this.eventEmitter.emit(
  654. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel, isLocal);
  655. }
  656. }
  657. };
  658. /* eslint-enable no-continue */