您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTPStatsCollector.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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.audioLevelReportHistory = {};
  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; // eslint-disable-line no-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. || isNaN(resolution?.height)
  276. || isNaN(resolution?.width)
  277. || resolution.height === -1
  278. || resolution.width === -1) {
  279. continue; // eslint-disable-line no-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()) {
  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. const avgAudioLevels = {};
  330. let localAvgAudioLevels;
  331. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  332. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  333. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  334. if (isLocal) {
  335. localAvgAudioLevels = avgAudioLevel;
  336. } else {
  337. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  338. if (track) {
  339. const participantId = track.getParticipantId();
  340. if (participantId) {
  341. avgAudioLevels[participantId] = avgAudioLevel;
  342. }
  343. }
  344. }
  345. });
  346. this.audioLevelReportHistory = {};
  347. this.eventEmitter.emit(
  348. StatisticsEvents.CONNECTION_STATS,
  349. this.peerconnection,
  350. {
  351. bandwidth: this.conferenceStats.bandwidth,
  352. bitrate: this.conferenceStats.bitrate,
  353. packetLoss: this.conferenceStats.packetLoss,
  354. resolution: resolutions,
  355. framerate: framerates,
  356. codec: codecs,
  357. transport: this.conferenceStats.transport,
  358. localAvgAudioLevels,
  359. avgAudioLevels
  360. });
  361. this.conferenceStats.transport = [];
  362. };
  363. /**
  364. * Converts the value to a non-negative number.
  365. * If the value is either invalid or negative then 0 will be returned.
  366. * @param {*} v
  367. * @return {number}
  368. * @private
  369. */
  370. StatsCollector.prototype.getNonNegativeValue = function(v) {
  371. let value = v;
  372. if (typeof value !== 'number') {
  373. value = Number(value);
  374. }
  375. if (isNaN(value)) {
  376. return 0;
  377. }
  378. return Math.max(0, value);
  379. };
  380. /**
  381. * Calculates bitrate between before and now using a supplied field name and its
  382. * value in the stats.
  383. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  384. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  385. * previous stats.
  386. * @param fieldName the field to use for calculations.
  387. * @return {number} the calculated bitrate between now and before.
  388. * @private
  389. */
  390. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  391. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  392. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  393. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  394. const timeMs = now.timestamp - before.timestamp;
  395. let bitrateKbps = 0;
  396. if (timeMs > 0) {
  397. // TODO is there any reason to round here?
  398. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  399. }
  400. return bitrateKbps;
  401. };
  402. /**
  403. * Calculates the frames per second rate between before and now using a supplied field name and its value in stats.
  404. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  405. * @param {RTCOutboundRtpStreamStats|RTCSentRtpStreamStats} before the previous stats
  406. * @param {string} fieldName the field to use for calculations.
  407. * @returns {number} the calculated frame rate between now and before.
  408. */
  409. StatsCollector.prototype._calculateFps = function(now, before, fieldName) {
  410. const timeMs = now.timestamp - before.timestamp;
  411. let frameRate = 0;
  412. if (timeMs > 0 && now[fieldName]) {
  413. const numberOfFramesSinceBefore = now[fieldName] - before[fieldName];
  414. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  415. }
  416. return frameRate;
  417. };
  418. /**
  419. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  420. */
  421. StatsCollector.prototype.processStatsReport = function() {
  422. const byteSentStats = {};
  423. const encodedTimeStatsPerSsrc = new Map();
  424. this.currentStatsReport.forEach(now => {
  425. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  426. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  427. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  428. const availableIncomingBitrate = now.availableIncomingBitrate;
  429. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  430. if (availableIncomingBitrate || availableOutgoingBitrate) {
  431. this.conferenceStats.bandwidth = {
  432. 'download': Math.round(availableIncomingBitrate / 1000),
  433. 'upload': Math.round(availableOutgoingBitrate / 1000)
  434. };
  435. }
  436. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  437. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  438. // RTCIceCandidateStats
  439. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  440. if (remoteUsedCandidate && localUsedCandidate) {
  441. const remoteIpAddress = browser.isChromiumBased()
  442. ? remoteUsedCandidate.ip
  443. : remoteUsedCandidate.address;
  444. const remotePort = remoteUsedCandidate.port;
  445. const ip = `${remoteIpAddress}:${remotePort}`;
  446. const localIpAddress = browser.isChromiumBased()
  447. ? localUsedCandidate.ip
  448. : localUsedCandidate.address;
  449. const localPort = localUsedCandidate.port;
  450. const localip = `${localIpAddress}:${localPort}`;
  451. const type = remoteUsedCandidate.protocol;
  452. // Save the address unless it has been saved already.
  453. const conferenceStatsTransport = this.conferenceStats.transport;
  454. if (!conferenceStatsTransport.some(t =>
  455. t.ip === ip
  456. && t.type === type
  457. && t.localip === localip)) {
  458. conferenceStatsTransport.push({
  459. ip,
  460. type,
  461. localip,
  462. p2p: this.peerconnection.isP2P,
  463. localCandidateType: localUsedCandidate.candidateType,
  464. remoteCandidateType: remoteUsedCandidate.candidateType,
  465. networkType: localUsedCandidate.networkType,
  466. rtt: now.currentRoundTripTime * 1000
  467. });
  468. }
  469. }
  470. // RTCReceivedRtpStreamStats
  471. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  472. // RTCSentRtpStreamStats
  473. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  474. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  475. const ssrc = this.getNonNegativeValue(now.ssrc);
  476. if (!ssrc) {
  477. return;
  478. }
  479. let ssrcStats = this.ssrc2stats.get(ssrc);
  480. if (!ssrcStats) {
  481. ssrcStats = new SsrcStats();
  482. this.ssrc2stats.set(ssrc, ssrcStats);
  483. }
  484. let isDownloadStream = true;
  485. let key = 'packetsReceived';
  486. if (now.type === 'outbound-rtp') {
  487. isDownloadStream = false;
  488. key = 'packetsSent';
  489. }
  490. let packetsNow = now[key];
  491. if (!packetsNow || packetsNow < 0) {
  492. packetsNow = 0;
  493. }
  494. if (before) {
  495. const packetsBefore = this.getNonNegativeValue(before[key]);
  496. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  497. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  498. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  499. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  500. ssrcStats.setLoss({
  501. packetsTotal: packetsDiff + packetsLostDiff,
  502. packetsLost: packetsLostDiff,
  503. isDownloadStream
  504. });
  505. }
  506. let resolution;
  507. // Process the stats for 'inbound-rtp' streams always and 'outbound-rtp' only if the browser is
  508. // Chromium based and version 112 and later since 'track' based stats are no longer available there
  509. // for calculating send resolution and frame rate.
  510. if (typeof now.frameHeight !== 'undefined' && typeof now.frameWidth !== 'undefined') {
  511. // Assume the stream is active if the field is missing in the stats(Firefox)
  512. const isStreamActive = now.active ?? true;
  513. if (now.type === 'inbound-rtp' || (!browser.supportsTrackBasedStats() && isStreamActive)) {
  514. resolution = {
  515. height: now.frameHeight,
  516. width: now.frameWidth
  517. };
  518. }
  519. }
  520. ssrcStats.setResolution(resolution);
  521. let frameRate = now.framesPerSecond;
  522. if (!frameRate && before) {
  523. frameRate = this._calculateFps(now, before, 'framesSent');
  524. }
  525. ssrcStats.setFramerate(Math.round(frameRate || 0));
  526. if (now.type === 'inbound-rtp' && before) {
  527. ssrcStats.addBitrate({
  528. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  529. 'upload': 0
  530. });
  531. } else if (before) {
  532. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  533. ssrcStats.addBitrate({
  534. 'download': 0,
  535. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  536. });
  537. }
  538. const codec = this.currentStatsReport.get(now.codecId);
  539. if (codec) {
  540. /**
  541. * The mime type has the following form: video/VP8 or audio/ISAC, so we what to keep just the type
  542. * after the '/', audio and video keys will be added on the processing side.
  543. */
  544. const codecShortType = codec.mimeType.split('/')[1];
  545. codecShortType && ssrcStats.setCodec(codecShortType);
  546. // Calculate the encodeTime stat for outbound video streams.
  547. const track = this.peerconnection.getTrackBySSRC(ssrc);
  548. if (now.type === 'outbound-rtp'
  549. && now.active
  550. && track?.isVideoTrack()
  551. && this.peerconnection.usesCodecSelectionAPI()
  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. };