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

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