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

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