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.

JitsiMeetJS.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /* global __filename */
  2. import { createGetUserMediaEvent } from './service/statistics/AnalyticsEvents';
  3. import AuthUtil from './modules/util/AuthUtil';
  4. import * as ConnectionQualityEvents
  5. from './service/connectivity/ConnectionQualityEvents';
  6. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  7. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  8. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  9. import JitsiConnection from './JitsiConnection';
  10. import * as JitsiConnectionErrors from './JitsiConnectionErrors';
  11. import * as JitsiConnectionEvents from './JitsiConnectionEvents';
  12. import JitsiMediaDevices from './JitsiMediaDevices';
  13. import * as JitsiMediaDevicesEvents from './JitsiMediaDevicesEvents';
  14. import JitsiTrackError from './JitsiTrackError';
  15. import * as JitsiTrackErrors from './JitsiTrackErrors';
  16. import * as JitsiTrackEvents from './JitsiTrackEvents';
  17. import * as JitsiTranscriptionStatus from './JitsiTranscriptionStatus';
  18. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  19. import Logger from 'jitsi-meet-logger';
  20. import * as MediaType from './service/RTC/MediaType';
  21. import Resolutions from './service/RTC/Resolutions';
  22. import { ParticipantConnectionStatus }
  23. from './modules/connectivity/ParticipantConnectionStatus';
  24. import RTC from './modules/RTC/RTC';
  25. import browser from './modules/browser';
  26. import ScriptUtil from './modules/util/ScriptUtil';
  27. import recordingConstants from './modules/recording/recordingConstants';
  28. import Statistics from './modules/statistics/statistics';
  29. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  30. const logger = Logger.getLogger(__filename);
  31. /**
  32. * The amount of time to wait until firing
  33. * {@link JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN} event.
  34. */
  35. const USER_MEDIA_PERMISSION_PROMPT_TIMEOUT = 1000;
  36. /**
  37. * Gets the next lowest desirable resolution to try for a camera. If the given
  38. * resolution is already the lowest acceptable resolution, returns {@code null}.
  39. *
  40. * @param resolution the current resolution
  41. * @return the next lowest resolution from the given one, or {@code null} if it
  42. * is already the lowest acceptable resolution.
  43. */
  44. function getLowerResolution(resolution) {
  45. if (!Resolutions[resolution]) {
  46. return null;
  47. }
  48. const order = Resolutions[resolution].order;
  49. let res = null;
  50. let resName = null;
  51. Object.keys(Resolutions).forEach(r => {
  52. const value = Resolutions[r];
  53. if (!res || (res.order < value.order && value.order < order)) {
  54. resName = r;
  55. res = value;
  56. }
  57. });
  58. if (resName === resolution) {
  59. resName = null;
  60. }
  61. return resName;
  62. }
  63. /**
  64. * Extracts from an 'options' objects with a specific format (TODO what IS the
  65. * format?) the attributes which are to be logged in analytics events.
  66. *
  67. * @param options gum options (???)
  68. * @returns {*} the attributes to attach to analytics events.
  69. */
  70. function getAnalyticsAttributesFromOptions(options) {
  71. const attributes = {
  72. 'audio_requested':
  73. options.devices.includes('audio'),
  74. 'video_requested':
  75. options.devices.includes('video'),
  76. 'screen_sharing_requested':
  77. options.devices.includes('desktop')
  78. };
  79. if (attributes.video_requested) {
  80. attributes.resolution = options.resolution;
  81. }
  82. return attributes;
  83. }
  84. /**
  85. * Tries to deal with the following problem: {@code JitsiMeetJS} is not only
  86. * this module, it's also a global (i.e. attached to {@code window}) namespace
  87. * for all globals of the projects in the Jitsi Meet family. If lib-jitsi-meet
  88. * is loaded through an HTML {@code script} tag, {@code JitsiMeetJS} will
  89. * automatically be attached to {@code window} by webpack. Unfortunately,
  90. * webpack's source code does not check whether the global variable has already
  91. * been assigned and overwrites it. Which is OK for the module
  92. * {@code JitsiMeetJS} but is not OK for the namespace {@code JitsiMeetJS}
  93. * because it may already contain the values of other projects in the Jitsi Meet
  94. * family. The solution offered here works around webpack by merging all
  95. * existing values of the namespace {@code JitsiMeetJS} into the module
  96. * {@code JitsiMeetJS}.
  97. *
  98. * @param {Object} module - The module {@code JitsiMeetJS} (which will be
  99. * exported and may be attached to {@code window} by webpack later on).
  100. * @private
  101. * @returns {Object} - A {@code JitsiMeetJS} module which contains all existing
  102. * value of the namespace {@code JitsiMeetJS} (if any).
  103. */
  104. function _mergeNamespaceAndModule(module) {
  105. return (
  106. typeof window.JitsiMeetJS === 'object'
  107. ? Object.assign({}, window.JitsiMeetJS, module)
  108. : module);
  109. }
  110. /**
  111. * The public API of the Jitsi Meet library (a.k.a. {@code JitsiMeetJS}).
  112. */
  113. export default _mergeNamespaceAndModule({
  114. version: '{#COMMIT_HASH#}',
  115. JitsiConnection,
  116. constants: {
  117. participantConnectionStatus: ParticipantConnectionStatus,
  118. recording: recordingConstants,
  119. sipVideoGW: VideoSIPGWConstants,
  120. transcriptionStatus: JitsiTranscriptionStatus
  121. },
  122. events: {
  123. conference: JitsiConferenceEvents,
  124. connection: JitsiConnectionEvents,
  125. track: JitsiTrackEvents,
  126. mediaDevices: JitsiMediaDevicesEvents,
  127. connectionQuality: ConnectionQualityEvents
  128. },
  129. errors: {
  130. conference: JitsiConferenceErrors,
  131. connection: JitsiConnectionErrors,
  132. track: JitsiTrackErrors
  133. },
  134. errorTypes: {
  135. JitsiTrackError
  136. },
  137. logLevels: Logger.levels,
  138. mediaDevices: JitsiMediaDevices,
  139. analytics: Statistics.analytics,
  140. init(options) {
  141. Statistics.init(options);
  142. // Initialize global window.connectionTimes
  143. // FIXME do not use 'window'
  144. if (!window.connectionTimes) {
  145. window.connectionTimes = {};
  146. }
  147. if (options.enableAnalyticsLogging !== true) {
  148. logger.warn('Analytics disabled, disposing.');
  149. this.analytics.dispose();
  150. }
  151. if (options.enableWindowOnErrorHandler) {
  152. GlobalOnErrorHandler.addHandler(
  153. this.getGlobalOnErrorHandler.bind(this));
  154. }
  155. // Log deployment-specific information, if available. Defined outside
  156. // the application by individual deployments
  157. const aprops = options.deploymentInfo;
  158. if (aprops && Object.keys(aprops).length > 0) {
  159. const logObject = {};
  160. for (const attr in aprops) {
  161. if (aprops.hasOwnProperty(attr)) {
  162. logObject[attr] = aprops[attr];
  163. }
  164. }
  165. logObject.id = 'deployment_info';
  166. Statistics.sendLog(JSON.stringify(logObject));
  167. }
  168. if (this.version) {
  169. const logObject = {
  170. id: 'component_version',
  171. component: 'lib-jitsi-meet',
  172. version: this.version
  173. };
  174. Statistics.sendLog(JSON.stringify(logObject));
  175. }
  176. return RTC.init(options || {});
  177. },
  178. /**
  179. * Returns whether the desktop sharing is enabled or not.
  180. *
  181. * @returns {boolean}
  182. */
  183. isDesktopSharingEnabled() {
  184. return RTC.isDesktopSharingEnabled();
  185. },
  186. setLogLevel(level) {
  187. Logger.setLogLevel(level);
  188. },
  189. /**
  190. * Sets the log level to the <tt>Logger</tt> instance with given id.
  191. *
  192. * @param {Logger.levels} level the logging level to be set
  193. * @param {string} id the logger id to which new logging level will be set.
  194. * Usually it's the name of the JavaScript source file including the path
  195. * ex. "modules/xmpp/ChatRoom.js"
  196. */
  197. setLogLevelById(level, id) {
  198. Logger.setLogLevelById(level, id);
  199. },
  200. /**
  201. * Registers new global logger transport to the library logging framework.
  202. *
  203. * @param globalTransport
  204. * @see Logger.addGlobalTransport
  205. */
  206. addGlobalLogTransport(globalTransport) {
  207. Logger.addGlobalTransport(globalTransport);
  208. },
  209. /**
  210. * Removes global logging transport from the library logging framework.
  211. *
  212. * @param globalTransport
  213. * @see Logger.removeGlobalTransport
  214. */
  215. removeGlobalLogTransport(globalTransport) {
  216. Logger.removeGlobalTransport(globalTransport);
  217. },
  218. /**
  219. * Creates the media tracks and returns them trough the callback.
  220. *
  221. * @param options Object with properties / settings specifying the tracks
  222. * which should be created. should be created or some additional
  223. * configurations about resolution for example.
  224. * @param {Array} options.devices the devices that will be requested
  225. * @param {string} options.resolution resolution constraints
  226. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  227. * the following structure {stream: the Media Stream, type: "audio" or
  228. * "video", videoType: "camera" or "desktop"} will be returned trough the
  229. * Promise, otherwise JitsiTrack objects will be returned.
  230. * @param {string} options.cameraDeviceId
  231. * @param {string} options.micDeviceId
  232. * @param {object} options.desktopSharingExtensionExternalInstallation -
  233. * enables external installation process for desktop sharing extension if
  234. * the inline installation is not posible. The following properties should
  235. * be provided:
  236. * @param {intiger} interval - the interval (in ms) for
  237. * checking whether the desktop sharing extension is installed or not
  238. * @param {Function} checkAgain - returns boolean. While checkAgain()==true
  239. * createLocalTracks will wait and check on every "interval" ms for the
  240. * extension. If the desktop extension is not install and checkAgain()==true
  241. * createLocalTracks will finish with rejected Promise.
  242. * @param {Function} listener - The listener will be called to notify the
  243. * user of lib-jitsi-meet that createLocalTracks is starting external
  244. * extension installation process.
  245. * NOTE: If the inline installation process is not possible and external
  246. * installation is enabled the listener property will be called to notify
  247. * the start of external installation process. After that createLocalTracks
  248. * will start to check for the extension on every interval ms until the
  249. * plugin is installed or until checkAgain return false. If the extension
  250. * is found createLocalTracks will try to get the desktop sharing track and
  251. * will finish the execution. If checkAgain returns false, createLocalTracks
  252. * will finish the execution with rejected Promise.
  253. *
  254. * @param {boolean} (firePermissionPromptIsShownEvent) - if event
  255. * JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN should be fired
  256. * @param originalOptions - internal use only, to be able to store the
  257. * originally requested options.
  258. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise
  259. * that returns an array of created JitsiTracks if resolved, or a
  260. * JitsiConferenceError if rejected.
  261. */
  262. createLocalTracks(
  263. options = {}, firePermissionPromptIsShownEvent, originalOptions) {
  264. let promiseFulfilled = false;
  265. if (firePermissionPromptIsShownEvent === true) {
  266. window.setTimeout(() => {
  267. if (!promiseFulfilled) {
  268. JitsiMediaDevices.emitEvent(
  269. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  270. browser.getName());
  271. }
  272. }, USER_MEDIA_PERMISSION_PROMPT_TIMEOUT);
  273. }
  274. if (!window.connectionTimes) {
  275. window.connectionTimes = {};
  276. }
  277. window.connectionTimes['obtainPermissions.start']
  278. = window.performance.now();
  279. return RTC.obtainAudioAndVideoPermissions(options)
  280. .then(tracks => {
  281. promiseFulfilled = true;
  282. window.connectionTimes['obtainPermissions.end']
  283. = window.performance.now();
  284. Statistics.sendAnalytics(
  285. createGetUserMediaEvent(
  286. 'success',
  287. getAnalyticsAttributesFromOptions(options)));
  288. if (!RTC.options.disableAudioLevels) {
  289. for (let i = 0; i < tracks.length; i++) {
  290. const track = tracks[i];
  291. const mStream = track.getOriginalStream();
  292. if (track.getType() === MediaType.AUDIO) {
  293. Statistics.startLocalStats(mStream,
  294. track.setAudioLevel.bind(track));
  295. track.addEventListener(
  296. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  297. () => {
  298. Statistics.stopLocalStats(mStream);
  299. });
  300. }
  301. }
  302. }
  303. // set real device ids
  304. const currentlyAvailableMediaDevices
  305. = RTC.getCurrentlyAvailableMediaDevices();
  306. if (currentlyAvailableMediaDevices) {
  307. for (let i = 0; i < tracks.length; i++) {
  308. const track = tracks[i];
  309. track._setRealDeviceIdFromDeviceList(
  310. currentlyAvailableMediaDevices);
  311. }
  312. }
  313. return tracks;
  314. })
  315. .catch(error => {
  316. promiseFulfilled = true;
  317. if (error.name === JitsiTrackErrors.UNSUPPORTED_RESOLUTION
  318. && !browser.usesNewGumFlow()) {
  319. const oldResolution = options.resolution || '720';
  320. const newResolution = getLowerResolution(oldResolution);
  321. if (newResolution !== null) {
  322. options.resolution = newResolution;
  323. logger.debug(
  324. 'Retry createLocalTracks with resolution',
  325. newResolution);
  326. Statistics.sendAnalytics(createGetUserMediaEvent(
  327. 'warning',
  328. {
  329. 'old_resolution': oldResolution,
  330. 'new_resolution': newResolution,
  331. reason: 'unsupported resolution'
  332. }));
  333. return this.createLocalTracks(
  334. options,
  335. undefined,
  336. originalOptions || Object.assign({}, options));
  337. }
  338. // We tried everything. If there is a mandatory device id,
  339. // remove it and let gum find a device to use.
  340. if (originalOptions
  341. && error.gum.constraints
  342. && error.gum.constraints.video
  343. && error.gum.constraints.video.mandatory
  344. && error.gum.constraints.video.mandatory.sourceId) {
  345. originalOptions.cameraDeviceId = undefined;
  346. return this.createLocalTracks(originalOptions);
  347. }
  348. }
  349. if (error.name
  350. === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  351. // User cancelled action is not really an error, so only
  352. // log it as an event to avoid having conference classified
  353. // as partially failed
  354. const logObject = {
  355. id: 'chrome_extension_user_canceled',
  356. message: error.message
  357. };
  358. Statistics.sendLog(JSON.stringify(logObject));
  359. Statistics.sendAnalytics(
  360. createGetUserMediaEvent(
  361. 'warning',
  362. {
  363. reason: 'extension install user canceled'
  364. }));
  365. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  366. // logs not found devices with just application log to cs
  367. const logObject = {
  368. id: 'usermedia_missing_device',
  369. status: error.gum.devices
  370. };
  371. Statistics.sendLog(JSON.stringify(logObject));
  372. const attributes
  373. = getAnalyticsAttributesFromOptions(options);
  374. attributes.reason = 'device not found';
  375. attributes.devices = error.gum.devices.join('.');
  376. Statistics.sendAnalytics(
  377. createGetUserMediaEvent('error', attributes));
  378. } else {
  379. // Report gUM failed to the stats
  380. Statistics.sendGetUserMediaFailed(error);
  381. const attributes
  382. = getAnalyticsAttributesFromOptions(options);
  383. attributes.reason = error.name;
  384. Statistics.sendAnalytics(
  385. createGetUserMediaEvent('error', attributes));
  386. }
  387. window.connectionTimes['obtainPermissions.end']
  388. = window.performance.now();
  389. return Promise.reject(error);
  390. });
  391. },
  392. /**
  393. * Checks if its possible to enumerate available cameras/microphones.
  394. *
  395. * @returns {Promise<boolean>} a Promise which will be resolved only once
  396. * the WebRTC stack is ready, either with true if the device listing is
  397. * available available or with false otherwise.
  398. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  399. */
  400. isDeviceListAvailable() {
  401. logger.warn('This method is deprecated, use '
  402. + 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  403. return this.mediaDevices.isDeviceListAvailable();
  404. },
  405. /**
  406. * Returns true if changing the input (camera / microphone) or output
  407. * (audio) device is supported and false if not.
  408. *
  409. * @param {string} [deviceType] - type of device to change. Default is
  410. * {@code undefined} or 'input', 'output' - for audio output device change.
  411. * @returns {boolean} {@code true} if available; {@code false}, otherwise.
  412. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  413. */
  414. isDeviceChangeAvailable(deviceType) {
  415. logger.warn('This method is deprecated, use '
  416. + 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  417. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  418. },
  419. /**
  420. * Checks if the current environment supports having multiple audio
  421. * input devices in use simultaneously.
  422. *
  423. * @returns {boolean} True if multiple audio input devices can be used.
  424. */
  425. isMultipleAudioInputSupported() {
  426. return this.mediaDevices.isMultipleAudioInputSupported();
  427. },
  428. /**
  429. * Checks if local tracks can collect stats and collection is enabled.
  430. *
  431. * @param {boolean} True if stats are being collected for local tracks.
  432. */
  433. isCollectingLocalStats() {
  434. return Statistics.audioLevelsEnabled
  435. && LocalStatsCollector.isLocalStatsSupported();
  436. },
  437. /**
  438. * Executes callback with list of media devices connected.
  439. *
  440. * @param {function} callback
  441. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  442. */
  443. enumerateDevices(callback) {
  444. logger.warn('This method is deprecated, use '
  445. + 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  446. this.mediaDevices.enumerateDevices(callback);
  447. },
  448. /* eslint-disable max-params */
  449. /**
  450. * @returns function that can be used to be attached to window.onerror and
  451. * if options.enableWindowOnErrorHandler is enabled returns
  452. * the function used by the lib.
  453. * (function(message, source, lineno, colno, error)).
  454. */
  455. getGlobalOnErrorHandler(message, source, lineno, colno, error) {
  456. logger.error(
  457. `UnhandledError: ${message}`,
  458. `Script: ${source}`,
  459. `Line: ${lineno}`,
  460. `Column: ${colno}`,
  461. 'StackTrace: ', error);
  462. Statistics.reportGlobalError(error);
  463. },
  464. /* eslint-enable max-params */
  465. /**
  466. * Represents a hub/namespace for utility functionality which may be of
  467. * interest to lib-jitsi-meet clients.
  468. */
  469. util: {
  470. AuthUtil,
  471. ScriptUtil,
  472. browser
  473. }
  474. });