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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. import { isValidNumber } from '../util/MathUtil';
  7. const logger = getLogger('modules/statistics/RTPStatsCollector');
  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 (lostPackets > 0 && totalPackets > 0) {
  17. return Math.round(lostPackets / totalPackets * 100);
  18. }
  19. return 0;
  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. SsrcStats.prototype.setEncodeStats = function(encodeStats) {
  77. this.encodeStats = encodeStats || {};
  78. };
  79. /**
  80. *
  81. */
  82. function ConferenceStats() {
  83. /**
  84. * The bandwidth
  85. * @type {{}}
  86. */
  87. this.bandwidth = {};
  88. /**
  89. * The bit rate
  90. * @type {{}}
  91. */
  92. this.bitrate = {};
  93. /**
  94. * The packet loss rate
  95. * @type {{}}
  96. */
  97. this.packetLoss = null;
  98. /**
  99. * Array with the transport information.
  100. * @type {Array}
  101. */
  102. this.transport = [];
  103. }
  104. /* eslint-disable max-params */
  105. /**
  106. * <tt>StatsCollector</tt> registers for stats updates of given
  107. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  108. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  109. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  110. * instance as an event source.
  111. *
  112. * @param peerconnection WebRTC PeerConnection object.
  113. * @param audioLevelsInterval
  114. * @param statsInterval stats refresh interval given in ms.
  115. * @param eventEmitter
  116. * @constructor
  117. */
  118. export default function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter) {
  119. this.peerconnection = peerconnection;
  120. this.currentStatsReport = null;
  121. this.previousStatsReport = null;
  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. 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. logger.error('Processing of RTP stats failed:', error);
  201. }
  202. this.previousStatsReport = this.currentStatsReport;
  203. })
  204. .catch(error => this.errorCallback(error));
  205. };
  206. processStats();
  207. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  208. };
  209. /**
  210. *
  211. */
  212. StatsCollector.prototype._processAndEmitReport = function() {
  213. // process stats
  214. const totalPackets = {
  215. download: 0,
  216. upload: 0
  217. };
  218. const lostPackets = {
  219. download: 0,
  220. upload: 0
  221. };
  222. let bitrateDownload = 0;
  223. let bitrateUpload = 0;
  224. const resolutions = {};
  225. const framerates = {};
  226. const codecs = {};
  227. let audioBitrateDownload = 0;
  228. let audioBitrateUpload = 0;
  229. let videoBitrateDownload = 0;
  230. let videoBitrateUpload = 0;
  231. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  232. // process packet loss stats
  233. const loss = ssrcStats.loss;
  234. const type = loss.isDownloadStream ? 'download' : 'upload';
  235. totalPackets[type] += loss.packetsTotal;
  236. lostPackets[type] += loss.packetsLost;
  237. const ssrcBitrateDownload = ssrcStats.bitrate.download;
  238. const ssrcBitrateUpload = ssrcStats.bitrate.upload;
  239. // process bitrate stats
  240. bitrateDownload += ssrcBitrateDownload;
  241. bitrateUpload += ssrcBitrateUpload;
  242. ssrcStats.resetBitrate();
  243. // collect resolutions and framerates
  244. const track = this.peerconnection.getTrackBySSRC(ssrc);
  245. if (!track) {
  246. continue; // eslint-disable-line no-continue
  247. }
  248. let audioCodec;
  249. let videoCodec;
  250. if (track.isAudioTrack()) {
  251. audioBitrateDownload += ssrcBitrateDownload;
  252. audioBitrateUpload += ssrcBitrateUpload;
  253. audioCodec = ssrcStats.codec;
  254. } else {
  255. videoBitrateDownload += ssrcBitrateDownload;
  256. videoBitrateUpload += ssrcBitrateUpload;
  257. videoCodec = ssrcStats.codec;
  258. }
  259. const participantId = track.getParticipantId();
  260. if (!participantId) {
  261. // All tracks in ssrc-rewriting mode need not have a participant associated with it.
  262. if (!FeatureFlags.isSsrcRewritingSupported()) {
  263. logger.error(`No participant ID returned by ${track}`);
  264. }
  265. continue;
  266. }
  267. const userCodecs = codecs[participantId] ?? { };
  268. userCodecs[ssrc] = {
  269. audio: audioCodec,
  270. video: videoCodec
  271. };
  272. codecs[participantId] = userCodecs;
  273. const { resolution } = ssrcStats;
  274. if (!track.isVideoTrack()
  275. || !isValidNumber(resolution?.height)
  276. || !isValidNumber(resolution?.width)
  277. || resolution.height === -1
  278. || resolution.width === -1) {
  279. continue;
  280. }
  281. const userResolutions = resolutions[participantId] || {};
  282. // If simulcast (VP8) is used, there will be 3 "outbound-rtp" streams with different resolutions and 3
  283. // different SSRCs. Based on the requested resolution and the current cpu and available bandwidth
  284. // values, some of the streams might get suspended. Therefore the actual send resolution needs to be
  285. // calculated based on the outbound-rtp streams that are currently active for the simulcast case.
  286. // However for the SVC case, there will be only 1 "outbound-rtp" stream which will have the correct
  287. // send resolution width and height.
  288. if (track.isLocal() && !browser.supportsTrackBasedStats() && this.peerconnection.doesTrueSimulcast(track)) {
  289. const localSsrcs = this.peerconnection.getLocalVideoSSRCs(track);
  290. for (const localSsrc of localSsrcs) {
  291. const ssrcResolution = this.ssrc2stats.get(localSsrc)?.resolution;
  292. // The code processes resolution stats only for 'outbound-rtp' streams that are currently active.
  293. if (ssrcResolution?.height && ssrcResolution?.width) {
  294. resolution.height = Math.max(resolution.height, ssrcResolution.height);
  295. resolution.width = Math.max(resolution.width, ssrcResolution.width);
  296. }
  297. }
  298. }
  299. userResolutions[ssrc] = resolution;
  300. resolutions[participantId] = userResolutions;
  301. if (ssrcStats.framerate > 0) {
  302. const userFramerates = framerates[participantId] || {};
  303. userFramerates[ssrc] = ssrcStats.framerate;
  304. framerates[participantId] = userFramerates;
  305. }
  306. }
  307. this.conferenceStats.bitrate = {
  308. upload: bitrateUpload,
  309. download: bitrateDownload
  310. };
  311. this.conferenceStats.bitrate.audio = {
  312. upload: audioBitrateUpload,
  313. download: audioBitrateDownload
  314. };
  315. this.conferenceStats.bitrate.video = {
  316. upload: videoBitrateUpload,
  317. download: videoBitrateDownload
  318. };
  319. this.conferenceStats.packetLoss = {
  320. total:
  321. calculatePacketLoss(
  322. lostPackets.download + lostPackets.upload,
  323. totalPackets.download + totalPackets.upload),
  324. download:
  325. calculatePacketLoss(lostPackets.download, totalPackets.download),
  326. upload:
  327. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  328. };
  329. this.eventEmitter.emit(
  330. StatisticsEvents.CONNECTION_STATS,
  331. this.peerconnection,
  332. {
  333. bandwidth: this.conferenceStats.bandwidth,
  334. bitrate: this.conferenceStats.bitrate,
  335. packetLoss: this.conferenceStats.packetLoss,
  336. resolution: resolutions,
  337. framerate: framerates,
  338. codec: codecs,
  339. transport: this.conferenceStats.transport
  340. });
  341. this.conferenceStats.transport = [];
  342. };
  343. /**
  344. * Converts the value to a non-negative number.
  345. * If the value is either invalid or negative then 0 will be returned.
  346. * @param {*} v
  347. * @return {number}
  348. * @private
  349. */
  350. StatsCollector.prototype.getNonNegativeValue = function(v) {
  351. let value = v;
  352. if (typeof value !== 'number') {
  353. value = Number(value);
  354. }
  355. if (!isValidNumber(value)) {
  356. return 0;
  357. }
  358. return Math.max(0, value);
  359. };
  360. /**
  361. * Calculates bitrate between before and now using a supplied field name and its
  362. * value in the stats.
  363. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  364. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  365. * previous stats.
  366. * @param fieldName the field to use for calculations.
  367. * @return {number} the calculated bitrate between now and before.
  368. * @private
  369. */
  370. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  371. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  372. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  373. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  374. const timeMs = now.timestamp - before.timestamp;
  375. let bitrateKbps = 0;
  376. if (timeMs > 0) {
  377. // TODO is there any reason to round here?
  378. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  379. }
  380. return bitrateKbps;
  381. };
  382. /**
  383. * Calculates the frames per second rate between before and now using a supplied field name and its value in stats.
  384. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  385. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} before the previous stats
  386. * @param {string} fieldName the field to use for calculations.
  387. * @returns {number} the calculated frame rate between now and before.
  388. */
  389. StatsCollector.prototype._calculateFps = function(now, before, fieldName) {
  390. const timeMs = now.timestamp - before.timestamp;
  391. let frameRate = 0;
  392. if (timeMs > 0 && now[fieldName]) {
  393. const numberOfFramesSinceBefore = now[fieldName] - before[fieldName];
  394. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  395. }
  396. return frameRate;
  397. };
  398. /**
  399. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  400. */
  401. StatsCollector.prototype.processStatsReport = function() {
  402. const byteSentStats = {};
  403. const encodedTimeStatsPerSsrc = new Map();
  404. this.currentStatsReport.forEach(now => {
  405. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  406. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  407. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  408. const availableIncomingBitrate = now.availableIncomingBitrate;
  409. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  410. if (availableIncomingBitrate || availableOutgoingBitrate) {
  411. this.conferenceStats.bandwidth = {
  412. 'download': Math.round(availableIncomingBitrate / 1000),
  413. 'upload': Math.round(availableOutgoingBitrate / 1000)
  414. };
  415. }
  416. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  417. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  418. // RTCIceCandidateStats
  419. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  420. if (remoteUsedCandidate && localUsedCandidate) {
  421. const remoteIpAddress = browser.isChromiumBased()
  422. ? remoteUsedCandidate.ip
  423. : remoteUsedCandidate.address;
  424. const remotePort = remoteUsedCandidate.port;
  425. const ip = `${remoteIpAddress}:${remotePort}`;
  426. const localIpAddress = browser.isChromiumBased()
  427. ? localUsedCandidate.ip
  428. : localUsedCandidate.address;
  429. const localPort = localUsedCandidate.port;
  430. const localip = `${localIpAddress}:${localPort}`;
  431. const type = remoteUsedCandidate.protocol;
  432. // Save the address unless it has been saved already.
  433. const conferenceStatsTransport = this.conferenceStats.transport;
  434. if (!conferenceStatsTransport.some(t =>
  435. t.ip === ip
  436. && t.type === type
  437. && t.localip === localip)) {
  438. conferenceStatsTransport.push({
  439. ip,
  440. type,
  441. localip,
  442. p2p: this.peerconnection.isP2P,
  443. localCandidateType: localUsedCandidate.candidateType,
  444. remoteCandidateType: remoteUsedCandidate.candidateType,
  445. networkType: localUsedCandidate.networkType,
  446. rtt: now.currentRoundTripTime * 1000
  447. });
  448. }
  449. }
  450. // RTCReceivedRtpStreamStats
  451. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  452. // RTCSentRtpStreamStats
  453. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  454. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  455. const ssrc = this.getNonNegativeValue(now.ssrc);
  456. if (!ssrc) {
  457. return;
  458. }
  459. let ssrcStats = this.ssrc2stats.get(ssrc);
  460. if (!ssrcStats) {
  461. ssrcStats = new SsrcStats();
  462. this.ssrc2stats.set(ssrc, ssrcStats);
  463. }
  464. let isDownloadStream = true;
  465. let key = 'packetsReceived';
  466. if (now.type === 'outbound-rtp') {
  467. isDownloadStream = false;
  468. key = 'packetsSent';
  469. }
  470. let packetsNow = now[key];
  471. if (!packetsNow || packetsNow < 0) {
  472. packetsNow = 0;
  473. }
  474. if (before) {
  475. const packetsBefore = this.getNonNegativeValue(before[key]);
  476. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  477. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  478. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  479. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  480. ssrcStats.setLoss({
  481. packetsTotal: packetsDiff + packetsLostDiff,
  482. packetsLost: packetsLostDiff,
  483. isDownloadStream
  484. });
  485. }
  486. let resolution;
  487. // Process the stats for 'inbound-rtp' streams always and 'outbound-rtp' only if the browser is
  488. // Chromium based and version 112 and later since 'track' based stats are no longer available there
  489. // for calculating send resolution and frame rate.
  490. if (typeof now.frameHeight !== 'undefined' && typeof now.frameWidth !== 'undefined') {
  491. // Assume the stream is active if the field is missing in the stats(Firefox)
  492. const isStreamActive = now.active ?? true;
  493. if (now.type === 'inbound-rtp' || (!browser.supportsTrackBasedStats() && isStreamActive)) {
  494. resolution = {
  495. height: now.frameHeight,
  496. width: now.frameWidth
  497. };
  498. }
  499. }
  500. ssrcStats.setResolution(resolution);
  501. let frameRate = now.framesPerSecond;
  502. if (!frameRate && before) {
  503. frameRate = this._calculateFps(now, before, 'framesSent');
  504. }
  505. ssrcStats.setFramerate(Math.round(frameRate || 0));
  506. if (now.type === 'inbound-rtp' && before) {
  507. ssrcStats.addBitrate({
  508. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  509. 'upload': 0
  510. });
  511. } else if (before) {
  512. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  513. ssrcStats.addBitrate({
  514. 'download': 0,
  515. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  516. });
  517. }
  518. const codec = this.currentStatsReport.get(now.codecId);
  519. if (codec) {
  520. /**
  521. * The mime type has the following form: video/VP8 or audio/ISAC, so we what to keep just the type
  522. * after the '/', audio and video keys will be added on the processing side.
  523. */
  524. const codecShortType = codec.mimeType.split('/')[1];
  525. codecShortType && ssrcStats.setCodec(codecShortType);
  526. // Calculate the encodeTime stat for outbound video streams.
  527. const track = this.peerconnection.getTrackBySSRC(ssrc);
  528. if (now.type === 'outbound-rtp'
  529. && now.active
  530. && track?.isVideoTrack()
  531. && before?.totalEncodeTime
  532. && before?.framesEncoded
  533. && now.frameHeight
  534. && now.frameWidth) {
  535. const encodeTimeDelta = now.totalEncodeTime - before.totalEncodeTime;
  536. const framesEncodedDelta = now.framesEncoded - before.framesEncoded;
  537. const encodeTimePerFrameInMs = 1000 * encodeTimeDelta / framesEncodedDelta;
  538. const encodeTimeStats = {
  539. codec: codecShortType,
  540. encodeTime: encodeTimePerFrameInMs,
  541. qualityLimitationReason: now.qualityLimitationReason,
  542. resolution,
  543. timestamp: now.timestamp
  544. };
  545. encodedTimeStatsPerSsrc.set(ssrc, encodeTimeStats);
  546. ssrcStats.setEncodeStats(encodedTimeStatsPerSsrc);
  547. }
  548. }
  549. // Continue to use the 'track' based stats for Firefox and Safari and older versions of Chromium.
  550. } else if (browser.supportsTrackBasedStats()
  551. && now.type === 'track'
  552. && now.kind === MediaType.VIDEO
  553. && !now.remoteSource) {
  554. const resolution = {
  555. height: now.frameHeight,
  556. width: now.frameWidth
  557. };
  558. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  559. if (!localVideoTracks?.length) {
  560. return;
  561. }
  562. const ssrc = this.peerconnection.getSsrcByTrackId(now.trackIdentifier);
  563. if (!ssrc) {
  564. return;
  565. }
  566. let ssrcStats = this.ssrc2stats.get(ssrc);
  567. if (!ssrcStats) {
  568. ssrcStats = new SsrcStats();
  569. this.ssrc2stats.set(ssrc, ssrcStats);
  570. }
  571. if (resolution.height && resolution.width) {
  572. ssrcStats.setResolution(resolution);
  573. }
  574. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  575. // Therefore, it needs to be divided by the total number of active simulcast streams.
  576. let frameRate = now.framesPerSecond;
  577. if (!frameRate && before) {
  578. frameRate = this._calculateFps(now, before, 'framesSent');
  579. }
  580. ssrcStats.setFramerate(frameRate);
  581. }
  582. });
  583. if (Object.keys(byteSentStats).length) {
  584. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  585. }
  586. if (encodedTimeStatsPerSsrc.size) {
  587. this.eventEmitter.emit(StatisticsEvents.ENCODE_TIME_STATS, this.peerconnection, encodedTimeStatsPerSsrc);
  588. }
  589. this._processAndEmitReport();
  590. };