modified lib-jitsi-meet dev repo
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. 'currentRoundTripTime': 'googRtt'
  45. };
  46. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_OPERA]
  47. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  48. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_NWJS]
  49. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  50. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_ELECTRON]
  51. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  52. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_IEXPLORER]
  53. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  54. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_SAFARI]
  55. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  56. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_REACT_NATIVE]
  57. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  58. /**
  59. * Calculates packet lost percent using the number of lost packets and the
  60. * number of all packet.
  61. * @param lostPackets the number of lost packets
  62. * @param totalPackets the number of all packets.
  63. * @returns {number} packet loss percent
  64. */
  65. function calculatePacketLoss(lostPackets, totalPackets) {
  66. if (!totalPackets || totalPackets <= 0
  67. || !lostPackets || lostPackets <= 0) {
  68. return 0;
  69. }
  70. return Math.round((lostPackets / totalPackets) * 100);
  71. }
  72. /**
  73. * Holds "statistics" for a single SSRC.
  74. * @constructor
  75. */
  76. function SsrcStats() {
  77. this.loss = {};
  78. this.bitrate = {
  79. download: 0,
  80. upload: 0
  81. };
  82. this.resolution = {};
  83. this.framerate = 0;
  84. }
  85. /**
  86. * Sets the "loss" object.
  87. * @param loss the value to set.
  88. */
  89. SsrcStats.prototype.setLoss = function(loss) {
  90. this.loss = loss || {};
  91. };
  92. /**
  93. * Sets resolution that belong to the ssrc represented by this instance.
  94. * @param resolution new resolution value to be set.
  95. */
  96. SsrcStats.prototype.setResolution = function(resolution) {
  97. this.resolution = resolution || {};
  98. };
  99. /**
  100. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  101. * the respective fields of the "bitrate" field of this object.
  102. * @param bitrate an object holding the values to add.
  103. */
  104. SsrcStats.prototype.addBitrate = function(bitrate) {
  105. this.bitrate.download += bitrate.download;
  106. this.bitrate.upload += bitrate.upload;
  107. };
  108. /**
  109. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  110. * represented by this instance.
  111. */
  112. SsrcStats.prototype.resetBitrate = function() {
  113. this.bitrate.download = 0;
  114. this.bitrate.upload = 0;
  115. };
  116. /**
  117. * Sets the "framerate".
  118. * @param framerate the value to set.
  119. */
  120. SsrcStats.prototype.setFramerate = function(framerate) {
  121. this.framerate = framerate || 0;
  122. };
  123. /**
  124. *
  125. */
  126. function ConferenceStats() {
  127. /**
  128. * The bandwidth
  129. * @type {{}}
  130. */
  131. this.bandwidth = {};
  132. /**
  133. * The bit rate
  134. * @type {{}}
  135. */
  136. this.bitrate = {};
  137. /**
  138. * The packet loss rate
  139. * @type {{}}
  140. */
  141. this.packetLoss = null;
  142. /**
  143. * Array with the transport information.
  144. * @type {Array}
  145. */
  146. this.transport = [];
  147. }
  148. /* eslint-disable max-params */
  149. /**
  150. * <tt>StatsCollector</tt> registers for stats updates of given
  151. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  152. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  153. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  154. * instance as an event source.
  155. *
  156. * @param peerconnection WebRTC PeerConnection object.
  157. * @param audioLevelsInterval
  158. * @param statsInterval stats refresh interval given in ms.
  159. * @param eventEmitter
  160. * @constructor
  161. */
  162. export default function StatsCollector(
  163. peerconnection,
  164. audioLevelsInterval,
  165. statsInterval,
  166. eventEmitter) {
  167. // StatsCollector depends entirely on the format of the reports returned by
  168. // RTCPeerConnection#getStats. Given that the value of
  169. // RTCBrowserType#getBrowserType() is very unlikely to change at runtime, it
  170. // makes sense to discover whether StatsCollector supports the executing
  171. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  172. // needlessly check a "static" condition multiple times very very often and
  173. // (2) the lack of support for the executing browser would be discovered and
  174. // reported multiple times very very often too late in the execution in some
  175. // totally unrelated callback.
  176. /**
  177. * The RTCBrowserType supported by this StatsCollector. In other words, the
  178. * RTCBrowserType of the browser which initialized this StatsCollector
  179. * instance.
  180. * @private
  181. */
  182. this._browserType = RTCBrowserType.getBrowserType();
  183. const keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  184. if (!keys) {
  185. // eslint-disable-next-line no-throw-literal
  186. throw `The browser type '${this._browserType}' isn't supported!`;
  187. }
  188. /**
  189. * The function which is to be used to retrieve the value associated in a
  190. * report returned by RTCPeerConnection#getStats with a LibJitsiMeet
  191. * browser-agnostic name/key.
  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 LibJitsiMeet 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 LibJitsiMeet 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 LibJitsiMeet browser-agnostic name.
  354. return function(item, name) {
  355. return itemStatByKey(item, keyFromName(name));
  356. };
  357. };
  358. /* eslint-disable no-continue */
  359. /**
  360. * Stats processing logic.
  361. */
  362. StatsCollector.prototype.processStatsReport = function() {
  363. if (!this.previousStatsReport) {
  364. return;
  365. }
  366. const getStatValue = this._getStatValue;
  367. /**
  368. *
  369. * @param report
  370. * @param name
  371. */
  372. function getNonNegativeStat(report, name) {
  373. let value = getStatValue(report, name);
  374. if (typeof value !== 'number') {
  375. value = Number(value);
  376. }
  377. if (isNaN(value)) {
  378. return 0;
  379. }
  380. return Math.max(0, value);
  381. }
  382. const byteSentStats = {};
  383. for (const idx in this.currentStatsReport) {
  384. if (!this.currentStatsReport.hasOwnProperty(idx)) {
  385. continue;
  386. }
  387. const now = this.currentStatsReport[idx];
  388. // The browser API may return "undefined" values in the array
  389. if (!now) {
  390. continue;
  391. }
  392. try {
  393. const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  394. const sendBandwidth = getStatValue(now, 'sendBandwidth');
  395. if (receiveBandwidth || sendBandwidth) {
  396. this.conferenceStats.bandwidth = {
  397. 'download': Math.round(receiveBandwidth / 1000),
  398. 'upload': Math.round(sendBandwidth / 1000)
  399. };
  400. }
  401. } catch (e) { /* not supported*/ }
  402. if (now.type === 'googCandidatePair') {
  403. let active, ip, localip, rtt, type;
  404. try {
  405. ip = getStatValue(now, 'remoteAddress');
  406. type = getStatValue(now, 'transportType');
  407. localip = getStatValue(now, 'localAddress');
  408. active = getStatValue(now, 'activeConnection');
  409. rtt = getNonNegativeStat(now, 'currentRoundTripTime');
  410. } catch (e) { /* not supported*/ }
  411. if (!ip || !type || !localip || active !== 'true') {
  412. continue;
  413. }
  414. // Save the address unless it has been saved already.
  415. const conferenceStatsTransport = this.conferenceStats.transport;
  416. if (!conferenceStatsTransport.some(
  417. t =>
  418. t.ip === ip
  419. && t.type === type
  420. && t.localip === localip)) {
  421. conferenceStatsTransport.push({
  422. ip,
  423. type,
  424. localip,
  425. p2p: this.peerconnection.isP2P,
  426. rtt
  427. });
  428. }
  429. continue;
  430. }
  431. if (now.type === 'candidatepair') {
  432. // we need succeeded pairs only
  433. if (now.state !== 'succeeded') {
  434. continue;
  435. }
  436. const local = this.currentStatsReport[now.localCandidateId];
  437. const remote = this.currentStatsReport[now.remoteCandidateId];
  438. this.conferenceStats.transport.push({
  439. ip: `${remote.ipAddress}:${remote.portNumber}`,
  440. type: local.transport,
  441. localip: `${local.ipAddress}:${local.portNumber}`,
  442. p2p: this.peerconnection.isP2P
  443. });
  444. }
  445. if (now.type !== 'ssrc' && now.type !== 'outboundrtp'
  446. && now.type !== 'inboundrtp') {
  447. continue;
  448. }
  449. const before = this.previousStatsReport[idx];
  450. const ssrc = getStatValue(now, 'ssrc');
  451. if (!before || !ssrc) {
  452. continue;
  453. }
  454. // isRemote is available only in FF and is ignored in case of chrome
  455. // according to the spec
  456. // https://www.w3.org/TR/webrtc-stats/#dom-rtcrtpstreamstats-isremote
  457. // when isRemote is true indicates that the measurements were done at
  458. // the remote endpoint and reported in an RTCP RR/XR
  459. // Fixes a problem where we are calculating local stats wrong adding
  460. // the sent bytes to the local download bitrate
  461. if (now.isRemote === true) {
  462. continue;
  463. }
  464. const ssrcStats
  465. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
  466. let isDownloadStream = true;
  467. let key = 'packetsReceived';
  468. let packetsNow = getStatValue(now, key);
  469. if (typeof packetsNow === 'undefined'
  470. || packetsNow === null || packetsNow === '') {
  471. isDownloadStream = false;
  472. key = 'packetsSent';
  473. packetsNow = getStatValue(now, key);
  474. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  475. logger.warn('No packetsReceived nor packetsSent stat found');
  476. continue;
  477. }
  478. }
  479. if (!packetsNow || packetsNow < 0) {
  480. packetsNow = 0;
  481. }
  482. const packetsBefore = getNonNegativeStat(before, key);
  483. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  484. const packetsLostNow = getNonNegativeStat(now, 'packetsLost');
  485. const packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
  486. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  487. ssrcStats.setLoss({
  488. packetsTotal: packetsDiff + packetsLostDiff,
  489. packetsLost: packetsLostDiff,
  490. isDownloadStream
  491. });
  492. const bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
  493. const bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
  494. const bytesReceived
  495. = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  496. let bytesSent = 0;
  497. // TODO: clean this mess up!
  498. let nowBytesTransmitted = getStatValue(now, 'bytesSent');
  499. if (typeof nowBytesTransmitted === 'number'
  500. || typeof nowBytesTransmitted === 'string') {
  501. nowBytesTransmitted = Number(nowBytesTransmitted);
  502. if (!isNaN(nowBytesTransmitted)) {
  503. byteSentStats[ssrc] = nowBytesTransmitted;
  504. if (nowBytesTransmitted > 0) {
  505. bytesSent = nowBytesTransmitted
  506. - getStatValue(before, 'bytesSent');
  507. }
  508. }
  509. }
  510. bytesSent = Math.max(0, bytesSent);
  511. const timeMs = now.timestamp - before.timestamp;
  512. let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  513. if (timeMs > 0) {
  514. // TODO is there any reason to round here?
  515. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  516. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  517. }
  518. ssrcStats.addBitrate({
  519. 'download': bitrateReceivedKbps,
  520. 'upload': bitrateSentKbps
  521. });
  522. const resolution = { height: null,
  523. width: null };
  524. try {
  525. let height, width;
  526. if ((height = getStatValue(now, 'googFrameHeightReceived'))
  527. && (width = getStatValue(now, 'googFrameWidthReceived'))) {
  528. resolution.height = height;
  529. resolution.width = width;
  530. } else if ((height = getStatValue(now, 'googFrameHeightSent'))
  531. && (width = getStatValue(now, 'googFrameWidthSent'))) {
  532. resolution.height = height;
  533. resolution.width = width;
  534. }
  535. } catch (e) { /* not supported*/ }
  536. // Tries to get frame rate
  537. try {
  538. ssrcStats.setFramerate(
  539. getStatValue(now, 'googFrameRateReceived')
  540. || getStatValue(now, 'googFrameRateSent')
  541. || 0);
  542. } catch (e) {
  543. // if it fails with previous properties(chrome),
  544. // let's try with another one (FF)
  545. try {
  546. ssrcStats.setFramerate(Math.round(
  547. getNonNegativeStat(now, 'framerateMean')));
  548. } catch (err) { /* not supported*/ }
  549. }
  550. if (resolution.height && resolution.width) {
  551. ssrcStats.setResolution(resolution);
  552. } else {
  553. ssrcStats.setResolution(null);
  554. }
  555. }
  556. // process stats
  557. const totalPackets = {
  558. download: 0,
  559. upload: 0
  560. };
  561. const lostPackets = {
  562. download: 0,
  563. upload: 0
  564. };
  565. let bitrateDownload = 0;
  566. let bitrateUpload = 0;
  567. const resolutions = {};
  568. const framerates = {};
  569. Object.keys(this.ssrc2stats).forEach(
  570. function(ssrc) {
  571. const ssrcStats = this.ssrc2stats[ssrc];
  572. // process packet loss stats
  573. const loss = ssrcStats.loss;
  574. const type = loss.isDownloadStream ? 'download' : 'upload';
  575. totalPackets[type] += loss.packetsTotal;
  576. lostPackets[type] += loss.packetsLost;
  577. // process bitrate stats
  578. bitrateDownload += ssrcStats.bitrate.download;
  579. bitrateUpload += ssrcStats.bitrate.upload;
  580. ssrcStats.resetBitrate();
  581. // collect resolutions
  582. resolutions[ssrc] = ssrcStats.resolution;
  583. // collect framerates
  584. framerates[ssrc] = ssrcStats.framerate;
  585. },
  586. this
  587. );
  588. this.eventEmitter.emit(
  589. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  590. this.conferenceStats.bitrate
  591. = { 'upload': bitrateUpload,
  592. 'download': bitrateDownload };
  593. this.conferenceStats.packetLoss = {
  594. total:
  595. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  596. totalPackets.download + totalPackets.upload),
  597. download:
  598. calculatePacketLoss(lostPackets.download, totalPackets.download),
  599. upload:
  600. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  601. };
  602. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  603. 'bandwidth': this.conferenceStats.bandwidth,
  604. 'bitrate': this.conferenceStats.bitrate,
  605. 'packetLoss': this.conferenceStats.packetLoss,
  606. 'resolution': resolutions,
  607. 'framerate': framerates,
  608. 'transport': this.conferenceStats.transport
  609. });
  610. this.conferenceStats.transport = [];
  611. };
  612. /**
  613. * Stats processing logic.
  614. */
  615. StatsCollector.prototype.processAudioLevelReport = function() {
  616. if (!this.baselineAudioLevelsReport) {
  617. return;
  618. }
  619. const getStatValue = this._getStatValue;
  620. for (const idx in this.currentAudioLevelsReport) {
  621. if (!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
  622. continue;
  623. }
  624. const now = this.currentAudioLevelsReport[idx];
  625. if (now.type !== 'ssrc') {
  626. continue;
  627. }
  628. const before = this.baselineAudioLevelsReport[idx];
  629. const ssrc = getStatValue(now, 'ssrc');
  630. if (!before) {
  631. logger.warn(`${ssrc} not enough data`);
  632. continue;
  633. }
  634. if (!ssrc) {
  635. if ((Date.now() - now.timestamp) < 3000) {
  636. logger.warn('No ssrc: ');
  637. }
  638. continue;
  639. }
  640. // Audio level
  641. let audioLevel;
  642. try {
  643. audioLevel
  644. = getStatValue(now, 'audioInputLevel')
  645. || getStatValue(now, 'audioOutputLevel');
  646. } catch (e) { /* not supported*/
  647. logger.warn('Audio Levels are not available in the statistics.');
  648. clearInterval(this.audioLevelsIntervalId);
  649. return;
  650. }
  651. if (audioLevel) {
  652. const isLocal = !getStatValue(now, 'packetsReceived');
  653. // TODO: Can't find specs about what this value really is, but it
  654. // seems to vary between 0 and around 32k.
  655. audioLevel = audioLevel / 32767;
  656. this.eventEmitter.emit(
  657. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel, isLocal);
  658. }
  659. }
  660. };
  661. /* eslint-enable no-continue */