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

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