Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTPStatsCollector.js 31KB

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