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

statistics.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /* global require */
  2. import analytics from './AnalyticsAdapter';
  3. const CallStats = require('./CallStats');
  4. const EventEmitter = require('events');
  5. import JitsiTrackError from '../../JitsiTrackError';
  6. const logger = require('jitsi-meet-logger').getLogger(__filename);
  7. const LocalStats = require('./LocalStatsCollector.js');
  8. const RTPStats = require('./RTPStatsCollector.js');
  9. const ScriptUtil = require('../util/ScriptUtil');
  10. import * as StatisticsEvents from '../../service/statistics/Events';
  11. /**
  12. * True if callstats API is loaded
  13. */
  14. let isCallstatsLoaded = false;
  15. // Since callstats.io is a third party, we cannot guarantee the quality of their
  16. // service. More specifically, their server may take noticeably long time to
  17. // respond. Consequently, it is in our best interest (in the sense that the
  18. // intergration of callstats.io is pretty important to us but not enough to
  19. // allow it to prevent people from joining a conference) to (1) start
  20. // downloading their API as soon as possible and (2) do the downloading
  21. // asynchronously.
  22. function loadCallStatsAPI(customScriptUrl) {
  23. if (!isCallstatsLoaded) {
  24. ScriptUtil.loadScript(
  25. customScriptUrl ? customScriptUrl
  26. : 'https://api.callstats.io/static/callstats-ws.min.js',
  27. /* async */ true,
  28. /* prepend */ true);
  29. isCallstatsLoaded = true;
  30. }
  31. // FIXME At the time of this writing, we hope that the callstats.io API will
  32. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  33. }
  34. /**
  35. * callstats strips any additional fields from Error except for "name", "stack",
  36. * "message" and "constraintName". So we need to bundle additional information
  37. * from JitsiTrackError into error passed to callstats to preserve valuable
  38. * information about error.
  39. * @param {JitsiTrackError} error
  40. */
  41. function formatJitsiTrackErrorForCallStats(error) {
  42. const err = new Error();
  43. // Just copy original stack from error
  44. err.stack = error.stack;
  45. // Combine name from error's name plus (possibly) name of original GUM error
  46. err.name = (error.name || 'Unknown error') + (error.gum && error.gum.error
  47. && error.gum.error.name ? ` - ${error.gum.error.name}` : '');
  48. // Put all constraints into this field. For constraint failed errors we will
  49. // still know which exactly constraint failed as it will be a part of
  50. // message.
  51. err.constraintName = error.gum && error.gum.constraints
  52. ? JSON.stringify(error.gum.constraints) : '';
  53. // Just copy error's message.
  54. err.message = error.message;
  55. return err;
  56. }
  57. /**
  58. * Init statistic options
  59. * @param options
  60. */
  61. Statistics.init = function(options) {
  62. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  63. if (typeof options.audioLevelsInterval === 'number') {
  64. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  65. }
  66. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  67. };
  68. function Statistics(xmpp, options) {
  69. this.rtpStats = null;
  70. this.eventEmitter = new EventEmitter();
  71. this.xmpp = xmpp;
  72. this.options = options || {};
  73. this.callStatsIntegrationEnabled
  74. = this.options.callStatsID && this.options.callStatsSecret
  75. // Even though AppID and AppSecret may be specified, the integration
  76. // of callstats.io may be disabled because of globally-disallowed
  77. // requests to any third parties.
  78. && (Statistics.disableThirdPartyRequests !== true);
  79. if (this.callStatsIntegrationEnabled) {
  80. loadCallStatsAPI(this.options.callStatsCustomScriptUrl);
  81. }
  82. this.callStats = null;
  83. // Flag indicates whether or not the CallStats have been started for this
  84. // Statistics instance
  85. this.callStatsStarted = false;
  86. }
  87. Statistics.audioLevelsEnabled = false;
  88. Statistics.audioLevelsInterval = 200;
  89. Statistics.disableThirdPartyRequests = false;
  90. Statistics.analytics = analytics;
  91. /**
  92. * Array of callstats instances. Used to call Statistics static methods and
  93. * send stats to all cs instances.
  94. */
  95. Statistics.callsStatsInstances = [];
  96. Statistics.prototype.startRemoteStats = function(peerconnection) {
  97. this.stopRemoteStats();
  98. try {
  99. this.rtpStats
  100. = new RTPStats(peerconnection,
  101. Statistics.audioLevelsInterval, 2000, this.eventEmitter);
  102. this.rtpStats.start(Statistics.audioLevelsEnabled);
  103. } catch (e) {
  104. this.rtpStats = null;
  105. logger.error(`Failed to start collecting remote statistics: ${e}`);
  106. }
  107. };
  108. Statistics.localStats = [];
  109. Statistics.startLocalStats = function(stream, callback) {
  110. if (!Statistics.audioLevelsEnabled) {
  111. return;
  112. }
  113. const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  114. callback);
  115. this.localStats.push(localStats);
  116. localStats.start();
  117. };
  118. Statistics.prototype.addAudioLevelListener = function(listener) {
  119. if (!Statistics.audioLevelsEnabled) {
  120. return;
  121. }
  122. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  123. };
  124. Statistics.prototype.removeAudioLevelListener = function(listener) {
  125. if (!Statistics.audioLevelsEnabled) {
  126. return;
  127. }
  128. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  129. };
  130. Statistics.prototype.addBeforeDisposedListener = function(listener) {
  131. this.eventEmitter.on(StatisticsEvents.BEFORE_DISPOSED, listener);
  132. };
  133. Statistics.prototype.removeBeforeDisposedListener = function(listener) {
  134. this.eventEmitter.removeListener(
  135. StatisticsEvents.BEFORE_DISPOSED, listener);
  136. };
  137. Statistics.prototype.addConnectionStatsListener = function(listener) {
  138. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  139. };
  140. Statistics.prototype.removeConnectionStatsListener = function(listener) {
  141. this.eventEmitter.removeListener(
  142. StatisticsEvents.CONNECTION_STATS,
  143. listener);
  144. };
  145. Statistics.prototype.addByteSentStatsListener = function(listener) {
  146. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  147. };
  148. Statistics.prototype.removeByteSentStatsListener = function(listener) {
  149. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  150. listener);
  151. };
  152. Statistics.prototype.dispose = function() {
  153. if (this.eventEmitter) {
  154. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  155. }
  156. this.stopCallStats();
  157. this.stopRemoteStats();
  158. if (this.eventEmitter) {
  159. this.eventEmitter.removeAllListeners();
  160. }
  161. };
  162. Statistics.stopLocalStats = function(stream) {
  163. if (!Statistics.audioLevelsEnabled) {
  164. return;
  165. }
  166. for (let i = 0; i < Statistics.localStats.length; i++) {
  167. if (Statistics.localStats[i].stream === stream) {
  168. const localStats = Statistics.localStats.splice(i, 1);
  169. localStats[0].stop();
  170. break;
  171. }
  172. }
  173. };
  174. Statistics.prototype.stopRemoteStats = function() {
  175. if (!this.rtpStats) {
  176. return;
  177. }
  178. this.rtpStats.stop();
  179. this.rtpStats = null;
  180. };
  181. // CALSTATS METHODS
  182. /**
  183. * Initializes the callstats.io API.
  184. * @param peerConnection {JingleSessionPC} the session object
  185. */
  186. Statistics.prototype.startCallStats = function(session) {
  187. if (this.callStatsIntegrationEnabled && !this.callStatsStarted) {
  188. // Here we overwrite the previous instance, but it must be bound to
  189. // the new PeerConnection
  190. this.callstats = new CallStats(session, this.options);
  191. Statistics.callsStatsInstances.push(this.callstats);
  192. this.callStatsStarted = true;
  193. }
  194. };
  195. /**
  196. * Removes the callstats.io instances.
  197. */
  198. Statistics.prototype.stopCallStats = function() {
  199. if (this.callStatsStarted) {
  200. const index = Statistics.callsStatsInstances.indexOf(this.callstats);
  201. if (index > -1) {
  202. Statistics.callsStatsInstances.splice(index, 1);
  203. }
  204. // The next line is commented because we need to be able to send
  205. // feedback even after the conference has been destroyed.
  206. // this.callstats = null;
  207. CallStats.dispose();
  208. this.callStatsStarted = false;
  209. }
  210. };
  211. /**
  212. * Returns true if the callstats integration is enabled, otherwise returns
  213. * false.
  214. *
  215. * @returns true if the callstats integration is enabled, otherwise returns
  216. * false.
  217. */
  218. Statistics.prototype.isCallstatsEnabled = function() {
  219. return this.callStatsIntegrationEnabled;
  220. };
  221. /**
  222. * Notifies CallStats and analytics(if present) for ice connection failed
  223. * @param {RTCPeerConnection} pc connection on which failure occured.
  224. */
  225. Statistics.prototype.sendIceConnectionFailedEvent = function(pc) {
  226. if (this.callstats) {
  227. this.callstats.sendIceConnectionFailedEvent(pc, this.callstats);
  228. }
  229. Statistics.analytics.sendEvent('connection.ice_failed');
  230. };
  231. /**
  232. * Notifies CallStats for mute events
  233. * @param mute {boolean} true for muted and false for not muted
  234. * @param type {String} "audio"/"video"
  235. */
  236. Statistics.prototype.sendMuteEvent = function(muted, type) {
  237. if (this.callstats) {
  238. CallStats.sendMuteEvent(muted, type, this.callstats);
  239. }
  240. };
  241. /**
  242. * Notifies CallStats for screen sharing events
  243. * @param start {boolean} true for starting screen sharing and
  244. * false for not stopping
  245. */
  246. Statistics.prototype.sendScreenSharingEvent = function(start) {
  247. if (this.callstats) {
  248. CallStats.sendScreenSharingEvent(start, this.callstats);
  249. }
  250. };
  251. /**
  252. * Notifies the statistics module that we are now the dominant speaker of the
  253. * conference.
  254. */
  255. Statistics.prototype.sendDominantSpeakerEvent = function() {
  256. if (this.callstats) {
  257. CallStats.sendDominantSpeakerEvent(this.callstats);
  258. }
  259. };
  260. /**
  261. * Notifies about active device.
  262. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  263. * their data
  264. */
  265. Statistics.sendActiveDeviceListEvent = function(devicesData) {
  266. if (Statistics.callsStatsInstances.length) {
  267. Statistics.callsStatsInstances.forEach(cs => {
  268. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  269. });
  270. } else {
  271. CallStats.sendActiveDeviceListEvent(devicesData, null);
  272. }
  273. };
  274. /* eslint-disable max-params */
  275. /**
  276. * Lets the underlying statistics module know where is given SSRC rendered by
  277. * providing renderer tag ID.
  278. * @param ssrc {number} the SSRC of the stream
  279. * @param isLocal {boolean} <tt>true<tt> if this stream is local or
  280. * <tt>false</tt> otherwise.
  281. * @param usageLabel {string} meaningful usage label of this stream like
  282. * 'microphone', 'camera' or 'screen'.
  283. * @param containerId {string} the id of media 'audio' or 'video' tag which
  284. * renders the stream.
  285. */
  286. Statistics.prototype.associateStreamWithVideoTag = function(
  287. ssrc,
  288. isLocal,
  289. usageLabel,
  290. containerId) {
  291. this.callstats && this.callstats.associateStreamWithVideoTag(
  292. ssrc,
  293. isLocal,
  294. usageLabel,
  295. containerId);
  296. };
  297. /* eslint-enable max-params */
  298. /**
  299. * Notifies CallStats that getUserMedia failed.
  300. *
  301. * @param {Error} e error to send
  302. */
  303. Statistics.sendGetUserMediaFailed = function(e) {
  304. if (Statistics.callsStatsInstances.length) {
  305. Statistics.callsStatsInstances.forEach(
  306. cs =>
  307. CallStats.sendGetUserMediaFailed(
  308. e instanceof JitsiTrackError
  309. ? formatJitsiTrackErrorForCallStats(e)
  310. : e,
  311. cs));
  312. } else {
  313. CallStats.sendGetUserMediaFailed(
  314. e instanceof JitsiTrackError
  315. ? formatJitsiTrackErrorForCallStats(e)
  316. : e,
  317. null);
  318. }
  319. };
  320. /**
  321. * Notifies CallStats that peer connection failed to create offer.
  322. *
  323. * @param {Error} e error to send
  324. * @param {RTCPeerConnection} pc connection on which failure occured.
  325. */
  326. Statistics.prototype.sendCreateOfferFailed = function(e, pc) {
  327. if (this.callstats) {
  328. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  329. }
  330. };
  331. /**
  332. * Notifies CallStats that peer connection failed to create answer.
  333. *
  334. * @param {Error} e error to send
  335. * @param {RTCPeerConnection} pc connection on which failure occured.
  336. */
  337. Statistics.prototype.sendCreateAnswerFailed = function(e, pc) {
  338. if (this.callstats) {
  339. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  340. }
  341. };
  342. /**
  343. * Notifies CallStats that peer connection failed to set local description.
  344. *
  345. * @param {Error} e error to send
  346. * @param {RTCPeerConnection} pc connection on which failure occured.
  347. */
  348. Statistics.prototype.sendSetLocalDescFailed = function(e, pc) {
  349. if (this.callstats) {
  350. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  351. }
  352. };
  353. /**
  354. * Notifies CallStats that peer connection failed to set remote description.
  355. *
  356. * @param {Error} e error to send
  357. * @param {RTCPeerConnection} pc connection on which failure occured.
  358. */
  359. Statistics.prototype.sendSetRemoteDescFailed = function(e, pc) {
  360. if (this.callstats) {
  361. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  362. }
  363. };
  364. /**
  365. * Notifies CallStats that peer connection failed to add ICE candidate.
  366. *
  367. * @param {Error} e error to send
  368. * @param {RTCPeerConnection} pc connection on which failure occured.
  369. */
  370. Statistics.prototype.sendAddIceCandidateFailed = function(e, pc) {
  371. if (this.callstats) {
  372. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  373. }
  374. };
  375. /**
  376. * Adds to CallStats an application log.
  377. *
  378. * @param {String} a log message to send or an {Error} object to be reported
  379. */
  380. Statistics.sendLog = function(m) {
  381. if (Statistics.callsStatsInstances.length) {
  382. Statistics.callsStatsInstances.forEach(
  383. cs => CallStats.sendApplicationLog(m, cs));
  384. } else {
  385. CallStats.sendApplicationLog(m, null);
  386. }
  387. };
  388. /**
  389. * Sends the given feedback through CallStats.
  390. *
  391. * @param overall an integer between 1 and 5 indicating the user feedback
  392. * @param detailed detailed feedback from the user. Not yet used
  393. */
  394. Statistics.prototype.sendFeedback = function(overall, detailed) {
  395. if (this.callstats) {
  396. this.callstats.sendFeedback(overall, detailed);
  397. }
  398. Statistics.analytics.sendEvent('feedback.rating',
  399. { value: overall,
  400. detailed });
  401. };
  402. Statistics.LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  403. /**
  404. * Reports global error to CallStats.
  405. *
  406. * @param {Error} error
  407. */
  408. Statistics.reportGlobalError = function(error) {
  409. if (error instanceof JitsiTrackError && error.gum) {
  410. Statistics.sendGetUserMediaFailed(error);
  411. } else {
  412. Statistics.sendLog(error);
  413. }
  414. };
  415. /**
  416. * Sends event to analytics and callstats.
  417. * @param {string} eventName the event name.
  418. * @param {Object} data the data to be sent.
  419. */
  420. Statistics.sendEventToAll = function(eventName, data) {
  421. this.analytics.sendEvent(eventName, data);
  422. Statistics.sendLog(JSON.stringify({ name: eventName,
  423. data }));
  424. };
  425. module.exports = Statistics;