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

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