Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

RTPStatsCollector.js 25KB

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