您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTPStatsCollector.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. /* global require */
  2. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  3. const logger = require('jitsi-meet-logger').getLogger(__filename);
  4. const RTCBrowserType = require('../RTC/RTCBrowserType');
  5. import * as StatisticsEvents from '../../service/statistics/Events';
  6. /* Whether we support the browser we are running into for logging statistics */
  7. const browserSupported = RTCBrowserType.isChrome()
  8. || RTCBrowserType.isOpera() || RTCBrowserType.isFirefox()
  9. || RTCBrowserType.isNWJS() || RTCBrowserType.isElectron();
  10. /**
  11. * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
  12. * 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. };
  46. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_OPERA]
  47. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  48. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_NWJS]
  49. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  50. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_ELECTRON]
  51. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  52. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_IEXPLORER]
  53. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  54. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_SAFARI]
  55. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  56. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_REACT_NATIVE]
  57. = KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  58. /**
  59. * Calculates packet lost percent using the number of lost packets and the
  60. * number of all packet.
  61. * @param lostPackets the number of lost packets
  62. * @param totalPackets the number of all packets.
  63. * @returns {number} packet loss percent
  64. */
  65. function calculatePacketLoss(lostPackets, totalPackets) {
  66. if (!totalPackets || totalPackets <= 0
  67. || !lostPackets || lostPackets <= 0) {
  68. return 0;
  69. }
  70. return Math.round((lostPackets / totalPackets) * 100);
  71. }
  72. /**
  73. * Holds "statistics" for a single SSRC.
  74. * @constructor
  75. */
  76. function SsrcStats() {
  77. this.loss = {};
  78. this.bitrate = {
  79. download: 0,
  80. upload: 0
  81. };
  82. this.resolution = {};
  83. this.framerate = 0;
  84. }
  85. /**
  86. * Sets the "loss" object.
  87. * @param loss the value to set.
  88. */
  89. SsrcStats.prototype.setLoss = function(loss) {
  90. this.loss = loss || {};
  91. };
  92. /**
  93. * Sets resolution that belong to the ssrc represented by this instance.
  94. * @param resolution new resolution value to be set.
  95. */
  96. SsrcStats.prototype.setResolution = function(resolution) {
  97. this.resolution = resolution || {};
  98. };
  99. /**
  100. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  101. * the respective fields of the "bitrate" field of this object.
  102. * @param bitrate an object holding the values to add.
  103. */
  104. SsrcStats.prototype.addBitrate = function(bitrate) {
  105. this.bitrate.download += bitrate.download;
  106. this.bitrate.upload += bitrate.upload;
  107. };
  108. /**
  109. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  110. * represented by this instance.
  111. */
  112. SsrcStats.prototype.resetBitrate = function() {
  113. this.bitrate.download = 0;
  114. this.bitrate.upload = 0;
  115. };
  116. /**
  117. * Sets the "framerate".
  118. * @param framerate the value to set.
  119. */
  120. SsrcStats.prototype.setFramerate = function(framerate) {
  121. this.framerate = framerate || 0;
  122. };
  123. /**
  124. *
  125. */
  126. function ConferenceStats() {
  127. /**
  128. * The bandwidth
  129. * @type {{}}
  130. */
  131. this.bandwidth = {};
  132. /**
  133. * The bit rate
  134. * @type {{}}
  135. */
  136. this.bitrate = {};
  137. /**
  138. * The packet loss rate
  139. * @type {{}}
  140. */
  141. this.packetLoss = null;
  142. /**
  143. * Array with the transport information.
  144. * @type {Array}
  145. */
  146. this.transport = [];
  147. }
  148. /* eslint-disable max-params */
  149. /**
  150. * <tt>StatsCollector</tt> registers for stats updates of given
  151. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  152. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  153. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  154. * instance as an event source.
  155. *
  156. * @param peerconnection WebRTC PeerConnection object.
  157. * @param audioLevelsInterval
  158. * @param statsInterval stats refresh interval given in ms.
  159. * @param eventEmitter
  160. * @constructor
  161. */
  162. function StatsCollector(
  163. peerconnection,
  164. audioLevelsInterval,
  165. statsInterval,
  166. eventEmitter) {
  167. // StatsCollector depends entirely on the format of the reports returned by
  168. // RTCPeerConnection#getStats. Given that the value of
  169. // RTCBrowserType#getBrowserType() is very unlikely to change at runtime, it
  170. // makes sense to discover whether StatsCollector supports the executing
  171. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  172. // needlessly check a "static" condition multiple times very very often and
  173. // (2) the lack of support for the executing browser would be discovered and
  174. // reported multiple times very very often too late in the execution in some
  175. // totally unrelated callback.
  176. /**
  177. * The RTCBrowserType supported by this StatsCollector. In other words, the
  178. * RTCBrowserType of the browser which initialized this StatsCollector
  179. * instance.
  180. * @private
  181. */
  182. this._browserType = RTCBrowserType.getBrowserType();
  183. const keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  184. if (!keys) {
  185. // eslint-disable-next-line no-throw-literal
  186. throw `The browser type '${this._browserType}' isn't supported!`;
  187. }
  188. /**
  189. * The function which is to be used to retrieve the value associated in a
  190. * report returned by RTCPeerConnection#getStats with a LibJitsiMeet
  191. * browser-agnostic name/key.
  192. * @function
  193. * @private
  194. */
  195. this._getStatValue = this._defineGetStatValueMethod(keys);
  196. this.peerconnection = peerconnection;
  197. this.baselineAudioLevelsReport = null;
  198. this.currentAudioLevelsReport = null;
  199. this.currentStatsReport = null;
  200. this.previousStatsReport = null;
  201. this.audioLevelsIntervalId = null;
  202. this.eventEmitter = eventEmitter;
  203. this.conferenceStats = new ConferenceStats();
  204. // Updates stats interval
  205. this.audioLevelsIntervalMilis = audioLevelsInterval;
  206. this.statsIntervalId = null;
  207. this.statsIntervalMilis = statsInterval;
  208. // Map of ssrcs to SsrcStats
  209. this.ssrc2stats = {};
  210. }
  211. /* eslint-enable max-params */
  212. module.exports = StatsCollector;
  213. /**
  214. * Stops stats updates.
  215. */
  216. StatsCollector.prototype.stop = function() {
  217. if (this.audioLevelsIntervalId) {
  218. clearInterval(this.audioLevelsIntervalId);
  219. this.audioLevelsIntervalId = null;
  220. }
  221. if (this.statsIntervalId) {
  222. clearInterval(this.statsIntervalId);
  223. this.statsIntervalId = null;
  224. }
  225. };
  226. /**
  227. * Callback passed to <tt>getStats</tt> method.
  228. * @param error an error that occurred on <tt>getStats</tt> call.
  229. */
  230. StatsCollector.prototype.errorCallback = function(error) {
  231. GlobalOnErrorHandler.callErrorHandler(error);
  232. logger.error('Get stats error', error);
  233. this.stop();
  234. };
  235. /**
  236. * Starts stats updates.
  237. */
  238. StatsCollector.prototype.start = function(startAudioLevelStats) {
  239. const self = this;
  240. if (startAudioLevelStats) {
  241. this.audioLevelsIntervalId = setInterval(
  242. () => {
  243. // Interval updates
  244. self.peerconnection.getStats(
  245. report => {
  246. let results = null;
  247. if (!report || !report.result
  248. || typeof report.result !== 'function') {
  249. results = report;
  250. } else {
  251. results = report.result();
  252. }
  253. self.currentAudioLevelsReport = results;
  254. self.processAudioLevelReport();
  255. self.baselineAudioLevelsReport
  256. = self.currentAudioLevelsReport;
  257. },
  258. self.errorCallback
  259. );
  260. },
  261. self.audioLevelsIntervalMilis
  262. );
  263. }
  264. if (browserSupported) {
  265. this.statsIntervalId = setInterval(
  266. () => {
  267. // Interval updates
  268. self.peerconnection.getStats(
  269. report => {
  270. let results = null;
  271. if (!report || !report.result
  272. || typeof report.result !== 'function') {
  273. // firefox
  274. results = report;
  275. } else {
  276. // chrome
  277. results = report.result();
  278. }
  279. self.currentStatsReport = results;
  280. try {
  281. self.processStatsReport();
  282. } catch (e) {
  283. GlobalOnErrorHandler.callErrorHandler(e);
  284. logger.error(`Unsupported key:${e}`, e);
  285. }
  286. self.previousStatsReport = self.currentStatsReport;
  287. },
  288. self.errorCallback
  289. );
  290. },
  291. self.statsIntervalMilis
  292. );
  293. }
  294. };
  295. /**
  296. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  297. * gets the value from a specific report returned by RTCPeerConnection#getStats
  298. * associated with a LibJitsiMeet browser-agnostic name.
  299. *
  300. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  301. * names to RTCPeerConnection#getStats browser-specific keys
  302. */
  303. StatsCollector.prototype._defineGetStatValueMethod = function(keys) {
  304. // Define the function which converts a LibJitsiMeet browser-asnostic name
  305. // to a browser-specific key of a report returned by
  306. // RTCPeerConnection#getStats.
  307. const keyFromName = function(name) {
  308. const key = keys[name];
  309. if (key) {
  310. return key;
  311. }
  312. // eslint-disable-next-line no-throw-literal
  313. throw `The property '${name}' isn't supported!`;
  314. };
  315. // Define the function which retrieves the value from a specific report
  316. // returned by RTCPeerConnection#getStats associated with a given
  317. // browser-specific key.
  318. let itemStatByKey;
  319. switch (this._browserType) {
  320. case RTCBrowserType.RTC_BROWSER_CHROME:
  321. case RTCBrowserType.RTC_BROWSER_OPERA:
  322. case RTCBrowserType.RTC_BROWSER_NWJS:
  323. case RTCBrowserType.RTC_BROWSER_ELECTRON:
  324. // TODO What about other types of browser which are based on Chrome such
  325. // as NW.js? Every time we want to support a new type browser we have to
  326. // go and add more conditions (here and in multiple other places).
  327. // Cannot we do a feature detection instead of a browser type check? For
  328. // example, if item has a stat property of type function, then it's very
  329. // likely that whoever defined it wanted you to call it in order to
  330. // retrieve the value associated with a specific key.
  331. itemStatByKey = (item, key) => item.stat(key);
  332. break;
  333. case RTCBrowserType.RTC_BROWSER_REACT_NATIVE:
  334. // The implementation provided by react-native-webrtc follows the
  335. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  336. // Array in which each element is a key-value pair.
  337. itemStatByKey = function(item, key) {
  338. let value;
  339. item.values.some(pair => {
  340. if (pair.hasOwnProperty(key)) {
  341. value = pair[key];
  342. return true;
  343. }
  344. return false;
  345. });
  346. return value;
  347. };
  348. break;
  349. default:
  350. itemStatByKey = (item, key) => item[key];
  351. }
  352. // Compose the 2 functions defined above to get a function which retrieves
  353. // the value from a specific report returned by RTCPeerConnection#getStats
  354. // associated with a specific LibJitsiMeet browser-agnostic name.
  355. return function(item, name) {
  356. return itemStatByKey(item, keyFromName(name));
  357. };
  358. };
  359. /* eslint-disable no-continue */
  360. /**
  361. * Stats processing logic.
  362. */
  363. StatsCollector.prototype.processStatsReport = function() {
  364. if (!this.previousStatsReport) {
  365. return;
  366. }
  367. const getStatValue = this._getStatValue;
  368. /**
  369. *
  370. * @param report
  371. * @param name
  372. */
  373. function getNonNegativeStat(report, name) {
  374. let value = getStatValue(report, name);
  375. if (typeof value !== 'number') {
  376. value = Number(value);
  377. }
  378. if (isNaN(value)) {
  379. return 0;
  380. }
  381. return Math.max(0, value);
  382. }
  383. const byteSentStats = {};
  384. for (const idx in this.currentStatsReport) {
  385. if (!this.currentStatsReport.hasOwnProperty(idx)) {
  386. continue;
  387. }
  388. const now = this.currentStatsReport[idx];
  389. try {
  390. const receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  391. const sendBandwidth = getStatValue(now, 'sendBandwidth');
  392. if (receiveBandwidth || sendBandwidth) {
  393. this.conferenceStats.bandwidth = {
  394. 'download': Math.round(receiveBandwidth / 1000),
  395. 'upload': Math.round(sendBandwidth / 1000)
  396. };
  397. }
  398. } catch (e) { /* not supported*/ }
  399. if (now.type === 'googCandidatePair') {
  400. let active, ip, localip, type;
  401. try {
  402. ip = getStatValue(now, 'remoteAddress');
  403. type = getStatValue(now, 'transportType');
  404. localip = getStatValue(now, 'localAddress');
  405. active = getStatValue(now, 'activeConnection');
  406. } catch (e) { /* not supported*/ }
  407. if (!ip || !type || !localip || active !== 'true') {
  408. continue;
  409. }
  410. // Save the address unless it has been saved already.
  411. const conferenceStatsTransport = this.conferenceStats.transport;
  412. if (!conferenceStatsTransport.some(
  413. t =>
  414. t.ip === ip
  415. && t.type === type
  416. && t.localip === localip)) {
  417. conferenceStatsTransport.push({
  418. ip,
  419. type,
  420. localip,
  421. p2p: this.peerconnection.isP2P
  422. });
  423. }
  424. continue;
  425. }
  426. if (now.type === 'candidatepair') {
  427. // we need succeeded pairs only
  428. if (now.state !== 'succeeded') {
  429. continue;
  430. }
  431. const local = this.currentStatsReport[now.localCandidateId];
  432. const remote = this.currentStatsReport[now.remoteCandidateId];
  433. this.conferenceStats.transport.push({
  434. ip: `${remote.ipAddress}:${remote.portNumber}`,
  435. type: local.transport,
  436. localip: `${local.ipAddress}:${local.portNumber}`,
  437. p2p: this.peerconnection.isP2P
  438. });
  439. }
  440. if (now.type !== 'ssrc' && now.type !== 'outboundrtp'
  441. && now.type !== 'inboundrtp') {
  442. continue;
  443. }
  444. const before = this.previousStatsReport[idx];
  445. const ssrc = getStatValue(now, 'ssrc');
  446. if (!before || !ssrc) {
  447. continue;
  448. }
  449. const ssrcStats
  450. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
  451. let isDownloadStream = true;
  452. let key = 'packetsReceived';
  453. let packetsNow = getStatValue(now, key);
  454. if (typeof packetsNow === 'undefined'
  455. || packetsNow === null || packetsNow === '') {
  456. isDownloadStream = false;
  457. key = 'packetsSent';
  458. packetsNow = getStatValue(now, key);
  459. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  460. logger.warn('No packetsReceived nor packetsSent stat found');
  461. continue;
  462. }
  463. }
  464. if (!packetsNow || packetsNow < 0) {
  465. packetsNow = 0;
  466. }
  467. const packetsBefore = getNonNegativeStat(before, key);
  468. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  469. const packetsLostNow = getNonNegativeStat(now, 'packetsLost');
  470. const packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
  471. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  472. ssrcStats.setLoss({
  473. packetsTotal: packetsDiff + packetsLostDiff,
  474. packetsLost: packetsLostDiff,
  475. isDownloadStream
  476. });
  477. const bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
  478. const bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
  479. const bytesReceived
  480. = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  481. let bytesSent = 0;
  482. // TODO: clean this mess up!
  483. let nowBytesTransmitted = getStatValue(now, 'bytesSent');
  484. if (typeof nowBytesTransmitted === 'number'
  485. || typeof nowBytesTransmitted === 'string') {
  486. nowBytesTransmitted = Number(nowBytesTransmitted);
  487. if (!isNaN(nowBytesTransmitted)) {
  488. byteSentStats[ssrc] = nowBytesTransmitted;
  489. if (nowBytesTransmitted > 0) {
  490. bytesSent = nowBytesTransmitted
  491. - getStatValue(before, 'bytesSent');
  492. }
  493. }
  494. }
  495. bytesSent = Math.max(0, bytesSent);
  496. const timeMs = now.timestamp - before.timestamp;
  497. let bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  498. if (timeMs > 0) {
  499. // TODO is there any reason to round here?
  500. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  501. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  502. }
  503. ssrcStats.addBitrate({
  504. 'download': bitrateReceivedKbps,
  505. 'upload': bitrateSentKbps
  506. });
  507. const resolution = { height: null,
  508. width: null };
  509. try {
  510. let height, width;
  511. if ((height = getStatValue(now, 'googFrameHeightReceived'))
  512. && (width = getStatValue(now, 'googFrameWidthReceived'))) {
  513. resolution.height = height;
  514. resolution.width = width;
  515. } else if ((height = getStatValue(now, 'googFrameHeightSent'))
  516. && (width = getStatValue(now, 'googFrameWidthSent'))) {
  517. resolution.height = height;
  518. resolution.width = width;
  519. }
  520. } catch (e) { /* not supported*/ }
  521. // Tries to get frame rate
  522. try {
  523. ssrcStats.setFramerate(
  524. getStatValue(now, 'googFrameRateReceived')
  525. || getStatValue(now, 'googFrameRateSent')
  526. || 0);
  527. } catch (e) {
  528. // if it fails with previous properties(chrome),
  529. // let's try with another one (FF)
  530. try {
  531. ssrcStats.setFramerate(Math.round(
  532. getNonNegativeStat(now, 'framerateMean')));
  533. } catch (err) { /* not supported*/ }
  534. }
  535. if (resolution.height && resolution.width) {
  536. ssrcStats.setResolution(resolution);
  537. } else {
  538. ssrcStats.setResolution(null);
  539. }
  540. }
  541. // process stats
  542. const totalPackets = {
  543. download: 0,
  544. upload: 0
  545. };
  546. const lostPackets = {
  547. download: 0,
  548. upload: 0
  549. };
  550. let bitrateDownload = 0;
  551. let bitrateUpload = 0;
  552. const resolutions = {};
  553. const framerates = {};
  554. Object.keys(this.ssrc2stats).forEach(
  555. function(ssrc) {
  556. const ssrcStats = this.ssrc2stats[ssrc];
  557. // process packet loss stats
  558. const loss = ssrcStats.loss;
  559. const type = loss.isDownloadStream ? 'download' : 'upload';
  560. totalPackets[type] += loss.packetsTotal;
  561. lostPackets[type] += loss.packetsLost;
  562. // process bitrate stats
  563. bitrateDownload += ssrcStats.bitrate.download;
  564. bitrateUpload += ssrcStats.bitrate.upload;
  565. ssrcStats.resetBitrate();
  566. // collect resolutions
  567. resolutions[ssrc] = ssrcStats.resolution;
  568. // collect framerates
  569. framerates[ssrc] = ssrcStats.framerate;
  570. },
  571. this
  572. );
  573. this.eventEmitter.emit(
  574. StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  575. this.conferenceStats.bitrate
  576. = { 'upload': bitrateUpload,
  577. 'download': bitrateDownload };
  578. this.conferenceStats.packetLoss = {
  579. total:
  580. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  581. totalPackets.download + totalPackets.upload),
  582. download:
  583. calculatePacketLoss(lostPackets.download, totalPackets.download),
  584. upload:
  585. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  586. };
  587. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  588. 'bandwidth': this.conferenceStats.bandwidth,
  589. 'bitrate': this.conferenceStats.bitrate,
  590. 'packetLoss': this.conferenceStats.packetLoss,
  591. 'resolution': resolutions,
  592. 'framerate': framerates,
  593. 'transport': this.conferenceStats.transport
  594. });
  595. this.conferenceStats.transport = [];
  596. };
  597. /**
  598. * Stats processing logic.
  599. */
  600. StatsCollector.prototype.processAudioLevelReport = function() {
  601. if (!this.baselineAudioLevelsReport) {
  602. return;
  603. }
  604. const getStatValue = this._getStatValue;
  605. for (const idx in this.currentAudioLevelsReport) {
  606. if (!this.currentAudioLevelsReport.hasOwnProperty(idx)) {
  607. continue;
  608. }
  609. const now = this.currentAudioLevelsReport[idx];
  610. if (now.type !== 'ssrc') {
  611. continue;
  612. }
  613. const before = this.baselineAudioLevelsReport[idx];
  614. const ssrc = getStatValue(now, 'ssrc');
  615. if (!before) {
  616. logger.warn(`${ssrc} not enough data`);
  617. continue;
  618. }
  619. if (!ssrc) {
  620. if ((Date.now() - now.timestamp) < 3000) {
  621. logger.warn('No ssrc: ');
  622. }
  623. continue;
  624. }
  625. // Audio level
  626. let audioLevel;
  627. try {
  628. audioLevel
  629. = getStatValue(now, 'audioInputLevel')
  630. || getStatValue(now, 'audioOutputLevel');
  631. } catch (e) { /* not supported*/
  632. logger.warn('Audio Levels are not available in the statistics.');
  633. clearInterval(this.audioLevelsIntervalId);
  634. return;
  635. }
  636. if (audioLevel) {
  637. const isLocal = !getStatValue(now, 'packetsReceived');
  638. // TODO: Can't find specs about what this value really is, but it
  639. // seems to vary between 0 and around 32k.
  640. audioLevel = audioLevel / 32767;
  641. this.eventEmitter.emit(
  642. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel, isLocal);
  643. }
  644. }
  645. };
  646. /* eslint-enable no-continue */