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

RTPStatsCollector.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. SsrcStats.prototype.setEncodeStats = function(encodeStats) {
  76. this.encodeStats = encodeStats || {};
  77. };
  78. /**
  79. *
  80. */
  81. function ConferenceStats() {
  82. /**
  83. * The bandwidth
  84. * @type {{}}
  85. */
  86. this.bandwidth = {};
  87. /**
  88. * The bit rate
  89. * @type {{}}
  90. */
  91. this.bitrate = {};
  92. /**
  93. * The packet loss rate
  94. * @type {{}}
  95. */
  96. this.packetLoss = null;
  97. /**
  98. * Array with the transport information.
  99. * @type {Array}
  100. */
  101. this.transport = [];
  102. }
  103. /* eslint-disable max-params */
  104. /**
  105. * <tt>StatsCollector</tt> registers for stats updates of given
  106. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  107. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  108. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  109. * instance as an event source.
  110. *
  111. * @param peerconnection WebRTC PeerConnection object.
  112. * @param audioLevelsInterval
  113. * @param statsInterval stats refresh interval given in ms.
  114. * @param eventEmitter
  115. * @constructor
  116. */
  117. export default function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter) {
  118. this.peerconnection = peerconnection;
  119. this.currentStatsReport = null;
  120. this.previousStatsReport = null;
  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. logger.error('Get stats error', error);
  163. this.stop();
  164. };
  165. /**
  166. * Starts stats updates.
  167. */
  168. StatsCollector.prototype.start = function(startAudioLevelStats) {
  169. if (startAudioLevelStats && browser.supportsReceiverStats()) {
  170. this.audioLevelsIntervalId = setInterval(
  171. () => {
  172. const audioLevels = this.peerconnection.getAudioLevels(this.speakerList);
  173. for (const ssrc in audioLevels) {
  174. if (audioLevels.hasOwnProperty(ssrc)) {
  175. // Use a scaling factor of 2.5 to report the same audio levels that getStats reports.
  176. const audioLevel = audioLevels[ssrc] * 2.5;
  177. this.eventEmitter.emit(
  178. StatisticsEvents.AUDIO_LEVEL,
  179. this.peerconnection,
  180. Number.parseInt(ssrc, 10),
  181. audioLevel,
  182. false /* isLocal */);
  183. }
  184. }
  185. },
  186. this.audioLevelsIntervalMilis
  187. );
  188. }
  189. const processStats = () => {
  190. // Interval updates
  191. this.peerconnection.getStats()
  192. .then(report => {
  193. this.currentStatsReport = typeof report?.result === 'function'
  194. ? report.result()
  195. : report;
  196. try {
  197. this.processStatsReport();
  198. } catch (error) {
  199. logger.error('Processing of RTP stats failed:', error);
  200. }
  201. this.previousStatsReport = this.currentStatsReport;
  202. })
  203. .catch(error => this.errorCallback(error));
  204. };
  205. processStats();
  206. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  207. };
  208. /**
  209. *
  210. */
  211. StatsCollector.prototype._processAndEmitReport = function() {
  212. // process stats
  213. const totalPackets = {
  214. download: 0,
  215. upload: 0
  216. };
  217. const lostPackets = {
  218. download: 0,
  219. upload: 0
  220. };
  221. let bitrateDownload = 0;
  222. let bitrateUpload = 0;
  223. const resolutions = {};
  224. const framerates = {};
  225. const codecs = {};
  226. let audioBitrateDownload = 0;
  227. let audioBitrateUpload = 0;
  228. let videoBitrateDownload = 0;
  229. let videoBitrateUpload = 0;
  230. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  231. // process packet loss stats
  232. const loss = ssrcStats.loss;
  233. const type = loss.isDownloadStream ? 'download' : 'upload';
  234. totalPackets[type] += loss.packetsTotal;
  235. lostPackets[type] += loss.packetsLost;
  236. const ssrcBitrateDownload = ssrcStats.bitrate.download;
  237. const ssrcBitrateUpload = ssrcStats.bitrate.upload;
  238. // process bitrate stats
  239. bitrateDownload += ssrcBitrateDownload;
  240. bitrateUpload += ssrcBitrateUpload;
  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 += ssrcBitrateDownload;
  251. audioBitrateUpload += ssrcBitrateUpload;
  252. audioCodec = ssrcStats.codec;
  253. } else {
  254. videoBitrateDownload += ssrcBitrateDownload;
  255. videoBitrateUpload += ssrcBitrateUpload;
  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(track)) {
  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. this.eventEmitter.emit(
  329. StatisticsEvents.CONNECTION_STATS,
  330. this.peerconnection,
  331. {
  332. bandwidth: this.conferenceStats.bandwidth,
  333. bitrate: this.conferenceStats.bitrate,
  334. packetLoss: this.conferenceStats.packetLoss,
  335. resolution: resolutions,
  336. framerate: framerates,
  337. codec: codecs,
  338. transport: this.conferenceStats.transport
  339. });
  340. this.conferenceStats.transport = [];
  341. };
  342. /**
  343. * Converts the value to a non-negative number.
  344. * If the value is either invalid or negative then 0 will be returned.
  345. * @param {*} v
  346. * @return {number}
  347. * @private
  348. */
  349. StatsCollector.prototype.getNonNegativeValue = function(v) {
  350. let value = v;
  351. if (typeof value !== 'number') {
  352. value = Number(value);
  353. }
  354. if (isNaN(value)) {
  355. return 0;
  356. }
  357. return Math.max(0, value);
  358. };
  359. /**
  360. * Calculates bitrate between before and now using a supplied field name and its
  361. * value in the stats.
  362. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  363. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  364. * previous stats.
  365. * @param fieldName the field to use for calculations.
  366. * @return {number} the calculated bitrate between now and before.
  367. * @private
  368. */
  369. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  370. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  371. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  372. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  373. const timeMs = now.timestamp - before.timestamp;
  374. let bitrateKbps = 0;
  375. if (timeMs > 0) {
  376. // TODO is there any reason to round here?
  377. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  378. }
  379. return bitrateKbps;
  380. };
  381. /**
  382. * Calculates the frames per second rate between before and now using a supplied field name and its value in stats.
  383. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  384. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} before the previous stats
  385. * @param {string} fieldName the field to use for calculations.
  386. * @returns {number} the calculated frame rate between now and before.
  387. */
  388. StatsCollector.prototype._calculateFps = function(now, before, fieldName) {
  389. const timeMs = now.timestamp - before.timestamp;
  390. let frameRate = 0;
  391. if (timeMs > 0 && now[fieldName]) {
  392. const numberOfFramesSinceBefore = now[fieldName] - before[fieldName];
  393. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  394. }
  395. return frameRate;
  396. };
  397. /**
  398. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  399. */
  400. StatsCollector.prototype.processStatsReport = function() {
  401. const byteSentStats = {};
  402. const encodedTimeStatsPerSsrc = new Map();
  403. this.currentStatsReport.forEach(now => {
  404. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  405. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  406. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  407. const availableIncomingBitrate = now.availableIncomingBitrate;
  408. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  409. if (availableIncomingBitrate || availableOutgoingBitrate) {
  410. this.conferenceStats.bandwidth = {
  411. 'download': Math.round(availableIncomingBitrate / 1000),
  412. 'upload': Math.round(availableOutgoingBitrate / 1000)
  413. };
  414. }
  415. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  416. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  417. // RTCIceCandidateStats
  418. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  419. if (remoteUsedCandidate && localUsedCandidate) {
  420. const remoteIpAddress = browser.isChromiumBased()
  421. ? remoteUsedCandidate.ip
  422. : remoteUsedCandidate.address;
  423. const remotePort = remoteUsedCandidate.port;
  424. const ip = `${remoteIpAddress}:${remotePort}`;
  425. const localIpAddress = browser.isChromiumBased()
  426. ? localUsedCandidate.ip
  427. : localUsedCandidate.address;
  428. const localPort = localUsedCandidate.port;
  429. const localip = `${localIpAddress}:${localPort}`;
  430. const type = remoteUsedCandidate.protocol;
  431. // Save the address unless it has been saved already.
  432. const conferenceStatsTransport = this.conferenceStats.transport;
  433. if (!conferenceStatsTransport.some(t =>
  434. t.ip === ip
  435. && t.type === type
  436. && t.localip === localip)) {
  437. conferenceStatsTransport.push({
  438. ip,
  439. type,
  440. localip,
  441. p2p: this.peerconnection.isP2P,
  442. localCandidateType: localUsedCandidate.candidateType,
  443. remoteCandidateType: remoteUsedCandidate.candidateType,
  444. networkType: localUsedCandidate.networkType,
  445. rtt: now.currentRoundTripTime * 1000
  446. });
  447. }
  448. }
  449. // RTCReceivedRtpStreamStats
  450. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  451. // RTCSentRtpStreamStats
  452. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  453. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  454. const ssrc = this.getNonNegativeValue(now.ssrc);
  455. if (!ssrc) {
  456. return;
  457. }
  458. let ssrcStats = this.ssrc2stats.get(ssrc);
  459. if (!ssrcStats) {
  460. ssrcStats = new SsrcStats();
  461. this.ssrc2stats.set(ssrc, ssrcStats);
  462. }
  463. let isDownloadStream = true;
  464. let key = 'packetsReceived';
  465. if (now.type === 'outbound-rtp') {
  466. isDownloadStream = false;
  467. key = 'packetsSent';
  468. }
  469. let packetsNow = now[key];
  470. if (!packetsNow || packetsNow < 0) {
  471. packetsNow = 0;
  472. }
  473. if (before) {
  474. const packetsBefore = this.getNonNegativeValue(before[key]);
  475. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  476. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  477. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  478. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  479. ssrcStats.setLoss({
  480. packetsTotal: packetsDiff + packetsLostDiff,
  481. packetsLost: packetsLostDiff,
  482. isDownloadStream
  483. });
  484. }
  485. let resolution;
  486. // Process the stats for 'inbound-rtp' streams always and 'outbound-rtp' only if the browser is
  487. // Chromium based and version 112 and later since 'track' based stats are no longer available there
  488. // for calculating send resolution and frame rate.
  489. if (typeof now.frameHeight !== 'undefined' && typeof now.frameWidth !== 'undefined') {
  490. // Assume the stream is active if the field is missing in the stats(Firefox)
  491. const isStreamActive = now.active ?? true;
  492. if (now.type === 'inbound-rtp' || (!browser.supportsTrackBasedStats() && isStreamActive)) {
  493. resolution = {
  494. height: now.frameHeight,
  495. width: now.frameWidth
  496. };
  497. }
  498. }
  499. ssrcStats.setResolution(resolution);
  500. let frameRate = now.framesPerSecond;
  501. if (!frameRate && before) {
  502. frameRate = this._calculateFps(now, before, 'framesSent');
  503. }
  504. ssrcStats.setFramerate(Math.round(frameRate || 0));
  505. if (now.type === 'inbound-rtp' && before) {
  506. ssrcStats.addBitrate({
  507. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  508. 'upload': 0
  509. });
  510. } else if (before) {
  511. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  512. ssrcStats.addBitrate({
  513. 'download': 0,
  514. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  515. });
  516. }
  517. const codec = this.currentStatsReport.get(now.codecId);
  518. if (codec) {
  519. /**
  520. * The mime type has the following form: video/VP8 or audio/ISAC, so we what to keep just the type
  521. * after the '/', audio and video keys will be added on the processing side.
  522. */
  523. const codecShortType = codec.mimeType.split('/')[1];
  524. codecShortType && ssrcStats.setCodec(codecShortType);
  525. // Calculate the encodeTime stat for outbound video streams.
  526. const track = this.peerconnection.getTrackBySSRC(ssrc);
  527. if (now.type === 'outbound-rtp'
  528. && now.active
  529. && track?.isVideoTrack()
  530. && before?.totalEncodeTime
  531. && before?.framesEncoded
  532. && now.frameHeight
  533. && now.frameWidth) {
  534. const encodeTimeDelta = now.totalEncodeTime - before.totalEncodeTime;
  535. const framesEncodedDelta = now.framesEncoded - before.framesEncoded;
  536. const encodeTimePerFrameInMs = 1000 * encodeTimeDelta / framesEncodedDelta;
  537. const encodeTimeStats = {
  538. codec: codecShortType,
  539. encodeTime: encodeTimePerFrameInMs,
  540. qualityLimitationReason: now.qualityLimitationReason,
  541. resolution,
  542. timestamp: now.timestamp
  543. };
  544. encodedTimeStatsPerSsrc.set(ssrc, encodeTimeStats);
  545. ssrcStats.setEncodeStats(encodedTimeStatsPerSsrc);
  546. }
  547. }
  548. // Continue to use the 'track' based stats for Firefox and Safari and older versions of Chromium.
  549. } else if (browser.supportsTrackBasedStats()
  550. && now.type === 'track'
  551. && now.kind === MediaType.VIDEO
  552. && !now.remoteSource) {
  553. const resolution = {
  554. height: now.frameHeight,
  555. width: now.frameWidth
  556. };
  557. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  558. if (!localVideoTracks?.length) {
  559. return;
  560. }
  561. const ssrc = this.peerconnection.getSsrcByTrackId(now.trackIdentifier);
  562. if (!ssrc) {
  563. return;
  564. }
  565. let ssrcStats = this.ssrc2stats.get(ssrc);
  566. if (!ssrcStats) {
  567. ssrcStats = new SsrcStats();
  568. this.ssrc2stats.set(ssrc, ssrcStats);
  569. }
  570. if (resolution.height && resolution.width) {
  571. ssrcStats.setResolution(resolution);
  572. }
  573. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  574. // Therefore, it needs to be divided by the total number of active simulcast streams.
  575. let frameRate = now.framesPerSecond;
  576. if (!frameRate && before) {
  577. frameRate = this._calculateFps(now, before, 'framesSent');
  578. }
  579. ssrcStats.setFramerate(frameRate);
  580. }
  581. });
  582. if (Object.keys(byteSentStats).length) {
  583. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  584. }
  585. if (encodedTimeStatsPerSsrc.size) {
  586. this.eventEmitter.emit(StatisticsEvents.ENCODE_TIME_STATS, this.peerconnection, encodedTimeStatsPerSsrc);
  587. }
  588. this._processAndEmitReport();
  589. };