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

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