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.

AvgRTPStatsReporter.js 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. /* global __filename */
  2. import { createRtpStatsEvent } from '../../service/statistics/AnalyticsEvents';
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import * as ConnectionQualityEvents
  5. from '../../service/connectivity/ConnectionQualityEvents';
  6. import * as ConferenceEvents from '../../JitsiConferenceEvents';
  7. import * as MediaType from '../../service/RTC/MediaType';
  8. import RTCBrowserType from '../RTC/RTCBrowserType';
  9. import Statistics from './statistics';
  10. import * as VideoType from '../../service/RTC/VideoType';
  11. const logger = getLogger(__filename);
  12. /**
  13. * This will calculate an average for one, named stat and submit it to
  14. * the analytics module when requested. It automatically counts the samples.
  15. */
  16. class AverageStatReport {
  17. /**
  18. * Creates new <tt>AverageStatReport</tt> for given name.
  19. * @param {string} name that's the name of the event that will be reported
  20. * to the analytics module.
  21. */
  22. constructor(name) {
  23. this.name = name;
  24. this.count = 0;
  25. this.sum = 0;
  26. this.samples = [];
  27. }
  28. /**
  29. * Adds the next value that will be included in the average when
  30. * {@link calculate} is called.
  31. * @param {number} nextValue
  32. */
  33. addNext(nextValue) {
  34. if (typeof nextValue !== 'number') {
  35. logger.error(
  36. `${this.name} - invalid value for idx: ${this.count}`,
  37. nextValue);
  38. } else if (!isNaN(nextValue)) {
  39. this.sum += nextValue;
  40. this.samples.push(nextValue);
  41. this.count += 1;
  42. }
  43. }
  44. /**
  45. * Calculates an average for the samples collected using {@link addNext}.
  46. * @return {number|NaN} an average of all collected samples or <tt>NaN</tt>
  47. * if no samples were collected.
  48. */
  49. calculate() {
  50. return this.sum / this.count;
  51. }
  52. /**
  53. * Appends the report to the analytics "data" object. The object will be
  54. * set under <tt>prefix</tt> + {@link this.name} key.
  55. * @param {Object} report the analytics "data" object
  56. */
  57. appendReport(report) {
  58. report[`${this.name}_avg`] = this.calculate();
  59. report[`${this.name}_samples`] = JSON.stringify(this.samples);
  60. }
  61. /**
  62. * Clears all memory of any samples collected, so that new average can be
  63. * calculated using this instance.
  64. */
  65. reset() {
  66. this.samples = [];
  67. this.sum = 0;
  68. this.count = 0;
  69. }
  70. }
  71. /**
  72. * Class gathers the stats that are calculated and reported for a
  73. * {@link TraceablePeerConnection} even if it's not currently active. For
  74. * example we want to monitor RTT for the JVB connection while in P2P mode.
  75. */
  76. class ConnectionAvgStats {
  77. /**
  78. * Creates new <tt>ConnectionAvgStats</tt>
  79. * @param {AvgRTPStatsReporter} avgRtpStatsReporter
  80. * @param {boolean} isP2P
  81. * @param {number} n the number of samples, before arithmetic mean is to be
  82. * calculated and values submitted to the analytics module.
  83. */
  84. constructor(avgRtpStatsReporter, isP2P, n) {
  85. /**
  86. * Is this instance for JVB or P2P connection ?
  87. * @type {boolean}
  88. */
  89. this.isP2P = isP2P;
  90. /**
  91. * How many samples are to be included in arithmetic mean calculation.
  92. * @type {number}
  93. * @private
  94. */
  95. this._n = n;
  96. /**
  97. * The current sample index. Starts from 0 and goes up to {@link _n})
  98. * when analytics report will be submitted.
  99. * @type {number}
  100. * @private
  101. */
  102. this._sampleIdx = 0;
  103. /**
  104. * Average round trip time reported by the ICE candidate pair.
  105. * @type {AverageStatReport}
  106. */
  107. this._avgRTT = new AverageStatReport('rtt');
  108. /**
  109. * Map stores average RTT to the JVB reported by remote participants.
  110. * Mapped per participant id {@link JitsiParticipant.getId}.
  111. *
  112. * This is used only when {@link ConnectionAvgStats.isP2P} equals to
  113. * <tt>false</tt>.
  114. *
  115. * @type {Map<string,AverageStatReport>}
  116. * @private
  117. */
  118. this._avgRemoteRTTMap = new Map();
  119. /**
  120. * The conference for which stats will be collected and reported.
  121. * @type {JitsiConference}
  122. * @private
  123. */
  124. this._avgRtpStatsReporter = avgRtpStatsReporter;
  125. /**
  126. * The latest average E2E RTT for the JVB connection only.
  127. *
  128. * This is used only when {@link ConnectionAvgStats.isP2P} equals to
  129. * <tt>false</tt>.
  130. *
  131. * @type {number}
  132. */
  133. this._avgEnd2EndRTT = undefined;
  134. this._onConnectionStats = (tpc, stats) => {
  135. if (this.isP2P === tpc.isP2P) {
  136. this._calculateAvgStats(stats);
  137. }
  138. };
  139. const conference = avgRtpStatsReporter._conference;
  140. conference.statistics.addConnectionStatsListener(
  141. this._onConnectionStats);
  142. if (!this.isP2P) {
  143. this._onUserLeft = id => this._avgRemoteRTTMap.delete(id);
  144. conference.on(ConferenceEvents.USER_LEFT, this._onUserLeft);
  145. this._onRemoteStatsUpdated
  146. = (id, data) => this._processRemoteStats(id, data);
  147. conference.on(
  148. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  149. this._onRemoteStatsUpdated);
  150. }
  151. }
  152. /**
  153. * Processes next batch of stats.
  154. * @param {go figure} data
  155. * @private
  156. */
  157. _calculateAvgStats(data) {
  158. if (!data) {
  159. logger.error('No stats');
  160. return;
  161. }
  162. if (RTCBrowserType.supportsRTTStatistics()) {
  163. if (data.transport && data.transport.length) {
  164. this._avgRTT.addNext(data.transport[0].rtt);
  165. }
  166. }
  167. this._sampleIdx += 1;
  168. if (this._sampleIdx >= this._n) {
  169. if (RTCBrowserType.supportsRTTStatistics()) {
  170. const conference = this._avgRtpStatsReporter._conference;
  171. const batchReport = {
  172. p2p: this.isP2P,
  173. 'conference_size': conference.getParticipantCount()
  174. };
  175. if (data.transport && data.transport.length) {
  176. Object.assign(batchReport, {
  177. 'local_candidate_type':
  178. data.transport[0].localCandidateType,
  179. 'remote_candidate_type':
  180. data.transport[0].remoteCandidateType,
  181. 'transport_type': data.transport[0].type
  182. });
  183. }
  184. this._avgRTT.appendReport(batchReport);
  185. if (this.isP2P) {
  186. // Report RTT diff only for P2P.
  187. const jvbEnd2EndRTT = this
  188. ._avgRtpStatsReporter.jvbStatsMonitor._avgEnd2EndRTT;
  189. if (!isNaN(jvbEnd2EndRTT)) {
  190. // eslint-disable-next-line dot-notation
  191. batchReport['rtt_diff']
  192. = this._avgRTT.calculate() - jvbEnd2EndRTT;
  193. }
  194. } else {
  195. // Report end to end RTT only for JVB.
  196. const avgRemoteRTT = this._calculateAvgRemoteRTT();
  197. const avgLocalRTT = this._avgRTT.calculate();
  198. this._avgEnd2EndRTT = avgLocalRTT + avgRemoteRTT;
  199. if (!isNaN(avgLocalRTT) && !isNaN(avgRemoteRTT)) {
  200. // eslint-disable-next-line dot-notation
  201. batchReport['end2end_rtt_avg'] = this._avgEnd2EndRTT;
  202. }
  203. }
  204. Statistics.sendAnalytics(createRtpStatsEvent(batchReport));
  205. }
  206. this._resetAvgStats();
  207. }
  208. }
  209. /**
  210. * Calculates arithmetic mean of all RTTs towards the JVB reported by
  211. * participants.
  212. * @return {number|NaN} NaN if not available (not enough data)
  213. * @private
  214. */
  215. _calculateAvgRemoteRTT() {
  216. let count = 0, sum = 0;
  217. // FIXME should we ignore RTT for participant
  218. // who "is having connectivity issues" ?
  219. for (const remoteAvg of this._avgRemoteRTTMap.values()) {
  220. const avg = remoteAvg.calculate();
  221. if (!isNaN(avg)) {
  222. sum += avg;
  223. count += 1;
  224. remoteAvg.reset();
  225. }
  226. }
  227. return sum / count;
  228. }
  229. /**
  230. * Processes {@link ConnectionQualityEvents.REMOTE_STATS_UPDATED} to analyse
  231. * RTT towards the JVB reported by each participant.
  232. * @param {string} id {@link JitsiParticipant.getId}
  233. * @param {go figure in ConnectionQuality.js} data
  234. * @private
  235. */
  236. _processRemoteStats(id, data) {
  237. const validData = typeof data.jvbRTT === 'number';
  238. let rttAvg = this._avgRemoteRTTMap.get(id);
  239. if (!rttAvg && validData) {
  240. rttAvg = new AverageStatReport(`${id}_stat_rtt`);
  241. this._avgRemoteRTTMap.set(id, rttAvg);
  242. }
  243. if (validData) {
  244. rttAvg.addNext(data.jvbRTT);
  245. } else if (rttAvg) {
  246. this._avgRemoteRTTMap.delete(id);
  247. }
  248. }
  249. /**
  250. * Reset cache of all averages and {@link _sampleIdx}.
  251. * @private
  252. */
  253. _resetAvgStats() {
  254. this._avgRTT.reset();
  255. if (this._avgRemoteRTTMap) {
  256. this._avgRemoteRTTMap.clear();
  257. }
  258. this._sampleIdx = 0;
  259. }
  260. /**
  261. *
  262. */
  263. dispose() {
  264. const conference = this._avgRtpStatsReporter._conference;
  265. conference.statistics.removeConnectionStatsListener(
  266. this._onConnectionStats);
  267. if (!this.isP2P) {
  268. conference.off(
  269. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  270. this._onRemoteStatsUpdated);
  271. conference.off(
  272. ConferenceEvents.USER_LEFT,
  273. this._onUserLeft);
  274. }
  275. }
  276. }
  277. /**
  278. * Reports average RTP statistics values (arithmetic mean) to the analytics
  279. * module for things like bit rate, bandwidth, packet loss etc. It keeps track
  280. * of the P2P vs JVB conference modes and submits the values under different
  281. * namespaces (the events for P2P mode have 'p2p.' prefix). Every switch between
  282. * P2P mode resets the data collected so far and averages are calculated from
  283. * scratch.
  284. */
  285. export default class AvgRTPStatsReporter {
  286. /**
  287. * Creates new instance of <tt>AvgRTPStatsReporter</tt>
  288. * @param {JitsiConference} conference
  289. * @param {number} n the number of samples, before arithmetic mean is to be
  290. * calculated and values submitted to the analytics module.
  291. */
  292. constructor(conference, n) {
  293. /**
  294. * How many {@link ConnectionQualityEvents.LOCAL_STATS_UPDATED} samples
  295. * are to be included in arithmetic mean calculation.
  296. * @type {number}
  297. * @private
  298. */
  299. this._n = n;
  300. if (n > 0) {
  301. logger.info(`Avg RTP stats will be calculated every ${n} samples`);
  302. } else {
  303. logger.info('Avg RTP stats reports are disabled.');
  304. // Do not initialize
  305. return;
  306. }
  307. /**
  308. * The current sample index. Starts from 0 and goes up to {@link _n})
  309. * when analytics report will be submitted.
  310. * @type {number}
  311. * @private
  312. */
  313. this._sampleIdx = 0;
  314. /**
  315. * The conference for which stats will be collected and reported.
  316. * @type {JitsiConference}
  317. * @private
  318. */
  319. this._conference = conference;
  320. /**
  321. * Average audio upload bitrate
  322. * XXX What are the units?
  323. * @type {AverageStatReport}
  324. * @private
  325. */
  326. this._avgAudioBitrateUp
  327. = new AverageStatReport('bitrate_audio_upload');
  328. /**
  329. * Average audio download bitrate
  330. * XXX What are the units?
  331. * @type {AverageStatReport}
  332. * @private
  333. */
  334. this._avgAudioBitrateDown
  335. = new AverageStatReport('bitrate_audio_download');
  336. /**
  337. * Average video upload bitrate
  338. * XXX What are the units?
  339. * @type {AverageStatReport}
  340. * @private
  341. */
  342. this._avgVideoBitrateUp
  343. = new AverageStatReport('bitrate_video_upload');
  344. /**
  345. * Average video download bitrate
  346. * XXX What are the units?
  347. * @type {AverageStatReport}
  348. * @private
  349. */
  350. this._avgVideoBitrateDown
  351. = new AverageStatReport('bitrate_video_download');
  352. /**
  353. * Average upload bandwidth
  354. * XXX What are the units?
  355. * @type {AverageStatReport}
  356. * @private
  357. */
  358. this._avgBandwidthUp
  359. = new AverageStatReport('bandwidth_upload');
  360. /**
  361. * Average download bandwidth
  362. * XXX What are the units?
  363. * @type {AverageStatReport}
  364. * @private
  365. */
  366. this._avgBandwidthDown
  367. = new AverageStatReport('bandwidth_download');
  368. /**
  369. * Average total packet loss
  370. * XXX What are the units?
  371. * @type {AverageStatReport}
  372. * @private
  373. */
  374. this._avgPacketLossTotal
  375. = new AverageStatReport('packet_loss_total');
  376. /**
  377. * Average upload packet loss
  378. * XXX What are the units?
  379. * @type {AverageStatReport}
  380. * @private
  381. */
  382. this._avgPacketLossUp
  383. = new AverageStatReport('packet_loss_upload');
  384. /**
  385. * Average download packet loss
  386. * XXX What are the units?
  387. * @type {AverageStatReport}
  388. * @private
  389. */
  390. this._avgPacketLossDown
  391. = new AverageStatReport('packet_loss_download');
  392. /**
  393. * Average FPS for remote videos
  394. * @type {AverageStatReport}
  395. * @private
  396. */
  397. this._avgRemoteFPS = new AverageStatReport('framerate_remote');
  398. /**
  399. * Average FPS for remote screen streaming videos (reported only if not
  400. * a <tt>NaN</tt>).
  401. * @type {AverageStatReport}
  402. * @private
  403. */
  404. this._avgRemoteScreenFPS
  405. = new AverageStatReport('framerate_screen_remote');
  406. /**
  407. * Average FPS for local video (camera)
  408. * @type {AverageStatReport}
  409. * @private
  410. */
  411. this._avgLocalFPS = new AverageStatReport('framerate_local');
  412. /**
  413. * Average FPS for local screen streaming video (reported only if not
  414. * a <tt>NaN</tt>).
  415. * @type {AverageStatReport}
  416. * @private
  417. */
  418. this._avgLocalScreenFPS
  419. = new AverageStatReport('framerate_screen_local');
  420. /**
  421. * Average pixels for remote screen streaming videos (reported only if
  422. * not a <tt>NaN</tt>).
  423. * @type {AverageStatReport}
  424. * @private
  425. */
  426. this._avgRemoteCameraPixels
  427. = new AverageStatReport('pixels_remote');
  428. /**
  429. * Average pixels for remote screen streaming videos (reported only if
  430. * not a <tt>NaN</tt>).
  431. * @type {AverageStatReport}
  432. * @private
  433. */
  434. this._avgRemoteScreenPixels
  435. = new AverageStatReport('pixels_screen_remote');
  436. /**
  437. * Average pixels for local video (camera)
  438. * @type {AverageStatReport}
  439. * @private
  440. */
  441. this._avgLocalCameraPixels
  442. = new AverageStatReport('pixels_local');
  443. /**
  444. * Average pixels for local screen streaming video (reported only if not
  445. * a <tt>NaN</tt>).
  446. * @type {AverageStatReport}
  447. * @private
  448. */
  449. this._avgLocalScreenPixels
  450. = new AverageStatReport('pixels_screen_local');
  451. /**
  452. * Average connection quality as defined by
  453. * the {@link ConnectionQuality} module.
  454. * @type {AverageStatReport}
  455. * @private
  456. */
  457. this._avgCQ = new AverageStatReport('connection_quality');
  458. this._onLocalStatsUpdated = data => this._calculateAvgStats(data);
  459. conference.on(
  460. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  461. this._onLocalStatsUpdated);
  462. this._onP2PStatusChanged = () => {
  463. logger.debug('Resetting average stats calculation');
  464. this._resetAvgStats();
  465. this.jvbStatsMonitor._resetAvgStats();
  466. this.p2pStatsMonitor._resetAvgStats();
  467. };
  468. conference.on(
  469. ConferenceEvents.P2P_STATUS,
  470. this._onP2PStatusChanged);
  471. this._onJvb121StatusChanged = (oldStatus, newStatus) => {
  472. // We want to reset only on the transition from false => true,
  473. // because otherwise those stats are resetted on JVB <=> P2P
  474. // transition.
  475. if (newStatus === true) {
  476. logger.info('Resetting JVB avg RTP stats');
  477. this._resetAvgJvbStats();
  478. }
  479. };
  480. conference.on(
  481. ConferenceEvents.JVB121_STATUS,
  482. this._onJvb121StatusChanged);
  483. this.jvbStatsMonitor
  484. = new ConnectionAvgStats(this, false /* JVB */, n);
  485. this.p2pStatsMonitor
  486. = new ConnectionAvgStats(this, true /* P2P */, n);
  487. }
  488. /**
  489. * Processes next batch of stats reported on
  490. * {@link ConnectionQualityEvents.LOCAL_STATS_UPDATED}.
  491. * @param {go figure} data
  492. * @private
  493. */
  494. _calculateAvgStats(data) {
  495. if (!data) {
  496. logger.error('No stats');
  497. return;
  498. }
  499. const isP2P = this._conference.isP2PActive();
  500. const confSize = this._conference.getParticipantCount();
  501. if (!isP2P && confSize < 2) {
  502. // There's no point in collecting stats for a JVB conference of 1.
  503. // That happens for short period of time after everyone leaves
  504. // the room, until Jicofo terminates the session.
  505. return;
  506. }
  507. /* Uncomment to figure out stats structure
  508. for (const key in data) {
  509. if (data.hasOwnProperty(key)) {
  510. logger.info(`local stat ${key}: `, data[key]);
  511. }
  512. } */
  513. const bitrate = data.bitrate;
  514. const bandwidth = data.bandwidth;
  515. const packetLoss = data.packetLoss;
  516. const frameRate = data.framerate;
  517. const resolution = data.resolution;
  518. if (!bitrate) {
  519. logger.error('No "bitrate"');
  520. return;
  521. } else if (!bandwidth) {
  522. logger.error('No "bandwidth"');
  523. return;
  524. } else if (!packetLoss) {
  525. logger.error('No "packetloss"');
  526. return;
  527. } else if (!frameRate) {
  528. logger.error('No "framerate"');
  529. return;
  530. } else if (!resolution) {
  531. logger.error('No resolution');
  532. return;
  533. }
  534. this._avgAudioBitrateUp.addNext(bitrate.audio.upload);
  535. this._avgAudioBitrateDown.addNext(bitrate.audio.download);
  536. this._avgVideoBitrateUp.addNext(bitrate.video.upload);
  537. this._avgVideoBitrateDown.addNext(bitrate.video.download);
  538. if (RTCBrowserType.supportsBandwidthStatistics()) {
  539. this._avgBandwidthUp.addNext(bandwidth.upload);
  540. this._avgBandwidthDown.addNext(bandwidth.download);
  541. }
  542. this._avgPacketLossUp.addNext(packetLoss.upload);
  543. this._avgPacketLossDown.addNext(packetLoss.download);
  544. this._avgPacketLossTotal.addNext(packetLoss.total);
  545. this._avgCQ.addNext(data.connectionQuality);
  546. if (frameRate) {
  547. this._avgRemoteFPS.addNext(
  548. this._calculateAvgVideoFps(
  549. frameRate, false /* remote */, VideoType.CAMERA));
  550. this._avgRemoteScreenFPS.addNext(
  551. this._calculateAvgVideoFps(
  552. frameRate, false /* remote */, VideoType.DESKTOP));
  553. this._avgLocalFPS.addNext(
  554. this._calculateAvgVideoFps(
  555. frameRate, true /* local */, VideoType.CAMERA));
  556. this._avgLocalScreenFPS.addNext(
  557. this._calculateAvgVideoFps(
  558. frameRate, true /* local */, VideoType.DESKTOP));
  559. }
  560. if (resolution) {
  561. this._avgRemoteCameraPixels.addNext(
  562. this._calculateAvgVideoPixels(
  563. resolution, false /* remote */, VideoType.CAMERA));
  564. this._avgRemoteScreenPixels.addNext(
  565. this._calculateAvgVideoPixels(
  566. resolution, false /* remote */, VideoType.DESKTOP));
  567. this._avgLocalCameraPixels.addNext(
  568. this._calculateAvgVideoPixels(
  569. resolution, true /* local */, VideoType.CAMERA));
  570. this._avgLocalScreenPixels.addNext(
  571. this._calculateAvgVideoPixels(
  572. resolution, true /* local */, VideoType.DESKTOP));
  573. }
  574. this._sampleIdx += 1;
  575. if (this._sampleIdx >= this._n) {
  576. const batchReport = {
  577. p2p: isP2P,
  578. 'conference_size': confSize
  579. };
  580. if (data.transport && data.transport.length) {
  581. Object.assign(batchReport, {
  582. 'local_candidate_type':
  583. data.transport[0].localCandidateType,
  584. 'remote_candidate_type':
  585. data.transport[0].remoteCandidateType,
  586. 'transport_type': data.transport[0].type
  587. });
  588. }
  589. this._avgAudioBitrateUp.appendReport(batchReport);
  590. this._avgAudioBitrateDown.appendReport(batchReport);
  591. this._avgVideoBitrateUp.appendReport(batchReport);
  592. this._avgVideoBitrateDown.appendReport(batchReport);
  593. if (RTCBrowserType.supportsBandwidthStatistics()) {
  594. this._avgBandwidthUp.appendReport(batchReport);
  595. this._avgBandwidthDown.appendReport(batchReport);
  596. }
  597. this._avgPacketLossUp.appendReport(batchReport);
  598. this._avgPacketLossDown.appendReport(batchReport);
  599. this._avgPacketLossTotal.appendReport(batchReport);
  600. this._avgRemoteFPS.appendReport(batchReport);
  601. if (!isNaN(this._avgRemoteScreenFPS.calculate())) {
  602. this._avgRemoteScreenFPS.appendReport(batchReport);
  603. }
  604. this._avgLocalFPS.appendReport(batchReport);
  605. if (!isNaN(this._avgLocalScreenFPS.calculate())) {
  606. this._avgLocalScreenFPS.appendReport(batchReport);
  607. }
  608. this._avgRemoteCameraPixels.appendReport(batchReport);
  609. if (!isNaN(this._avgRemoteScreenPixels.calculate())) {
  610. this._avgRemoteScreenPixels.appendReport(batchReport);
  611. }
  612. this._avgLocalCameraPixels.appendReport(batchReport);
  613. if (!isNaN(this._avgLocalScreenPixels.calculate())) {
  614. this._avgLocalScreenPixels.appendReport(batchReport);
  615. }
  616. this._avgCQ.appendReport(batchReport);
  617. Statistics.sendAnalytics(createRtpStatsEvent(batchReport));
  618. this._resetAvgStats();
  619. }
  620. }
  621. /**
  622. * Calculates average number of pixels for the report
  623. *
  624. * @param {map} peerResolutions a map of peer resolutions
  625. * @param {boolean} isLocal if the average is to be calculated for the local
  626. * video or <tt>false</tt> if for remote videos.
  627. * @param {VideoType} videoType
  628. * @return {number|NaN} average number of pixels or <tt>NaN</tt> if there
  629. * are no samples.
  630. * @private
  631. */
  632. _calculateAvgVideoPixels(peerResolutions, isLocal, videoType) {
  633. let peerPixelsSum = 0;
  634. let peerCount = 0;
  635. const myID = this._conference.myUserId();
  636. for (const peerID of Object.keys(peerResolutions)) {
  637. if (isLocal ? peerID === myID : peerID !== myID) {
  638. const participant
  639. = isLocal
  640. ? null
  641. : this._conference.getParticipantById(peerID);
  642. const videosResolution = peerResolutions[peerID];
  643. // Do not continue without participant for non local peerID
  644. if ((isLocal || participant) && videosResolution) {
  645. const peerAvgPixels = this._calculatePeerAvgVideoPixels(
  646. videosResolution, participant, videoType);
  647. if (!isNaN(peerAvgPixels)) {
  648. peerPixelsSum += peerAvgPixels;
  649. peerCount += 1;
  650. }
  651. }
  652. }
  653. }
  654. return peerPixelsSum / peerCount;
  655. }
  656. /**
  657. * Calculate average pixels for either remote or local participant
  658. * @param {object} videos maps resolution per video SSRC
  659. * @param {JitsiParticipant|null} participant remote participant or
  660. * <tt>null</tt> for local video pixels calculation.
  661. * @param {VideoType} videoType the type of the video for which an average
  662. * will be calculated.
  663. * @return {number|NaN} average video pixels of all participant's videos or
  664. * <tt>NaN</tt> if currently not available
  665. * @private
  666. */
  667. _calculatePeerAvgVideoPixels(videos, participant, videoType) {
  668. let ssrcs = Object.keys(videos).map(ssrc => Number(ssrc));
  669. let videoTracks = null;
  670. // NOTE that this method is supposed to be called for the stats
  671. // received from the current peerconnection.
  672. const tpc = this._conference.getActivePeerConnection();
  673. if (participant) {
  674. videoTracks = participant.getTracksByMediaType(MediaType.VIDEO);
  675. if (videoTracks) {
  676. ssrcs
  677. = ssrcs.filter(
  678. ssrc => videoTracks.find(
  679. track =>
  680. !track.isMuted()
  681. && track.getSSRC() === ssrc
  682. && track.videoType === videoType));
  683. }
  684. } else {
  685. videoTracks = this._conference.getLocalTracks(MediaType.VIDEO);
  686. ssrcs
  687. = ssrcs.filter(
  688. ssrc => videoTracks.find(
  689. track =>
  690. !track.isMuted()
  691. && tpc.getLocalSSRC(track) === ssrc
  692. && track.videoType === videoType));
  693. }
  694. let peerPixelsSum = 0;
  695. let peerSsrcCount = 0;
  696. for (const ssrc of ssrcs) {
  697. const peerSsrcPixels
  698. = Number(videos[ssrc].height) * Number(videos[ssrc].width);
  699. // FPS is reported as 0 for users with no video
  700. if (!isNaN(peerSsrcPixels) && peerSsrcPixels > 0) {
  701. peerPixelsSum += peerSsrcPixels;
  702. peerSsrcCount += 1;
  703. }
  704. }
  705. return peerPixelsSum / peerSsrcCount;
  706. }
  707. /**
  708. * Calculates average FPS for the report
  709. * @param {go figure} frameRate
  710. * @param {boolean} isLocal if the average is to be calculated for the local
  711. * video or <tt>false</tt> if for remote videos.
  712. * @param {VideoType} videoType
  713. * @return {number|NaN} average FPS or <tt>NaN</tt> if there are no samples.
  714. * @private
  715. */
  716. _calculateAvgVideoFps(frameRate, isLocal, videoType) {
  717. let peerFpsSum = 0;
  718. let peerCount = 0;
  719. const myID = this._conference.myUserId();
  720. for (const peerID of Object.keys(frameRate)) {
  721. if (isLocal ? peerID === myID : peerID !== myID) {
  722. const participant
  723. = isLocal
  724. ? null : this._conference.getParticipantById(peerID);
  725. const videosFps = frameRate[peerID];
  726. // Do not continue without participant for non local peerID
  727. if ((isLocal || participant) && videosFps) {
  728. const peerAvgFPS
  729. = this._calculatePeerAvgVideoFps(
  730. videosFps, participant, videoType);
  731. if (!isNaN(peerAvgFPS)) {
  732. peerFpsSum += peerAvgFPS;
  733. peerCount += 1;
  734. }
  735. }
  736. }
  737. }
  738. return peerFpsSum / peerCount;
  739. }
  740. /**
  741. * Calculate average FPS for either remote or local participant
  742. * @param {object} videos maps FPS per video SSRC
  743. * @param {JitsiParticipant|null} participant remote participant or
  744. * <tt>null</tt> for local FPS calculation.
  745. * @param {VideoType} videoType the type of the video for which an average
  746. * will be calculated.
  747. * @return {number|NaN} average FPS of all participant's videos or
  748. * <tt>NaN</tt> if currently not available
  749. * @private
  750. */
  751. _calculatePeerAvgVideoFps(videos, participant, videoType) {
  752. let ssrcs = Object.keys(videos).map(ssrc => Number(ssrc));
  753. let videoTracks = null;
  754. // NOTE that this method is supposed to be called for the stats
  755. // received from the current peerconnection.
  756. const tpc = this._conference.getActivePeerConnection();
  757. if (participant) {
  758. videoTracks = participant.getTracksByMediaType(MediaType.VIDEO);
  759. if (videoTracks) {
  760. ssrcs
  761. = ssrcs.filter(
  762. ssrc => videoTracks.find(
  763. track => !track.isMuted()
  764. && track.getSSRC() === ssrc
  765. && track.videoType === videoType));
  766. }
  767. } else {
  768. videoTracks = this._conference.getLocalTracks(MediaType.VIDEO);
  769. ssrcs
  770. = ssrcs.filter(
  771. ssrc => videoTracks.find(
  772. track => !track.isMuted()
  773. && tpc.getLocalSSRC(track) === ssrc
  774. && track.videoType === videoType));
  775. }
  776. let peerFpsSum = 0;
  777. let peerSsrcCount = 0;
  778. for (const ssrc of ssrcs) {
  779. const peerSsrcFps = Number(videos[ssrc]);
  780. // FPS is reported as 0 for users with no video
  781. if (!isNaN(peerSsrcFps) && peerSsrcFps > 0) {
  782. peerFpsSum += peerSsrcFps;
  783. peerSsrcCount += 1;
  784. }
  785. }
  786. return peerFpsSum / peerSsrcCount;
  787. }
  788. /**
  789. * Resets the stats related to JVB connection. Must not be called when in
  790. * P2P mode, because then the {@link AverageStatReport} instances are
  791. * tracking P2P stats. Note that this should never happen unless something
  792. * is wrong with the P2P and JVB121 events.
  793. * @private
  794. */
  795. _resetAvgJvbStats() {
  796. this._resetAvgStats();
  797. this.jvbStatsMonitor._resetAvgStats();
  798. }
  799. /**
  800. * Reset cache of all averages and {@link _sampleIdx}.
  801. * @private
  802. */
  803. _resetAvgStats() {
  804. this._avgAudioBitrateUp.reset();
  805. this._avgAudioBitrateDown.reset();
  806. this._avgVideoBitrateUp.reset();
  807. this._avgVideoBitrateDown.reset();
  808. this._avgBandwidthUp.reset();
  809. this._avgBandwidthDown.reset();
  810. this._avgPacketLossUp.reset();
  811. this._avgPacketLossDown.reset();
  812. this._avgPacketLossTotal.reset();
  813. this._avgRemoteFPS.reset();
  814. this._avgRemoteScreenFPS.reset();
  815. this._avgLocalFPS.reset();
  816. this._avgLocalScreenFPS.reset();
  817. this._avgRemoteCameraPixels.reset();
  818. this._avgRemoteScreenPixels.reset();
  819. this._avgLocalCameraPixels.reset();
  820. this._avgLocalScreenPixels.reset();
  821. this._avgCQ.reset();
  822. this._sampleIdx = 0;
  823. }
  824. /**
  825. * Unregisters all event listeners and stops working.
  826. */
  827. dispose() {
  828. this._conference.off(
  829. ConferenceEvents.P2P_STATUS,
  830. this._onP2PStatusChanged);
  831. this._conference.off(
  832. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  833. this._onLocalStatsUpdated);
  834. this._conference.off(
  835. ConferenceEvents.JVB121_STATUS,
  836. this._onJvb121StatusChanged);
  837. this.jvbStatsMonitor.dispose();
  838. this.p2pStatsMonitor.dispose();
  839. }
  840. }