Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTPStatsCollector.js 32KB

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