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

RTPStatsCollector.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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 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 (lostPackets > 0 && totalPackets > 0) {
  16. return Math.round(lostPackets / totalPackets * 100);
  17. }
  18. return 0;
  19. }
  20. /**
  21. * Holds "statistics" for a single SSRC.
  22. * @constructor
  23. */
  24. function SsrcStats() {
  25. this.loss = {};
  26. this.bitrate = {
  27. download: 0,
  28. upload: 0
  29. };
  30. this.resolution = {};
  31. this.framerate = 0;
  32. this.codec = '';
  33. }
  34. /**
  35. * Sets the "loss" object.
  36. * @param loss the value to set.
  37. */
  38. SsrcStats.prototype.setLoss = function(loss) {
  39. this.loss = loss || {};
  40. };
  41. /**
  42. * Sets resolution that belong to the ssrc represented by this instance.
  43. * @param resolution new resolution value to be set.
  44. */
  45. SsrcStats.prototype.setResolution = function(resolution) {
  46. this.resolution = resolution || {};
  47. };
  48. /**
  49. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  50. * the respective fields of the "bitrate" field of this object.
  51. * @param bitrate an object holding the values to add.
  52. */
  53. SsrcStats.prototype.addBitrate = function(bitrate) {
  54. this.bitrate.download += bitrate.download;
  55. this.bitrate.upload += bitrate.upload;
  56. };
  57. /**
  58. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  59. * represented by this instance.
  60. */
  61. SsrcStats.prototype.resetBitrate = function() {
  62. this.bitrate.download = 0;
  63. this.bitrate.upload = 0;
  64. };
  65. /**
  66. * Sets the "framerate".
  67. * @param framerate the value to set.
  68. */
  69. SsrcStats.prototype.setFramerate = function(framerate) {
  70. this.framerate = framerate || 0;
  71. };
  72. SsrcStats.prototype.setCodec = function(codec) {
  73. this.codec = codec || '';
  74. };
  75. /**
  76. *
  77. */
  78. function ConferenceStats() {
  79. /**
  80. * The bandwidth
  81. * @type {{}}
  82. */
  83. this.bandwidth = {};
  84. /**
  85. * The bit rate
  86. * @type {{}}
  87. */
  88. this.bitrate = {};
  89. /**
  90. * The packet loss rate
  91. * @type {{}}
  92. */
  93. this.packetLoss = null;
  94. /**
  95. * Array with the transport information.
  96. * @type {Array}
  97. */
  98. this.transport = [];
  99. }
  100. /* eslint-disable max-params */
  101. /**
  102. * <tt>StatsCollector</tt> registers for stats updates of given
  103. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  104. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  105. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  106. * instance as an event source.
  107. *
  108. * @param peerconnection WebRTC PeerConnection object.
  109. * @param audioLevelsInterval
  110. * @param statsInterval stats refresh interval given in ms.
  111. * @param eventEmitter
  112. * @constructor
  113. */
  114. export default function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter) {
  115. this.peerconnection = peerconnection;
  116. this.currentStatsReport = null;
  117. this.previousStatsReport = null;
  118. this.audioLevelReportHistory = {};
  119. this.audioLevelsIntervalId = null;
  120. this.eventEmitter = eventEmitter;
  121. this.conferenceStats = new ConferenceStats();
  122. // Updates stats interval
  123. this.audioLevelsIntervalMilis = audioLevelsInterval;
  124. this.speakerList = [];
  125. this.statsIntervalId = null;
  126. this.statsIntervalMilis = statsInterval;
  127. /**
  128. * Maps SSRC numbers to {@link SsrcStats}.
  129. * @type {Map<number,SsrcStats}
  130. */
  131. this.ssrc2stats = new Map();
  132. }
  133. /**
  134. * Set the list of the remote speakers for which audio levels are to be calculated.
  135. *
  136. * @param {Array<string>} speakerList - Endpoint ids.
  137. * @returns {void}
  138. */
  139. StatsCollector.prototype.setSpeakerList = function(speakerList) {
  140. this.speakerList = speakerList;
  141. };
  142. /**
  143. * Stops stats updates.
  144. */
  145. StatsCollector.prototype.stop = function() {
  146. if (this.audioLevelsIntervalId) {
  147. clearInterval(this.audioLevelsIntervalId);
  148. this.audioLevelsIntervalId = null;
  149. }
  150. if (this.statsIntervalId) {
  151. clearInterval(this.statsIntervalId);
  152. this.statsIntervalId = null;
  153. }
  154. };
  155. /**
  156. * Callback passed to <tt>getStats</tt> method.
  157. * @param error an error that occurred on <tt>getStats</tt> call.
  158. */
  159. StatsCollector.prototype.errorCallback = function(error) {
  160. logger.error('Get stats error', error);
  161. this.stop();
  162. };
  163. /**
  164. * Starts stats updates.
  165. */
  166. StatsCollector.prototype.start = function(startAudioLevelStats) {
  167. if (startAudioLevelStats && browser.supportsReceiverStats()) {
  168. this.audioLevelsIntervalId = setInterval(
  169. () => {
  170. const audioLevels = this.peerconnection.getAudioLevels(this.speakerList);
  171. for (const ssrc in audioLevels) {
  172. if (audioLevels.hasOwnProperty(ssrc)) {
  173. // Use a scaling factor of 2.5 to report the same audio levels that getStats reports.
  174. const audioLevel = audioLevels[ssrc] * 2.5;
  175. this.eventEmitter.emit(
  176. StatisticsEvents.AUDIO_LEVEL,
  177. this.peerconnection,
  178. Number.parseInt(ssrc, 10),
  179. audioLevel,
  180. false /* isLocal */);
  181. }
  182. }
  183. },
  184. this.audioLevelsIntervalMilis
  185. );
  186. }
  187. const processStats = () => {
  188. // Interval updates
  189. this.peerconnection.getStats()
  190. .then(report => {
  191. this.currentStatsReport = typeof report?.result === 'function'
  192. ? report.result()
  193. : report;
  194. try {
  195. this.processStatsReport();
  196. } catch (error) {
  197. logger.error('Processing of RTP stats failed:', error);
  198. }
  199. this.previousStatsReport = this.currentStatsReport;
  200. })
  201. .catch(error => this.errorCallback(error));
  202. };
  203. processStats();
  204. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  205. };
  206. /**
  207. *
  208. */
  209. StatsCollector.prototype._processAndEmitReport = function() {
  210. // process stats
  211. const totalPackets = {
  212. download: 0,
  213. upload: 0
  214. };
  215. const lostPackets = {
  216. download: 0,
  217. upload: 0
  218. };
  219. let bitrateDownload = 0;
  220. let bitrateUpload = 0;
  221. const resolutions = {};
  222. const framerates = {};
  223. const codecs = {};
  224. let audioBitrateDownload = 0;
  225. let audioBitrateUpload = 0;
  226. let videoBitrateDownload = 0;
  227. let videoBitrateUpload = 0;
  228. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  229. // process packet loss stats
  230. const loss = ssrcStats.loss;
  231. const type = loss.isDownloadStream ? 'download' : 'upload';
  232. totalPackets[type] += loss.packetsTotal;
  233. lostPackets[type] += loss.packetsLost;
  234. const ssrcBitrateDownload = ssrcStats.bitrate.download;
  235. const ssrcBitrateUpload = ssrcStats.bitrate.upload;
  236. // process bitrate stats
  237. bitrateDownload += ssrcBitrateDownload;
  238. bitrateUpload += ssrcBitrateUpload;
  239. ssrcStats.resetBitrate();
  240. // collect resolutions and framerates
  241. const track = this.peerconnection.getTrackBySSRC(ssrc);
  242. if (!track) {
  243. continue; // eslint-disable-line no-continue
  244. }
  245. let audioCodec;
  246. let videoCodec;
  247. if (track.isAudioTrack()) {
  248. audioBitrateDownload += ssrcBitrateDownload;
  249. audioBitrateUpload += ssrcBitrateUpload;
  250. audioCodec = ssrcStats.codec;
  251. } else {
  252. videoBitrateDownload += ssrcBitrateDownload;
  253. videoBitrateUpload += ssrcBitrateUpload;
  254. videoCodec = ssrcStats.codec;
  255. }
  256. const participantId = track.getParticipantId();
  257. if (!participantId) {
  258. // All tracks in ssrc-rewriting mode need not have a participant associated with it.
  259. if (!FeatureFlags.isSsrcRewritingSupported()) {
  260. logger.error(`No participant ID returned by ${track}`);
  261. }
  262. continue; // eslint-disable-line no-continue
  263. }
  264. const userCodecs = codecs[participantId] ?? { };
  265. userCodecs[ssrc] = {
  266. audio: audioCodec,
  267. video: videoCodec
  268. };
  269. codecs[participantId] = userCodecs;
  270. const { resolution } = ssrcStats;
  271. if (!track.isVideoTrack()
  272. || isNaN(resolution?.height)
  273. || isNaN(resolution?.width)
  274. || resolution.height === -1
  275. || resolution.width === -1) {
  276. continue; // eslint-disable-line no-continue
  277. }
  278. const userResolutions = resolutions[participantId] || {};
  279. // If simulcast (VP8) is used, there will be 3 "outbound-rtp" streams with different resolutions and 3
  280. // different SSRCs. Based on the requested resolution and the current cpu and available bandwidth
  281. // values, some of the streams might get suspended. Therefore the actual send resolution needs to be
  282. // calculated based on the outbound-rtp streams that are currently active for the simulcast case.
  283. // However for the SVC case, there will be only 1 "outbound-rtp" stream which will have the correct
  284. // send resolution width and height.
  285. if (track.isLocal() && !browser.supportsTrackBasedStats() && this.peerconnection.doesTrueSimulcast()) {
  286. const localSsrcs = this.peerconnection.getLocalVideoSSRCs(track);
  287. for (const localSsrc of localSsrcs) {
  288. const ssrcResolution = this.ssrc2stats.get(localSsrc)?.resolution;
  289. // The code processes resolution stats only for 'outbound-rtp' streams that are currently active.
  290. if (ssrcResolution?.height && ssrcResolution?.width) {
  291. resolution.height = Math.max(resolution.height, ssrcResolution.height);
  292. resolution.width = Math.max(resolution.width, ssrcResolution.width);
  293. }
  294. }
  295. }
  296. userResolutions[ssrc] = resolution;
  297. resolutions[participantId] = userResolutions;
  298. if (ssrcStats.framerate > 0) {
  299. const userFramerates = framerates[participantId] || {};
  300. userFramerates[ssrc] = ssrcStats.framerate;
  301. framerates[participantId] = userFramerates;
  302. }
  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. * Calculates the frames per second rate between before and now using a supplied field name and its value in stats.
  401. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  402. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} before the previous stats
  403. * @param {string} fieldName the field to use for calculations.
  404. * @returns {number} the calculated frame rate between now and before.
  405. */
  406. StatsCollector.prototype._calculateFps = function(now, before, fieldName) {
  407. const timeMs = now.timestamp - before.timestamp;
  408. let frameRate = 0;
  409. if (timeMs > 0 && now[fieldName]) {
  410. const numberOfFramesSinceBefore = now[fieldName] - before[fieldName];
  411. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  412. }
  413. return frameRate;
  414. };
  415. /**
  416. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  417. */
  418. StatsCollector.prototype.processStatsReport = function() {
  419. const byteSentStats = {};
  420. this.currentStatsReport.forEach(now => {
  421. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  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 ssrc = this.getNonNegativeValue(now.ssrc);
  472. if (!ssrc) {
  473. return;
  474. }
  475. let ssrcStats = this.ssrc2stats.get(ssrc);
  476. if (!ssrcStats) {
  477. ssrcStats = new SsrcStats();
  478. this.ssrc2stats.set(ssrc, ssrcStats);
  479. }
  480. let isDownloadStream = true;
  481. let key = 'packetsReceived';
  482. if (now.type === 'outbound-rtp') {
  483. isDownloadStream = false;
  484. key = 'packetsSent';
  485. }
  486. let packetsNow = now[key];
  487. if (!packetsNow || packetsNow < 0) {
  488. packetsNow = 0;
  489. }
  490. if (before) {
  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. }
  502. let resolution;
  503. // Process the stats for 'inbound-rtp' streams always and 'outbound-rtp' only if the browser is
  504. // Chromium based and version 112 and later since 'track' based stats are no longer available there
  505. // for calculating send resolution and frame rate.
  506. if (typeof now.frameHeight !== 'undefined' && typeof now.frameWidth !== 'undefined') {
  507. // Assume the stream is active if the field is missing in the stats(Firefox)
  508. const isStreamActive = now.active ?? true;
  509. if (now.type === 'inbound-rtp' || (!browser.supportsTrackBasedStats() && isStreamActive)) {
  510. resolution = {
  511. height: now.frameHeight,
  512. width: now.frameWidth
  513. };
  514. }
  515. }
  516. ssrcStats.setResolution(resolution);
  517. let frameRate = now.framesPerSecond;
  518. if (!frameRate && before) {
  519. frameRate = this._calculateFps(now, before, 'framesSent');
  520. }
  521. ssrcStats.setFramerate(Math.round(frameRate || 0));
  522. if (now.type === 'inbound-rtp' && before) {
  523. ssrcStats.addBitrate({
  524. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  525. 'upload': 0
  526. });
  527. } else if (before) {
  528. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  529. ssrcStats.addBitrate({
  530. 'download': 0,
  531. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  532. });
  533. }
  534. const codec = this.currentStatsReport.get(now.codecId);
  535. if (codec) {
  536. /**
  537. * The mime type has the following form: video/VP8 or audio/ISAC,
  538. * so we what to keep just the type after the '/', audio and video
  539. * keys will be added on the processing side.
  540. */
  541. const codecShortType = codec.mimeType.split('/')[1];
  542. codecShortType && ssrcStats.setCodec(codecShortType);
  543. }
  544. // Continue to use the 'track' based stats for Firefox and Safari and older versions of Chromium.
  545. } else if (browser.supportsTrackBasedStats()
  546. && now.type === 'track'
  547. && now.kind === MediaType.VIDEO
  548. && !now.remoteSource) {
  549. const resolution = {
  550. height: now.frameHeight,
  551. width: now.frameWidth
  552. };
  553. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  554. if (!localVideoTracks?.length) {
  555. return;
  556. }
  557. const ssrc = this.peerconnection.getSsrcByTrackId(now.trackIdentifier);
  558. if (!ssrc) {
  559. return;
  560. }
  561. let ssrcStats = this.ssrc2stats.get(ssrc);
  562. if (!ssrcStats) {
  563. ssrcStats = new SsrcStats();
  564. this.ssrc2stats.set(ssrc, ssrcStats);
  565. }
  566. if (resolution.height && resolution.width) {
  567. ssrcStats.setResolution(resolution);
  568. }
  569. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  570. // Therefore, it needs to be divided by the total number of active simulcast streams.
  571. let frameRate = now.framesPerSecond;
  572. if (!frameRate && before) {
  573. frameRate = this._calculateFps(now, before, 'framesSent');
  574. }
  575. ssrcStats.setFramerate(frameRate);
  576. }
  577. });
  578. if (Object.keys(byteSentStats).length) {
  579. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  580. }
  581. this._processAndEmitReport();
  582. };