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 21KB

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