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

RTPStatsCollector.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. import { getLogger } from '@jitsi/logger';
  2. import * as 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 audioCodec;
  249. let videoBitrateDownload = 0;
  250. let videoBitrateUpload = 0;
  251. let videoCodec;
  252. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  253. // process packet loss stats
  254. const loss = ssrcStats.loss;
  255. const type = loss.isDownloadStream ? 'download' : 'upload';
  256. totalPackets[type] += loss.packetsTotal;
  257. lostPackets[type] += loss.packetsLost;
  258. // process bitrate stats
  259. bitrateDownload += ssrcStats.bitrate.download;
  260. bitrateUpload += ssrcStats.bitrate.upload;
  261. // collect resolutions and framerates
  262. const track = this.peerconnection.getTrackBySSRC(ssrc);
  263. if (track) {
  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. if (audioCodec && videoCodec) {
  290. const codecDesc = {
  291. 'audio': audioCodec,
  292. 'video': videoCodec
  293. };
  294. const userCodecs = codecs[participantId] || {};
  295. userCodecs[ssrc] = codecDesc;
  296. codecs[participantId] = userCodecs;
  297. }
  298. } else {
  299. logger.error(`No participant ID returned by ${track}`);
  300. }
  301. }
  302. ssrcStats.resetBitrate();
  303. }
  304. this.conferenceStats.bitrate = {
  305. 'upload': bitrateUpload,
  306. 'download': bitrateDownload
  307. };
  308. this.conferenceStats.bitrate.audio = {
  309. 'upload': audioBitrateUpload,
  310. 'download': audioBitrateDownload
  311. };
  312. this.conferenceStats.bitrate.video = {
  313. 'upload': videoBitrateUpload,
  314. 'download': videoBitrateDownload
  315. };
  316. this.conferenceStats.packetLoss = {
  317. total:
  318. calculatePacketLoss(
  319. lostPackets.download + lostPackets.upload,
  320. totalPackets.download + totalPackets.upload),
  321. download:
  322. calculatePacketLoss(lostPackets.download, totalPackets.download),
  323. upload:
  324. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  325. };
  326. const avgAudioLevels = {};
  327. let localAvgAudioLevels;
  328. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  329. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  330. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  331. if (isLocal) {
  332. localAvgAudioLevels = avgAudioLevel;
  333. } else {
  334. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  335. if (track) {
  336. const participantId = track.getParticipantId();
  337. if (participantId) {
  338. avgAudioLevels[participantId] = avgAudioLevel;
  339. }
  340. }
  341. }
  342. });
  343. this.audioLevelReportHistory = {};
  344. this.eventEmitter.emit(
  345. StatisticsEvents.CONNECTION_STATS,
  346. this.peerconnection,
  347. {
  348. 'bandwidth': this.conferenceStats.bandwidth,
  349. 'bitrate': this.conferenceStats.bitrate,
  350. 'packetLoss': this.conferenceStats.packetLoss,
  351. 'resolution': resolutions,
  352. 'framerate': framerates,
  353. 'codec': codecs,
  354. 'transport': this.conferenceStats.transport,
  355. localAvgAudioLevels,
  356. avgAudioLevels
  357. });
  358. this.conferenceStats.transport = [];
  359. };
  360. /**
  361. * Converts the value to a non-negative number.
  362. * If the value is either invalid or negative then 0 will be returned.
  363. * @param {*} v
  364. * @return {number}
  365. * @private
  366. */
  367. StatsCollector.prototype.getNonNegativeValue = function(v) {
  368. let value = v;
  369. if (typeof value !== 'number') {
  370. value = Number(value);
  371. }
  372. if (isNaN(value)) {
  373. return 0;
  374. }
  375. return Math.max(0, value);
  376. };
  377. /**
  378. * Calculates bitrate between before and now using a supplied field name and its
  379. * value in the stats.
  380. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  381. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  382. * previous stats.
  383. * @param fieldName the field to use for calculations.
  384. * @return {number} the calculated bitrate between now and before.
  385. * @private
  386. */
  387. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  388. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  389. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  390. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  391. const timeMs = now.timestamp - before.timestamp;
  392. let bitrateKbps = 0;
  393. if (timeMs > 0) {
  394. // TODO is there any reason to round here?
  395. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  396. }
  397. return bitrateKbps;
  398. };
  399. /**
  400. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  401. */
  402. StatsCollector.prototype.processStatsReport = function() {
  403. if (!this.previousStatsReport) {
  404. return;
  405. }
  406. const byteSentStats = {};
  407. this.currentStatsReport.forEach(now => {
  408. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  409. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  410. const availableIncomingBitrate = now.availableIncomingBitrate;
  411. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  412. if (availableIncomingBitrate || availableOutgoingBitrate) {
  413. this.conferenceStats.bandwidth = {
  414. 'download': Math.round(availableIncomingBitrate / 1000),
  415. 'upload': Math.round(availableOutgoingBitrate / 1000)
  416. };
  417. }
  418. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  419. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  420. // RTCIceCandidateStats
  421. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  422. if (remoteUsedCandidate && localUsedCandidate) {
  423. const remoteIpAddress = browser.isChromiumBased()
  424. ? remoteUsedCandidate.ip
  425. : remoteUsedCandidate.address;
  426. const remotePort = remoteUsedCandidate.port;
  427. const ip = `${remoteIpAddress}:${remotePort}`;
  428. const localIpAddress = browser.isChromiumBased()
  429. ? localUsedCandidate.ip
  430. : localUsedCandidate.address;
  431. const localPort = localUsedCandidate.port;
  432. const localip = `${localIpAddress}:${localPort}`;
  433. const type = remoteUsedCandidate.protocol;
  434. // Save the address unless it has been saved already.
  435. const conferenceStatsTransport = this.conferenceStats.transport;
  436. if (!conferenceStatsTransport.some(t =>
  437. t.ip === ip
  438. && t.type === type
  439. && t.localip === localip)) {
  440. conferenceStatsTransport.push({
  441. ip,
  442. type,
  443. localip,
  444. p2p: this.peerconnection.isP2P,
  445. localCandidateType: localUsedCandidate.candidateType,
  446. remoteCandidateType: remoteUsedCandidate.candidateType,
  447. networkType: localUsedCandidate.networkType,
  448. rtt: now.currentRoundTripTime * 1000
  449. });
  450. }
  451. }
  452. // RTCReceivedRtpStreamStats
  453. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  454. // RTCSentRtpStreamStats
  455. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  456. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  457. const before = this.previousStatsReport.get(now.id);
  458. const ssrc = this.getNonNegativeValue(now.ssrc);
  459. if (!before || !ssrc) {
  460. return;
  461. }
  462. let ssrcStats = this.ssrc2stats.get(ssrc);
  463. if (!ssrcStats) {
  464. ssrcStats = new SsrcStats();
  465. this.ssrc2stats.set(ssrc, ssrcStats);
  466. }
  467. let isDownloadStream = true;
  468. let key = 'packetsReceived';
  469. if (now.type === 'outbound-rtp') {
  470. isDownloadStream = false;
  471. key = 'packetsSent';
  472. }
  473. let packetsNow = now[key];
  474. if (!packetsNow || packetsNow < 0) {
  475. packetsNow = 0;
  476. }
  477. const packetsBefore = this.getNonNegativeValue(before[key]);
  478. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  479. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  480. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  481. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  482. ssrcStats.setLoss({
  483. packetsTotal: packetsDiff + packetsLostDiff,
  484. packetsLost: packetsLostDiff,
  485. isDownloadStream
  486. });
  487. // Get the resolution and framerate for only remote video sources here. For the local video sources,
  488. // 'track' stats will be used since they have the updated resolution based on the simulcast streams
  489. // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be
  490. // more calculations needed to determine what is the highest resolution stream sent by the client if the
  491. // 'outbound-rtp' stats are used.
  492. if (now.type === 'inbound-rtp') {
  493. const resolution = {
  494. height: now.frameHeight,
  495. width: now.frameWidth
  496. };
  497. const frameRate = now.framesPerSecond;
  498. if (resolution.height && resolution.width) {
  499. ssrcStats.setResolution(resolution);
  500. }
  501. ssrcStats.setFramerate(Math.round(frameRate || 0));
  502. ssrcStats.addBitrate({
  503. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  504. 'upload': 0
  505. });
  506. } else {
  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.getLocalSSRC(localVideoTracks[0]);
  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. const before = this.previousStatsReport.get(now.id);
  552. if (before) {
  553. const timeMs = now.timestamp - before.timestamp;
  554. if (timeMs > 0 && now.framesSent) {
  555. const numberOfFramesSinceBefore = now.framesSent - before.framesSent;
  556. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  557. }
  558. }
  559. if (!frameRate) {
  560. return;
  561. }
  562. }
  563. // Get the number of simulcast streams currently enabled from TPC.
  564. const numberOfActiveStreams = this.peerconnection.getActiveSimulcastStreams();
  565. // Reset frame rate to 0 when video is suspended as a result of endpoint falling out of last-n.
  566. frameRate = numberOfActiveStreams ? Math.round(frameRate / numberOfActiveStreams) : 0;
  567. ssrcStats.setFramerate(frameRate);
  568. }
  569. });
  570. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  571. this._processAndEmitReport();
  572. };
  573. /**
  574. * Stats processing logic.
  575. */
  576. StatsCollector.prototype.processAudioLevelReport = function() {
  577. if (!this.baselineAudioLevelsReport) {
  578. return;
  579. }
  580. this.currentAudioLevelsReport.forEach(now => {
  581. if (now.type !== 'track') {
  582. return;
  583. }
  584. // Audio level
  585. const audioLevel = now.audioLevel;
  586. if (!audioLevel) {
  587. return;
  588. }
  589. const trackIdentifier = now.trackIdentifier;
  590. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  591. if (ssrc) {
  592. const isLocal
  593. = ssrc === this.peerconnection.getLocalSSRC(
  594. this.peerconnection.getLocalTracks(MediaType.AUDIO));
  595. this.eventEmitter.emit(
  596. StatisticsEvents.AUDIO_LEVEL,
  597. this.peerconnection,
  598. ssrc,
  599. audioLevel,
  600. isLocal);
  601. }
  602. });
  603. };