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 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. import { getLogger } from 'jitsi-meet-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. report => {
  196. let results = null;
  197. if (!report || !report.result
  198. || typeof report.result !== 'function') {
  199. results = report;
  200. } else {
  201. results = report.result();
  202. }
  203. this.currentAudioLevelsReport = results;
  204. this.processAudioLevelReport();
  205. this.baselineAudioLevelsReport = this.currentAudioLevelsReport;
  206. },
  207. error => this.errorCallback(error)
  208. );
  209. }
  210. },
  211. this.audioLevelsIntervalMilis
  212. );
  213. }
  214. const processStats = () => {
  215. // Interval updates
  216. this.peerconnection.getStats(
  217. report => {
  218. let results = null;
  219. if (!report || !report.result
  220. || typeof report.result !== 'function') {
  221. // firefox
  222. results = report;
  223. } else {
  224. // chrome
  225. results = report.result();
  226. }
  227. this.currentStatsReport = results;
  228. try {
  229. this.processStatsReport();
  230. } catch (error) {
  231. GlobalOnErrorHandler.callErrorHandler(error);
  232. logger.error('Processing of RTP stats failed:', error);
  233. }
  234. this.previousStatsReport = this.currentStatsReport;
  235. },
  236. error => this.errorCallback(error)
  237. );
  238. };
  239. processStats();
  240. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  241. };
  242. /**
  243. *
  244. */
  245. StatsCollector.prototype._processAndEmitReport = function() {
  246. // process stats
  247. const totalPackets = {
  248. download: 0,
  249. upload: 0
  250. };
  251. const lostPackets = {
  252. download: 0,
  253. upload: 0
  254. };
  255. let bitrateDownload = 0;
  256. let bitrateUpload = 0;
  257. const resolutions = {};
  258. const framerates = {};
  259. const codecs = {};
  260. let audioBitrateDownload = 0;
  261. let audioBitrateUpload = 0;
  262. let audioCodec;
  263. let videoBitrateDownload = 0;
  264. let videoBitrateUpload = 0;
  265. let videoCodec;
  266. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  267. // process packet loss stats
  268. const loss = ssrcStats.loss;
  269. const type = loss.isDownloadStream ? 'download' : 'upload';
  270. totalPackets[type] += loss.packetsTotal;
  271. lostPackets[type] += loss.packetsLost;
  272. // process bitrate stats
  273. bitrateDownload += ssrcStats.bitrate.download;
  274. bitrateUpload += ssrcStats.bitrate.upload;
  275. // collect resolutions and framerates
  276. const track = this.peerconnection.getTrackBySSRC(ssrc);
  277. if (track) {
  278. if (track.isAudioTrack()) {
  279. audioBitrateDownload += ssrcStats.bitrate.download;
  280. audioBitrateUpload += ssrcStats.bitrate.upload;
  281. audioCodec = ssrcStats.codec;
  282. } else {
  283. videoBitrateDownload += ssrcStats.bitrate.download;
  284. videoBitrateUpload += ssrcStats.bitrate.upload;
  285. videoCodec = ssrcStats.codec;
  286. }
  287. const participantId = track.getParticipantId();
  288. if (participantId) {
  289. const resolution = ssrcStats.resolution;
  290. if (resolution.width
  291. && resolution.height
  292. && resolution.width !== -1
  293. && resolution.height !== -1) {
  294. const userResolutions = resolutions[participantId] || {};
  295. userResolutions[ssrc] = resolution;
  296. resolutions[participantId] = userResolutions;
  297. }
  298. if (ssrcStats.framerate !== 0) {
  299. const userFramerates = framerates[participantId] || {};
  300. userFramerates[ssrc] = ssrcStats.framerate;
  301. framerates[participantId] = userFramerates;
  302. }
  303. if (audioCodec && videoCodec) {
  304. const codecDesc = {
  305. 'audio': audioCodec,
  306. 'video': videoCodec
  307. };
  308. const userCodecs = codecs[participantId] || {};
  309. userCodecs[ssrc] = codecDesc;
  310. codecs[participantId] = userCodecs;
  311. }
  312. } else {
  313. logger.error(`No participant ID returned by ${track}`);
  314. }
  315. }
  316. ssrcStats.resetBitrate();
  317. }
  318. this.conferenceStats.bitrate = {
  319. 'upload': bitrateUpload,
  320. 'download': bitrateDownload
  321. };
  322. this.conferenceStats.bitrate.audio = {
  323. 'upload': audioBitrateUpload,
  324. 'download': audioBitrateDownload
  325. };
  326. this.conferenceStats.bitrate.video = {
  327. 'upload': videoBitrateUpload,
  328. 'download': videoBitrateDownload
  329. };
  330. this.conferenceStats.packetLoss = {
  331. total:
  332. calculatePacketLoss(
  333. lostPackets.download + lostPackets.upload,
  334. totalPackets.download + totalPackets.upload),
  335. download:
  336. calculatePacketLoss(lostPackets.download, totalPackets.download),
  337. upload:
  338. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  339. };
  340. const avgAudioLevels = {};
  341. let localAvgAudioLevels;
  342. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  343. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  344. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  345. if (isLocal) {
  346. localAvgAudioLevels = avgAudioLevel;
  347. } else {
  348. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  349. if (track) {
  350. const participantId = track.getParticipantId();
  351. if (participantId) {
  352. avgAudioLevels[participantId] = avgAudioLevel;
  353. }
  354. }
  355. }
  356. });
  357. this.audioLevelReportHistory = {};
  358. this.eventEmitter.emit(
  359. StatisticsEvents.CONNECTION_STATS,
  360. this.peerconnection,
  361. {
  362. 'bandwidth': this.conferenceStats.bandwidth,
  363. 'bitrate': this.conferenceStats.bitrate,
  364. 'packetLoss': this.conferenceStats.packetLoss,
  365. 'resolution': resolutions,
  366. 'framerate': framerates,
  367. 'codec': codecs,
  368. 'transport': this.conferenceStats.transport,
  369. localAvgAudioLevels,
  370. avgAudioLevels
  371. });
  372. this.conferenceStats.transport = [];
  373. };
  374. /**
  375. * Converts the value to a non-negative number.
  376. * If the value is either invalid or negative then 0 will be returned.
  377. * @param {*} v
  378. * @return {number}
  379. * @private
  380. */
  381. StatsCollector.prototype.getNonNegativeValue = function(v) {
  382. let value = v;
  383. if (typeof value !== 'number') {
  384. value = Number(value);
  385. }
  386. if (isNaN(value)) {
  387. return 0;
  388. }
  389. return Math.max(0, value);
  390. };
  391. /**
  392. * Calculates bitrate between before and now using a supplied field name and its
  393. * value in the stats.
  394. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  395. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  396. * previous stats.
  397. * @param fieldName the field to use for calculations.
  398. * @return {number} the calculated bitrate between now and before.
  399. * @private
  400. */
  401. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  402. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  403. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  404. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  405. const timeMs = now.timestamp - before.timestamp;
  406. let bitrateKbps = 0;
  407. if (timeMs > 0) {
  408. // TODO is there any reason to round here?
  409. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  410. }
  411. return bitrateKbps;
  412. };
  413. /**
  414. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  415. */
  416. StatsCollector.prototype.processStatsReport = function() {
  417. if (!this.previousStatsReport) {
  418. return;
  419. }
  420. const byteSentStats = {};
  421. this.currentStatsReport.forEach(now => {
  422. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  423. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  424. const availableIncomingBitrate = now.availableIncomingBitrate;
  425. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  426. if (availableIncomingBitrate || availableOutgoingBitrate) {
  427. this.conferenceStats.bandwidth = {
  428. 'download': Math.round(availableIncomingBitrate / 1000),
  429. 'upload': Math.round(availableOutgoingBitrate / 1000)
  430. };
  431. }
  432. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  433. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  434. // RTCIceCandidateStats
  435. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  436. if (remoteUsedCandidate && localUsedCandidate) {
  437. const remoteIpAddress = browser.isChromiumBased()
  438. ? remoteUsedCandidate.ip
  439. : remoteUsedCandidate.address;
  440. const remotePort = remoteUsedCandidate.port;
  441. const ip = `${remoteIpAddress}:${remotePort}`;
  442. const localIpAddress = browser.isChromiumBased()
  443. ? localUsedCandidate.ip
  444. : localUsedCandidate.address;
  445. const localPort = localUsedCandidate.port;
  446. const localip = `${localIpAddress}:${localPort}`;
  447. const type = remoteUsedCandidate.protocol;
  448. // Save the address unless it has been saved already.
  449. const conferenceStatsTransport = this.conferenceStats.transport;
  450. if (!conferenceStatsTransport.some(t =>
  451. t.ip === ip
  452. && t.type === type
  453. && t.localip === localip)) {
  454. conferenceStatsTransport.push({
  455. ip,
  456. type,
  457. localip,
  458. p2p: this.peerconnection.isP2P,
  459. localCandidateType: localUsedCandidate.candidateType,
  460. remoteCandidateType: remoteUsedCandidate.candidateType,
  461. networkType: localUsedCandidate.networkType,
  462. rtt: now.currentRoundTripTime * 1000
  463. });
  464. }
  465. }
  466. // RTCReceivedRtpStreamStats
  467. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  468. // RTCSentRtpStreamStats
  469. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  470. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  471. const before = this.previousStatsReport.get(now.id);
  472. const ssrc = this.getNonNegativeValue(now.ssrc);
  473. if (!before || !ssrc) {
  474. return;
  475. }
  476. let ssrcStats = this.ssrc2stats.get(ssrc);
  477. if (!ssrcStats) {
  478. ssrcStats = new SsrcStats();
  479. this.ssrc2stats.set(ssrc, ssrcStats);
  480. }
  481. let isDownloadStream = true;
  482. let key = 'packetsReceived';
  483. if (now.type === 'outbound-rtp') {
  484. isDownloadStream = false;
  485. key = 'packetsSent';
  486. }
  487. let packetsNow = now[key];
  488. if (!packetsNow || packetsNow < 0) {
  489. packetsNow = 0;
  490. }
  491. const packetsBefore = this.getNonNegativeValue(before[key]);
  492. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  493. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  494. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  495. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  496. ssrcStats.setLoss({
  497. packetsTotal: packetsDiff + packetsLostDiff,
  498. packetsLost: packetsLostDiff,
  499. isDownloadStream
  500. });
  501. // Get the resolution and framerate for only remote video sources here. For the local video sources,
  502. // 'track' stats will be used since they have the updated resolution based on the simulcast streams
  503. // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be
  504. // more calculations needed to determine what is the highest resolution stream sent by the client if the
  505. // 'outbound-rtp' stats are used.
  506. if (now.type === 'inbound-rtp') {
  507. const resolution = {
  508. height: now.frameHeight,
  509. width: now.frameWidth
  510. };
  511. const frameRate = now.framesPerSecond;
  512. if (resolution.height && resolution.width) {
  513. ssrcStats.setResolution(resolution);
  514. }
  515. ssrcStats.setFramerate(Math.round(frameRate || 0));
  516. ssrcStats.addBitrate({
  517. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  518. 'upload': 0
  519. });
  520. } else {
  521. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  522. ssrcStats.addBitrate({
  523. 'download': 0,
  524. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  525. });
  526. }
  527. const codec = this.currentStatsReport.get(now.codecId);
  528. if (codec) {
  529. /**
  530. * The mime type has the following form: video/VP8 or audio/ISAC,
  531. * so we what to keep just the type after the '/', audio and video
  532. * keys will be added on the processing side.
  533. */
  534. const codecShortType = codec.mimeType.split('/')[1];
  535. codecShortType && ssrcStats.setCodec(codecShortType);
  536. }
  537. // Use track stats for resolution and framerate of the local video source.
  538. // RTCVideoHandlerStats - https://w3c.github.io/webrtc-stats/#vststats-dict*
  539. // RTCMediaHandlerStats - https://w3c.github.io/webrtc-stats/#mststats-dict*
  540. } else if (now.type === 'track' && now.kind === MediaType.VIDEO && !now.remoteSource) {
  541. const resolution = {
  542. height: now.frameHeight,
  543. width: now.frameWidth
  544. };
  545. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  546. if (!localVideoTracks?.length) {
  547. return;
  548. }
  549. const ssrc = this.peerconnection.getLocalSSRC(localVideoTracks[0]);
  550. if (!ssrc) {
  551. return;
  552. }
  553. let ssrcStats = this.ssrc2stats.get(ssrc);
  554. if (!ssrcStats) {
  555. ssrcStats = new SsrcStats();
  556. this.ssrc2stats.set(ssrc, ssrcStats);
  557. }
  558. if (resolution.height && resolution.width) {
  559. ssrcStats.setResolution(resolution);
  560. }
  561. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  562. // Therefore, it needs to be divided by the total number of active simulcast streams.
  563. let frameRate = now.framesPerSecond;
  564. if (!frameRate) {
  565. const before = this.previousStatsReport.get(now.id);
  566. if (before) {
  567. const timeMs = now.timestamp - before.timestamp;
  568. if (timeMs > 0 && now.framesSent) {
  569. const numberOfFramesSinceBefore = now.framesSent - before.framesSent;
  570. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  571. }
  572. }
  573. if (!frameRate) {
  574. return;
  575. }
  576. }
  577. // Get the number of simulcast streams currently enabled from TPC.
  578. const numberOfActiveStreams = this.peerconnection.getActiveSimulcastStreams();
  579. ssrcStats.setFramerate(Math.round((frameRate / numberOfActiveStreams) || 0));
  580. }
  581. });
  582. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  583. this._processAndEmitReport();
  584. };
  585. /**
  586. * Stats processing logic.
  587. */
  588. StatsCollector.prototype.processAudioLevelReport = function() {
  589. if (!this.baselineAudioLevelsReport) {
  590. return;
  591. }
  592. this.currentAudioLevelsReport.forEach(now => {
  593. if (now.type !== 'track') {
  594. return;
  595. }
  596. // Audio level
  597. const audioLevel = now.audioLevel;
  598. if (!audioLevel) {
  599. return;
  600. }
  601. const trackIdentifier = now.trackIdentifier;
  602. const ssrc = this.peerconnection.getSsrcByTrackId(trackIdentifier);
  603. if (ssrc) {
  604. const isLocal
  605. = ssrc === this.peerconnection.getLocalSSRC(
  606. this.peerconnection.getLocalTracks(MediaType.AUDIO));
  607. this.eventEmitter.emit(
  608. StatisticsEvents.AUDIO_LEVEL,
  609. this.peerconnection,
  610. ssrc,
  611. audioLevel,
  612. isLocal);
  613. }
  614. });
  615. };