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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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(StatisticsEvents.CONNECTION_STATS, listener);
  142. };
  143. Statistics.prototype.addByteSentStatsListener = function(listener) {
  144. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  145. };
  146. Statistics.prototype.removeByteSentStatsListener = function(listener) {
  147. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  148. listener);
  149. };
  150. Statistics.prototype.dispose = function() {
  151. if (this.eventEmitter) {
  152. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  153. }
  154. this.stopCallStats();
  155. this.stopRemoteStats();
  156. if(this.eventEmitter) {
  157. this.eventEmitter.removeAllListeners();
  158. }
  159. };
  160. Statistics.stopLocalStats = function(stream) {
  161. if(!Statistics.audioLevelsEnabled) {
  162. return;
  163. }
  164. for(let i = 0; i < Statistics.localStats.length; i++) {
  165. if(Statistics.localStats[i].stream === stream) {
  166. const localStats = Statistics.localStats.splice(i, 1);
  167. localStats[0].stop();
  168. break;
  169. }
  170. }
  171. };
  172. Statistics.prototype.stopRemoteStats = function() {
  173. if (!this.rtpStats) {
  174. return;
  175. }
  176. this.rtpStats.stop();
  177. this.rtpStats = null;
  178. };
  179. // CALSTATS METHODS
  180. /**
  181. * Initializes the callstats.io API.
  182. * @param peerConnection {JingleSessionPC} the session object
  183. */
  184. Statistics.prototype.startCallStats = function(session) {
  185. if(this.callStatsIntegrationEnabled && !this.callStatsStarted) {
  186. // Here we overwrite the previous instance, but it must be bound to
  187. // the new PeerConnection
  188. this.callstats = new CallStats(session, this.options);
  189. Statistics.callsStatsInstances.push(this.callstats);
  190. this.callStatsStarted = true;
  191. }
  192. };
  193. /**
  194. * Removes the callstats.io instances.
  195. */
  196. Statistics.prototype.stopCallStats = function() {
  197. if(this.callStatsStarted) {
  198. const index = Statistics.callsStatsInstances.indexOf(this.callstats);
  199. if(index > -1) {
  200. Statistics.callsStatsInstances.splice(index, 1);
  201. }
  202. // The next line is commented because we need to be able to send
  203. // feedback even after the conference has been destroyed.
  204. // this.callstats = null;
  205. CallStats.dispose();
  206. this.callStatsStarted = false;
  207. }
  208. };
  209. /**
  210. * Returns true if the callstats integration is enabled, otherwise returns
  211. * false.
  212. *
  213. * @returns true if the callstats integration is enabled, otherwise returns
  214. * false.
  215. */
  216. Statistics.prototype.isCallstatsEnabled = function() {
  217. return this.callStatsIntegrationEnabled;
  218. };
  219. /**
  220. * Notifies CallStats and analytics(if present) for ice connection failed
  221. * @param {RTCPeerConnection} pc connection on which failure occured.
  222. */
  223. Statistics.prototype.sendIceConnectionFailedEvent = function(pc) {
  224. if(this.callstats) {
  225. this.callstats.sendIceConnectionFailedEvent(pc, this.callstats);
  226. }
  227. Statistics.analytics.sendEvent('connection.ice_failed');
  228. };
  229. /**
  230. * Notifies CallStats for mute events
  231. * @param mute {boolean} true for muted and false for not muted
  232. * @param type {String} "audio"/"video"
  233. */
  234. Statistics.prototype.sendMuteEvent = function(muted, type) {
  235. if(this.callstats) {
  236. CallStats.sendMuteEvent(muted, type, this.callstats);
  237. }
  238. };
  239. /**
  240. * Notifies CallStats for screen sharing events
  241. * @param start {boolean} true for starting screen sharing and
  242. * false for not stopping
  243. */
  244. Statistics.prototype.sendScreenSharingEvent = function(start) {
  245. if(this.callstats) {
  246. CallStats.sendScreenSharingEvent(start, this.callstats);
  247. }
  248. };
  249. /**
  250. * Notifies the statistics module that we are now the dominant speaker of the
  251. * conference.
  252. */
  253. Statistics.prototype.sendDominantSpeakerEvent = function() {
  254. if(this.callstats) {
  255. CallStats.sendDominantSpeakerEvent(this.callstats);
  256. }
  257. };
  258. /**
  259. * Notifies about active device.
  260. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  261. * their data
  262. */
  263. Statistics.sendActiveDeviceListEvent = function(devicesData) {
  264. if (Statistics.callsStatsInstances.length) {
  265. Statistics.callsStatsInstances.forEach(cs => {
  266. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  267. });
  268. } else {
  269. CallStats.sendActiveDeviceListEvent(devicesData, null);
  270. }
  271. };
  272. /**
  273. * Lets the underlying statistics module know where is given SSRC rendered by
  274. * providing renderer tag ID.
  275. * @param ssrc {number} the SSRC of the stream
  276. * @param isLocal {boolean} <tt>true<tt> if this stream is local or
  277. * <tt>false</tt> otherwise.
  278. * @param usageLabel {string} meaningful usage label of this stream like
  279. * 'microphone', 'camera' or 'screen'.
  280. * @param containerId {string} the id of media 'audio' or 'video' tag which
  281. * renders the stream.
  282. */
  283. Statistics.prototype.associateStreamWithVideoTag
  284. = function(ssrc, isLocal, usageLabel, containerId) {
  285. if(this.callstats) {
  286. this.callstats.associateStreamWithVideoTag(
  287. ssrc, isLocal, usageLabel, containerId);
  288. }
  289. };
  290. /**
  291. * Notifies CallStats that getUserMedia failed.
  292. *
  293. * @param {Error} e error to send
  294. */
  295. Statistics.sendGetUserMediaFailed = function(e) {
  296. if (Statistics.callsStatsInstances.length) {
  297. Statistics.callsStatsInstances.forEach(
  298. cs =>
  299. CallStats.sendGetUserMediaFailed(
  300. e instanceof JitsiTrackError
  301. ? formatJitsiTrackErrorForCallStats(e)
  302. : e,
  303. cs));
  304. } else {
  305. CallStats.sendGetUserMediaFailed(
  306. e instanceof JitsiTrackError
  307. ? formatJitsiTrackErrorForCallStats(e)
  308. : e,
  309. null);
  310. }
  311. };
  312. /**
  313. * Notifies CallStats that peer connection failed to create offer.
  314. *
  315. * @param {Error} e error to send
  316. * @param {RTCPeerConnection} pc connection on which failure occured.
  317. */
  318. Statistics.prototype.sendCreateOfferFailed = function(e, pc) {
  319. if(this.callstats) {
  320. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  321. }
  322. };
  323. /**
  324. * Notifies CallStats that peer connection failed to create answer.
  325. *
  326. * @param {Error} e error to send
  327. * @param {RTCPeerConnection} pc connection on which failure occured.
  328. */
  329. Statistics.prototype.sendCreateAnswerFailed = function(e, pc) {
  330. if(this.callstats) {
  331. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  332. }
  333. };
  334. /**
  335. * Notifies CallStats that peer connection failed to set local description.
  336. *
  337. * @param {Error} e error to send
  338. * @param {RTCPeerConnection} pc connection on which failure occured.
  339. */
  340. Statistics.prototype.sendSetLocalDescFailed = function(e, pc) {
  341. if(this.callstats) {
  342. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  343. }
  344. };
  345. /**
  346. * Notifies CallStats that peer connection failed to set remote description.
  347. *
  348. * @param {Error} e error to send
  349. * @param {RTCPeerConnection} pc connection on which failure occured.
  350. */
  351. Statistics.prototype.sendSetRemoteDescFailed = function(e, pc) {
  352. if(this.callstats) {
  353. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  354. }
  355. };
  356. /**
  357. * Notifies CallStats that peer connection failed to add ICE candidate.
  358. *
  359. * @param {Error} e error to send
  360. * @param {RTCPeerConnection} pc connection on which failure occured.
  361. */
  362. Statistics.prototype.sendAddIceCandidateFailed = function(e, pc) {
  363. if(this.callstats) {
  364. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  365. }
  366. };
  367. /**
  368. * Adds to CallStats an application log.
  369. *
  370. * @param {String} a log message to send or an {Error} object to be reported
  371. */
  372. Statistics.sendLog = function(m) {
  373. if (Statistics.callsStatsInstances.length) {
  374. Statistics.callsStatsInstances.forEach(
  375. cs => CallStats.sendApplicationLog(m, cs));
  376. } else {
  377. CallStats.sendApplicationLog(m, null);
  378. }
  379. };
  380. /**
  381. * Sends the given feedback through CallStats.
  382. *
  383. * @param overall an integer between 1 and 5 indicating the user feedback
  384. * @param detailed detailed feedback from the user. Not yet used
  385. */
  386. Statistics.prototype.sendFeedback = function(overall, detailed) {
  387. if(this.callstats) {
  388. this.callstats.sendFeedback(overall, detailed);
  389. }
  390. Statistics.analytics.sendEvent('feedback.rating',
  391. {value: overall, detailed});
  392. };
  393. Statistics.LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  394. /**
  395. * Reports global error to CallStats.
  396. *
  397. * @param {Error} error
  398. */
  399. Statistics.reportGlobalError = function(error) {
  400. if (error instanceof JitsiTrackError && error.gum) {
  401. Statistics.sendGetUserMediaFailed(error);
  402. } else {
  403. Statistics.sendLog(error);
  404. }
  405. };
  406. /**
  407. * Sends event to analytics and callstats.
  408. * @param {string} eventName the event name.
  409. * @param {Object} data the data to be sent.
  410. */
  411. Statistics.sendEventToAll = function(eventName, data) {
  412. this.analytics.sendEvent(eventName, data);
  413. Statistics.sendLog(JSON.stringify({name: eventName, data}));
  414. };
  415. module.exports = Statistics;