Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTPStatsCollector.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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.currentStatsReport = null;
  119. this.previousStatsReport = null;
  120. this.audioLevelReportHistory = {};
  121. this.audioLevelsIntervalId = null;
  122. this.eventEmitter = eventEmitter;
  123. this.conferenceStats = new ConferenceStats();
  124. // Updates stats interval
  125. this.audioLevelsIntervalMilis = audioLevelsInterval;
  126. this.speakerList = [];
  127. this.statsIntervalId = null;
  128. this.statsIntervalMilis = statsInterval;
  129. /**
  130. * Maps SSRC numbers to {@link SsrcStats}.
  131. * @type {Map<number,SsrcStats}
  132. */
  133. this.ssrc2stats = new Map();
  134. }
  135. /**
  136. * Set the list of the remote speakers for which audio levels are to be calculated.
  137. *
  138. * @param {Array<string>} speakerList - Endpoint ids.
  139. * @returns {void}
  140. */
  141. StatsCollector.prototype.setSpeakerList = function(speakerList) {
  142. this.speakerList = speakerList;
  143. };
  144. /**
  145. * Stops stats updates.
  146. */
  147. StatsCollector.prototype.stop = function() {
  148. if (this.audioLevelsIntervalId) {
  149. clearInterval(this.audioLevelsIntervalId);
  150. this.audioLevelsIntervalId = null;
  151. }
  152. if (this.statsIntervalId) {
  153. clearInterval(this.statsIntervalId);
  154. this.statsIntervalId = null;
  155. }
  156. };
  157. /**
  158. * Callback passed to <tt>getStats</tt> method.
  159. * @param error an error that occurred on <tt>getStats</tt> call.
  160. */
  161. StatsCollector.prototype.errorCallback = function(error) {
  162. GlobalOnErrorHandler.callErrorHandler(error);
  163. logger.error('Get stats error', error);
  164. this.stop();
  165. };
  166. /**
  167. * Starts stats updates.
  168. */
  169. StatsCollector.prototype.start = function(startAudioLevelStats) {
  170. if (startAudioLevelStats && browser.supportsReceiverStats()) {
  171. this.audioLevelsIntervalId = setInterval(
  172. () => {
  173. const audioLevels = this.peerconnection.getAudioLevels(this.speakerList);
  174. for (const ssrc in audioLevels) {
  175. if (audioLevels.hasOwnProperty(ssrc)) {
  176. // Use a scaling factor of 2.5 to report the same audio levels that getStats reports.
  177. const audioLevel = audioLevels[ssrc] * 2.5;
  178. this.eventEmitter.emit(
  179. StatisticsEvents.AUDIO_LEVEL,
  180. this.peerconnection,
  181. Number.parseInt(ssrc, 10),
  182. audioLevel,
  183. false /* isLocal */);
  184. }
  185. }
  186. },
  187. this.audioLevelsIntervalMilis
  188. );
  189. }
  190. const processStats = () => {
  191. // Interval updates
  192. this.peerconnection.getStats()
  193. .then(report => {
  194. this.currentStatsReport = typeof report?.result === 'function'
  195. ? report.result()
  196. : report;
  197. try {
  198. this.processStatsReport();
  199. } catch (error) {
  200. GlobalOnErrorHandler.callErrorHandler(error);
  201. logger.error('Processing of RTP stats failed:', error);
  202. }
  203. this.previousStatsReport = this.currentStatsReport;
  204. })
  205. .catch(error => this.errorCallback(error));
  206. };
  207. processStats();
  208. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  209. };
  210. /**
  211. *
  212. */
  213. StatsCollector.prototype._processAndEmitReport = function() {
  214. // process stats
  215. const totalPackets = {
  216. download: 0,
  217. upload: 0
  218. };
  219. const lostPackets = {
  220. download: 0,
  221. upload: 0
  222. };
  223. let bitrateDownload = 0;
  224. let bitrateUpload = 0;
  225. const resolutions = {};
  226. const framerates = {};
  227. const codecs = {};
  228. let audioBitrateDownload = 0;
  229. let audioBitrateUpload = 0;
  230. let videoBitrateDownload = 0;
  231. let videoBitrateUpload = 0;
  232. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  233. // process packet loss stats
  234. const loss = ssrcStats.loss;
  235. const type = loss.isDownloadStream ? 'download' : 'upload';
  236. totalPackets[type] += loss.packetsTotal;
  237. lostPackets[type] += loss.packetsLost;
  238. // process bitrate stats
  239. bitrateDownload += ssrcStats.bitrate.download;
  240. bitrateUpload += ssrcStats.bitrate.upload;
  241. ssrcStats.resetBitrate();
  242. // collect resolutions and framerates
  243. const track = this.peerconnection.getTrackBySSRC(ssrc);
  244. if (!track) {
  245. continue; // eslint-disable-line no-continue
  246. }
  247. let audioCodec;
  248. let videoCodec;
  249. if (track.isAudioTrack()) {
  250. audioBitrateDownload += ssrcStats.bitrate.download;
  251. audioBitrateUpload += ssrcStats.bitrate.upload;
  252. audioCodec = ssrcStats.codec;
  253. } else {
  254. videoBitrateDownload += ssrcStats.bitrate.download;
  255. videoBitrateUpload += ssrcStats.bitrate.upload;
  256. videoCodec = ssrcStats.codec;
  257. }
  258. const participantId = track.getParticipantId();
  259. if (!participantId) {
  260. // All tracks in ssrc-rewriting mode need not have a participant associated with it.
  261. if (!FeatureFlags.isSsrcRewritingSupported()) {
  262. logger.error(`No participant ID returned by ${track}`);
  263. }
  264. continue; // eslint-disable-line no-continue
  265. }
  266. const userCodecs = codecs[participantId] ?? { };
  267. userCodecs[ssrc] = {
  268. audio: audioCodec,
  269. video: videoCodec
  270. };
  271. codecs[participantId] = userCodecs;
  272. const { resolution } = ssrcStats;
  273. if (!track.isVideoTrack()
  274. || isNaN(resolution?.height)
  275. || isNaN(resolution?.width)
  276. || resolution.height === -1
  277. || resolution.width === -1) {
  278. continue; // eslint-disable-line no-continue
  279. }
  280. const userResolutions = resolutions[participantId] || {};
  281. // If simulcast (VP8) is used, there will be 3 "outbound-rtp" streams with different resolutions and 3
  282. // different SSRCs. Based on the requested resolution and the current cpu and available bandwidth
  283. // values, some of the streams might get suspended. Therefore the actual send resolution needs to be
  284. // calculated based on the outbound-rtp streams that are currently active for the simulcast case.
  285. // However for the SVC case, there will be only 1 "outbound-rtp" stream which will have the correct
  286. // send resolution width and height.
  287. if (track.isLocal() && !browser.supportsTrackBasedStats() && this.peerconnection.doesTrueSimulcast()) {
  288. const localSsrcs = this.peerconnection.getLocalVideoSSRCs(track);
  289. for (const localSsrc of localSsrcs) {
  290. const ssrcResolution = this.ssrc2stats.get(localSsrc)?.resolution;
  291. // The code processes resolution stats only for 'outbound-rtp' streams that are currently active.
  292. if (ssrcResolution?.height && ssrcResolution?.width) {
  293. resolution.height = Math.max(resolution.height, ssrcResolution.height);
  294. resolution.width = Math.max(resolution.width, ssrcResolution.width);
  295. }
  296. }
  297. }
  298. userResolutions[ssrc] = resolution;
  299. resolutions[participantId] = userResolutions;
  300. if (ssrcStats.framerate > 0) {
  301. const userFramerates = framerates[participantId] || {};
  302. userFramerates[ssrc] = ssrcStats.framerate;
  303. framerates[participantId] = userFramerates;
  304. }
  305. }
  306. this.conferenceStats.bitrate = {
  307. 'upload': bitrateUpload,
  308. 'download': bitrateDownload
  309. };
  310. this.conferenceStats.bitrate.audio = {
  311. 'upload': audioBitrateUpload,
  312. 'download': audioBitrateDownload
  313. };
  314. this.conferenceStats.bitrate.video = {
  315. 'upload': videoBitrateUpload,
  316. 'download': videoBitrateDownload
  317. };
  318. this.conferenceStats.packetLoss = {
  319. total:
  320. calculatePacketLoss(
  321. lostPackets.download + lostPackets.upload,
  322. totalPackets.download + totalPackets.upload),
  323. download:
  324. calculatePacketLoss(lostPackets.download, totalPackets.download),
  325. upload:
  326. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  327. };
  328. const avgAudioLevels = {};
  329. let localAvgAudioLevels;
  330. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  331. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  332. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  333. if (isLocal) {
  334. localAvgAudioLevels = avgAudioLevel;
  335. } else {
  336. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  337. if (track) {
  338. const participantId = track.getParticipantId();
  339. if (participantId) {
  340. avgAudioLevels[participantId] = avgAudioLevel;
  341. }
  342. }
  343. }
  344. });
  345. this.audioLevelReportHistory = {};
  346. this.eventEmitter.emit(
  347. StatisticsEvents.CONNECTION_STATS,
  348. this.peerconnection,
  349. {
  350. 'bandwidth': this.conferenceStats.bandwidth,
  351. 'bitrate': this.conferenceStats.bitrate,
  352. 'packetLoss': this.conferenceStats.packetLoss,
  353. 'resolution': resolutions,
  354. 'framerate': framerates,
  355. 'codec': codecs,
  356. 'transport': this.conferenceStats.transport,
  357. localAvgAudioLevels,
  358. avgAudioLevels
  359. });
  360. this.conferenceStats.transport = [];
  361. };
  362. /**
  363. * Converts the value to a non-negative number.
  364. * If the value is either invalid or negative then 0 will be returned.
  365. * @param {*} v
  366. * @return {number}
  367. * @private
  368. */
  369. StatsCollector.prototype.getNonNegativeValue = function(v) {
  370. let value = v;
  371. if (typeof value !== 'number') {
  372. value = Number(value);
  373. }
  374. if (isNaN(value)) {
  375. return 0;
  376. }
  377. return Math.max(0, value);
  378. };
  379. /**
  380. * Calculates bitrate between before and now using a supplied field name and its
  381. * value in the stats.
  382. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  383. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  384. * previous stats.
  385. * @param fieldName the field to use for calculations.
  386. * @return {number} the calculated bitrate between now and before.
  387. * @private
  388. */
  389. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  390. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  391. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  392. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  393. const timeMs = now.timestamp - before.timestamp;
  394. let bitrateKbps = 0;
  395. if (timeMs > 0) {
  396. // TODO is there any reason to round here?
  397. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  398. }
  399. return bitrateKbps;
  400. };
  401. /**
  402. * Calculates the frames per second rate between before and now using a supplied field name and its value in stats.
  403. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  404. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} before the previous stats
  405. * @param {string} fieldName the field to use for calculations.
  406. * @returns {number} the calculated frame rate between now and before.
  407. */
  408. StatsCollector.prototype._calculateFps = function(now, before, fieldName) {
  409. const timeMs = now.timestamp - before.timestamp;
  410. let frameRate = 0;
  411. if (timeMs > 0 && now[fieldName]) {
  412. const numberOfFramesSinceBefore = now[fieldName] - before[fieldName];
  413. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  414. }
  415. return frameRate;
  416. };
  417. /**
  418. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  419. */
  420. StatsCollector.prototype.processStatsReport = function() {
  421. const byteSentStats = {};
  422. this.currentStatsReport.forEach(now => {
  423. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  424. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  425. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  426. const availableIncomingBitrate = now.availableIncomingBitrate;
  427. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  428. if (availableIncomingBitrate || availableOutgoingBitrate) {
  429. this.conferenceStats.bandwidth = {
  430. 'download': Math.round(availableIncomingBitrate / 1000),
  431. 'upload': Math.round(availableOutgoingBitrate / 1000)
  432. };
  433. }
  434. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  435. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  436. // RTCIceCandidateStats
  437. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  438. if (remoteUsedCandidate && localUsedCandidate) {
  439. const remoteIpAddress = browser.isChromiumBased()
  440. ? remoteUsedCandidate.ip
  441. : remoteUsedCandidate.address;
  442. const remotePort = remoteUsedCandidate.port;
  443. const ip = `${remoteIpAddress}:${remotePort}`;
  444. const localIpAddress = browser.isChromiumBased()
  445. ? localUsedCandidate.ip
  446. : localUsedCandidate.address;
  447. const localPort = localUsedCandidate.port;
  448. const localip = `${localIpAddress}:${localPort}`;
  449. const type = remoteUsedCandidate.protocol;
  450. // Save the address unless it has been saved already.
  451. const conferenceStatsTransport = this.conferenceStats.transport;
  452. if (!conferenceStatsTransport.some(t =>
  453. t.ip === ip
  454. && t.type === type
  455. && t.localip === localip)) {
  456. conferenceStatsTransport.push({
  457. ip,
  458. type,
  459. localip,
  460. p2p: this.peerconnection.isP2P,
  461. localCandidateType: localUsedCandidate.candidateType,
  462. remoteCandidateType: remoteUsedCandidate.candidateType,
  463. networkType: localUsedCandidate.networkType,
  464. rtt: now.currentRoundTripTime * 1000
  465. });
  466. }
  467. }
  468. // RTCReceivedRtpStreamStats
  469. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  470. // RTCSentRtpStreamStats
  471. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  472. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  473. const ssrc = this.getNonNegativeValue(now.ssrc);
  474. if (!ssrc) {
  475. return;
  476. }
  477. let ssrcStats = this.ssrc2stats.get(ssrc);
  478. if (!ssrcStats) {
  479. ssrcStats = new SsrcStats();
  480. this.ssrc2stats.set(ssrc, ssrcStats);
  481. }
  482. let isDownloadStream = true;
  483. let key = 'packetsReceived';
  484. if (now.type === 'outbound-rtp') {
  485. isDownloadStream = false;
  486. key = 'packetsSent';
  487. }
  488. let packetsNow = now[key];
  489. if (!packetsNow || packetsNow < 0) {
  490. packetsNow = 0;
  491. }
  492. if (before) {
  493. const packetsBefore = this.getNonNegativeValue(before[key]);
  494. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  495. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  496. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  497. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  498. ssrcStats.setLoss({
  499. packetsTotal: packetsDiff + packetsLostDiff,
  500. packetsLost: packetsLostDiff,
  501. isDownloadStream
  502. });
  503. }
  504. let resolution;
  505. // Process the stats for 'inbound-rtp' streams always and 'outbound-rtp' only if the browser is
  506. // Chromium based and version 112 and later since 'track' based stats are no longer available there
  507. // for calculating send resolution and frame rate.
  508. if (typeof now.frameHeight !== 'undefined' && typeof now.frameWidth !== 'undefined') {
  509. // Assume the stream is active if the field is missing in the stats(Firefox)
  510. const isStreamActive = now.active ?? true;
  511. if (now.type === 'inbound-rtp' || (!browser.supportsTrackBasedStats() && isStreamActive)) {
  512. resolution = {
  513. height: now.frameHeight,
  514. width: now.frameWidth
  515. };
  516. }
  517. }
  518. ssrcStats.setResolution(resolution);
  519. let frameRate = now.framesPerSecond;
  520. if (!frameRate && before) {
  521. frameRate = this._calculateFps(now, before, 'framesSent');
  522. }
  523. ssrcStats.setFramerate(Math.round(frameRate || 0));
  524. if (now.type === 'inbound-rtp' && before) {
  525. ssrcStats.addBitrate({
  526. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  527. 'upload': 0
  528. });
  529. } else if (before) {
  530. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  531. ssrcStats.addBitrate({
  532. 'download': 0,
  533. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  534. });
  535. }
  536. const codec = this.currentStatsReport.get(now.codecId);
  537. if (codec) {
  538. /**
  539. * The mime type has the following form: video/VP8 or audio/ISAC,
  540. * so we what to keep just the type after the '/', audio and video
  541. * keys will be added on the processing side.
  542. */
  543. const codecShortType = codec.mimeType.split('/')[1];
  544. codecShortType && ssrcStats.setCodec(codecShortType);
  545. }
  546. // Continue to use the 'track' based stats for Firefox and Safari and older versions of Chromium.
  547. } else if (browser.supportsTrackBasedStats()
  548. && now.type === 'track'
  549. && now.kind === MediaType.VIDEO
  550. && !now.remoteSource) {
  551. const resolution = {
  552. height: now.frameHeight,
  553. width: now.frameWidth
  554. };
  555. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  556. if (!localVideoTracks?.length) {
  557. return;
  558. }
  559. const ssrc = this.peerconnection.getSsrcByTrackId(now.trackIdentifier);
  560. if (!ssrc) {
  561. return;
  562. }
  563. let ssrcStats = this.ssrc2stats.get(ssrc);
  564. if (!ssrcStats) {
  565. ssrcStats = new SsrcStats();
  566. this.ssrc2stats.set(ssrc, ssrcStats);
  567. }
  568. if (resolution.height && resolution.width) {
  569. ssrcStats.setResolution(resolution);
  570. }
  571. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  572. // Therefore, it needs to be divided by the total number of active simulcast streams.
  573. let frameRate = now.framesPerSecond;
  574. if (!frameRate && before) {
  575. frameRate = this._calculateFps(now, before, 'framesSent');
  576. }
  577. ssrcStats.setFramerate(frameRate);
  578. }
  579. });
  580. if (Object.keys(byteSentStats).length) {
  581. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  582. }
  583. this._processAndEmitReport();
  584. };