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

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