Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JitsiMeetJS.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 getActiveAudioDevice from './modules/detection/ActiveDeviceDetector';
  19. import * as DetectionEvents from './modules/detection/DetectionEvents';
  20. import TrackVADEmitter from './modules/detection/TrackVADEmitter';
  21. import FeatureFlags from './modules/flags/FeatureFlags';
  22. import ProxyConnectionService
  23. from './modules/proxyconnection/ProxyConnectionService';
  24. import recordingConstants from './modules/recording/recordingConstants';
  25. import Settings from './modules/settings/Settings';
  26. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  27. import precallTest from './modules/statistics/PrecallTest';
  28. import Statistics from './modules/statistics/statistics';
  29. import AuthUtil from './modules/util/AuthUtil';
  30. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  31. import ScriptUtil from './modules/util/ScriptUtil';
  32. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  33. import AudioMixer from './modules/webaudio/AudioMixer';
  34. import * as MediaType from './service/RTC/MediaType';
  35. import * as ConnectionQualityEvents
  36. from './service/connectivity/ConnectionQualityEvents';
  37. import * as E2ePingEvents from './service/e2eping/E2ePingEvents';
  38. import { createGetUserMediaEvent } from './service/statistics/AnalyticsEvents';
  39. const logger = Logger.getLogger(__filename);
  40. /**
  41. * The amount of time to wait until firing
  42. * {@link JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN} event.
  43. */
  44. const USER_MEDIA_SLOW_PROMISE_TIMEOUT = 1000;
  45. /**
  46. * Extracts from an 'options' objects with a specific format (TODO what IS the
  47. * format?) the attributes which are to be logged in analytics events.
  48. *
  49. * @param options gum options (???)
  50. * @returns {*} the attributes to attach to analytics events.
  51. */
  52. function getAnalyticsAttributesFromOptions(options) {
  53. const attributes = {
  54. 'audio_requested':
  55. options.devices.includes('audio'),
  56. 'video_requested':
  57. options.devices.includes('video'),
  58. 'screen_sharing_requested':
  59. options.devices.includes('desktop')
  60. };
  61. if (attributes.video_requested) {
  62. attributes.resolution = options.resolution;
  63. }
  64. return attributes;
  65. }
  66. /**
  67. * Tries to deal with the following problem: {@code JitsiMeetJS} is not only
  68. * this module, it's also a global (i.e. attached to {@code window}) namespace
  69. * for all globals of the projects in the Jitsi Meet family. If lib-jitsi-meet
  70. * is loaded through an HTML {@code script} tag, {@code JitsiMeetJS} will
  71. * automatically be attached to {@code window} by webpack. Unfortunately,
  72. * webpack's source code does not check whether the global variable has already
  73. * been assigned and overwrites it. Which is OK for the module
  74. * {@code JitsiMeetJS} but is not OK for the namespace {@code JitsiMeetJS}
  75. * because it may already contain the values of other projects in the Jitsi Meet
  76. * family. The solution offered here works around webpack by merging all
  77. * existing values of the namespace {@code JitsiMeetJS} into the module
  78. * {@code JitsiMeetJS}.
  79. *
  80. * @param {Object} module - The module {@code JitsiMeetJS} (which will be
  81. * exported and may be attached to {@code window} by webpack later on).
  82. * @private
  83. * @returns {Object} - A {@code JitsiMeetJS} module which contains all existing
  84. * value of the namespace {@code JitsiMeetJS} (if any).
  85. */
  86. function _mergeNamespaceAndModule(module) {
  87. return (
  88. typeof window.JitsiMeetJS === 'object'
  89. ? Object.assign({}, window.JitsiMeetJS, module)
  90. : module);
  91. }
  92. /**
  93. * The public API of the Jitsi Meet library (a.k.a. {@code JitsiMeetJS}).
  94. */
  95. export default _mergeNamespaceAndModule({
  96. version: '{#COMMIT_HASH#}',
  97. JitsiConnection,
  98. /**
  99. * {@code ProxyConnectionService} is used to connect a remote peer to a
  100. * local Jitsi participant without going through a Jitsi conference. It is
  101. * currently used for room integration development, specifically wireless
  102. * screensharing. Its API is experimental and will likely change; usage of
  103. * it is advised against.
  104. */
  105. ProxyConnectionService,
  106. constants: {
  107. participantConnectionStatus: ParticipantConnectionStatus,
  108. recording: recordingConstants,
  109. sipVideoGW: VideoSIPGWConstants,
  110. transcriptionStatus: JitsiTranscriptionStatus
  111. },
  112. events: {
  113. conference: JitsiConferenceEvents,
  114. connection: JitsiConnectionEvents,
  115. detection: DetectionEvents,
  116. track: JitsiTrackEvents,
  117. mediaDevices: JitsiMediaDevicesEvents,
  118. connectionQuality: ConnectionQualityEvents,
  119. e2eping: E2ePingEvents
  120. },
  121. errors: {
  122. conference: JitsiConferenceErrors,
  123. connection: JitsiConnectionErrors,
  124. track: JitsiTrackErrors
  125. },
  126. errorTypes: {
  127. JitsiTrackError
  128. },
  129. logLevels: Logger.levels,
  130. mediaDevices: JitsiMediaDevices,
  131. analytics: Statistics.analytics,
  132. init(options = {}) {
  133. Settings.init(options.externalStorage);
  134. Statistics.init(options);
  135. // Configure the feature flags.
  136. FeatureFlags.init(options.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 = {}, oldfirePermissionPromptIsShownEvent) {
  260. let promiseFulfilled = false;
  261. const { firePermissionPromptIsShownEvent, fireSlowPromiseEvent, ...restOptions } = options;
  262. const firePermissionPrompt = firePermissionPromptIsShownEvent || oldfirePermissionPromptIsShownEvent;
  263. if (firePermissionPrompt && !RTC.arePermissionsGrantedForAvailableDevices()) {
  264. JitsiMediaDevices.emitEvent(
  265. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  266. browser.getName());
  267. } else if (fireSlowPromiseEvent) {
  268. window.setTimeout(() => {
  269. if (!promiseFulfilled) {
  270. JitsiMediaDevices.emitEvent(JitsiMediaDevicesEvents.SLOW_GET_USER_MEDIA);
  271. }
  272. }, USER_MEDIA_SLOW_PROMISE_TIMEOUT);
  273. }
  274. if (!window.connectionTimes) {
  275. window.connectionTimes = {};
  276. }
  277. window.connectionTimes['obtainPermissions.start']
  278. = window.performance.now();
  279. return RTC.obtainAudioAndVideoPermissions(restOptions)
  280. .then(tracks => {
  281. promiseFulfilled = true;
  282. window.connectionTimes['obtainPermissions.end']
  283. = window.performance.now();
  284. Statistics.sendAnalytics(
  285. createGetUserMediaEvent(
  286. 'success',
  287. getAnalyticsAttributesFromOptions(restOptions)));
  288. if (!RTC.options.disableAudioLevels) {
  289. for (let i = 0; i < tracks.length; i++) {
  290. const track = tracks[i];
  291. const mStream = track.getOriginalStream();
  292. if (track.getType() === MediaType.AUDIO) {
  293. Statistics.startLocalStats(mStream,
  294. track.setAudioLevel.bind(track));
  295. track.addEventListener(
  296. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  297. () => {
  298. Statistics.stopLocalStats(mStream);
  299. });
  300. }
  301. }
  302. }
  303. // set real device ids
  304. const currentlyAvailableMediaDevices
  305. = RTC.getCurrentlyAvailableMediaDevices();
  306. if (currentlyAvailableMediaDevices) {
  307. for (let i = 0; i < tracks.length; i++) {
  308. const track = tracks[i];
  309. track._setRealDeviceIdFromDeviceList(
  310. currentlyAvailableMediaDevices);
  311. }
  312. }
  313. // set the contentHint to "detail" for desktop tracks
  314. // eslint-disable-next-line prefer-const
  315. for (const track of tracks) {
  316. if (track.type === MediaType.VIDEO
  317. && track.videoType === 'desktop') {
  318. this.setVideoTrackContentHints(track.track, 'detail');
  319. }
  320. }
  321. return tracks;
  322. })
  323. .catch(error => {
  324. promiseFulfilled = true;
  325. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  326. // User cancelled action is not really an error, so only
  327. // log it as an event to avoid having conference classified
  328. // as partially failed
  329. const logObject = {
  330. id: 'screensharing_user_canceled',
  331. message: error.message
  332. };
  333. Statistics.sendLog(JSON.stringify(logObject));
  334. Statistics.sendAnalytics(
  335. createGetUserMediaEvent(
  336. 'warning',
  337. {
  338. reason: 'extension install user canceled'
  339. }));
  340. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  341. // logs not found devices with just application log to cs
  342. const logObject = {
  343. id: 'usermedia_missing_device',
  344. status: error.gum.devices
  345. };
  346. Statistics.sendLog(JSON.stringify(logObject));
  347. const attributes
  348. = getAnalyticsAttributesFromOptions(options);
  349. attributes.reason = 'device not found';
  350. attributes.devices = error.gum.devices.join('.');
  351. Statistics.sendAnalytics(
  352. createGetUserMediaEvent('error', attributes));
  353. } else {
  354. // Report gUM failed to the stats
  355. Statistics.sendGetUserMediaFailed(error);
  356. const attributes
  357. = getAnalyticsAttributesFromOptions(options);
  358. attributes.reason = error.name;
  359. Statistics.sendAnalytics(
  360. createGetUserMediaEvent('error', attributes));
  361. }
  362. window.connectionTimes['obtainPermissions.end']
  363. = window.performance.now();
  364. return Promise.reject(error);
  365. });
  366. },
  367. /**
  368. * Create a TrackVADEmitter service that connects an audio track to an VAD (voice activity detection) processor in
  369. * order to obtain VAD scores for individual PCM audio samples.
  370. * @param {string} localAudioDeviceId - The target local audio device.
  371. * @param {number} sampleRate - Sample rate at which the emitter will operate. Possible values 256, 512, 1024,
  372. * 4096, 8192, 16384. Passing other values will default to closes neighbor.
  373. * I.e. Providing a value of 4096 means that the emitter will process 4096 PCM samples at a time, higher values mean
  374. * longer calls, lowers values mean more calls but shorter.
  375. * @param {Object} vadProcessor - VAD Processors that does the actual compute on a PCM sample.The processor needs
  376. * to implement the following functions:
  377. * - <tt>getSampleLength()</tt> - Returns the sample size accepted by calculateAudioFrameVAD.
  378. * - <tt>getRequiredPCMFrequency()</tt> - Returns the PCM frequency at which the processor operates.
  379. * i.e. (16KHz, 44.1 KHz etc.)
  380. * - <tt>calculateAudioFrameVAD(pcmSample)</tt> - Process a 32 float pcm sample of getSampleLength size.
  381. * @returns {Promise<TrackVADEmitter>}
  382. */
  383. createTrackVADEmitter(localAudioDeviceId, sampleRate, vadProcessor) {
  384. return TrackVADEmitter.create(localAudioDeviceId, sampleRate, vadProcessor);
  385. },
  386. /**
  387. * Create AudioMixer, which is essentially a wrapper over web audio ChannelMergerNode. It essentially allows the
  388. * user to mix multiple MediaStreams into a single one.
  389. *
  390. * @returns {AudioMixer}
  391. */
  392. createAudioMixer() {
  393. return new AudioMixer();
  394. },
  395. /**
  396. * Go through all audio devices on the system and return one that is active, i.e. has audio signal.
  397. *
  398. * @returns Promise<Object> - Object containing information about the found device.
  399. */
  400. getActiveAudioDevice() {
  401. return getActiveAudioDevice();
  402. },
  403. /**
  404. * Checks if its possible to enumerate available cameras/microphones.
  405. *
  406. * @returns {Promise<boolean>} a Promise which will be resolved only once
  407. * the WebRTC stack is ready, either with true if the device listing is
  408. * available available or with false otherwise.
  409. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  410. */
  411. isDeviceListAvailable() {
  412. logger.warn('This method is deprecated, use '
  413. + 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  414. return this.mediaDevices.isDeviceListAvailable();
  415. },
  416. /**
  417. * Returns true if changing the input (camera / microphone) or output
  418. * (audio) device is supported and false if not.
  419. *
  420. * @param {string} [deviceType] - type of device to change. Default is
  421. * {@code undefined} or 'input', 'output' - for audio output device change.
  422. * @returns {boolean} {@code true} if available; {@code false}, otherwise.
  423. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  424. */
  425. isDeviceChangeAvailable(deviceType) {
  426. logger.warn('This method is deprecated, use '
  427. + 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  428. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  429. },
  430. /**
  431. * Checks if the current environment supports having multiple audio
  432. * input devices in use simultaneously.
  433. *
  434. * @returns {boolean} True if multiple audio input devices can be used.
  435. */
  436. isMultipleAudioInputSupported() {
  437. return this.mediaDevices.isMultipleAudioInputSupported();
  438. },
  439. /**
  440. * Checks if local tracks can collect stats and collection is enabled.
  441. *
  442. * @param {boolean} True if stats are being collected for local tracks.
  443. */
  444. isCollectingLocalStats() {
  445. return Statistics.audioLevelsEnabled
  446. && LocalStatsCollector.isLocalStatsSupported();
  447. },
  448. /**
  449. * Executes callback with list of media devices connected.
  450. *
  451. * @param {function} callback
  452. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  453. */
  454. enumerateDevices(callback) {
  455. logger.warn('This method is deprecated, use '
  456. + 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  457. this.mediaDevices.enumerateDevices(callback);
  458. },
  459. /* eslint-disable max-params */
  460. /**
  461. * @returns function that can be used to be attached to window.onerror and
  462. * if options.enableWindowOnErrorHandler is enabled returns
  463. * the function used by the lib.
  464. * (function(message, source, lineno, colno, error)).
  465. */
  466. getGlobalOnErrorHandler(message, source, lineno, colno, error) {
  467. logger.error(
  468. `UnhandledError: ${message}`,
  469. `Script: ${source}`,
  470. `Line: ${lineno}`,
  471. `Column: ${colno}`,
  472. 'StackTrace: ', error);
  473. Statistics.reportGlobalError(error);
  474. },
  475. /**
  476. * Informs lib-jitsi-meet about the current network status.
  477. *
  478. * @param {boolean} isOnline - {@code true} if the internet connectivity is online or {@code false}
  479. * otherwise.
  480. */
  481. setNetworkInfo({ isOnline }) {
  482. NetworkInfo.updateNetworkInfo({ isOnline });
  483. },
  484. /**
  485. * Set the contentHint on the transmitted stream track to indicate
  486. * charaterstics in the video stream, which informs PeerConnection
  487. * on how to encode the track (to prefer motion or individual frame detail)
  488. * @param {MediaStreamTrack} track - the track that is transmitted
  489. * @param {String} hint - contentHint value that needs to be set on the track
  490. */
  491. setVideoTrackContentHints(track, hint) {
  492. if ('contentHint' in track) {
  493. track.contentHint = hint;
  494. if (track.contentHint !== hint) {
  495. logger.debug('Invalid video track contentHint');
  496. }
  497. } else {
  498. logger.debug('MediaStreamTrack contentHint attribute not supported');
  499. }
  500. },
  501. precallTest,
  502. /* eslint-enable max-params */
  503. /**
  504. * Represents a hub/namespace for utility functionality which may be of
  505. * interest to lib-jitsi-meet clients.
  506. */
  507. util: {
  508. AuthUtil,
  509. ScriptUtil,
  510. browser
  511. }
  512. });