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

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