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.

AvgRTPStatsReporter.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /* global __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import * as ConnectionQualityEvents
  4. from '../../service/connectivity/ConnectionQualityEvents';
  5. import * as ConferenceEvents from '../../JitsiConferenceEvents';
  6. import RTCBrowserType from '../RTC/RTCBrowserType';
  7. import Statistics from './statistics';
  8. const logger = getLogger(__filename);
  9. /**
  10. * This will calculate an average for one, named stat and submit it to
  11. * the analytics module when requested. It automatically counts the samples.
  12. */
  13. class AverageStatReport {
  14. /**
  15. * Creates new <tt>AverageStatReport</tt> for given name.
  16. * @param {string} name that's the name of the event that will be reported
  17. * to the analytics module.
  18. */
  19. constructor(name) {
  20. this.name = name;
  21. this.count = 0;
  22. this.sum = 0;
  23. }
  24. /**
  25. * Adds the next value that will be included in the average when
  26. * {@link calculate} is called.
  27. * @param {number} nextValue
  28. */
  29. addNext(nextValue) {
  30. if (typeof nextValue !== 'number') {
  31. logger.error(
  32. `${this.name} - invalid value for idx: ${this.count}`,
  33. nextValue);
  34. return;
  35. }
  36. this.sum += nextValue;
  37. this.count += 1;
  38. }
  39. /**
  40. * Calculates an average for the samples collected using {@link addNext}.
  41. * @return {number|NaN} an average of all collected samples or <tt>NaN</tt>
  42. * if no samples were collected.
  43. */
  44. calculate() {
  45. return this.sum / this.count;
  46. }
  47. /**
  48. * Calculates an average and submit the report to the analytics module.
  49. * @param {boolean} isP2P indicates if the report is to be submitted for
  50. * the P2P connection (when conference is currently in the P2P mode). This
  51. * will add 'p2p.' prefix to the name of the event. All averages should be
  52. * cleared when the conference switches, between P2P and JVB modes.
  53. */
  54. report(isP2P) {
  55. Statistics.analytics.sendEvent(
  56. `${isP2P ? 'p2p.' : ''}${this.name}`,
  57. { value: this.calculate() });
  58. }
  59. /**
  60. * Clears all memory of any samples collected, so that new average can be
  61. * calculated using this instance.
  62. */
  63. reset() {
  64. this.sum = 0;
  65. this.count = 0;
  66. }
  67. }
  68. /**
  69. * Reports average RTP statistics values (arithmetic mean) to the analytics
  70. * module for things like bit rate, bandwidth, packet loss etc. It keeps track
  71. * of the P2P vs JVB conference modes and submits the values under different
  72. * namespaces (the events for P2P mode have 'p2p.' prefix). Every switch between
  73. * P2P mode resets the data collected so far and averages are calculated from
  74. * scratch.
  75. */
  76. export default class AvgRTPStatsReporter {
  77. /**
  78. * Creates new instance of <tt>AvgRTPStatsReporter</tt>
  79. * @param {JitsiConference} conference
  80. * @param {number} n the number of samples, before arithmetic mean is to be
  81. * calculated and values submitted to the analytics module.
  82. */
  83. constructor(conference, n) {
  84. /**
  85. * How many {@link ConnectionQualityEvents.LOCAL_STATS_UPDATED} samples
  86. * are to be included in arithmetic mean calculation.
  87. * @type {number}
  88. * @private
  89. */
  90. this._n = n;
  91. if (n > 0) {
  92. logger.info(`Avg RTP stats will be calculated every ${n} samples`);
  93. } else {
  94. logger.info('Avg RTP stats reports are disabled.');
  95. // Do not initialize
  96. return;
  97. }
  98. /**
  99. * The current sample index. Starts from 0 and goes up to {@link _n})
  100. * when analytics report will be submitted.
  101. * @type {number}
  102. * @private
  103. */
  104. this._sampleIdx = 0;
  105. /**
  106. * The conference for which stats will be collected and reported.
  107. * @type {JitsiConference}
  108. * @private
  109. */
  110. this._conference = conference;
  111. /**
  112. * Average upload bitrate
  113. * @type {AverageStatReport}
  114. * @private
  115. */
  116. this._avgBitrateUp = new AverageStatReport('stat.avg.bitrate.upload');
  117. /**
  118. * Average download bitrate
  119. * @type {AverageStatReport}
  120. * @private
  121. */
  122. this._avgBitrateDown
  123. = new AverageStatReport('stat.avg.bitrate.download');
  124. /**
  125. * Average upload bandwidth
  126. * @type {AverageStatReport}
  127. * @private
  128. */
  129. this._avgBandwidthUp
  130. = new AverageStatReport('stat.avg.bandwidth.upload');
  131. /**
  132. * Average download bandwidth
  133. * @type {AverageStatReport}
  134. * @private
  135. */
  136. this._avgBandwidthDown
  137. = new AverageStatReport('stat.avg.bandwidth.download');
  138. /**
  139. * Average total packet loss
  140. * @type {AverageStatReport}
  141. * @private
  142. */
  143. this._avgPacketLossTotal
  144. = new AverageStatReport('stat.avg.packetloss.total');
  145. /**
  146. * Average upload packet loss
  147. * @type {AverageStatReport}
  148. * @private
  149. */
  150. this._avgPacketLossUp
  151. = new AverageStatReport('stat.avg.packetloss.upload');
  152. /**
  153. * Average download packet loss
  154. * @type {AverageStatReport}
  155. * @private
  156. */
  157. this._avgPacketLossDown
  158. = new AverageStatReport('stat.avg.packetloss.download');
  159. /**
  160. * Average FPS for remote videos
  161. * @type {AverageStatReport}
  162. * @private
  163. */
  164. this._avgRemoteFPS = new AverageStatReport('stat.avg.framerate.remote');
  165. /**
  166. * Map stores average RTT to the JVB reported by remote participants.
  167. * Mapped per participant id {@link JitsiParticipant.getId}.
  168. * @type {Map<string,AverageStatReport>}
  169. * @private
  170. */
  171. this._avgRemoteRTTMap = new Map();
  172. /**
  173. * Average round trip time reported by the ICE candidate pair.
  174. * FIXME currently reported only for P2P
  175. * @type {AverageStatReport}
  176. * @private
  177. */
  178. this._avgRTT = new AverageStatReport('stat.avg.rtt');
  179. /**
  180. * Average FPS for local video
  181. * @type {AverageStatReport}
  182. * @private
  183. */
  184. this._avgLocalFPS = new AverageStatReport('stat.avg.framerate.local');
  185. /**
  186. * Average connection quality as defined by
  187. * the {@link ConnectionQuality} module.
  188. * @type {AverageStatReport}
  189. * @private
  190. */
  191. this._avgCQ = new AverageStatReport('stat.avg.cq');
  192. this._onLocalStatsUpdated = data => this._calculateAvgStats(data);
  193. conference.on(
  194. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  195. this._onLocalStatsUpdated);
  196. this._onRemoteStatsUpdated
  197. = (id, data) => this._processRemoteStats(id, data);
  198. conference.on(
  199. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  200. this._onRemoteStatsUpdated);
  201. this._onP2PStatusChanged = () => {
  202. logger.debug('Resetting average stats calculation');
  203. this._resetAvgStats();
  204. };
  205. conference.on(
  206. ConferenceEvents.P2P_STATUS,
  207. this._onP2PStatusChanged);
  208. this._onUserLeft = id => this._avgRemoteRTTMap.delete(id);
  209. conference.on(ConferenceEvents.USER_LEFT, this._onUserLeft);
  210. }
  211. /**
  212. * Calculates arithmetic mean of all RTTs towards the JVB reported by
  213. * participants.
  214. * @return {number|NaN} NaN if not available (not enough data)
  215. * @private
  216. */
  217. _calculateAvgRemoteRTT() {
  218. let count = 0, sum = 0;
  219. // FIXME should we ignore RTT for participant
  220. // who "is having connectivity issues" ?
  221. for (const remoteAvg of this._avgRemoteRTTMap.values()) {
  222. const avg = remoteAvg.calculate();
  223. if (!isNaN(avg)) {
  224. sum += avg;
  225. count += 1;
  226. remoteAvg.reset();
  227. }
  228. }
  229. return sum / count;
  230. }
  231. /**
  232. * Processes next batch of stats reported on
  233. * {@link ConnectionQualityEvents.LOCAL_STATS_UPDATED}.
  234. * @param {go figure} data
  235. * @private
  236. */
  237. _calculateAvgStats(data) {
  238. const isP2P = this._conference.isP2PActive();
  239. const peerCount = this._conference.getParticipants().length;
  240. if (!isP2P && peerCount < 1) {
  241. // There's no point in collecting stats for a JVB conference of 1.
  242. // That happens for short period of time after everyone leaves
  243. // the room, until Jicofo terminates the session.
  244. return;
  245. }
  246. /* Uncomment to figure out stats structure
  247. for (const key in data) {
  248. if (data.hasOwnProperty(key)) {
  249. logger.info(`local stat ${key}: `, data[key]);
  250. }
  251. } */
  252. if (!data) {
  253. logger.error('No stats');
  254. return;
  255. }
  256. const bitrate = data.bitrate;
  257. const bandwidth = data.bandwidth;
  258. const packetLoss = data.packetLoss;
  259. const frameRate = data.framerate;
  260. if (!bitrate) {
  261. logger.error('No "bitrate"');
  262. return;
  263. } else if (!bandwidth) {
  264. logger.error('No "bandwidth"');
  265. return;
  266. } else if (!packetLoss) {
  267. logger.error('No "packetloss"');
  268. return;
  269. } else if (!frameRate) {
  270. logger.error('No "framerate"');
  271. return;
  272. }
  273. this._avgBitrateUp.addNext(bitrate.upload);
  274. this._avgBitrateDown.addNext(bitrate.download);
  275. if (RTCBrowserType.supportsBandwidthStatistics()) {
  276. this._avgBandwidthUp.addNext(bandwidth.upload);
  277. this._avgBandwidthDown.addNext(bandwidth.download);
  278. }
  279. this._avgPacketLossUp.addNext(packetLoss.upload);
  280. this._avgPacketLossDown.addNext(packetLoss.download);
  281. this._avgPacketLossTotal.addNext(packetLoss.total);
  282. this._avgCQ.addNext(data.connectionQuality);
  283. if (RTCBrowserType.supportsRTTStatistics()) {
  284. if (data.transport && data.transport.length) {
  285. this._avgRTT.addNext(data.transport[0].rtt);
  286. } else {
  287. this._avgRTT.reset();
  288. }
  289. }
  290. if (frameRate) {
  291. this._avgRemoteFPS.addNext(
  292. this._calculateAvgVideoFps(frameRate, false /* remote */));
  293. this._avgLocalFPS.addNext(
  294. this._calculateAvgVideoFps(frameRate, true /* local */));
  295. }
  296. this._sampleIdx += 1;
  297. if (this._sampleIdx >= this._n) {
  298. this._avgBitrateUp.report(isP2P);
  299. this._avgBitrateDown.report(isP2P);
  300. if (RTCBrowserType.supportsBandwidthStatistics()) {
  301. this._avgBandwidthUp.report(isP2P);
  302. this._avgBandwidthDown.report(isP2P);
  303. }
  304. this._avgPacketLossUp.report(isP2P);
  305. this._avgPacketLossDown.report(isP2P);
  306. this._avgPacketLossTotal.report(isP2P);
  307. this._avgRemoteFPS.report(isP2P);
  308. this._avgLocalFPS.report(isP2P);
  309. this._avgCQ.report(isP2P);
  310. if (RTCBrowserType.supportsRTTStatistics()) {
  311. this._avgRTT.report(isP2P);
  312. if (!isP2P) {
  313. const avgRemoteRTT = this._calculateAvgRemoteRTT();
  314. const avgLocalRTT = this._avgRTT.calculate();
  315. if (!isNaN(avgLocalRTT) && !isNaN(avgRemoteRTT)) {
  316. Statistics.analytics.sendEvent(
  317. 'stat.avg.end2endrtt',
  318. avgLocalRTT + avgRemoteRTT);
  319. }
  320. }
  321. }
  322. this._resetAvgStats();
  323. }
  324. }
  325. /**
  326. * Calculates average FPS for the report
  327. * @param {go figure} frameRate
  328. * @param {boolean} isLocal if the average is to be calculated for the local
  329. * video or <tt>false</tt> if for remote videos.
  330. * @return {number|NaN} average FPS or <tt>NaN</tt> if there are no samples.
  331. * @private
  332. */
  333. _calculateAvgVideoFps(frameRate, isLocal) {
  334. let peerCount = 0;
  335. let subFrameAvg = 0;
  336. const myID = this._conference.myUserId();
  337. for (const peerID of Object.keys(frameRate)) {
  338. if (isLocal ? peerID === myID : peerID !== myID) {
  339. const videos = frameRate[peerID];
  340. const ssrcs = Object.keys(videos);
  341. if (ssrcs.length) {
  342. let peerAvg = 0;
  343. for (const ssrc of ssrcs) {
  344. peerAvg += parseInt(videos[ssrc], 10);
  345. }
  346. peerAvg /= ssrcs.length;
  347. subFrameAvg += peerAvg;
  348. peerCount += 1;
  349. }
  350. }
  351. }
  352. return subFrameAvg / peerCount;
  353. }
  354. /**
  355. * Processes {@link ConnectionQualityEvents.REMOTE_STATS_UPDATED} to analyse
  356. * RTT towards the JVB reported by each participant.
  357. * @param {string} id {@link JitsiParticipant.getId}
  358. * @param {go figure in ConnectionQuality.js} data
  359. * @private
  360. */
  361. _processRemoteStats(id, data) {
  362. const validData = typeof data.jvbRTT === 'number';
  363. let rttAvg = this._avgRemoteRTTMap.get(id);
  364. if (!rttAvg && validData) {
  365. rttAvg = new AverageStatReport(`${id}.stat.rtt`);
  366. this._avgRemoteRTTMap.set(id, rttAvg);
  367. }
  368. if (validData) {
  369. rttAvg.addNext(data.jvbRTT);
  370. } else if (rttAvg) {
  371. this._avgRemoteRTTMap.delete(id);
  372. }
  373. }
  374. /**
  375. * Reset cache of all averages and {@link _sampleIdx}.
  376. * @private
  377. */
  378. _resetAvgStats() {
  379. this._avgBitrateUp.reset();
  380. this._avgBitrateDown.reset();
  381. this._avgBandwidthUp.reset();
  382. this._avgBandwidthDown.reset();
  383. this._avgPacketLossUp.reset();
  384. this._avgPacketLossDown.reset();
  385. this._avgRemoteFPS.reset();
  386. this._avgLocalFPS.reset();
  387. this._avgCQ.reset();
  388. this._avgRTT.reset();
  389. this._avgRemoteRTTMap.clear();
  390. this._sampleIdx = 0;
  391. }
  392. /**
  393. * Unregisters all event listeners and stops working.
  394. */
  395. dispose() {
  396. this._conference.off(
  397. ConferenceEvents.P2P_STATUS,
  398. this._onP2PStatusChanged);
  399. this._conference.off(
  400. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  401. this._onLocalStatsUpdated);
  402. this._conference.off(
  403. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  404. this._onRemoteStatsUpdated);
  405. this._conference.off(
  406. ConferenceEvents.USER_LEFT,
  407. this._onUserLeft);
  408. }
  409. }