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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. import Logger from '@jitsi/logger';
  2. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  3. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  4. import JitsiConnection from './JitsiConnection';
  5. import * as JitsiConnectionErrors from './JitsiConnectionErrors';
  6. import * as JitsiConnectionEvents from './JitsiConnectionEvents';
  7. import JitsiMediaDevices from './JitsiMediaDevices';
  8. import * as JitsiMediaDevicesEvents from './JitsiMediaDevicesEvents';
  9. import JitsiTrackError from './JitsiTrackError';
  10. import * as JitsiTrackErrors from './JitsiTrackErrors';
  11. import * as JitsiTrackEvents from './JitsiTrackEvents';
  12. import * as JitsiTranscriptionStatus from './JitsiTranscriptionStatus';
  13. import RTC from './modules/RTC/RTC';
  14. import browser from './modules/browser';
  15. import NetworkInfo from './modules/connectivity/NetworkInfo';
  16. import { ParticipantConnectionStatus }
  17. from './modules/connectivity/ParticipantConnectionStatus';
  18. import { TrackStreamingStatus } from './modules/connectivity/TrackStreamingStatus';
  19. import getActiveAudioDevice from './modules/detection/ActiveDeviceDetector';
  20. import * as DetectionEvents from './modules/detection/DetectionEvents';
  21. import TrackVADEmitter from './modules/detection/TrackVADEmitter';
  22. import FeatureFlags from './modules/flags/FeatureFlags';
  23. import ProxyConnectionService
  24. from './modules/proxyconnection/ProxyConnectionService';
  25. import recordingConstants from './modules/recording/recordingConstants';
  26. import Settings from './modules/settings/Settings';
  27. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  28. import precallTest from './modules/statistics/PrecallTest';
  29. import Statistics from './modules/statistics/statistics';
  30. import AuthUtil from './modules/util/AuthUtil';
  31. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  32. import ScriptUtil from './modules/util/ScriptUtil';
  33. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  34. import AudioMixer from './modules/webaudio/AudioMixer';
  35. import { MediaType } from './service/RTC/MediaType';
  36. import * as ConnectionQualityEvents
  37. from './service/connectivity/ConnectionQualityEvents';
  38. import * as E2ePingEvents from './service/e2eping/E2ePingEvents';
  39. import { createGetUserMediaEvent } from './service/statistics/AnalyticsEvents';
  40. const logger = Logger.getLogger(__filename);
  41. /**
  42. * The amount of time to wait until firing
  43. * {@link JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN} event.
  44. */
  45. const USER_MEDIA_SLOW_PROMISE_TIMEOUT = 1000;
  46. /**
  47. * Extracts from an 'options' objects with a specific format (TODO what IS the
  48. * format?) the attributes which are to be logged in analytics events.
  49. *
  50. * @param options gum options (???)
  51. * @returns {*} the attributes to attach to analytics events.
  52. */
  53. function getAnalyticsAttributesFromOptions(options) {
  54. const attributes = {
  55. 'audio_requested':
  56. options.devices.includes('audio'),
  57. 'video_requested':
  58. options.devices.includes('video'),
  59. 'screen_sharing_requested':
  60. options.devices.includes('desktop')
  61. };
  62. if (attributes.video_requested) {
  63. attributes.resolution = options.resolution;
  64. }
  65. return attributes;
  66. }
  67. /**
  68. * Tries to deal with the following problem: {@code JitsiMeetJS} is not only
  69. * this module, it's also a global (i.e. attached to {@code window}) namespace
  70. * for all globals of the projects in the Jitsi Meet family. If lib-jitsi-meet
  71. * is loaded through an HTML {@code script} tag, {@code JitsiMeetJS} will
  72. * automatically be attached to {@code window} by webpack. Unfortunately,
  73. * webpack's source code does not check whether the global variable has already
  74. * been assigned and overwrites it. Which is OK for the module
  75. * {@code JitsiMeetJS} but is not OK for the namespace {@code JitsiMeetJS}
  76. * because it may already contain the values of other projects in the Jitsi Meet
  77. * family. The solution offered here works around webpack by merging all
  78. * existing values of the namespace {@code JitsiMeetJS} into the module
  79. * {@code JitsiMeetJS}.
  80. *
  81. * @param {Object} module - The module {@code JitsiMeetJS} (which will be
  82. * exported and may be attached to {@code window} by webpack later on).
  83. * @private
  84. * @returns {Object} - A {@code JitsiMeetJS} module which contains all existing
  85. * value of the namespace {@code JitsiMeetJS} (if any).
  86. */
  87. function _mergeNamespaceAndModule(module) {
  88. return (
  89. typeof window.JitsiMeetJS === 'object'
  90. ? Object.assign({}, window.JitsiMeetJS, module)
  91. : module);
  92. }
  93. /**
  94. * The public API of the Jitsi Meet library (a.k.a. {@code JitsiMeetJS}).
  95. */
  96. export default _mergeNamespaceAndModule({
  97. version: '{#COMMIT_HASH#}',
  98. JitsiConnection,
  99. /**
  100. * {@code ProxyConnectionService} is used to connect a remote peer to a
  101. * local Jitsi participant without going through a Jitsi conference. It is
  102. * currently used for room integration development, specifically wireless
  103. * screensharing. Its API is experimental and will likely change; usage of
  104. * it is advised against.
  105. */
  106. ProxyConnectionService,
  107. constants: {
  108. participantConnectionStatus: ParticipantConnectionStatus,
  109. recording: recordingConstants,
  110. sipVideoGW: VideoSIPGWConstants,
  111. transcriptionStatus: JitsiTranscriptionStatus,
  112. trackStreamingStatus: TrackStreamingStatus
  113. },
  114. events: {
  115. conference: JitsiConferenceEvents,
  116. connection: JitsiConnectionEvents,
  117. detection: DetectionEvents,
  118. track: JitsiTrackEvents,
  119. mediaDevices: JitsiMediaDevicesEvents,
  120. connectionQuality: ConnectionQualityEvents,
  121. e2eping: E2ePingEvents
  122. },
  123. errors: {
  124. conference: JitsiConferenceErrors,
  125. connection: JitsiConnectionErrors,
  126. track: JitsiTrackErrors
  127. },
  128. errorTypes: {
  129. JitsiTrackError
  130. },
  131. logLevels: Logger.levels,
  132. mediaDevices: JitsiMediaDevices,
  133. analytics: Statistics.analytics,
  134. init(options = {}) {
  135. Settings.init(options.externalStorage);
  136. Statistics.init(options);
  137. const flags = options.flags || {};
  138. // Multi-stream is supported only on endpoints running in Unified plan mode and the flag to disable unified
  139. // plan also needs to be taken into consideration.
  140. if (typeof options.enableUnifiedOnChrome !== 'undefined') {
  141. flags.enableUnifiedOnChrome = options.enableUnifiedOnChrome;
  142. }
  143. // Configure the feature flags.
  144. FeatureFlags.init(flags);
  145. // Initialize global window.connectionTimes
  146. // FIXME do not use 'window'
  147. if (!window.connectionTimes) {
  148. window.connectionTimes = {};
  149. }
  150. if (options.enableAnalyticsLogging !== true) {
  151. logger.warn('Analytics disabled, disposing.');
  152. this.analytics.dispose();
  153. }
  154. if (options.enableWindowOnErrorHandler) {
  155. GlobalOnErrorHandler.addHandler(
  156. this.getGlobalOnErrorHandler.bind(this));
  157. }
  158. if (this.version) {
  159. const logObject = {
  160. id: 'component_version',
  161. component: 'lib-jitsi-meet',
  162. version: this.version
  163. };
  164. Statistics.sendLog(JSON.stringify(logObject));
  165. }
  166. return RTC.init(options);
  167. },
  168. /**
  169. * Returns whether the desktop sharing is enabled or not.
  170. *
  171. * @returns {boolean}
  172. */
  173. isDesktopSharingEnabled() {
  174. return RTC.isDesktopSharingEnabled();
  175. },
  176. /**
  177. * Returns whether the current execution environment supports WebRTC (for
  178. * use within this library).
  179. *
  180. * @returns {boolean} {@code true} if WebRTC is supported in the current
  181. * execution environment (for use within this library); {@code false},
  182. * otherwise.
  183. */
  184. isWebRtcSupported() {
  185. return RTC.isWebRtcSupported();
  186. },
  187. setLogLevel(level) {
  188. Logger.setLogLevel(level);
  189. },
  190. /**
  191. * Sets the log level to the <tt>Logger</tt> instance with given id.
  192. *
  193. * @param {Logger.levels} level the logging level to be set
  194. * @param {string} id the logger id to which new logging level will be set.
  195. * Usually it's the name of the JavaScript source file including the path
  196. * ex. "modules/xmpp/ChatRoom.js"
  197. */
  198. setLogLevelById(level, id) {
  199. Logger.setLogLevelById(level, id);
  200. },
  201. /**
  202. * Registers new global logger transport to the library logging framework.
  203. *
  204. * @param globalTransport
  205. * @see Logger.addGlobalTransport
  206. */
  207. addGlobalLogTransport(globalTransport) {
  208. Logger.addGlobalTransport(globalTransport);
  209. },
  210. /**
  211. * Removes global logging transport from the library logging framework.
  212. *
  213. * @param globalTransport
  214. * @see Logger.removeGlobalTransport
  215. */
  216. removeGlobalLogTransport(globalTransport) {
  217. Logger.removeGlobalTransport(globalTransport);
  218. },
  219. /**
  220. * Sets global options which will be used by all loggers. Changing these
  221. * works even after other loggers are created.
  222. *
  223. * @param options
  224. * @see Logger.setGlobalOptions
  225. */
  226. setGlobalLogOptions(options) {
  227. Logger.setGlobalOptions(options);
  228. },
  229. /**
  230. * Creates the media tracks and returns them trough the callback.
  231. *
  232. * @param options Object with properties / settings specifying the tracks
  233. * which should be created. should be created or some additional
  234. * configurations about resolution for example.
  235. * @param {Array} options.effects optional effects array for the track
  236. * @param {boolean} options.firePermissionPromptIsShownEvent - if event
  237. * JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN should be fired
  238. * @param {boolean} options.fireSlowPromiseEvent - if event
  239. * JitsiMediaDevicesEvents.USER_MEDIA_SLOW_PROMISE_TIMEOUT should be fired
  240. * @param {Array} options.devices the devices that will be requested
  241. * @param {string} options.resolution resolution constraints
  242. * @param {string} options.cameraDeviceId
  243. * @param {string} options.micDeviceId
  244. * @param {intiger} interval - the interval (in ms) for
  245. * checking whether the desktop sharing extension is installed or not
  246. * @param {Function} checkAgain - returns boolean. While checkAgain()==true
  247. * createLocalTracks will wait and check on every "interval" ms for the
  248. * extension. If the desktop extension is not install and checkAgain()==true
  249. * createLocalTracks will finish with rejected Promise.
  250. * @param {Function} listener - The listener will be called to notify the
  251. * user of lib-jitsi-meet that createLocalTracks is starting external
  252. * extension installation process.
  253. * NOTE: If the inline installation process is not possible and external
  254. * installation is enabled the listener property will be called to notify
  255. * the start of external installation process. After that createLocalTracks
  256. * will start to check for the extension on every interval ms until the
  257. * plugin is installed or until checkAgain return false. If the extension
  258. * is found createLocalTracks will try to get the desktop sharing track and
  259. * will finish the execution. If checkAgain returns false, createLocalTracks
  260. * will finish the execution with rejected Promise.
  261. *
  262. * @deprecated old firePermissionPromptIsShownEvent
  263. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise
  264. * that returns an array of created JitsiTracks if resolved, or a
  265. * JitsiConferenceError if rejected.
  266. */
  267. createLocalTracks(options = {}, oldfirePermissionPromptIsShownEvent) {
  268. let promiseFulfilled = false;
  269. const { firePermissionPromptIsShownEvent, fireSlowPromiseEvent, ...restOptions } = options;
  270. const firePermissionPrompt = firePermissionPromptIsShownEvent || oldfirePermissionPromptIsShownEvent;
  271. if (firePermissionPrompt && !RTC.arePermissionsGrantedForAvailableDevices()) {
  272. JitsiMediaDevices.emitEvent(
  273. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  274. browser.getName());
  275. } else if (fireSlowPromiseEvent) {
  276. window.setTimeout(() => {
  277. if (!promiseFulfilled) {
  278. JitsiMediaDevices.emitEvent(JitsiMediaDevicesEvents.SLOW_GET_USER_MEDIA);
  279. }
  280. }, USER_MEDIA_SLOW_PROMISE_TIMEOUT);
  281. }
  282. if (!window.connectionTimes) {
  283. window.connectionTimes = {};
  284. }
  285. window.connectionTimes['obtainPermissions.start']
  286. = window.performance.now();
  287. return RTC.obtainAudioAndVideoPermissions(restOptions)
  288. .then(tracks => {
  289. promiseFulfilled = true;
  290. window.connectionTimes['obtainPermissions.end']
  291. = window.performance.now();
  292. Statistics.sendAnalytics(
  293. createGetUserMediaEvent(
  294. 'success',
  295. getAnalyticsAttributesFromOptions(restOptions)));
  296. if (!RTC.options.disableAudioLevels) {
  297. for (let i = 0; i < tracks.length; i++) {
  298. const track = tracks[i];
  299. if (track.getType() === MediaType.AUDIO) {
  300. Statistics.startLocalStats(track,
  301. track.setAudioLevel.bind(track));
  302. }
  303. }
  304. }
  305. // set real device ids
  306. const currentlyAvailableMediaDevices
  307. = RTC.getCurrentlyAvailableMediaDevices();
  308. if (currentlyAvailableMediaDevices) {
  309. for (let i = 0; i < tracks.length; i++) {
  310. const track = tracks[i];
  311. track._setRealDeviceIdFromDeviceList(
  312. currentlyAvailableMediaDevices);
  313. }
  314. }
  315. // set the contentHint to "detail" for desktop tracks
  316. // eslint-disable-next-line prefer-const
  317. for (const track of tracks) {
  318. if (track.type === MediaType.VIDEO
  319. && track.videoType === 'desktop') {
  320. this.setVideoTrackContentHints(track.track, 'detail');
  321. }
  322. }
  323. return tracks;
  324. })
  325. .catch(error => {
  326. promiseFulfilled = true;
  327. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  328. // User cancelled action is not really an error, so only
  329. // log it as an event to avoid having conference classified
  330. // as partially failed
  331. const logObject = {
  332. id: 'screensharing_user_canceled',
  333. message: error.message
  334. };
  335. Statistics.sendLog(JSON.stringify(logObject));
  336. Statistics.sendAnalytics(
  337. createGetUserMediaEvent(
  338. 'warning',
  339. {
  340. reason: 'extension install user canceled'
  341. }));
  342. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  343. // logs not found devices with just application log to cs
  344. const logObject = {
  345. id: 'usermedia_missing_device',
  346. status: error.gum.devices
  347. };
  348. Statistics.sendLog(JSON.stringify(logObject));
  349. const attributes
  350. = getAnalyticsAttributesFromOptions(options);
  351. attributes.reason = 'device not found';
  352. attributes.devices = error.gum.devices.join('.');
  353. Statistics.sendAnalytics(
  354. createGetUserMediaEvent('error', attributes));
  355. } else {
  356. // Report gUM failed to the stats
  357. Statistics.sendGetUserMediaFailed(error);
  358. const attributes
  359. = getAnalyticsAttributesFromOptions(options);
  360. attributes.reason = error.name;
  361. Statistics.sendAnalytics(
  362. createGetUserMediaEvent('error', attributes));
  363. }
  364. window.connectionTimes['obtainPermissions.end']
  365. = window.performance.now();
  366. return Promise.reject(error);
  367. });
  368. },
  369. /**
  370. * Create a TrackVADEmitter service that connects an audio track to an VAD (voice activity detection) processor in
  371. * order to obtain VAD scores for individual PCM audio samples.
  372. * @param {string} localAudioDeviceId - The target local audio device.
  373. * @param {number} sampleRate - Sample rate at which the emitter will operate. Possible values 256, 512, 1024,
  374. * 4096, 8192, 16384. Passing other values will default to closes neighbor.
  375. * I.e. Providing a value of 4096 means that the emitter will process 4096 PCM samples at a time, higher values mean
  376. * longer calls, lowers values mean more calls but shorter.
  377. * @param {Object} vadProcessor - VAD Processors that does the actual compute on a PCM sample.The processor needs
  378. * to implement the following functions:
  379. * - <tt>getSampleLength()</tt> - Returns the sample size accepted by calculateAudioFrameVAD.
  380. * - <tt>getRequiredPCMFrequency()</tt> - Returns the PCM frequency at which the processor operates.
  381. * i.e. (16KHz, 44.1 KHz etc.)
  382. * - <tt>calculateAudioFrameVAD(pcmSample)</tt> - Process a 32 float pcm sample of getSampleLength size.
  383. * @returns {Promise<TrackVADEmitter>}
  384. */
  385. createTrackVADEmitter(localAudioDeviceId, sampleRate, vadProcessor) {
  386. return TrackVADEmitter.create(localAudioDeviceId, sampleRate, vadProcessor);
  387. },
  388. /**
  389. * Create AudioMixer, which is essentially a wrapper over web audio ChannelMergerNode. It essentially allows the
  390. * user to mix multiple MediaStreams into a single one.
  391. *
  392. * @returns {AudioMixer}
  393. */
  394. createAudioMixer() {
  395. return new AudioMixer();
  396. },
  397. /**
  398. * Go through all audio devices on the system and return one that is active, i.e. has audio signal.
  399. *
  400. * @returns Promise<Object> - Object containing information about the found device.
  401. */
  402. getActiveAudioDevice() {
  403. return getActiveAudioDevice();
  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. /**
  478. * Informs lib-jitsi-meet about the current network status.
  479. *
  480. * @param {boolean} isOnline - {@code true} if the internet connectivity is online or {@code false}
  481. * otherwise.
  482. */
  483. setNetworkInfo({ isOnline }) {
  484. NetworkInfo.updateNetworkInfo({ isOnline });
  485. },
  486. /**
  487. * Set the contentHint on the transmitted stream track to indicate
  488. * charaterstics in the video stream, which informs PeerConnection
  489. * on how to encode the track (to prefer motion or individual frame detail)
  490. * @param {MediaStreamTrack} track - the track that is transmitted
  491. * @param {String} hint - contentHint value that needs to be set on the track
  492. */
  493. setVideoTrackContentHints(track, hint) {
  494. if ('contentHint' in track) {
  495. track.contentHint = hint;
  496. if (track.contentHint !== hint) {
  497. logger.debug('Invalid video track contentHint');
  498. }
  499. } else {
  500. logger.debug('MediaStreamTrack contentHint attribute not supported');
  501. }
  502. },
  503. precallTest,
  504. /* eslint-enable max-params */
  505. /**
  506. * Represents a hub/namespace for utility functionality which may be of
  507. * interest to lib-jitsi-meet clients.
  508. */
  509. util: {
  510. AuthUtil,
  511. ScriptUtil,
  512. browser
  513. }
  514. });