Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTPStatsCollector.js 42KB

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