modified lib-jitsi-meet dev repo
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

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