您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiMeetJS.ts 20KB

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