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

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