Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTPStatsCollector.js 31KB

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