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.

statistics.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { JitsiTrackEvents } from '../../JitsiTrackEvents';
  2. import { FEEDBACK } from '../../service/statistics/AnalyticsEvents';
  3. import * as StatisticsEvents from '../../service/statistics/Events';
  4. import RTCStats from '../RTCStats/RTCStats';
  5. import browser from '../browser';
  6. import EventEmitter from '../util/EventEmitter';
  7. import WatchRTC from '../watchRTC/WatchRTC';
  8. import analytics from './AnalyticsAdapter';
  9. import LocalStats from './LocalStatsCollector';
  10. import RTPStats from './RTPStatsCollector';
  11. const logger = require('@jitsi/logger').getLogger('modules/statistics/statistics');
  12. /**
  13. * Statistics class provides various functionality related to collecting and reporting statistics.
  14. */
  15. export default class Statistics {
  16. /**
  17. * Stores all active Statistics instances.
  18. * @type {Set<Statistics>}
  19. */
  20. static _instances;
  21. /**
  22. * Static getter for instances property
  23. * Returns the Set holding all active Statistics instances. Lazily
  24. * initializes the Set to allow any Set polyfills to be applied.
  25. * @type {Set<Statistics>}
  26. */
  27. static get instances() {
  28. if (!Statistics._instances) {
  29. Statistics._instances = new Set();
  30. }
  31. return Statistics._instances;
  32. }
  33. /**
  34. * Flag indicating whether audio levels are enabled or not.
  35. * @static
  36. * @type {boolean}
  37. */
  38. static audioLevelsEnabled = false;
  39. /**
  40. * The interval for audio levels stats collection.
  41. * @static
  42. * @type {number}
  43. */
  44. static audioLevelsInterval = 200;
  45. /**
  46. * The interval for peer connection stats collection.
  47. * @static
  48. * @type {number}
  49. */
  50. static pcStatsInterval = 10000;
  51. /**
  52. * Flag indicating whether third party requests are disabled.
  53. * @static
  54. * @type {boolean}
  55. */
  56. static disableThirdPartyRequests = false;
  57. /**
  58. * Analytics adapter for sending events.
  59. * @static
  60. * @type {Object}
  61. */
  62. static analytics = analytics;
  63. /**
  64. * Array holding local statistics collectors.
  65. * @static
  66. * @type {Array}
  67. */
  68. static localStats = [];
  69. /**
  70. * Local JID constant.
  71. * @static
  72. * @type {string}
  73. */
  74. static LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  75. /**
  76. * Init statistic options
  77. * @static
  78. * @param {Object} options - The options to initialize statistics with
  79. */
  80. static init(options) {
  81. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  82. if (typeof options.pcStatsInterval === 'number') {
  83. Statistics.pcStatsInterval = options.pcStatsInterval;
  84. }
  85. if (typeof options.audioLevelsInterval === 'number') {
  86. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  87. }
  88. if (typeof options.longTasksStatsInterval === 'number') {
  89. Statistics.longTasksStatsInterval = options.longTasksStatsInterval;
  90. }
  91. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  92. LocalStats.init();
  93. WatchRTC.init(options);
  94. }
  95. /**
  96. * Starts collecting local statistics for a track.
  97. * @static
  98. * @param {JitsiTrack} track - The track to collect statistics for
  99. * @param {Function} callback - The callback to invoke with audio levels
  100. */
  101. static startLocalStats(track, callback) {
  102. if (browser.isIosBrowser()) {
  103. // On iOS browsers audio is lost if the audio input device is in use by another app
  104. // https://bugs.webkit.org/show_bug.cgi?id=233473
  105. // The culprit was using the AudioContext, so now we close the AudioContext during
  106. // the track being muted, and re-instantiate it afterwards.
  107. track.addEventListener(
  108. JitsiTrackEvents.NO_DATA_FROM_SOURCE,
  109. /**
  110. * Closes AudioContext on no audio data, and enables it on data received again.
  111. *
  112. * @param {boolean} value - Whether we receive audio data or not.
  113. */
  114. async value => {
  115. if (value) {
  116. for (const localStat of Statistics.localStats) {
  117. localStat.stop();
  118. }
  119. await LocalStats.disconnectAudioContext();
  120. } else {
  121. LocalStats.connectAudioContext();
  122. for (const localStat of Statistics.localStats) {
  123. localStat.start();
  124. }
  125. }
  126. });
  127. }
  128. if (!Statistics.audioLevelsEnabled) {
  129. return;
  130. }
  131. track.addEventListener(
  132. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  133. () => {
  134. Statistics.stopLocalStats(track);
  135. });
  136. const stream = track.getOriginalStream();
  137. const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  138. callback);
  139. this.localStats.push(localStats);
  140. localStats.start();
  141. }
  142. /**
  143. * Stops collecting local statistics for a track.
  144. * @static
  145. * @param {JitsiTrack} track - The track to stop collecting statistics for
  146. */
  147. static stopLocalStats(track) {
  148. if (!Statistics.audioLevelsEnabled) {
  149. return;
  150. }
  151. const stream = track.getOriginalStream();
  152. for (let i = 0; i < Statistics.localStats.length; i++) {
  153. if (Statistics.localStats[i].stream === stream) {
  154. const localStats = Statistics.localStats.splice(i, 1);
  155. localStats[0].stop();
  156. break;
  157. }
  158. }
  159. }
  160. /**
  161. * Sends event to analytics and logs a message to the logger/console.
  162. * @static
  163. * @param {string | Object} event - The event name, or an object which represents the entire event
  164. * @param {Object} properties - Properties to attach to the event
  165. */
  166. static sendAnalyticsAndLog(event, properties = {}) {
  167. if (!event) {
  168. logger.warn('No event or event name given.');
  169. return;
  170. }
  171. let eventToLog;
  172. // Also support an API with a single object as an event.
  173. if (typeof event === 'object') {
  174. eventToLog = event;
  175. } else {
  176. eventToLog = {
  177. name: event,
  178. properties
  179. };
  180. }
  181. logger.debug(JSON.stringify(eventToLog));
  182. // We do this last, because it may modify the object which is passed.
  183. this.analytics.sendEvent(event, properties);
  184. }
  185. /**
  186. * Sends event to analytics.
  187. * @static
  188. * @param {string | Object} eventName - The event name, or an object which represents the entire event
  189. * @param {Object} properties - Properties to attach to the event
  190. */
  191. static sendAnalytics(eventName, properties = {}) {
  192. this.analytics.sendEvent(eventName, properties);
  193. }
  194. /**
  195. * The options to configure Statistics.
  196. * @typedef {Object} StatisticsOptions
  197. * @property {string} userName - The user name to use
  198. * @property {string} roomName - The room name we are currently in.
  199. *
  200. * @param {JitsiConference} conference - The conference instance from which the statistics were initialized.
  201. * @param {StatisticsOptions} options - The options to use creating the
  202. * Statistics.
  203. */
  204. constructor(conference, options) {
  205. /**
  206. * {@link RTPStats} mapped by {@link TraceablePeerConnection.id} which
  207. * collect RTP statistics for each peerconnection.
  208. * @type {Map<string, RTPStats}
  209. */
  210. this.rtpStatsMap = new Map();
  211. this.eventEmitter = new EventEmitter();
  212. this.conference = conference;
  213. this.xmpp = conference?.xmpp;
  214. this.options = options || {};
  215. Statistics.instances.add(this);
  216. RTCStats.attachToConference(this.conference);
  217. // WatchRTC is not required to work for react native
  218. if (!browser.isReactNative()) {
  219. WatchRTC.start(this.options.roomName, this.options.userName);
  220. }
  221. }
  222. /**
  223. * Starts collecting RTP stats for given peerconnection.
  224. * @param {TraceablePeerConnection} peerconnection
  225. */
  226. startRemoteStats(peerconnection) {
  227. this.stopRemoteStats(peerconnection);
  228. try {
  229. const rtpStats
  230. = new RTPStats(
  231. peerconnection,
  232. Statistics.audioLevelsInterval,
  233. Statistics.pcStatsInterval,
  234. this.eventEmitter);
  235. rtpStats.start(Statistics.audioLevelsEnabled);
  236. this.rtpStatsMap.set(peerconnection.id, rtpStats);
  237. } catch (e) {
  238. logger.error(`Failed to start collecting remote statistics: ${e}`);
  239. }
  240. }
  241. /**
  242. * Adds a listener for audio level events.
  243. * @param {Function} listener - The listener to add
  244. */
  245. addAudioLevelListener(listener) {
  246. if (!Statistics.audioLevelsEnabled) {
  247. return;
  248. }
  249. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  250. }
  251. /**
  252. * Removes an audio level listener.
  253. * @param {Function} listener - The listener to remove
  254. */
  255. removeAudioLevelListener(listener) {
  256. if (!Statistics.audioLevelsEnabled) {
  257. return;
  258. }
  259. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  260. }
  261. /**
  262. * Adds a listener for before disposed events.
  263. * @param {Function} listener - The listener to add
  264. */
  265. addBeforeDisposedListener(listener) {
  266. this.eventEmitter.on(StatisticsEvents.BEFORE_DISPOSED, listener);
  267. }
  268. /**
  269. * Removes a before disposed listener.
  270. * @param {Function} listener - The listener to remove
  271. */
  272. removeBeforeDisposedListener(listener) {
  273. this.eventEmitter.removeListener(
  274. StatisticsEvents.BEFORE_DISPOSED, listener);
  275. }
  276. /**
  277. * Adds a listener for connection stats events.
  278. * @param {Function} listener - The listener to add
  279. */
  280. addConnectionStatsListener(listener) {
  281. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  282. }
  283. /**
  284. * Removes a connection stats listener.
  285. * @param {Function} listener - The listener to remove
  286. */
  287. removeConnectionStatsListener(listener) {
  288. this.eventEmitter.removeListener(
  289. StatisticsEvents.CONNECTION_STATS,
  290. listener);
  291. }
  292. /**
  293. * Adds a listener for encode time stats events.
  294. * @param {Function} listener - The listener to add
  295. */
  296. addEncodeTimeStatsListener(listener) {
  297. this.eventEmitter.on(StatisticsEvents.ENCODE_TIME_STATS, listener);
  298. }
  299. /**
  300. * Removes an encode time stats listener.
  301. * @param {Function} listener - The listener to remove
  302. */
  303. removeEncodeTimeStatsListener(listener) {
  304. this.eventEmitter.removeListener(StatisticsEvents.ENCODE_TIME_STATS, listener);
  305. }
  306. /**
  307. * Adds a listener for byte sent stats events.
  308. * @param {Function} listener - The listener to add
  309. */
  310. addByteSentStatsListener(listener) {
  311. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  312. }
  313. /**
  314. * Removes a byte sent stats listener.
  315. * @param {Function} listener - The listener to remove
  316. */
  317. removeByteSentStatsListener(listener) {
  318. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  319. listener);
  320. }
  321. /**
  322. * Add a listener that would be notified on a LONG_TASKS_STATS event.
  323. *
  324. * @param {Function} listener a function that would be called when notified.
  325. * @returns {void}
  326. */
  327. addLongTasksStatsListener(listener) {
  328. this.eventEmitter.on(StatisticsEvents.LONG_TASKS_STATS, listener);
  329. }
  330. /**
  331. * Removes the given listener for the LONG_TASKS_STATS event.
  332. *
  333. * @param {Function} listener the listener we want to remove.
  334. * @returns {void}
  335. */
  336. removeLongTasksStatsListener(listener) {
  337. this.eventEmitter.removeListener(StatisticsEvents.LONG_TASKS_STATS, listener);
  338. }
  339. /**
  340. * Updates the list of speakers for which the audio levels are to be calculated. This is needed for the jvb pc only.
  341. *
  342. * @param {Array<string>} speakerList The list of remote endpoint ids.
  343. * @returns {void}
  344. */
  345. setSpeakerList(speakerList) {
  346. for (const rtpStats of Array.from(this.rtpStatsMap.values())) {
  347. if (!rtpStats.peerconnection.isP2P) {
  348. rtpStats.setSpeakerList(speakerList);
  349. }
  350. }
  351. }
  352. /**
  353. * Disposes of this instance, stopping any ongoing stats collection.
  354. */
  355. dispose() {
  356. try {
  357. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  358. for (const tpcId of this.rtpStatsMap.keys()) {
  359. this._stopRemoteStats(tpcId);
  360. }
  361. if (this.eventEmitter) {
  362. this.eventEmitter.removeAllListeners();
  363. }
  364. } finally {
  365. Statistics.instances.delete(this);
  366. }
  367. }
  368. /**
  369. * Stops remote RTP stats for given peerconnection ID.
  370. * @param {string} tpcId {@link TraceablePeerConnection.id}
  371. * @private
  372. */
  373. _stopRemoteStats(tpcId) {
  374. const rtpStats = this.rtpStatsMap.get(tpcId);
  375. if (rtpStats) {
  376. rtpStats.stop();
  377. this.rtpStatsMap.delete(tpcId);
  378. }
  379. }
  380. /**
  381. * Stops collecting RTP stats for given peerconnection
  382. * @param {TraceablePeerConnection} tpc
  383. */
  384. stopRemoteStats(tpc) {
  385. this._stopRemoteStats(tpc.id);
  386. }
  387. /**
  388. * Sends the given feedback
  389. *
  390. * @param {number} overall an integer between 1 and 5 indicating the user's rating.
  391. * @param {string} comment the comment from the user.
  392. * @returns {Promise} Resolves immediately.
  393. */
  394. sendFeedback(overall, comment) {
  395. // Statistics.analytics.sendEvent is currently fire and forget, without
  396. // confirmation of successful send.
  397. Statistics.analytics.sendEvent(
  398. FEEDBACK,
  399. {
  400. rating: overall,
  401. comment
  402. });
  403. return Promise.resolve();
  404. }
  405. }