You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTPStatsCollector.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. import { getLogger } from '@jitsi/logger';
  2. import { MediaType } from '../../service/RTC/MediaType';
  3. import * as StatisticsEvents from '../../service/statistics/Events';
  4. import browser from '../browser';
  5. import FeatureFlags from '../flags/FeatureFlags';
  6. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  7. const logger = getLogger(__filename);
  8. /**
  9. * Calculates packet lost percent using the number of lost packets and the
  10. * number of all packet.
  11. * @param lostPackets the number of lost packets
  12. * @param totalPackets the number of all packets.
  13. * @returns {number} packet loss percent
  14. */
  15. function calculatePacketLoss(lostPackets, totalPackets) {
  16. if (!totalPackets || totalPackets <= 0
  17. || !lostPackets || lostPackets <= 0) {
  18. return 0;
  19. }
  20. return Math.round((lostPackets / totalPackets) * 100);
  21. }
  22. /**
  23. * Holds "statistics" for a single SSRC.
  24. * @constructor
  25. */
  26. function SsrcStats() {
  27. this.loss = {};
  28. this.bitrate = {
  29. download: 0,
  30. upload: 0
  31. };
  32. this.resolution = {};
  33. this.framerate = 0;
  34. this.codec = '';
  35. }
  36. /**
  37. * Sets the "loss" object.
  38. * @param loss the value to set.
  39. */
  40. SsrcStats.prototype.setLoss = function(loss) {
  41. this.loss = loss || {};
  42. };
  43. /**
  44. * Sets resolution that belong to the ssrc represented by this instance.
  45. * @param resolution new resolution value to be set.
  46. */
  47. SsrcStats.prototype.setResolution = function(resolution) {
  48. this.resolution = resolution || {};
  49. };
  50. /**
  51. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  52. * the respective fields of the "bitrate" field of this object.
  53. * @param bitrate an object holding the values to add.
  54. */
  55. SsrcStats.prototype.addBitrate = function(bitrate) {
  56. this.bitrate.download += bitrate.download;
  57. this.bitrate.upload += bitrate.upload;
  58. };
  59. /**
  60. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  61. * represented by this instance.
  62. */
  63. SsrcStats.prototype.resetBitrate = function() {
  64. this.bitrate.download = 0;
  65. this.bitrate.upload = 0;
  66. };
  67. /**
  68. * Sets the "framerate".
  69. * @param framerate the value to set.
  70. */
  71. SsrcStats.prototype.setFramerate = function(framerate) {
  72. this.framerate = framerate || 0;
  73. };
  74. SsrcStats.prototype.setCodec = function(codec) {
  75. this.codec = codec || '';
  76. };
  77. /**
  78. *
  79. */
  80. function ConferenceStats() {
  81. /**
  82. * The bandwidth
  83. * @type {{}}
  84. */
  85. this.bandwidth = {};
  86. /**
  87. * The bit rate
  88. * @type {{}}
  89. */
  90. this.bitrate = {};
  91. /**
  92. * The packet loss rate
  93. * @type {{}}
  94. */
  95. this.packetLoss = null;
  96. /**
  97. * Array with the transport information.
  98. * @type {Array}
  99. */
  100. this.transport = [];
  101. }
  102. /* eslint-disable max-params */
  103. /**
  104. * <tt>StatsCollector</tt> registers for stats updates of given
  105. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  106. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  107. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  108. * instance as an event source.
  109. *
  110. * @param peerconnection WebRTC PeerConnection object.
  111. * @param audioLevelsInterval
  112. * @param statsInterval stats refresh interval given in ms.
  113. * @param eventEmitter
  114. * @constructor
  115. */
  116. export default function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter) {
  117. this.peerconnection = peerconnection;
  118. this.baselineAudioLevelsReport = null;
  119. this.currentAudioLevelsReport = null;
  120. this.currentStatsReport = null;
  121. this.previousStatsReport = null;
  122. this.audioLevelReportHistory = {};
  123. this.audioLevelsIntervalId = null;
  124. this.eventEmitter = eventEmitter;
  125. this.conferenceStats = new ConferenceStats();
  126. // Updates stats interval
  127. this.audioLevelsIntervalMilis = audioLevelsInterval;
  128. this.speakerList = [];
  129. this.statsIntervalId = null;
  130. this.statsIntervalMilis = statsInterval;
  131. /**
  132. * Maps SSRC numbers to {@link SsrcStats}.
  133. * @type {Map<number,SsrcStats}
  134. */
  135. this.ssrc2stats = new Map();
  136. }
  137. /**
  138. * Set the list of the remote speakers for which audio levels are to be calculated.
  139. *
  140. * @param {Array<string>} speakerList - Endpoint ids.
  141. * @returns {void}
  142. */
  143. StatsCollector.prototype.setSpeakerList = function(speakerList) {
  144. this.speakerList = speakerList;
  145. };
  146. /**
  147. * Stops stats updates.
  148. */
  149. StatsCollector.prototype.stop = function() {
  150. if (this.audioLevelsIntervalId) {
  151. clearInterval(this.audioLevelsIntervalId);
  152. this.audioLevelsIntervalId = null;
  153. }
  154. if (this.statsIntervalId) {
  155. clearInterval(this.statsIntervalId);
  156. this.statsIntervalId = null;
  157. }
  158. };
  159. /**
  160. * Callback passed to <tt>getStats</tt> method.
  161. * @param error an error that occurred on <tt>getStats</tt> call.
  162. */
  163. StatsCollector.prototype.errorCallback = function(error) {
  164. GlobalOnErrorHandler.callErrorHandler(error);
  165. logger.error('Get stats error', error);
  166. this.stop();
  167. };
  168. /**
  169. * Starts stats updates.
  170. */
  171. StatsCollector.prototype.start = function(startAudioLevelStats) {
  172. if (startAudioLevelStats) {
  173. if (browser.supportsReceiverStats()) {
  174. logger.info('Using RTCRtpSynchronizationSource for remote audio levels');
  175. }
  176. this.audioLevelsIntervalId = setInterval(
  177. () => {
  178. if (browser.supportsReceiverStats()) {
  179. const audioLevels = this.peerconnection.getAudioLevels(this.speakerList);
  180. for (const ssrc in audioLevels) {
  181. if (audioLevels.hasOwnProperty(ssrc)) {
  182. // Use a scaling factor of 2.5 to report the same
  183. // audio levels that getStats reports.
  184. const audioLevel = audioLevels[ssrc] * 2.5;
  185. this.eventEmitter.emit(
  186. StatisticsEvents.AUDIO_LEVEL,
  187. this.peerconnection,
  188. Number.parseInt(ssrc, 10),
  189. audioLevel,
  190. false /* isLocal */);
  191. }
  192. }
  193. } else {
  194. // Interval updates
  195. this.peerconnection.getStats()
  196. .then(report => {
  197. this.currentAudioLevelsReport = typeof report?.result === 'function'
  198. ? report.result()
  199. : report;
  200. this.processAudioLevelReport();
  201. this.baselineAudioLevelsReport = this.currentAudioLevelsReport;
  202. })
  203. .catch(error => this.errorCallback(error));
  204. }
  205. },
  206. this.audioLevelsIntervalMilis
  207. );
  208. }
  209. const processStats = () => {
  210. // Interval updates
  211. this.peerconnection.getStats()
  212. .then(report => {
  213. this.currentStatsReport = typeof report?.result === 'function'
  214. ? report.result()
  215. : report;
  216. try {
  217. this.processStatsReport();
  218. } catch (error) {
  219. GlobalOnErrorHandler.callErrorHandler(error);
  220. logger.error('Processing of RTP stats failed:', error);
  221. }
  222. this.previousStatsReport = this.currentStatsReport;
  223. })
  224. .catch(error => this.errorCallback(error));
  225. };
  226. processStats();
  227. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  228. };
  229. /**
  230. *
  231. */
  232. StatsCollector.prototype._processAndEmitReport = function() {
  233. // process stats
  234. const totalPackets = {
  235. download: 0,
  236. upload: 0
  237. };
  238. const lostPackets = {
  239. download: 0,
  240. upload: 0
  241. };
  242. let bitrateDownload = 0;
  243. let bitrateUpload = 0;
  244. const resolutions = {};
  245. const framerates = {};
  246. const codecs = {};
  247. let audioBitrateDownload = 0;
  248. let audioBitrateUpload = 0;
  249. let videoBitrateDownload = 0;
  250. let videoBitrateUpload = 0;
  251. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  252. // process packet loss stats
  253. const loss = ssrcStats.loss;
  254. const type = loss.isDownloadStream ? 'download' : 'upload';
  255. totalPackets[type] += loss.packetsTotal;
  256. lostPackets[type] += loss.packetsLost;
  257. // process bitrate stats
  258. bitrateDownload += ssrcStats.bitrate.download;
  259. bitrateUpload += ssrcStats.bitrate.upload;
  260. // collect resolutions and framerates
  261. const track = this.peerconnection.getTrackBySSRC(ssrc);
  262. if (track) {
  263. let audioCodec;
  264. let videoCodec;
  265. if (track.isAudioTrack()) {
  266. audioBitrateDownload += ssrcStats.bitrate.download;
  267. audioBitrateUpload += ssrcStats.bitrate.upload;
  268. audioCodec = ssrcStats.codec;
  269. } else {
  270. videoBitrateDownload += ssrcStats.bitrate.download;
  271. videoBitrateUpload += ssrcStats.bitrate.upload;
  272. videoCodec = ssrcStats.codec;
  273. }
  274. const participantId = track.getParticipantId();
  275. if (participantId) {
  276. const resolution = ssrcStats.resolution;
  277. if (resolution.width
  278. && resolution.height
  279. && resolution.width !== -1
  280. && resolution.height !== -1) {
  281. const userResolutions = resolutions[participantId] || {};
  282. userResolutions[ssrc] = resolution;
  283. resolutions[participantId] = userResolutions;
  284. }
  285. if (ssrcStats.framerate > 0) {
  286. const userFramerates = framerates[participantId] || {};
  287. userFramerates[ssrc] = ssrcStats.framerate;
  288. framerates[participantId] = userFramerates;
  289. }
  290. const userCodecs = codecs[participantId] ?? { };
  291. userCodecs[ssrc] = {
  292. audio: audioCodec,
  293. video: videoCodec
  294. };
  295. codecs[participantId] = userCodecs;
  296. // All tracks in ssrc-rewriting mode need not have a participant associated with it.
  297. } else if (!FeatureFlags.isSsrcRewritingSupported()) {
  298. logger.error(`No participant ID returned by ${track}`);
  299. }
  300. }
  301. ssrcStats.resetBitrate();
  302. }
  303. this.conferenceStats.bitrate = {
  304. 'upload': bitrateUpload,
  305. 'download': bitrateDownload
  306. };
  307. this.conferenceStats.bitrate.audio = {
  308. 'upload': audioBitrateUpload,
  309. 'download': audioBitrateDownload
  310. };
  311. this.conferenceStats.bitrate.video = {
  312. 'upload': videoBitrateUpload,
  313. 'download': videoBitrateDownload
  314. };
  315. this.conferenceStats.packetLoss = {
  316. total:
  317. calculatePacketLoss(
  318. lostPackets.download + lostPackets.upload,
  319. totalPackets.download + totalPackets.upload),
  320. download:
  321. calculatePacketLoss(lostPackets.download, totalPackets.download),
  322. upload:
  323. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  324. };
  325. const avgAudioLevels = {};
  326. let localAvgAudioLevels;
  327. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  328. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  329. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  330. if (isLocal) {
  331. localAvgAudioLevels = avgAudioLevel;
  332. } else {
  333. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  334. if (track) {
  335. const participantId = track.getParticipantId();
  336. if (participantId) {
  337. avgAudioLevels[participantId] = avgAudioLevel;
  338. }
  339. }
  340. }
  341. });
  342. this.audioLevelReportHistory = {};
  343. this.eventEmitter.emit(
  344. StatisticsEvents.CONNECTION_STATS,
  345. this.peerconnection,
  346. {
  347. 'bandwidth': this.conferenceStats.bandwidth,
  348. 'bitrate': this.conferenceStats.bitrate,
  349. 'packetLoss': this.conferenceStats.packetLoss,
  350. 'resolution': resolutions,
  351. 'framerate': framerates,
  352. 'codec': codecs,
  353. 'transport': this.conferenceStats.transport,
  354. localAvgAudioLevels,
  355. avgAudioLevels
  356. });
  357. this.conferenceStats.transport = [];
  358. };
  359. /**
  360. * Converts the value to a non-negative number.
  361. * If the value is either invalid or negative then 0 will be returned.
  362. * @param {*} v
  363. * @return {number}
  364. * @private
  365. */
  366. StatsCollector.prototype.getNonNegativeValue = function(v) {
  367. let value = v;
  368. if (typeof value !== 'number') {
  369. value = Number(value);
  370. }
  371. if (isNaN(value)) {
  372. return 0;
  373. }
  374. return Math.max(0, value);
  375. };
  376. /**
  377. * Calculates bitrate between before and now using a supplied field name and its
  378. * value in the stats.
  379. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  380. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  381. * previous stats.
  382. * @param fieldName the field to use for calculations.
  383. * @return {number} the calculated bitrate between now and before.
  384. * @private
  385. */
  386. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  387. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  388. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  389. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  390. const timeMs = now.timestamp - before.timestamp;
  391. let bitrateKbps = 0;
  392. if (timeMs > 0) {
  393. // TODO is there any reason to round here?
  394. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  395. }
  396. return bitrateKbps;
  397. };
  398. /**
  399. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  400. */
  401. StatsCollector.prototype.processStatsReport = function() {
  402. const byteSentStats = {};
  403. this.currentStatsReport.forEach(now => {
  404. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  405. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  406. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  407. const availableIncomingBitrate = now.availableIncomingBitrate;
  408. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  409. if (availableIncomingBitrate || availableOutgoingBitrate) {
  410. this.conferenceStats.bandwidth = {
  411. 'download': Math.round(availableIncomingBitrate / 1000),
  412. 'upload': Math.round(availableOutgoingBitrate / 1000)
  413. };
  414. }
  415. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  416. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  417. // RTCIceCandidateStats
  418. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  419. if (remoteUsedCandidate && localUsedCandidate) {
  420. const remoteIpAddress = browser.isChromiumBased()
  421. ? remoteUsedCandidate.ip
  422. : remoteUsedCandidate.address;
  423. const remotePort = remoteUsedCandidate.port;
  424. const ip = `${remoteIpAddress}:${remotePort}`;
  425. const localIpAddress = browser.isChromiumBased()
  426. ? localUsedCandidate.ip
  427. : localUsedCandidate.address;
  428. const localPort = localUsedCandidate.port;
  429. const localip = `${localIpAddress}:${localPort}`;
  430. const type = remoteUsedCandidate.protocol;
  431. // Save the address unless it has been saved already.
  432. const conferenceStatsTransport = this.conferenceStats.transport;
  433. if (!conferenceStatsTransport.some(t =>
  434. t.ip === ip
  435. && t.type === type
  436. && t.localip === localip)) {
  437. conferenceStatsTransport.push({
  438. ip,
  439. type,
  440. localip,
  441. p2p: this.peerconnection.isP2P,
  442. localCandidateType: localUsedCandidate.candidateType,
  443. remoteCandidateType: remoteUsedCandidate.candidateType,
  444. networkType: localUsedCandidate.networkType,
  445. rtt: now.currentRoundTripTime * 1000
  446. });
  447. }
  448. }
  449. // RTCReceivedRtpStreamStats
  450. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  451. // RTCSentRtpStreamStats
  452. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  453. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  454. const ssrc = this.getNonNegativeValue(now.ssrc);
  455. if (!ssrc) {
  456. return;
  457. }
  458. let ssrcStats = this.ssrc2stats.get(ssrc);
  459. if (!ssrcStats) {
  460. ssrcStats = new SsrcStats();
  461. this.ssrc2stats.set(ssrc, ssrcStats);
  462. }
  463. let isDownloadStream = true;
  464. let key = 'packetsReceived';
  465. if (now.type === 'outbound-rtp') {
  466. isDownloadStream = false;
  467. key = 'packetsSent';
  468. }
  469. let packetsNow = now[key];
  470. if (!packetsNow || packetsNow < 0) {
  471. packetsNow = 0;
  472. }
  473. if (before) {
  474. const packetsBefore = this.getNonNegativeValue(before[key]);
  475. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  476. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  477. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  478. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  479. ssrcStats.setLoss({
  480. packetsTotal: packetsDiff + packetsLostDiff,
  481. packetsLost: packetsLostDiff,
  482. isDownloadStream
  483. });
  484. }
  485. // Get the resolution and framerate for only remote video sources here. For the local video sources,
  486. // 'track' stats will be used since they have the updated resolution based on the simulcast streams
  487. // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be
  488. // more calculations needed to determine what is the highest resolution stream sent by the client if the
  489. // 'outbound-rtp' stats are used.
  490. if (now.type === 'inbound-rtp') {
  491. const resolution = {
  492. height: now.frameHeight,
  493. width: now.frameWidth
  494. };
  495. const frameRate = now.framesPerSecond;
  496. if (resolution.height && resolution.width) {
  497. ssrcStats.setResolution(resolution);
  498. }
  499. ssrcStats.setFramerate(Math.round(frameRate || 0));
  500. if (before) {
  501. ssrcStats.addBitrate({
  502. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  503. 'upload': 0
  504. });
  505. }
  506. } else if (before) {
  507. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  508. ssrcStats.addBitrate({
  509. 'download': 0,
  510. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  511. });
  512. }
  513. const codec = this.currentStatsReport.get(now.codecId);
  514. if (codec) {
  515. /**
  516. * The mime type has the following form: video/VP8 or audio/ISAC,
  517. * so we what to keep just the type after the '/', audio and video
  518. * keys will be added on the processing side.
  519. */
  520. const codecShortType = codec.mimeType.split('/')[1];
  521. codecShortType && ssrcStats.setCodec(codecShortType);
  522. }
  523. // Use track stats for resolution and framerate of the local video source.
  524. // RTCVideoHandlerStats - https://w3c.github.io/webrtc-stats/#vststats-dict*
  525. // RTCMediaHandlerStats - https://w3c.github.io/webrtc-stats/#mststats-dict*
  526. } else if (now.type === 'track' && now.kind === MediaType.VIDEO && !now.remoteSource) {
  527. const resolution = {
  528. height: now.frameHeight,
  529. width: now.frameWidth
  530. };
  531. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  532. if (!localVideoTracks?.length) {
  533. return;
  534. }
  535. const ssrc = this.peerconnection.getSsrcByTrackId(now.trackIdentifier);
  536. if (!ssrc) {
  537. return;
  538. }
  539. let ssrcStats = this.ssrc2stats.get(ssrc);
  540. if (!ssrcStats) {
  541. ssrcStats = new SsrcStats();
  542. this.ssrc2stats.set(ssrc, ssrcStats);
  543. }
  544. if (resolution.height && resolution.width) {
  545. ssrcStats.setResolution(resolution);
  546. }
  547. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  548. // Therefore, it needs to be divided by the total number of active simulcast streams.
  549. let frameRate = now.framesPerSecond;
  550. if (!frameRate) {
  551. if (before) {
  552. const timeMs = now.timestamp - before.timestamp;
  553. if (timeMs > 0 && now.framesSent) {
  554. const numberOfFramesSinceBefore = now.framesSent - before.framesSent;
  555. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  556. }
  557. }
  558. if (!frameRate) {
  559. return;
  560. }
  561. }
  562. // Get the number of simulcast streams currently enabled from TPC.
  563. const numberOfActiveStreams = this.peerconnection.getActiveSimulcastStreams();
  564. // Reset frame rate to 0 when video is suspended as a result of endpoint falling out of last-n.
  565. frameRate = numberOfActiveStreams ? Math.round(frameRate / numberOfActiveStreams) : 0;
  566. ssrcStats.setFramerate(frameRate);
  567. }
  568. });
  569. if (Object.keys(byteSentStats).length) {
  570. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  571. }
  572. this._processAndEmitReport();
  573. };
  574. /**
  575. * Stats processing logic.
  576. */
  577. StatsCollector.prototype.processAudioLevelReport = function() {
  578. if (!this.baselineAudioLevelsReport) {
  579. return;
  580. }
  581. this.currentAudioLevelsReport.forEach(now => {
  582. if (now.type !== 'track') {
  583. return;
  584. }
  585. // Audio level
  586. const audioLevel = now.audioLevel;
  587. if (!audioLevel) {
  588. return;
  589. }
  590. const trackIdentifier = now.trackIdentifier;
  591. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  592. if (ssrc) {
  593. const isLocal
  594. = ssrc === this.peerconnection.getLocalSSRC(
  595. this.peerconnection.getLocalTracks(MediaType.AUDIO));
  596. this.eventEmitter.emit(
  597. StatisticsEvents.AUDIO_LEVEL,
  598. this.peerconnection,
  599. ssrc,
  600. audioLevel,
  601. isLocal);
  602. }
  603. });
  604. };