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.ts 22KB

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