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

statistics.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. import EventEmitter from 'events';
  2. import analytics from './AnalyticsAdapter';
  3. import CallStats from './CallStats';
  4. import LocalStats from './LocalStatsCollector';
  5. import RTPStats from './RTPStatsCollector';
  6. import RTCBrowserType from '../RTC/RTCBrowserType';
  7. import Settings from '../settings/Settings';
  8. import ScriptUtil from '../util/ScriptUtil';
  9. import JitsiTrackError from '../../JitsiTrackError';
  10. import * as StatisticsEvents from '../../service/statistics/Events';
  11. const logger = require('jitsi-meet-logger').getLogger(__filename);
  12. /**
  13. * Stores all active {@link Statistics} instances.
  14. * @type {Set<Statistics>}
  15. */
  16. let _instances;
  17. /**
  18. * True if callstats API is loaded
  19. */
  20. let isCallstatsLoaded = false;
  21. /**
  22. * Since callstats.io is a third party, we cannot guarantee the quality of their
  23. * service. More specifically, their server may take noticeably long time to
  24. * respond. Consequently, it is in our best interest (in the sense that the
  25. * intergration of callstats.io is pretty important to us but not enough to
  26. * allow it to prevent people from joining a conference) to (1) start
  27. * downloading their API as soon as possible and (2) do the downloading
  28. * asynchronously.
  29. *
  30. * @param customScriptUrl
  31. */
  32. function loadCallStatsAPI(customScriptUrl) {
  33. if (!isCallstatsLoaded) {
  34. ScriptUtil.loadScript(
  35. customScriptUrl ? customScriptUrl
  36. : 'https://api.callstats.io/static/callstats-ws.min.js',
  37. /* async */ true,
  38. /* prepend */ true);
  39. isCallstatsLoaded = true;
  40. }
  41. // FIXME At the time of this writing, we hope that the callstats.io API will
  42. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  43. }
  44. /**
  45. * callstats strips any additional fields from Error except for "name", "stack",
  46. * "message" and "constraintName". So we need to bundle additional information
  47. * from JitsiTrackError into error passed to callstats to preserve valuable
  48. * information about error.
  49. * @param {JitsiTrackError} error
  50. */
  51. function formatJitsiTrackErrorForCallStats(error) {
  52. const err = new Error();
  53. // Just copy original stack from error
  54. err.stack = error.stack;
  55. // Combine name from error's name plus (possibly) name of original GUM error
  56. err.name = (error.name || 'Unknown error') + (error.gum && error.gum.error
  57. && error.gum.error.name ? ` - ${error.gum.error.name}` : '');
  58. // Put all constraints into this field. For constraint failed errors we will
  59. // still know which exactly constraint failed as it will be a part of
  60. // message.
  61. err.constraintName = error.gum && error.gum.constraints
  62. ? JSON.stringify(error.gum.constraints) : '';
  63. // Just copy error's message.
  64. err.message = error.message;
  65. return err;
  66. }
  67. /**
  68. * Init statistic options
  69. * @param options
  70. */
  71. Statistics.init = function(options) {
  72. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  73. if (typeof options.audioLevelsInterval === 'number') {
  74. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  75. }
  76. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  77. };
  78. /**
  79. *
  80. * @param xmpp
  81. * @param options
  82. */
  83. export default function Statistics(xmpp, options) {
  84. /**
  85. * {@link RTPStats} mapped by {@link TraceablePeerConnection.id} which
  86. * collect RTP statistics for each peerconnection.
  87. * @type {Map<string, RTPStats}
  88. */
  89. this.rtpStatsMap = new Map();
  90. this.eventEmitter = new EventEmitter();
  91. this.xmpp = xmpp;
  92. this.options = options || {};
  93. this.callStatsIntegrationEnabled
  94. = this.options.callStatsID && this.options.callStatsSecret
  95. // Even though AppID and AppSecret may be specified, the integration
  96. // of callstats.io may be disabled because of globally-disallowed
  97. // requests to any third parties.
  98. && (Statistics.disableThirdPartyRequests !== true);
  99. if (this.callStatsIntegrationEnabled) {
  100. if (!RTCBrowserType.isReactNative()) {
  101. loadCallStatsAPI(this.options.callStatsCustomScriptUrl);
  102. }
  103. if (!this.options.callStatsConfIDNamespace) {
  104. logger.warn('"callStatsConfIDNamespace" is not defined');
  105. }
  106. }
  107. /**
  108. * Stores {@link CallStats} instances for each
  109. * {@link TraceablePeerConnection} (one {@link CallStats} instance serves
  110. * one TPC). The instances are mapped by {@link TraceablePeerConnection.id}.
  111. * @type {Map<number, CallStats>}
  112. */
  113. this.callsStatsInstances = new Map();
  114. Statistics.instances.add(this);
  115. }
  116. Statistics.audioLevelsEnabled = false;
  117. Statistics.audioLevelsInterval = 200;
  118. Statistics.disableThirdPartyRequests = false;
  119. Statistics.analytics = analytics;
  120. Object.defineProperty(Statistics, 'instances', {
  121. /**
  122. * Returns the Set holding all active {@link Statistics} instances. Lazily
  123. * initializes the Set to allow any Set polyfills to be applied.
  124. * @type {Set<Statistics>}
  125. */
  126. get() {
  127. if (!_instances) {
  128. _instances = new Set();
  129. }
  130. return _instances;
  131. }
  132. });
  133. /**
  134. * Starts collecting RTP stats for given peerconnection.
  135. * @param {TraceablePeerConnection} peerconnection
  136. */
  137. Statistics.prototype.startRemoteStats = function(peerconnection) {
  138. this.stopRemoteStats(peerconnection);
  139. try {
  140. const rtpStats
  141. = new RTPStats(peerconnection,
  142. Statistics.audioLevelsInterval, 2000, this.eventEmitter);
  143. rtpStats.start(Statistics.audioLevelsEnabled);
  144. this.rtpStatsMap.set(peerconnection.id, rtpStats);
  145. } catch (e) {
  146. logger.error(`Failed to start collecting remote statistics: ${e}`);
  147. }
  148. };
  149. Statistics.localStats = [];
  150. Statistics.startLocalStats = function(stream, callback) {
  151. if (!Statistics.audioLevelsEnabled) {
  152. return;
  153. }
  154. const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  155. callback);
  156. this.localStats.push(localStats);
  157. localStats.start();
  158. };
  159. Statistics.prototype.addAudioLevelListener = function(listener) {
  160. if (!Statistics.audioLevelsEnabled) {
  161. return;
  162. }
  163. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  164. };
  165. Statistics.prototype.removeAudioLevelListener = function(listener) {
  166. if (!Statistics.audioLevelsEnabled) {
  167. return;
  168. }
  169. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  170. };
  171. Statistics.prototype.addBeforeDisposedListener = function(listener) {
  172. this.eventEmitter.on(StatisticsEvents.BEFORE_DISPOSED, listener);
  173. };
  174. Statistics.prototype.removeBeforeDisposedListener = function(listener) {
  175. this.eventEmitter.removeListener(
  176. StatisticsEvents.BEFORE_DISPOSED, listener);
  177. };
  178. Statistics.prototype.addConnectionStatsListener = function(listener) {
  179. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  180. };
  181. Statistics.prototype.removeConnectionStatsListener = function(listener) {
  182. this.eventEmitter.removeListener(
  183. StatisticsEvents.CONNECTION_STATS,
  184. listener);
  185. };
  186. Statistics.prototype.addByteSentStatsListener = function(listener) {
  187. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  188. };
  189. Statistics.prototype.removeByteSentStatsListener = function(listener) {
  190. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  191. listener);
  192. };
  193. Statistics.prototype.dispose = function() {
  194. try {
  195. // NOTE Before reading this please see the comment in stopCallStats...
  196. //
  197. // Here we prevent from emitting the event twice in case it will be
  198. // triggered from stopCallStats.
  199. // If the event is triggered from here it means that the logs will not
  200. // be submitted anyway (because there is no CallStats instance), but
  201. // we're doing that for the sake of some kind of consistency.
  202. if (!this.callsStatsInstances.size) {
  203. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  204. }
  205. for (const callStats of this.callsStatsInstances.values()) {
  206. this.stopCallStats(callStats.tpc);
  207. }
  208. for (const tpcId of this.rtpStatsMap.keys()) {
  209. this._stopRemoteStats(tpcId);
  210. }
  211. if (this.eventEmitter) {
  212. this.eventEmitter.removeAllListeners();
  213. }
  214. } finally {
  215. Statistics.instances.delete(this);
  216. }
  217. };
  218. Statistics.stopLocalStats = function(stream) {
  219. if (!Statistics.audioLevelsEnabled) {
  220. return;
  221. }
  222. for (let i = 0; i < Statistics.localStats.length; i++) {
  223. if (Statistics.localStats[i].stream === stream) {
  224. const localStats = Statistics.localStats.splice(i, 1);
  225. localStats[0].stop();
  226. break;
  227. }
  228. }
  229. };
  230. /**
  231. * Stops remote RTP stats for given peerconnection ID.
  232. * @param {string} tpcId {@link TraceablePeerConnection.id}
  233. * @private
  234. */
  235. Statistics.prototype._stopRemoteStats = function(tpcId) {
  236. const rtpStats = this.rtpStatsMap.get(tpcId);
  237. if (rtpStats) {
  238. rtpStats.stop();
  239. this.rtpStatsMap.delete(tpcId);
  240. }
  241. };
  242. /**
  243. * Stops collecting RTP stats for given peerconnection
  244. * @param {TraceablePeerConnection} tpc
  245. */
  246. Statistics.prototype.stopRemoteStats = function(tpc) {
  247. this._stopRemoteStats(tpc.id);
  248. };
  249. // CALSTATS METHODS
  250. /**
  251. * Initializes the callstats.io API.
  252. * @param {TraceablePeerConnection} tpc the {@link TraceablePeerConnection}
  253. * instance for which CalStats will be started.
  254. * @param {string} remoteUserID
  255. */
  256. Statistics.prototype.startCallStats = function(tpc, remoteUserID) {
  257. if (!this.callStatsIntegrationEnabled) {
  258. return;
  259. } else if (this.callsStatsInstances.has(tpc.id)) {
  260. logger.error('CallStats instance for ${tpc} exists already');
  261. return;
  262. }
  263. if (!CallStats.isBackendInitialized()) {
  264. const userName = Settings.callStatsUserName;
  265. if (!CallStats.initBackend({
  266. callStatsID: this.options.callStatsID,
  267. callStatsSecret: this.options.callStatsSecret,
  268. userName,
  269. aliasName: this.options.callStatsAliasName
  270. })) {
  271. // Backend initialization failed bad
  272. return;
  273. }
  274. }
  275. logger.info(`Starting CallStats for ${tpc}...`);
  276. const newInstance
  277. = new CallStats(
  278. tpc,
  279. {
  280. confID: this._getCallStatsConfID(),
  281. remoteUserID
  282. });
  283. this.callsStatsInstances.set(tpc.id, newInstance);
  284. };
  285. /**
  286. * Obtains the list of *all* {@link CallStats} instances collected from every
  287. * valid {@link Statistics} instance.
  288. * @return {Set<CallStats>}
  289. * @private
  290. */
  291. Statistics._getAllCallStatsInstances = function() {
  292. const csInstances = new Set();
  293. for (const statistics of Statistics.instances) {
  294. for (const cs of statistics.callsStatsInstances.values()) {
  295. csInstances.add(cs);
  296. }
  297. }
  298. return csInstances;
  299. };
  300. /**
  301. * Constructs the CallStats conference ID based on the options currently
  302. * configured in this instance.
  303. * @return {string}
  304. * @private
  305. */
  306. Statistics.prototype._getCallStatsConfID = function() {
  307. // The conference ID is case sensitive!!!
  308. return this.options.callStatsConfIDNamespace
  309. ? `${this.options.callStatsConfIDNamespace}/${this.options.roomName}`
  310. : this.options.roomName;
  311. };
  312. /**
  313. * Removes the callstats.io instances.
  314. */
  315. Statistics.prototype.stopCallStats = function(tpc) {
  316. const callStatsInstance = this.callsStatsInstances.get(tpc.id);
  317. if (callStatsInstance) {
  318. // FIXME the original purpose of adding BEFORE_DISPOSED event was to be
  319. // able to submit the last log batch from jitsi-meet to CallStats. After
  320. // recent changes we dispose the CallStats earlier
  321. // (before Statistics.dispose), so we need to emit this event here to
  322. // give this last chance for final log batch submission.
  323. //
  324. // Eventually there should be a separate module called "log storage"
  325. // which should emit proper events when it's underlying
  326. // CallStats instance is going away.
  327. if (this.callsStatsInstances.size === 1) {
  328. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  329. }
  330. this.callsStatsInstances.delete(tpc.id);
  331. // The fabric needs to be terminated when being stopped
  332. callStatsInstance.sendTerminateEvent();
  333. }
  334. };
  335. /**
  336. * Returns true if the callstats integration is enabled, otherwise returns
  337. * false.
  338. *
  339. * @returns true if the callstats integration is enabled, otherwise returns
  340. * false.
  341. */
  342. Statistics.prototype.isCallstatsEnabled = function() {
  343. return this.callStatsIntegrationEnabled;
  344. };
  345. /**
  346. * Logs either resume or hold event for the given peer connection.
  347. * @param {TraceablePeerConnection} tpc the connection for which event will be
  348. * reported
  349. * @param {boolean} isResume true for resume or false for hold
  350. */
  351. Statistics.prototype.sendConnectionResumeOrHoldEvent = function(tpc, isResume) {
  352. const instance = this.callsStatsInstances.get(tpc.id);
  353. if (instance) {
  354. instance.sendResumeOrHoldEvent(isResume);
  355. }
  356. };
  357. /**
  358. * Notifies CallStats and analytics(if present) for ice connection failed
  359. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  360. */
  361. Statistics.prototype.sendIceConnectionFailedEvent = function(tpc) {
  362. const instance = this.callsStatsInstances.get(tpc.id);
  363. if (instance) {
  364. instance.sendIceConnectionFailedEvent();
  365. }
  366. Statistics.analytics.sendEvent('connection.ice_failed');
  367. };
  368. /**
  369. * Notifies CallStats for mute events
  370. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  371. * @param {boolean} muted true for muted and false for not muted
  372. * @param {String} type "audio"/"video"
  373. */
  374. Statistics.prototype.sendMuteEvent = function(tpc, muted, type) {
  375. const instance = tpc && this.callsStatsInstances.get(tpc.id);
  376. CallStats.sendMuteEvent(muted, type, instance);
  377. };
  378. /**
  379. * Notifies CallStats for screen sharing events
  380. * @param start {boolean} true for starting screen sharing and
  381. * false for not stopping
  382. */
  383. Statistics.prototype.sendScreenSharingEvent = function(start) {
  384. for (const cs of this.callsStatsInstances.values()) {
  385. cs.sendScreenSharingEvent(start);
  386. }
  387. };
  388. /**
  389. * Notifies the statistics module that we are now the dominant speaker of the
  390. * conference.
  391. */
  392. Statistics.prototype.sendDominantSpeakerEvent = function() {
  393. for (const cs of this.callsStatsInstances.values()) {
  394. cs.sendDominantSpeakerEvent();
  395. }
  396. };
  397. /**
  398. * Notifies about active device.
  399. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  400. * their data
  401. */
  402. Statistics.sendActiveDeviceListEvent = function(devicesData) {
  403. const globalSet = Statistics._getAllCallStatsInstances();
  404. if (globalSet.size) {
  405. for (const cs of globalSet) {
  406. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  407. }
  408. } else {
  409. CallStats.sendActiveDeviceListEvent(devicesData, null);
  410. }
  411. };
  412. /* eslint-disable max-params */
  413. /**
  414. * Lets the underlying statistics module know where is given SSRC rendered by
  415. * providing renderer tag ID.
  416. * @param {TraceablePeerConnection} tpc the connection to which the stream
  417. * belongs to
  418. * @param {number} ssrc the SSRC of the stream
  419. * @param {boolean} isLocal
  420. * @param {string} userId
  421. * @param {string} usageLabel meaningful usage label of this stream like
  422. * 'microphone', 'camera' or 'screen'.
  423. * @param {string} containerId the id of media 'audio' or 'video' tag which
  424. * renders the stream.
  425. */
  426. Statistics.prototype.associateStreamWithVideoTag = function(
  427. tpc,
  428. ssrc,
  429. isLocal,
  430. userId,
  431. usageLabel,
  432. containerId) {
  433. const instance = this.callsStatsInstances.get(tpc.id);
  434. if (instance) {
  435. instance.associateStreamWithVideoTag(
  436. ssrc,
  437. isLocal,
  438. userId,
  439. usageLabel,
  440. containerId);
  441. }
  442. };
  443. /* eslint-enable max-params */
  444. /**
  445. * Notifies CallStats that getUserMedia failed.
  446. *
  447. * @param {Error} e error to send
  448. */
  449. Statistics.sendGetUserMediaFailed = function(e) {
  450. const error
  451. = e instanceof JitsiTrackError
  452. ? formatJitsiTrackErrorForCallStats(e) : e;
  453. const globalSet = Statistics._getAllCallStatsInstances();
  454. if (globalSet.size) {
  455. for (const cs of globalSet) {
  456. CallStats.sendGetUserMediaFailed(error, cs);
  457. }
  458. } else {
  459. CallStats.sendGetUserMediaFailed(error, null);
  460. }
  461. };
  462. /**
  463. * Notifies CallStats that peer connection failed to create offer.
  464. *
  465. * @param {Error} e error to send
  466. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  467. */
  468. Statistics.prototype.sendCreateOfferFailed = function(e, tpc) {
  469. const instance = this.callsStatsInstances.get(tpc.id);
  470. if (instance) {
  471. instance.sendCreateOfferFailed(e);
  472. }
  473. };
  474. /**
  475. * Notifies CallStats that peer connection failed to create answer.
  476. *
  477. * @param {Error} e error to send
  478. * @param {TraceablePeerConnection} tpc connection on which failure occured.
  479. */
  480. Statistics.prototype.sendCreateAnswerFailed = function(e, tpc) {
  481. const instance = this.callsStatsInstances.get(tpc.id);
  482. if (instance) {
  483. instance.sendCreateAnswerFailed(e);
  484. }
  485. };
  486. /**
  487. * Notifies CallStats that peer connection failed to set local description.
  488. *
  489. * @param {Error} e error to send
  490. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  491. */
  492. Statistics.prototype.sendSetLocalDescFailed = function(e, tpc) {
  493. const instance = this.callsStatsInstances.get(tpc.id);
  494. if (instance) {
  495. instance.sendSetLocalDescFailed(e);
  496. }
  497. };
  498. /**
  499. * Notifies CallStats that peer connection failed to set remote description.
  500. *
  501. * @param {Error} e error to send
  502. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  503. */
  504. Statistics.prototype.sendSetRemoteDescFailed = function(e, tpc) {
  505. const instance = this.callsStatsInstances.get(tpc.id);
  506. if (instance) {
  507. instance.sendSetRemoteDescFailed(e);
  508. }
  509. };
  510. /**
  511. * Notifies CallStats that peer connection failed to add ICE candidate.
  512. *
  513. * @param {Error} e error to send
  514. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  515. */
  516. Statistics.prototype.sendAddIceCandidateFailed = function(e, tpc) {
  517. const instance = this.callsStatsInstances.get(tpc.id);
  518. if (instance) {
  519. instance.sendAddIceCandidateFailed(e);
  520. }
  521. };
  522. /**
  523. * Adds to CallStats an application log.
  524. *
  525. * @param {String} m a log message to send or an {Error} object to be reported
  526. */
  527. Statistics.sendLog = function(m) {
  528. const globalSubSet = new Set();
  529. // FIXME we don't want to duplicate logs over P2P instance, but
  530. // here we should go over instances and call this method for each
  531. // unique conference ID rather than selecting the first one.
  532. // We don't have such use case though, so leaving as is for now.
  533. for (const stats of Statistics.instances) {
  534. if (stats.callsStatsInstances.size) {
  535. globalSubSet.add(stats.callsStatsInstances.values().next().value);
  536. }
  537. }
  538. if (globalSubSet.size) {
  539. for (const csPerStats of globalSubSet) {
  540. CallStats.sendApplicationLog(m, csPerStats);
  541. }
  542. } else {
  543. CallStats.sendApplicationLog(m, null);
  544. }
  545. };
  546. /**
  547. * Sends the given feedback through CallStats.
  548. *
  549. * @param overall an integer between 1 and 5 indicating the user feedback
  550. * @param detailed detailed feedback from the user. Not yet used
  551. */
  552. Statistics.prototype.sendFeedback = function(overall, detailed) {
  553. CallStats.sendFeedback(this._getCallStatsConfID(), overall, detailed);
  554. Statistics.analytics.sendEvent('feedback.rating',
  555. { value: overall,
  556. detailed });
  557. };
  558. Statistics.LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  559. /**
  560. * Reports global error to CallStats.
  561. *
  562. * @param {Error} error
  563. */
  564. Statistics.reportGlobalError = function(error) {
  565. if (error instanceof JitsiTrackError && error.gum) {
  566. Statistics.sendGetUserMediaFailed(error);
  567. } else {
  568. Statistics.sendLog(error);
  569. }
  570. };
  571. /**
  572. * Sends event to analytics and callstats.
  573. * @param {string} eventName the event name.
  574. * @param {Object} data the data to be sent.
  575. */
  576. Statistics.sendEventToAll = function(eventName, data) {
  577. this.analytics.sendEvent(eventName, data);
  578. Statistics.sendLog(JSON.stringify({ name: eventName,
  579. data }));
  580. };