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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. import browser from '../browser';
  2. import { browsers } from 'js-utils';
  3. import * as StatisticsEvents from '../../service/statistics/Events';
  4. import * as MediaType from '../../service/RTC/MediaType';
  5. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  6. const logger = require('jitsi-meet-logger').getLogger(__filename);
  7. /**
  8. * The lib-jitsi-meet browser-agnostic names of the browser-specific keys
  9. * reported by RTCPeerConnection#getStats mapped by browser.
  10. */
  11. const KEYS_BY_BROWSER_TYPE = {};
  12. KEYS_BY_BROWSER_TYPE[browsers.FIREFOX] = {
  13. 'ssrc': 'ssrc',
  14. 'packetsReceived': 'packetsReceived',
  15. 'packetsLost': 'packetsLost',
  16. 'packetsSent': 'packetsSent',
  17. 'bytesReceived': 'bytesReceived',
  18. 'bytesSent': 'bytesSent',
  19. 'framerateMean': 'framerateMean',
  20. 'ip': 'ipAddress',
  21. 'port': 'portNumber',
  22. 'protocol': 'transport'
  23. };
  24. KEYS_BY_BROWSER_TYPE[browsers.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. 'remoteCandidateType': 'googRemoteCandidateType',
  47. 'localCandidateType': 'googLocalCandidateType',
  48. 'ip': 'ip',
  49. 'port': 'port',
  50. 'protocol': 'protocol'
  51. };
  52. KEYS_BY_BROWSER_TYPE[browsers.OPERA]
  53. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  54. KEYS_BY_BROWSER_TYPE[browsers.NWJS]
  55. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  56. KEYS_BY_BROWSER_TYPE[browsers.ELECTRON]
  57. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  58. KEYS_BY_BROWSER_TYPE[browsers.SAFARI]
  59. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  60. KEYS_BY_BROWSER_TYPE[browsers.REACT_NATIVE]
  61. = KEYS_BY_BROWSER_TYPE[browsers.CHROME];
  62. /**
  63. * Calculates packet lost percent using the number of lost packets and the
  64. * number of all packet.
  65. * @param lostPackets the number of lost packets
  66. * @param totalPackets the number of all packets.
  67. * @returns {number} packet loss percent
  68. */
  69. function calculatePacketLoss(lostPackets, totalPackets) {
  70. if (!totalPackets || totalPackets <= 0
  71. || !lostPackets || lostPackets <= 0) {
  72. return 0;
  73. }
  74. return Math.round((lostPackets / totalPackets) * 100);
  75. }
  76. /**
  77. * Holds "statistics" for a single SSRC.
  78. * @constructor
  79. */
  80. function SsrcStats() {
  81. this.loss = {};
  82. this.bitrate = {
  83. download: 0,
  84. upload: 0
  85. };
  86. this.resolution = {};
  87. this.framerate = 0;
  88. }
  89. /**
  90. * Sets the "loss" object.
  91. * @param loss the value to set.
  92. */
  93. SsrcStats.prototype.setLoss = function(loss) {
  94. this.loss = loss || {};
  95. };
  96. /**
  97. * Sets resolution that belong to the ssrc represented by this instance.
  98. * @param resolution new resolution value to be set.
  99. */
  100. SsrcStats.prototype.setResolution = function(resolution) {
  101. this.resolution = resolution || {};
  102. };
  103. /**
  104. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  105. * the respective fields of the "bitrate" field of this object.
  106. * @param bitrate an object holding the values to add.
  107. */
  108. SsrcStats.prototype.addBitrate = function(bitrate) {
  109. this.bitrate.download += bitrate.download;
  110. this.bitrate.upload += bitrate.upload;
  111. };
  112. /**
  113. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  114. * represented by this instance.
  115. */
  116. SsrcStats.prototype.resetBitrate = function() {
  117. this.bitrate.download = 0;
  118. this.bitrate.upload = 0;
  119. };
  120. /**
  121. * Sets the "framerate".
  122. * @param framerate the value to set.
  123. */
  124. SsrcStats.prototype.setFramerate = function(framerate) {
  125. this.framerate = framerate || 0;
  126. };
  127. /**
  128. *
  129. */
  130. function ConferenceStats() {
  131. /**
  132. * The bandwidth
  133. * @type {{}}
  134. */
  135. this.bandwidth = {};
  136. /**
  137. * The bit rate
  138. * @type {{}}
  139. */
  140. this.bitrate = {};
  141. /**
  142. * The packet loss rate
  143. * @type {{}}
  144. */
  145. this.packetLoss = null;
  146. /**
  147. * Array with the transport information.
  148. * @type {Array}
  149. */
  150. this.transport = [];
  151. }
  152. /* eslint-disable max-params */
  153. /**
  154. * <tt>StatsCollector</tt> registers for stats updates of given
  155. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  156. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  157. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  158. * instance as an event source.
  159. *
  160. * @param peerconnection WebRTC PeerConnection object.
  161. * @param audioLevelsInterval
  162. * @param statsInterval stats refresh interval given in ms.
  163. * @param eventEmitter
  164. * @constructor
  165. */
  166. export default function StatsCollector(
  167. peerconnection,
  168. audioLevelsInterval,
  169. statsInterval,
  170. eventEmitter) {
  171. // StatsCollector depends entirely on the format of the reports returned by
  172. // RTCPeerConnection#getStats. Given that the value of
  173. // browser#getName() is very unlikely to change at runtime, it
  174. // makes sense to discover whether StatsCollector supports the executing
  175. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  176. // needlessly check a "static" condition multiple times very very often and
  177. // (2) the lack of support for the executing browser would be discovered and
  178. // reported multiple times very very often too late in the execution in some
  179. // totally unrelated callback.
  180. /**
  181. * The browser type supported by this StatsCollector. In other words, the
  182. * type of the browser which initialized this StatsCollector
  183. * instance.
  184. * @private
  185. */
  186. this._browserType = browser.getName();
  187. const keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  188. if (!keys) {
  189. // eslint-disable-next-line no-throw-literal
  190. throw `The browser type '${this._browserType}' isn't supported!`;
  191. }
  192. /**
  193. * Whether to use the Promise-based getStats API or not.
  194. * @type {boolean}
  195. */
  196. this._usesPromiseGetStats
  197. = browser.isSafari() || browser.isFirefox();
  198. /**
  199. * The function which is to be used to retrieve the value associated in a
  200. * report returned by RTCPeerConnection#getStats with a lib-jitsi-meet
  201. * browser-agnostic name/key.
  202. *
  203. * @function
  204. * @private
  205. */
  206. this._getStatValue
  207. = this._usesPromiseGetStats
  208. ? this._defineNewGetStatValueMethod(keys)
  209. : this._defineGetStatValueMethod(keys);
  210. this.peerconnection = peerconnection;
  211. this.baselineAudioLevelsReport = null;
  212. this.currentAudioLevelsReport = null;
  213. this.currentStatsReport = null;
  214. this.previousStatsReport = null;
  215. this.audioLevelReportHistory = {};
  216. this.audioLevelsIntervalId = null;
  217. this.eventEmitter = eventEmitter;
  218. this.conferenceStats = new ConferenceStats();
  219. // Updates stats interval
  220. this.audioLevelsIntervalMilis = audioLevelsInterval;
  221. this.statsIntervalId = null;
  222. this.statsIntervalMilis = statsInterval;
  223. /**
  224. * Maps SSRC numbers to {@link SsrcStats}.
  225. * @type {Map<number,SsrcStats}
  226. */
  227. this.ssrc2stats = new Map();
  228. }
  229. /* eslint-enable max-params */
  230. /**
  231. * Stops stats updates.
  232. */
  233. StatsCollector.prototype.stop = function() {
  234. if (this.audioLevelsIntervalId) {
  235. clearInterval(this.audioLevelsIntervalId);
  236. this.audioLevelsIntervalId = null;
  237. }
  238. if (this.statsIntervalId) {
  239. clearInterval(this.statsIntervalId);
  240. this.statsIntervalId = null;
  241. }
  242. };
  243. /**
  244. * Callback passed to <tt>getStats</tt> method.
  245. * @param error an error that occurred on <tt>getStats</tt> call.
  246. */
  247. StatsCollector.prototype.errorCallback = function(error) {
  248. GlobalOnErrorHandler.callErrorHandler(error);
  249. logger.error('Get stats error', error);
  250. this.stop();
  251. };
  252. /**
  253. * Starts stats updates.
  254. */
  255. StatsCollector.prototype.start = function(startAudioLevelStats) {
  256. const self = this;
  257. if (startAudioLevelStats) {
  258. this.audioLevelsIntervalId = setInterval(
  259. () => {
  260. // Interval updates
  261. self.peerconnection.getStats(
  262. report => {
  263. let results = null;
  264. if (!report || !report.result
  265. || typeof report.result !== 'function') {
  266. results = report;
  267. } else {
  268. results = report.result();
  269. }
  270. self.currentAudioLevelsReport = results;
  271. if (this._usesPromiseGetStats) {
  272. self.processNewAudioLevelReport();
  273. } else {
  274. self.processAudioLevelReport();
  275. }
  276. self.baselineAudioLevelsReport
  277. = self.currentAudioLevelsReport;
  278. },
  279. error => self.errorCallback(error)
  280. );
  281. },
  282. self.audioLevelsIntervalMilis
  283. );
  284. }
  285. this.statsIntervalId = setInterval(
  286. () => {
  287. // Interval updates
  288. self.peerconnection.getStats(
  289. report => {
  290. let results = null;
  291. if (!report || !report.result
  292. || typeof report.result !== 'function') {
  293. // firefox
  294. results = report;
  295. } else {
  296. // chrome
  297. results = report.result();
  298. }
  299. self.currentStatsReport = results;
  300. try {
  301. if (this._usesPromiseGetStats) {
  302. self.processNewStatsReport();
  303. } else {
  304. self.processStatsReport();
  305. }
  306. } catch (e) {
  307. GlobalOnErrorHandler.callErrorHandler(e);
  308. logger.error(`Unsupported key:${e}`, e);
  309. }
  310. self.previousStatsReport = self.currentStatsReport;
  311. },
  312. error => self.errorCallback(error)
  313. );
  314. },
  315. self.statsIntervalMilis
  316. );
  317. };
  318. /**
  319. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  320. * gets the value from a specific report returned by RTCPeerConnection#getStats
  321. * associated with a lib-jitsi-meet browser-agnostic name.
  322. *
  323. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  324. * names to RTCPeerConnection#getStats browser-specific keys
  325. */
  326. StatsCollector.prototype._defineGetStatValueMethod = function(keys) {
  327. // Define the function which converts a lib-jitsi-meet browser-asnostic name
  328. // to a browser-specific key of a report returned by
  329. // RTCPeerConnection#getStats.
  330. const keyFromName = function(name) {
  331. const key = keys[name];
  332. if (key) {
  333. return key;
  334. }
  335. // eslint-disable-next-line no-throw-literal
  336. throw `The property '${name}' isn't supported!`;
  337. };
  338. // Define the function which retrieves the value from a specific report
  339. // returned by RTCPeerConnection#getStats associated with a given
  340. // browser-specific key.
  341. let itemStatByKey;
  342. switch (this._browserType) {
  343. case browsers.CHROME:
  344. case browsers.OPERA:
  345. case browsers.NWJS:
  346. case browsers.ELECTRON:
  347. // TODO What about other types of browser which are based on Chrome such
  348. // as NW.js? Every time we want to support a new type browser we have to
  349. // go and add more conditions (here and in multiple other places).
  350. // Cannot we do a feature detection instead of a browser type check? For
  351. // example, if item has a stat property of type function, then it's very
  352. // likely that whoever defined it wanted you to call it in order to
  353. // retrieve the value associated with a specific key.
  354. itemStatByKey = (item, key) => item.stat(key);
  355. break;
  356. case browsers.REACT_NATIVE:
  357. // The implementation provided by react-native-webrtc follows the
  358. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  359. // Array in which each element is a key-value pair.
  360. itemStatByKey = function(item, key) {
  361. let value;
  362. item.values.some(pair => {
  363. if (pair.hasOwnProperty(key)) {
  364. value = pair[key];
  365. return true;
  366. }
  367. return false;
  368. });
  369. return value;
  370. };
  371. break;
  372. default:
  373. itemStatByKey = (item, key) => item[key];
  374. }
  375. // Compose the 2 functions defined above to get a function which retrieves
  376. // the value from a specific report returned by RTCPeerConnection#getStats
  377. // associated with a specific lib-jitsi-meet browser-agnostic name.
  378. return (item, name) => itemStatByKey(item, keyFromName(name));
  379. };
  380. /**
  381. * Obtains a stat value from given stat and converts it to a non-negative
  382. * number. If the value is either invalid or negative then 0 will be returned.
  383. * @param report
  384. * @param {string} name
  385. * @return {number}
  386. * @private
  387. */
  388. StatsCollector.prototype.getNonNegativeStat = function(report, name) {
  389. let value = this._getStatValue(report, name);
  390. if (typeof value !== 'number') {
  391. value = Number(value);
  392. }
  393. if (isNaN(value)) {
  394. return 0;
  395. }
  396. return Math.max(0, value);
  397. };
  398. /* eslint-disable no-continue */
  399. /**
  400. * Stats processing logic.
  401. */
  402. StatsCollector.prototype.processStatsReport = function() {
  403. if (!this.previousStatsReport) {
  404. return;
  405. }
  406. const getStatValue = this._getStatValue;
  407. const byteSentStats = {};
  408. for (const idx in this.currentStatsReport) {
  409. if (!this.currentStatsReport.hasOwnProperty(idx)) {
  410. continue;
  411. }
  412. const now = this.currentStatsReport[idx];
  413. // The browser API may return "undefined" values in the array
  414. if (!now) {
  415. continue;
  416. }
  417. try {
  418. const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  419. const sendBandwidth = getStatValue(now, 'sendBandwidth');
  420. if (receiveBandwidth || sendBandwidth) {
  421. this.conferenceStats.bandwidth = {
  422. 'download': Math.round(receiveBandwidth / 1000),
  423. 'upload': Math.round(sendBandwidth / 1000)
  424. };
  425. }
  426. } catch (e) { /* not supported*/ }
  427. if (now.type === 'googCandidatePair') {
  428. let active, ip, localCandidateType, localip,
  429. remoteCandidateType, rtt, type;
  430. try {
  431. active = getStatValue(now, 'activeConnection');
  432. if (!active) {
  433. continue;
  434. }
  435. ip = getStatValue(now, 'remoteAddress');
  436. type = getStatValue(now, 'transportType');
  437. localip = getStatValue(now, 'localAddress');
  438. localCandidateType = getStatValue(now, 'localCandidateType');
  439. remoteCandidateType = getStatValue(now, 'remoteCandidateType');
  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. localCandidateType,
  458. remoteCandidateType,
  459. rtt
  460. });
  461. }
  462. continue;
  463. }
  464. if (now.type === 'candidatepair') {
  465. // we need succeeded and selected pairs only
  466. if (now.state !== 'succeeded' || !now.selected) {
  467. continue;
  468. }
  469. const local = this.currentStatsReport[now.localCandidateId];
  470. const remote = this.currentStatsReport[now.remoteCandidateId];
  471. this.conferenceStats.transport.push({
  472. ip: `${remote.ipAddress}:${remote.portNumber}`,
  473. type: local.transport,
  474. localip: `${local.ipAddress}:${local.portNumber}`,
  475. p2p: this.peerconnection.isP2P,
  476. localCandidateType: local.candidateType,
  477. remoteCandidateType: remote.candidateType
  478. });
  479. }
  480. if (now.type !== 'ssrc' && now.type !== 'outboundrtp'
  481. && now.type !== 'inboundrtp' && now.type !== 'track') {
  482. continue;
  483. }
  484. const before = this.previousStatsReport[idx];
  485. let ssrc = this.getNonNegativeStat(now, 'ssrc');
  486. // If type="track", take the first SSRC from ssrcIds.
  487. if (now.type === 'track' && Array.isArray(now.ssrcIds)) {
  488. ssrc = Number(now.ssrcIds[0]);
  489. }
  490. if (!before || !ssrc) {
  491. continue;
  492. }
  493. // isRemote is available only in FF and is ignored in case of chrome
  494. // according to the spec
  495. // https://www.w3.org/TR/webrtc-stats/#dom-rtcrtpstreamstats-isremote
  496. // when isRemote is true indicates that the measurements were done at
  497. // the remote endpoint and reported in an RTCP RR/XR.
  498. // Fixes a problem where we are calculating local stats wrong adding
  499. // the sent bytes to the local download bitrate.
  500. // In new W3 stats spec, type="track" has a remoteSource boolean
  501. // property.
  502. if (now.isRemote === true || now.remoteSource === true) {
  503. continue;
  504. }
  505. let ssrcStats = this.ssrc2stats.get(ssrc);
  506. if (!ssrcStats) {
  507. ssrcStats = new SsrcStats();
  508. this.ssrc2stats.set(ssrc, ssrcStats);
  509. }
  510. let isDownloadStream = true;
  511. let key = 'packetsReceived';
  512. let packetsNow = getStatValue(now, key);
  513. if (typeof packetsNow === 'undefined'
  514. || packetsNow === null || packetsNow === '') {
  515. isDownloadStream = false;
  516. key = 'packetsSent';
  517. packetsNow = getStatValue(now, key);
  518. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  519. logger.warn('No packetsReceived nor packetsSent stat found');
  520. }
  521. }
  522. if (!packetsNow || packetsNow < 0) {
  523. packetsNow = 0;
  524. }
  525. const packetsBefore = this.getNonNegativeStat(before, key);
  526. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  527. const packetsLostNow
  528. = this.getNonNegativeStat(now, 'packetsLost');
  529. const packetsLostBefore
  530. = this.getNonNegativeStat(before, 'packetsLost');
  531. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  532. ssrcStats.setLoss({
  533. packetsTotal: packetsDiff + packetsLostDiff,
  534. packetsLost: packetsLostDiff,
  535. isDownloadStream
  536. });
  537. const bytesReceivedNow
  538. = this.getNonNegativeStat(now, 'bytesReceived');
  539. const bytesReceivedBefore
  540. = this.getNonNegativeStat(before, 'bytesReceived');
  541. const bytesReceived
  542. = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  543. let bytesSent = 0;
  544. // TODO: clean this mess up!
  545. let nowBytesTransmitted = getStatValue(now, 'bytesSent');
  546. if (typeof nowBytesTransmitted === 'number'
  547. || typeof nowBytesTransmitted === 'string') {
  548. nowBytesTransmitted = Number(nowBytesTransmitted);
  549. if (!isNaN(nowBytesTransmitted)) {
  550. byteSentStats[ssrc] = nowBytesTransmitted;
  551. if (nowBytesTransmitted > 0) {
  552. bytesSent = nowBytesTransmitted
  553. - getStatValue(before, 'bytesSent');
  554. }
  555. }
  556. }
  557. bytesSent = Math.max(0, bytesSent);
  558. const timeMs = now.timestamp - before.timestamp;
  559. let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  560. if (timeMs > 0) {
  561. // TODO is there any reason to round here?
  562. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  563. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  564. }
  565. ssrcStats.addBitrate({
  566. 'download': bitrateReceivedKbps,
  567. 'upload': bitrateSentKbps
  568. });
  569. const resolution = {
  570. height: null,
  571. width: null
  572. };
  573. try {
  574. let height, width;
  575. if ((height = getStatValue(now, 'googFrameHeightReceived'))
  576. && (width = getStatValue(now, 'googFrameWidthReceived'))) {
  577. resolution.height = height;
  578. resolution.width = width;
  579. } else if ((height = getStatValue(now, 'googFrameHeightSent'))
  580. && (width = getStatValue(now, 'googFrameWidthSent'))) {
  581. resolution.height = height;
  582. resolution.width = width;
  583. }
  584. } catch (e) { /* not supported*/ }
  585. // Tries to get frame rate
  586. let frameRate;
  587. try {
  588. frameRate = getStatValue(now, 'googFrameRateReceived')
  589. || getStatValue(now, 'googFrameRateSent') || 0;
  590. } catch (e) {
  591. // if it fails with previous properties(chrome),
  592. // let's try with another one (FF)
  593. try {
  594. frameRate = this.getNonNegativeStat(now, 'framerateMean');
  595. } catch (err) { /* not supported*/ }
  596. }
  597. ssrcStats.setFramerate(Math.round(frameRate || 0));
  598. if (resolution.height && resolution.width) {
  599. ssrcStats.setResolution(resolution);
  600. } else {
  601. ssrcStats.setResolution(null);
  602. }
  603. }
  604. this.eventEmitter.emit(
  605. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  606. this._processAndEmitReport();
  607. };
  608. /**
  609. *
  610. */
  611. StatsCollector.prototype._processAndEmitReport = function() {
  612. // process stats
  613. const totalPackets = {
  614. download: 0,
  615. upload: 0
  616. };
  617. const lostPackets = {
  618. download: 0,
  619. upload: 0
  620. };
  621. let bitrateDownload = 0;
  622. let bitrateUpload = 0;
  623. const resolutions = {};
  624. const framerates = {};
  625. let audioBitrateDownload = 0;
  626. let audioBitrateUpload = 0;
  627. let videoBitrateDownload = 0;
  628. let videoBitrateUpload = 0;
  629. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  630. // process packet loss stats
  631. const loss = ssrcStats.loss;
  632. const type = loss.isDownloadStream ? 'download' : 'upload';
  633. totalPackets[type] += loss.packetsTotal;
  634. lostPackets[type] += loss.packetsLost;
  635. // process bitrate stats
  636. bitrateDownload += ssrcStats.bitrate.download;
  637. bitrateUpload += ssrcStats.bitrate.upload;
  638. // collect resolutions and framerates
  639. const track = this.peerconnection.getTrackBySSRC(ssrc);
  640. if (track) {
  641. if (track.isAudioTrack()) {
  642. audioBitrateDownload += ssrcStats.bitrate.download;
  643. audioBitrateUpload += ssrcStats.bitrate.upload;
  644. } else {
  645. videoBitrateDownload += ssrcStats.bitrate.download;
  646. videoBitrateUpload += ssrcStats.bitrate.upload;
  647. }
  648. const participantId = track.getParticipantId();
  649. if (participantId) {
  650. const resolution = ssrcStats.resolution;
  651. if (resolution.width
  652. && resolution.height
  653. && resolution.width !== -1
  654. && resolution.height !== -1) {
  655. const userResolutions = resolutions[participantId] || {};
  656. userResolutions[ssrc] = resolution;
  657. resolutions[participantId] = userResolutions;
  658. }
  659. if (ssrcStats.framerate !== 0) {
  660. const userFramerates = framerates[participantId] || {};
  661. userFramerates[ssrc] = ssrcStats.framerate;
  662. framerates[participantId] = userFramerates;
  663. }
  664. } else {
  665. logger.error(`No participant ID returned by ${track}`);
  666. }
  667. }
  668. ssrcStats.resetBitrate();
  669. }
  670. this.conferenceStats.bitrate = {
  671. 'upload': bitrateUpload,
  672. 'download': bitrateDownload
  673. };
  674. this.conferenceStats.bitrate.audio = {
  675. 'upload': audioBitrateUpload,
  676. 'download': audioBitrateDownload
  677. };
  678. this.conferenceStats.bitrate.video = {
  679. 'upload': videoBitrateUpload,
  680. 'download': videoBitrateDownload
  681. };
  682. this.conferenceStats.packetLoss = {
  683. total:
  684. calculatePacketLoss(
  685. lostPackets.download + lostPackets.upload,
  686. totalPackets.download + totalPackets.upload),
  687. download:
  688. calculatePacketLoss(lostPackets.download, totalPackets.download),
  689. upload:
  690. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  691. };
  692. const avgAudioLevels = {};
  693. let localAvgAudioLevels;
  694. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  695. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  696. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  697. if (isLocal) {
  698. localAvgAudioLevels = avgAudioLevel;
  699. } else {
  700. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  701. if (track) {
  702. const participantId = track.getParticipantId();
  703. if (participantId) {
  704. avgAudioLevels[participantId] = avgAudioLevel;
  705. }
  706. }
  707. }
  708. });
  709. this.audioLevelReportHistory = {};
  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. localAvgAudioLevels,
  721. avgAudioLevels
  722. });
  723. this.conferenceStats.transport = [];
  724. };
  725. /**
  726. * Stats processing logic.
  727. */
  728. StatsCollector.prototype.processAudioLevelReport = function() {
  729. if (!this.baselineAudioLevelsReport) {
  730. return;
  731. }
  732. const getStatValue = this._getStatValue;
  733. for (const idx in this.currentAudioLevelsReport) {
  734. if (!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
  735. continue;
  736. }
  737. const now = this.currentAudioLevelsReport[idx];
  738. if (now.type !== 'ssrc' && now.type !== 'track') {
  739. continue;
  740. }
  741. const before = this.baselineAudioLevelsReport[idx];
  742. let ssrc = this.getNonNegativeStat(now, 'ssrc');
  743. if (!ssrc && Array.isArray(now.ssrcIds)) {
  744. ssrc = Number(now.ssrcIds[0]);
  745. }
  746. if (!before) {
  747. logger.warn(`${ssrc} not enough data`);
  748. continue;
  749. }
  750. if (!ssrc) {
  751. if ((Date.now() - now.timestamp) < 3000) {
  752. logger.warn('No ssrc: ');
  753. }
  754. continue;
  755. }
  756. // Audio level
  757. let audioLevel;
  758. try {
  759. audioLevel
  760. = getStatValue(now, 'audioInputLevel')
  761. || getStatValue(now, 'audioOutputLevel');
  762. } catch (e) { /* not supported*/
  763. logger.warn('Audio Levels are not available in the statistics.');
  764. clearInterval(this.audioLevelsIntervalId);
  765. return;
  766. }
  767. if (audioLevel) {
  768. let isLocal;
  769. // If type="ssrc" (legacy) check whether they are received packets.
  770. if (now.type === 'ssrc') {
  771. isLocal = !getStatValue(now, 'packetsReceived');
  772. // If type="track", check remoteSource boolean property.
  773. } else {
  774. isLocal = !now.remoteSource;
  775. }
  776. // According to the W3C WebRTC Stats spec, audioLevel should be in
  777. // 0..1 range (0 == silence). However browsers don't behave that
  778. // way so we must convert it to 0..1.
  779. // TODO: Can't find specs about what this value really is, but it
  780. // seems to vary between 0 and around 32k.
  781. audioLevel = audioLevel / 32767;
  782. if (!(ssrc in this.audioLevelReportHistory)) {
  783. this.audioLevelReportHistory[ssrc] = {
  784. isLocal,
  785. data: []
  786. };
  787. }
  788. this.audioLevelReportHistory[ssrc].data.push(audioLevel);
  789. this.eventEmitter.emit(
  790. StatisticsEvents.AUDIO_LEVEL,
  791. this.peerconnection,
  792. ssrc,
  793. audioLevel,
  794. isLocal);
  795. }
  796. }
  797. };
  798. /* eslint-enable no-continue */
  799. /**
  800. * New promised based getStats report processing.
  801. * Tested with chrome, firefox and safari. Not switching it on for chrome as
  802. * frameRate stat is missing and calculating it using framesSent,
  803. * gives values double the values seen in webrtc-internals.
  804. * https://w3c.github.io/webrtc-stats/
  805. */
  806. /**
  807. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  808. * gets the value from a specific report returned by RTCPeerConnection#getStats
  809. * associated with a lib-jitsi-meet browser-agnostic name in case of using
  810. * Promised based getStats.
  811. *
  812. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  813. * names to RTCPeerConnection#getStats browser-specific keys
  814. */
  815. StatsCollector.prototype._defineNewGetStatValueMethod = function(keys) {
  816. // Define the function which converts a lib-jitsi-meet browser-asnostic name
  817. // to a browser-specific key of a report returned by
  818. // RTCPeerConnection#getStats.
  819. const keyFromName = function(name) {
  820. const key = keys[name];
  821. if (key) {
  822. return key;
  823. }
  824. // eslint-disable-next-line no-throw-literal
  825. throw `The property '${name}' isn't supported!`;
  826. };
  827. // Compose the 2 functions defined above to get a function which retrieves
  828. // the value from a specific report returned by RTCPeerConnection#getStats
  829. // associated with a specific lib-jitsi-meet browser-agnostic name.
  830. return (item, name) => item[keyFromName(name)];
  831. };
  832. /**
  833. * Converts the value to a non-negative number.
  834. * If the value is either invalid or negative then 0 will be returned.
  835. * @param {*} v
  836. * @return {number}
  837. * @private
  838. */
  839. StatsCollector.prototype.getNonNegativeValue = function(v) {
  840. let value = v;
  841. if (typeof value !== 'number') {
  842. value = Number(value);
  843. }
  844. if (isNaN(value)) {
  845. return 0;
  846. }
  847. return Math.max(0, value);
  848. };
  849. /**
  850. * Calculates bitrate between before and now using a supplied field name and its
  851. * value in the stats.
  852. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  853. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  854. * previous stats.
  855. * @param fieldName the field to use for calculations.
  856. * @return {number} the calculated bitrate between now and before.
  857. * @private
  858. */
  859. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  860. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  861. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  862. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  863. const timeMs = now.timestamp - before.timestamp;
  864. let bitrateKbps = 0;
  865. if (timeMs > 0) {
  866. // TODO is there any reason to round here?
  867. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  868. }
  869. return bitrateKbps;
  870. };
  871. /**
  872. * Stats processing new getStats logic.
  873. */
  874. StatsCollector.prototype.processNewStatsReport = function() {
  875. if (!this.previousStatsReport) {
  876. return;
  877. }
  878. const getStatValue = this._getStatValue;
  879. const byteSentStats = {};
  880. this.currentStatsReport.forEach(now => {
  881. // RTCIceCandidatePairStats
  882. // https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  883. if (now.type === 'candidate-pair'
  884. && now.nominated
  885. && now.state === 'succeeded') {
  886. const availableIncomingBitrate = now.availableIncomingBitrate;
  887. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  888. if (availableIncomingBitrate || availableOutgoingBitrate) {
  889. this.conferenceStats.bandwidth = {
  890. 'download': Math.round(availableIncomingBitrate / 1000),
  891. 'upload': Math.round(availableOutgoingBitrate / 1000)
  892. };
  893. }
  894. const remoteUsedCandidate
  895. = this.currentStatsReport.get(now.remoteCandidateId);
  896. const localUsedCandidate
  897. = this.currentStatsReport.get(now.localCandidateId);
  898. // RTCIceCandidateStats
  899. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  900. // safari currently does not provide ice candidates in stats
  901. if (remoteUsedCandidate && localUsedCandidate) {
  902. // FF uses non-standard ipAddress, portNumber, transport
  903. // instead of ip, port, protocol
  904. const remoteIpAddress = getStatValue(remoteUsedCandidate, 'ip');
  905. const remotePort = getStatValue(remoteUsedCandidate, 'port');
  906. const ip = `${remoteIpAddress}:${remotePort}`;
  907. const localIpAddress = getStatValue(localUsedCandidate, 'ip');
  908. const localPort = getStatValue(localUsedCandidate, 'port');
  909. const localIp = `${localIpAddress}:${localPort}`;
  910. const type = getStatValue(remoteUsedCandidate, 'protocol');
  911. // Save the address unless it has been saved already.
  912. const conferenceStatsTransport = this.conferenceStats.transport;
  913. if (!conferenceStatsTransport.some(
  914. t =>
  915. t.ip === ip
  916. && t.type === type
  917. && t.localip === localIp)) {
  918. conferenceStatsTransport.push({
  919. ip,
  920. type,
  921. localIp,
  922. p2p: this.peerconnection.isP2P,
  923. localCandidateType: localUsedCandidate.candidateType,
  924. remoteCandidateType: remoteUsedCandidate.candidateType,
  925. networkType: localUsedCandidate.networkType,
  926. rtt: now.currentRoundTripTime * 1000
  927. });
  928. }
  929. }
  930. // RTCReceivedRtpStreamStats
  931. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  932. // RTCSentRtpStreamStats
  933. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  934. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  935. const before = this.previousStatsReport.get(now.id);
  936. const ssrc = this.getNonNegativeValue(now.ssrc);
  937. if (!before || !ssrc) {
  938. return;
  939. }
  940. let ssrcStats = this.ssrc2stats.get(ssrc);
  941. if (!ssrcStats) {
  942. ssrcStats = new SsrcStats();
  943. this.ssrc2stats.set(ssrc, ssrcStats);
  944. }
  945. let isDownloadStream = true;
  946. let key = 'packetsReceived';
  947. if (now.type === 'outbound-rtp') {
  948. isDownloadStream = false;
  949. key = 'packetsSent';
  950. }
  951. let packetsNow = now[key];
  952. if (!packetsNow || packetsNow < 0) {
  953. packetsNow = 0;
  954. }
  955. const packetsBefore = this.getNonNegativeValue(before[key]);
  956. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  957. const packetsLostNow
  958. = this.getNonNegativeValue(now.packetsLost);
  959. const packetsLostBefore
  960. = this.getNonNegativeValue(before.packetsLost);
  961. const packetsLostDiff
  962. = Math.max(0, packetsLostNow - packetsLostBefore);
  963. ssrcStats.setLoss({
  964. packetsTotal: packetsDiff + packetsLostDiff,
  965. packetsLost: packetsLostDiff,
  966. isDownloadStream
  967. });
  968. if (now.type === 'inbound-rtp') {
  969. ssrcStats.addBitrate({
  970. 'download': this._calculateBitrate(
  971. now, before, 'bytesReceived'),
  972. 'upload': 0
  973. });
  974. // RTCInboundRtpStreamStats
  975. // https://w3c.github.io/webrtc-stats/#inboundrtpstats-dict*
  976. // TODO: can we use framesDecoded for frame rate, available
  977. // in chrome
  978. } else {
  979. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  980. ssrcStats.addBitrate({
  981. 'download': 0,
  982. 'upload': this._calculateBitrate(
  983. now, before, 'bytesSent')
  984. });
  985. // RTCOutboundRtpStreamStats
  986. // https://w3c.github.io/webrtc-stats/#outboundrtpstats-dict*
  987. // TODO: can we use framesEncoded for frame rate, available
  988. // in chrome
  989. }
  990. // FF has framerateMean out of spec
  991. const framerateMean = now.framerateMean;
  992. if (framerateMean) {
  993. ssrcStats.setFramerate(Math.round(framerateMean || 0));
  994. }
  995. // track for resolution
  996. // RTCVideoHandlerStats
  997. // https://w3c.github.io/webrtc-stats/#vststats-dict*
  998. // RTCMediaHandlerStats
  999. // https://w3c.github.io/webrtc-stats/#mststats-dict*
  1000. } else if (now.type === 'track') {
  1001. const resolution = {
  1002. height: now.frameHeight,
  1003. width: now.frameWidth
  1004. };
  1005. // Tries to get frame rate
  1006. let frameRate = now.framesPerSecond;
  1007. if (!frameRate) {
  1008. // we need to calculate it
  1009. const before = this.previousStatsReport.get(now.id);
  1010. if (before) {
  1011. const timeMs = now.timestamp - before.timestamp;
  1012. if (timeMs > 0 && now.framesSent) {
  1013. const numberOfFramesSinceBefore
  1014. = now.framesSent - before.framesSent;
  1015. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  1016. }
  1017. }
  1018. if (!frameRate) {
  1019. return;
  1020. }
  1021. }
  1022. const trackIdentifier = now.trackIdentifier;
  1023. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  1024. let ssrcStats = this.ssrc2stats.get(ssrc);
  1025. if (!ssrcStats) {
  1026. ssrcStats = new SsrcStats();
  1027. this.ssrc2stats.set(ssrc, ssrcStats);
  1028. }
  1029. ssrcStats.setFramerate(Math.round(frameRate || 0));
  1030. if (resolution.height && resolution.width) {
  1031. ssrcStats.setResolution(resolution);
  1032. } else {
  1033. ssrcStats.setResolution(null);
  1034. }
  1035. }
  1036. });
  1037. this.eventEmitter.emit(
  1038. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  1039. this._processAndEmitReport();
  1040. };
  1041. /**
  1042. * Stats processing logic.
  1043. */
  1044. StatsCollector.prototype.processNewAudioLevelReport = function() {
  1045. if (!this.baselineAudioLevelsReport) {
  1046. return;
  1047. }
  1048. this.currentAudioLevelsReport.forEach(now => {
  1049. if (now.type !== 'track') {
  1050. return;
  1051. }
  1052. // Audio level
  1053. const audioLevel = now.audioLevel;
  1054. if (!audioLevel) {
  1055. return;
  1056. }
  1057. const trackIdentifier = now.trackIdentifier;
  1058. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  1059. if (ssrc) {
  1060. const isLocal
  1061. = ssrc === this.peerconnection.getLocalSSRC(
  1062. this.peerconnection.getLocalTracks(MediaType.AUDIO));
  1063. this.eventEmitter.emit(
  1064. StatisticsEvents.AUDIO_LEVEL,
  1065. this.peerconnection,
  1066. ssrc,
  1067. audioLevel,
  1068. isLocal);
  1069. }
  1070. });
  1071. };
  1072. /**
  1073. * End new promised based getStats processing methods.
  1074. */