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

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