您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

statistics.js 12KB

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