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

statistics.js 12KB

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