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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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.currentStatsReport = null;
  119. this.previousStatsReport = null;
  120. this.audioLevelReportHistory = {};
  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. GlobalOnErrorHandler.callErrorHandler(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. GlobalOnErrorHandler.callErrorHandler(error);
  201. logger.error('Processing of RTP stats failed:', error);
  202. }
  203. this.previousStatsReport = this.currentStatsReport;
  204. })
  205. .catch(error => this.errorCallback(error));
  206. };
  207. processStats();
  208. this.statsIntervalId = setInterval(processStats, this.statsIntervalMilis);
  209. };
  210. /**
  211. *
  212. */
  213. StatsCollector.prototype._processAndEmitReport = function() {
  214. // process stats
  215. const totalPackets = {
  216. download: 0,
  217. upload: 0
  218. };
  219. const lostPackets = {
  220. download: 0,
  221. upload: 0
  222. };
  223. let bitrateDownload = 0;
  224. let bitrateUpload = 0;
  225. const resolutions = {};
  226. const framerates = {};
  227. const codecs = {};
  228. let audioBitrateDownload = 0;
  229. let audioBitrateUpload = 0;
  230. let videoBitrateDownload = 0;
  231. let videoBitrateUpload = 0;
  232. for (const [ ssrc, ssrcStats ] of this.ssrc2stats) {
  233. // process packet loss stats
  234. const loss = ssrcStats.loss;
  235. const type = loss.isDownloadStream ? 'download' : 'upload';
  236. totalPackets[type] += loss.packetsTotal;
  237. lostPackets[type] += loss.packetsLost;
  238. // process bitrate stats
  239. bitrateDownload += ssrcStats.bitrate.download;
  240. bitrateUpload += ssrcStats.bitrate.upload;
  241. // collect resolutions and framerates
  242. const track = this.peerconnection.getTrackBySSRC(ssrc);
  243. if (track) {
  244. let audioCodec;
  245. let videoCodec;
  246. if (track.isAudioTrack()) {
  247. audioBitrateDownload += ssrcStats.bitrate.download;
  248. audioBitrateUpload += ssrcStats.bitrate.upload;
  249. audioCodec = ssrcStats.codec;
  250. } else {
  251. videoBitrateDownload += ssrcStats.bitrate.download;
  252. videoBitrateUpload += ssrcStats.bitrate.upload;
  253. videoCodec = ssrcStats.codec;
  254. }
  255. const participantId = track.getParticipantId();
  256. if (participantId) {
  257. const resolution = ssrcStats.resolution;
  258. if (resolution.width
  259. && resolution.height
  260. && resolution.width !== -1
  261. && resolution.height !== -1) {
  262. const userResolutions = resolutions[participantId] || {};
  263. userResolutions[ssrc] = resolution;
  264. resolutions[participantId] = userResolutions;
  265. }
  266. if (ssrcStats.framerate > 0) {
  267. const userFramerates = framerates[participantId] || {};
  268. userFramerates[ssrc] = ssrcStats.framerate;
  269. framerates[participantId] = userFramerates;
  270. }
  271. const userCodecs = codecs[participantId] ?? { };
  272. userCodecs[ssrc] = {
  273. audio: audioCodec,
  274. video: videoCodec
  275. };
  276. codecs[participantId] = userCodecs;
  277. // All tracks in ssrc-rewriting mode need not have a participant associated with it.
  278. } else if (!FeatureFlags.isSsrcRewritingSupported()) {
  279. logger.error(`No participant ID returned by ${track}`);
  280. }
  281. }
  282. ssrcStats.resetBitrate();
  283. }
  284. this.conferenceStats.bitrate = {
  285. 'upload': bitrateUpload,
  286. 'download': bitrateDownload
  287. };
  288. this.conferenceStats.bitrate.audio = {
  289. 'upload': audioBitrateUpload,
  290. 'download': audioBitrateDownload
  291. };
  292. this.conferenceStats.bitrate.video = {
  293. 'upload': videoBitrateUpload,
  294. 'download': videoBitrateDownload
  295. };
  296. this.conferenceStats.packetLoss = {
  297. total:
  298. calculatePacketLoss(
  299. lostPackets.download + lostPackets.upload,
  300. totalPackets.download + totalPackets.upload),
  301. download:
  302. calculatePacketLoss(lostPackets.download, totalPackets.download),
  303. upload:
  304. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  305. };
  306. const avgAudioLevels = {};
  307. let localAvgAudioLevels;
  308. Object.keys(this.audioLevelReportHistory).forEach(ssrc => {
  309. const { data, isLocal } = this.audioLevelReportHistory[ssrc];
  310. const avgAudioLevel = data.reduce((sum, currentValue) => sum + currentValue) / data.length;
  311. if (isLocal) {
  312. localAvgAudioLevels = avgAudioLevel;
  313. } else {
  314. const track = this.peerconnection.getTrackBySSRC(Number(ssrc));
  315. if (track) {
  316. const participantId = track.getParticipantId();
  317. if (participantId) {
  318. avgAudioLevels[participantId] = avgAudioLevel;
  319. }
  320. }
  321. }
  322. });
  323. this.audioLevelReportHistory = {};
  324. this.eventEmitter.emit(
  325. StatisticsEvents.CONNECTION_STATS,
  326. this.peerconnection,
  327. {
  328. 'bandwidth': this.conferenceStats.bandwidth,
  329. 'bitrate': this.conferenceStats.bitrate,
  330. 'packetLoss': this.conferenceStats.packetLoss,
  331. 'resolution': resolutions,
  332. 'framerate': framerates,
  333. 'codec': codecs,
  334. 'transport': this.conferenceStats.transport,
  335. localAvgAudioLevels,
  336. avgAudioLevels
  337. });
  338. this.conferenceStats.transport = [];
  339. };
  340. /**
  341. * Converts the value to a non-negative number.
  342. * If the value is either invalid or negative then 0 will be returned.
  343. * @param {*} v
  344. * @return {number}
  345. * @private
  346. */
  347. StatsCollector.prototype.getNonNegativeValue = function(v) {
  348. let value = v;
  349. if (typeof value !== 'number') {
  350. value = Number(value);
  351. }
  352. if (isNaN(value)) {
  353. return 0;
  354. }
  355. return Math.max(0, value);
  356. };
  357. /**
  358. * Calculates bitrate between before and now using a supplied field name and its
  359. * value in the stats.
  360. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} now the current stats
  361. * @param {RTCInboundRtpStreamStats|RTCSentRtpStreamStats} before the
  362. * previous stats.
  363. * @param fieldName the field to use for calculations.
  364. * @return {number} the calculated bitrate between now and before.
  365. * @private
  366. */
  367. StatsCollector.prototype._calculateBitrate = function(now, before, fieldName) {
  368. const bytesNow = this.getNonNegativeValue(now[fieldName]);
  369. const bytesBefore = this.getNonNegativeValue(before[fieldName]);
  370. const bytesProcessed = Math.max(0, bytesNow - bytesBefore);
  371. const timeMs = now.timestamp - before.timestamp;
  372. let bitrateKbps = 0;
  373. if (timeMs > 0) {
  374. // TODO is there any reason to round here?
  375. bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);
  376. }
  377. return bitrateKbps;
  378. };
  379. /**
  380. * Stats processing for spec-compliant RTCPeerConnection#getStats.
  381. */
  382. StatsCollector.prototype.processStatsReport = function() {
  383. const byteSentStats = {};
  384. this.currentStatsReport.forEach(now => {
  385. const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
  386. // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*
  387. if (now.type === 'candidate-pair' && now.nominated && now.state === 'succeeded') {
  388. const availableIncomingBitrate = now.availableIncomingBitrate;
  389. const availableOutgoingBitrate = now.availableOutgoingBitrate;
  390. if (availableIncomingBitrate || availableOutgoingBitrate) {
  391. this.conferenceStats.bandwidth = {
  392. 'download': Math.round(availableIncomingBitrate / 1000),
  393. 'upload': Math.round(availableOutgoingBitrate / 1000)
  394. };
  395. }
  396. const remoteUsedCandidate = this.currentStatsReport.get(now.remoteCandidateId);
  397. const localUsedCandidate = this.currentStatsReport.get(now.localCandidateId);
  398. // RTCIceCandidateStats
  399. // https://w3c.github.io/webrtc-stats/#icecandidate-dict*
  400. if (remoteUsedCandidate && localUsedCandidate) {
  401. const remoteIpAddress = browser.isChromiumBased()
  402. ? remoteUsedCandidate.ip
  403. : remoteUsedCandidate.address;
  404. const remotePort = remoteUsedCandidate.port;
  405. const ip = `${remoteIpAddress}:${remotePort}`;
  406. const localIpAddress = browser.isChromiumBased()
  407. ? localUsedCandidate.ip
  408. : localUsedCandidate.address;
  409. const localPort = localUsedCandidate.port;
  410. const localip = `${localIpAddress}:${localPort}`;
  411. const type = remoteUsedCandidate.protocol;
  412. // Save the address unless it has been saved already.
  413. const conferenceStatsTransport = this.conferenceStats.transport;
  414. if (!conferenceStatsTransport.some(t =>
  415. t.ip === ip
  416. && t.type === type
  417. && t.localip === localip)) {
  418. conferenceStatsTransport.push({
  419. ip,
  420. type,
  421. localip,
  422. p2p: this.peerconnection.isP2P,
  423. localCandidateType: localUsedCandidate.candidateType,
  424. remoteCandidateType: remoteUsedCandidate.candidateType,
  425. networkType: localUsedCandidate.networkType,
  426. rtt: now.currentRoundTripTime * 1000
  427. });
  428. }
  429. }
  430. // RTCReceivedRtpStreamStats
  431. // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
  432. // RTCSentRtpStreamStats
  433. // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*
  434. } else if (now.type === 'inbound-rtp' || now.type === 'outbound-rtp') {
  435. const ssrc = this.getNonNegativeValue(now.ssrc);
  436. if (!ssrc) {
  437. return;
  438. }
  439. let ssrcStats = this.ssrc2stats.get(ssrc);
  440. if (!ssrcStats) {
  441. ssrcStats = new SsrcStats();
  442. this.ssrc2stats.set(ssrc, ssrcStats);
  443. }
  444. let isDownloadStream = true;
  445. let key = 'packetsReceived';
  446. if (now.type === 'outbound-rtp') {
  447. isDownloadStream = false;
  448. key = 'packetsSent';
  449. }
  450. let packetsNow = now[key];
  451. if (!packetsNow || packetsNow < 0) {
  452. packetsNow = 0;
  453. }
  454. if (before) {
  455. const packetsBefore = this.getNonNegativeValue(before[key]);
  456. const packetsDiff = Math.max(0, packetsNow - packetsBefore);
  457. const packetsLostNow = this.getNonNegativeValue(now.packetsLost);
  458. const packetsLostBefore = this.getNonNegativeValue(before.packetsLost);
  459. const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  460. ssrcStats.setLoss({
  461. packetsTotal: packetsDiff + packetsLostDiff,
  462. packetsLost: packetsLostDiff,
  463. isDownloadStream
  464. });
  465. }
  466. // Get the resolution and framerate for only remote video sources here. For the local video sources,
  467. // 'track' stats will be used since they have the updated resolution based on the simulcast streams
  468. // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be
  469. // more calculations needed to determine what is the highest resolution stream sent by the client if the
  470. // 'outbound-rtp' stats are used.
  471. if (now.type === 'inbound-rtp') {
  472. const resolution = {
  473. height: now.frameHeight,
  474. width: now.frameWidth
  475. };
  476. const frameRate = now.framesPerSecond;
  477. if (resolution.height && resolution.width) {
  478. ssrcStats.setResolution(resolution);
  479. }
  480. ssrcStats.setFramerate(Math.round(frameRate || 0));
  481. if (before) {
  482. ssrcStats.addBitrate({
  483. 'download': this._calculateBitrate(now, before, 'bytesReceived'),
  484. 'upload': 0
  485. });
  486. }
  487. } else if (before) {
  488. byteSentStats[ssrc] = this.getNonNegativeValue(now.bytesSent);
  489. ssrcStats.addBitrate({
  490. 'download': 0,
  491. 'upload': this._calculateBitrate(now, before, 'bytesSent')
  492. });
  493. }
  494. const codec = this.currentStatsReport.get(now.codecId);
  495. if (codec) {
  496. /**
  497. * The mime type has the following form: video/VP8 or audio/ISAC,
  498. * so we what to keep just the type after the '/', audio and video
  499. * keys will be added on the processing side.
  500. */
  501. const codecShortType = codec.mimeType.split('/')[1];
  502. codecShortType && ssrcStats.setCodec(codecShortType);
  503. }
  504. // Use track stats for resolution and framerate of the local video source.
  505. // RTCVideoHandlerStats - https://w3c.github.io/webrtc-stats/#vststats-dict*
  506. // RTCMediaHandlerStats - https://w3c.github.io/webrtc-stats/#mststats-dict*
  507. } else if (now.type === 'track' && now.kind === MediaType.VIDEO && !now.remoteSource) {
  508. const resolution = {
  509. height: now.frameHeight,
  510. width: now.frameWidth
  511. };
  512. const localVideoTracks = this.peerconnection.getLocalTracks(MediaType.VIDEO);
  513. if (!localVideoTracks?.length) {
  514. return;
  515. }
  516. const ssrc = this.peerconnection.getSsrcByTrackId(now.trackIdentifier);
  517. if (!ssrc) {
  518. return;
  519. }
  520. let ssrcStats = this.ssrc2stats.get(ssrc);
  521. if (!ssrcStats) {
  522. ssrcStats = new SsrcStats();
  523. this.ssrc2stats.set(ssrc, ssrcStats);
  524. }
  525. if (resolution.height && resolution.width) {
  526. ssrcStats.setResolution(resolution);
  527. }
  528. // Calculate the frame rate. 'framesSent' is the total aggregate value for all the simulcast streams.
  529. // Therefore, it needs to be divided by the total number of active simulcast streams.
  530. let frameRate = now.framesPerSecond;
  531. if (!frameRate) {
  532. if (before) {
  533. const timeMs = now.timestamp - before.timestamp;
  534. if (timeMs > 0 && now.framesSent) {
  535. const numberOfFramesSinceBefore = now.framesSent - before.framesSent;
  536. frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;
  537. }
  538. }
  539. if (!frameRate) {
  540. return;
  541. }
  542. }
  543. // Get the number of simulcast streams currently enabled from TPC.
  544. const numberOfActiveStreams = this.peerconnection.getActiveSimulcastStreams();
  545. // Reset frame rate to 0 when video is suspended as a result of endpoint falling out of last-n.
  546. frameRate = numberOfActiveStreams ? Math.round(frameRate / numberOfActiveStreams) : 0;
  547. ssrcStats.setFramerate(frameRate);
  548. }
  549. });
  550. if (Object.keys(byteSentStats).length) {
  551. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, this.peerconnection, byteSentStats);
  552. }
  553. this._processAndEmitReport();
  554. };