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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. * Stores all active {@link Statistics} instances.
  14. * @type {Set<Statistics>}
  15. */
  16. let _instances;
  17. /**
  18. * Init statistic options
  19. * @param options
  20. */
  21. Statistics.init = function(options) {
  22. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  23. if (typeof options.pcStatsInterval === 'number') {
  24. Statistics.pcStatsInterval = options.pcStatsInterval;
  25. }
  26. if (typeof options.audioLevelsInterval === 'number') {
  27. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  28. }
  29. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  30. LocalStats.init();
  31. WatchRTC.init(options);
  32. };
  33. /**
  34. * The options to configure Statistics.
  35. * @typedef {Object} StatisticsOptions
  36. * @property {string} userName - The user name to use
  37. * @property {string} roomName - The room name we are currently in.
  38. *
  39. * @param {JitsiConference} conference - The conference instance from which the statistics were initialized.
  40. * @param {StatisticsOptions} options - The options to use creating the
  41. * Statistics.
  42. */
  43. export default function Statistics(conference, options) {
  44. /**
  45. * {@link RTPStats} mapped by {@link TraceablePeerConnection.id} which
  46. * collect RTP statistics for each peerconnection.
  47. * @type {Map<string, RTPStats}
  48. */
  49. this.rtpStatsMap = new Map();
  50. this.eventEmitter = new EventEmitter();
  51. this.conference = conference;
  52. this.xmpp = conference?.xmpp;
  53. this.options = options || {};
  54. Statistics.instances.add(this);
  55. RTCStats.attachToConference(this.conference);
  56. // WatchRTC is not required to work for react native
  57. if (!browser.isReactNative()) {
  58. WatchRTC.start(this.options.roomName, this.options.userName);
  59. }
  60. }
  61. Statistics.audioLevelsEnabled = false;
  62. Statistics.audioLevelsInterval = 200;
  63. Statistics.pcStatsInterval = 10000;
  64. Statistics.disableThirdPartyRequests = false;
  65. Statistics.analytics = analytics;
  66. Object.defineProperty(Statistics, 'instances', {
  67. /**
  68. * Returns the Set holding all active {@link Statistics} instances. Lazily
  69. * initializes the Set to allow any Set polyfills to be applied.
  70. * @type {Set<Statistics>}
  71. */
  72. get() {
  73. if (!_instances) {
  74. _instances = new Set();
  75. }
  76. return _instances;
  77. }
  78. });
  79. /**
  80. * Starts collecting RTP stats for given peerconnection.
  81. * @param {TraceablePeerConnection} peerconnection
  82. */
  83. Statistics.prototype.startRemoteStats = function(peerconnection) {
  84. this.stopRemoteStats(peerconnection);
  85. try {
  86. const rtpStats
  87. = new RTPStats(
  88. peerconnection,
  89. Statistics.audioLevelsInterval,
  90. Statistics.pcStatsInterval,
  91. this.eventEmitter);
  92. rtpStats.start(Statistics.audioLevelsEnabled);
  93. this.rtpStatsMap.set(peerconnection.id, rtpStats);
  94. } catch (e) {
  95. logger.error(`Failed to start collecting remote statistics: ${e}`);
  96. }
  97. };
  98. Statistics.localStats = [];
  99. Statistics.startLocalStats = function(track, callback) {
  100. if (browser.isIosBrowser()) {
  101. // On iOS browsers audio is lost if the audio input device is in use by another app
  102. // https://bugs.webkit.org/show_bug.cgi?id=233473
  103. // The culprit was using the AudioContext, so now we close the AudioContext during
  104. // the track being muted, and re-instantiate it afterwards.
  105. track.addEventListener(
  106. JitsiTrackEvents.NO_DATA_FROM_SOURCE,
  107. /**
  108. * Closes AudioContext on no audio data, and enables it on data received again.
  109. *
  110. * @param {boolean} value - Whether we receive audio data or not.
  111. */
  112. async value => {
  113. if (value) {
  114. for (const localStat of Statistics.localStats) {
  115. localStat.stop();
  116. }
  117. await LocalStats.disconnectAudioContext();
  118. } else {
  119. LocalStats.connectAudioContext();
  120. for (const localStat of Statistics.localStats) {
  121. localStat.start();
  122. }
  123. }
  124. });
  125. }
  126. if (!Statistics.audioLevelsEnabled) {
  127. return;
  128. }
  129. track.addEventListener(
  130. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  131. () => {
  132. Statistics.stopLocalStats(track);
  133. });
  134. const stream = track.getOriginalStream();
  135. const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  136. callback);
  137. this.localStats.push(localStats);
  138. localStats.start();
  139. };
  140. Statistics.prototype.addAudioLevelListener = function(listener) {
  141. if (!Statistics.audioLevelsEnabled) {
  142. return;
  143. }
  144. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  145. };
  146. Statistics.prototype.removeAudioLevelListener = function(listener) {
  147. if (!Statistics.audioLevelsEnabled) {
  148. return;
  149. }
  150. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  151. };
  152. Statistics.prototype.addBeforeDisposedListener = function(listener) {
  153. this.eventEmitter.on(StatisticsEvents.BEFORE_DISPOSED, listener);
  154. };
  155. Statistics.prototype.removeBeforeDisposedListener = function(listener) {
  156. this.eventEmitter.removeListener(
  157. StatisticsEvents.BEFORE_DISPOSED, listener);
  158. };
  159. Statistics.prototype.addConnectionStatsListener = function(listener) {
  160. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  161. };
  162. Statistics.prototype.removeConnectionStatsListener = function(listener) {
  163. this.eventEmitter.removeListener(
  164. StatisticsEvents.CONNECTION_STATS,
  165. listener);
  166. };
  167. Statistics.prototype.addEncodeTimeStatsListener = function(listener) {
  168. this.eventEmitter.on(StatisticsEvents.ENCODE_TIME_STATS, listener);
  169. };
  170. Statistics.prototype.removeEncodeTimeStatsListener = function(listener) {
  171. this.eventEmitter.removeListener(StatisticsEvents.ENCODE_TIME_STATS, listener);
  172. };
  173. Statistics.prototype.addByteSentStatsListener = function(listener) {
  174. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  175. };
  176. Statistics.prototype.removeByteSentStatsListener = function(listener) {
  177. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  178. listener);
  179. };
  180. /**
  181. * Add a listener that would be notified on a LONG_TASKS_STATS event.
  182. *
  183. * @param {Function} listener a function that would be called when notified.
  184. * @returns {void}
  185. */
  186. Statistics.prototype.addLongTasksStatsListener = function(listener) {
  187. this.eventEmitter.on(StatisticsEvents.LONG_TASKS_STATS, listener);
  188. };
  189. /**
  190. * Obtains the current value of the LongTasks event statistics.
  191. *
  192. * @returns {Object|null} stats object if the observer has been
  193. * created, null otherwise.
  194. */
  195. Statistics.prototype.getLongTasksStats = function() {
  196. return this.performanceObserverStats
  197. ? this.performanceObserverStats.getLongTasksStats()
  198. : null;
  199. };
  200. /**
  201. * Removes the given listener for the LONG_TASKS_STATS event.
  202. *
  203. * @param {Function} listener the listener we want to remove.
  204. * @returns {void}
  205. */
  206. Statistics.prototype.removeLongTasksStatsListener = function(listener) {
  207. this.eventEmitter.removeListener(StatisticsEvents.LONG_TASKS_STATS, listener);
  208. };
  209. /**
  210. * Updates the list of speakers for which the audio levels are to be calculated. This is needed for the jvb pc only.
  211. *
  212. * @param {Array<string>} speakerList The list of remote endpoint ids.
  213. * @returns {void}
  214. */
  215. Statistics.prototype.setSpeakerList = function(speakerList) {
  216. for (const rtpStats of Array.from(this.rtpStatsMap.values())) {
  217. if (!rtpStats.peerconnection.isP2P) {
  218. rtpStats.setSpeakerList(speakerList);
  219. }
  220. }
  221. };
  222. Statistics.prototype.dispose = function() {
  223. try {
  224. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  225. for (const tpcId of this.rtpStatsMap.keys()) {
  226. this._stopRemoteStats(tpcId);
  227. }
  228. if (this.eventEmitter) {
  229. this.eventEmitter.removeAllListeners();
  230. }
  231. } finally {
  232. Statistics.instances.delete(this);
  233. }
  234. };
  235. Statistics.stopLocalStats = function(track) {
  236. if (!Statistics.audioLevelsEnabled) {
  237. return;
  238. }
  239. const stream = track.getOriginalStream();
  240. for (let i = 0; i < Statistics.localStats.length; i++) {
  241. if (Statistics.localStats[i].stream === stream) {
  242. const localStats = Statistics.localStats.splice(i, 1);
  243. localStats[0].stop();
  244. break;
  245. }
  246. }
  247. };
  248. /**
  249. * Stops remote RTP stats for given peerconnection ID.
  250. * @param {string} tpcId {@link TraceablePeerConnection.id}
  251. * @private
  252. */
  253. Statistics.prototype._stopRemoteStats = function(tpcId) {
  254. const rtpStats = this.rtpStatsMap.get(tpcId);
  255. if (rtpStats) {
  256. rtpStats.stop();
  257. this.rtpStatsMap.delete(tpcId);
  258. }
  259. };
  260. /**
  261. * Stops collecting RTP stats for given peerconnection
  262. * @param {TraceablePeerConnection} tpc
  263. */
  264. Statistics.prototype.stopRemoteStats = function(tpc) {
  265. this._stopRemoteStats(tpc.id);
  266. };
  267. /**
  268. * Sends the given feedback
  269. *
  270. * @param overall an integer between 1 and 5 indicating the user's rating.
  271. * @param comment the comment from the user.
  272. * @returns {Promise} Resolves immediately.
  273. */
  274. Statistics.prototype.sendFeedback = function(overall, comment) {
  275. // Statistics.analytics.sendEvent is currently fire and forget, without
  276. // confirmation of successful send.
  277. Statistics.analytics.sendEvent(
  278. FEEDBACK,
  279. {
  280. rating: overall,
  281. comment
  282. });
  283. return Promise.resolve();
  284. };
  285. Statistics.LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  286. /**
  287. * Sends event to analytics and logs a message to the logger/console.
  288. *
  289. * @param {string | Object} event the event name, or an object which
  290. * represents the entire event.
  291. * @param {Object} properties properties to attach to the event (if an event
  292. * name as opposed to an event object is provided).
  293. */
  294. Statistics.sendAnalyticsAndLog = function(event, properties = {}) {
  295. if (!event) {
  296. logger.warn('No event or event name given.');
  297. return;
  298. }
  299. let eventToLog;
  300. // Also support an API with a single object as an event.
  301. if (typeof event === 'object') {
  302. eventToLog = event;
  303. } else {
  304. eventToLog = {
  305. name: event,
  306. properties
  307. };
  308. }
  309. logger.debug(JSON.stringify(eventToLog));
  310. // We do this last, because it may modify the object which is passed.
  311. this.analytics.sendEvent(event, properties);
  312. };
  313. /**
  314. * Sends event to analytics.
  315. *
  316. * @param {string | Object} eventName the event name, or an object which
  317. * represents the entire event.
  318. * @param {Object} properties properties to attach to the event
  319. */
  320. Statistics.sendAnalytics = function(eventName, properties = {}) {
  321. this.analytics.sendEvent(eventName, properties);
  322. };