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

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