Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiMeetJS.js 21KB

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