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

JitsiMeetJS.ts 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 RTCStats from './modules/RTCStats/RTCStats';
  15. import browser from './modules/browser';
  16. import NetworkInfo from './modules/connectivity/NetworkInfo';
  17. import { TrackStreamingStatus } from './modules/connectivity/TrackStreamingStatus';
  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 Statistics from './modules/statistics/statistics';
  28. import ScriptUtil from './modules/util/ScriptUtil';
  29. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  30. import AudioMixer from './modules/webaudio/AudioMixer';
  31. import { MediaType } from './service/RTC/MediaType';
  32. import * as ConnectionQualityEvents
  33. from './service/connectivity/ConnectionQualityEvents';
  34. import * as E2ePingEvents from './service/e2eping/E2ePingEvents';
  35. import { createGetUserMediaEvent } from './service/statistics/AnalyticsEvents';
  36. import * as RTCStatsEvents from './modules/RTCStats/RTCStatsEvents';
  37. import { VideoType } from './service/RTC/VideoType';
  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. * Indicates whether GUM has been executed or not.
  46. */
  47. let hasGUMExecuted = false;
  48. /**
  49. * Extracts from an 'options' objects with a specific format (TODO what IS the
  50. * format?) the attributes which are to be logged in analytics events.
  51. *
  52. * @param options gum options (???)
  53. * @returns {*} the attributes to attach to analytics events.
  54. */
  55. function getAnalyticsAttributesFromOptions(options) {
  56. const attributes: any = {};
  57. attributes['audio_requested'] = options.devices.includes('audio');
  58. attributes['video_requested'] = options.devices.includes('video');
  59. attributes['screen_sharing_requested'] = options.devices.includes('desktop');
  60. if (attributes.video_requested) {
  61. attributes.resolution = options.resolution;
  62. }
  63. return attributes;
  64. }
  65. interface ICreateLocalTrackOptions {
  66. cameraDeviceId?: string;
  67. devices?: any[];
  68. firePermissionPromptIsShownEvent?: boolean;
  69. fireSlowPromiseEvent?: boolean;
  70. micDeviceId?: string;
  71. resolution?: string;
  72. }
  73. interface IJitsiMeetJSOptions {
  74. enableAnalyticsLogging?: boolean;
  75. enableWindowOnErrorHandler?: boolean;
  76. externalStorage?: Storage;
  77. flags?: {
  78. runInLiteMode?: boolean;
  79. ssrcRewritingEnabled?: boolean;
  80. }
  81. }
  82. interface ICreateLocalTrackFromMediaStreamOptions {
  83. stream: MediaStream,
  84. sourceType: string,
  85. mediaType: MediaType,
  86. videoType?: VideoType
  87. }
  88. /**
  89. * The public API of the Jitsi Meet library (a.k.a. {@code JitsiMeetJS}).
  90. */
  91. export default {
  92. version: '{#COMMIT_HASH#}',
  93. JitsiConnection,
  94. /**
  95. * {@code ProxyConnectionService} is used to connect a remote peer to a
  96. * local Jitsi participant without going through a Jitsi conference. It is
  97. * currently used for room integration development, specifically wireless
  98. * screensharing. Its API is experimental and will likely change; usage of
  99. * it is advised against.
  100. */
  101. ProxyConnectionService,
  102. constants: {
  103. recording: recordingConstants,
  104. sipVideoGW: VideoSIPGWConstants,
  105. transcriptionStatus: JitsiTranscriptionStatus,
  106. trackStreamingStatus: TrackStreamingStatus
  107. },
  108. events: {
  109. conference: JitsiConferenceEvents,
  110. connection: JitsiConnectionEvents,
  111. detection: DetectionEvents,
  112. track: JitsiTrackEvents,
  113. mediaDevices: JitsiMediaDevicesEvents,
  114. connectionQuality: ConnectionQualityEvents,
  115. e2eping: E2ePingEvents,
  116. rtcstats: RTCStatsEvents
  117. },
  118. errors: {
  119. conference: JitsiConferenceErrors,
  120. connection: JitsiConnectionErrors,
  121. track: JitsiTrackErrors
  122. },
  123. errorTypes: {
  124. JitsiTrackError
  125. },
  126. logLevels: Logger.levels,
  127. mediaDevices: JitsiMediaDevices as unknown,
  128. analytics: Statistics.analytics as unknown,
  129. init(options: IJitsiMeetJSOptions = {}) {
  130. // @ts-ignore
  131. logger.info(`This appears to be ${browser.getName()}, ver: ${browser.getVersion()}`);
  132. Settings.init(options.externalStorage);
  133. Statistics.init(options);
  134. const flags = options.flags || {};
  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. 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. * Expose rtcstats to the public API.
  172. */
  173. rtcstats: {
  174. /**
  175. * Sends identity data to the rtcstats server. This data is used
  176. * to identify the specifics of a particular client, it can be any object
  177. * and will show in the generated rtcstats dump under "identity" entries.
  178. *
  179. * @param {Object} identityData - Identity data to send.
  180. * @returns {void}
  181. */
  182. sendIdentityEntry(identityData) {
  183. RTCStats.sendIdentity(identityData);
  184. },
  185. /**
  186. * Sends a stats entry to rtcstats server.
  187. * @param {string} statsType - The type of stats to send.
  188. * @param {Object} data - The stats data to send.
  189. */
  190. sendStatsEntry(statsType, data) {
  191. RTCStats.sendStatsEntry(statsType, null, data);
  192. },
  193. /**
  194. * Events generated by rtcstats, such as PeerConnections state,
  195. * and websocket connection state.
  196. *
  197. * @param {RTCStatsEvents} event - The event name.
  198. * @param {function} handler - The event handler.
  199. */
  200. on(event, handler) {
  201. RTCStats.events.on(event, handler);
  202. }
  203. },
  204. /**
  205. * Sets the log level to the <tt>Logger</tt> instance with given id.
  206. *
  207. * @param {Logger.levels} level the logging level to be set
  208. * @param {string} id the logger id to which new logging level will be set.
  209. * Usually it's the name of the JavaScript source file including the path
  210. * ex. "modules/xmpp/ChatRoom.js"
  211. */
  212. setLogLevelById(level, id) {
  213. Logger.setLogLevelById(level, id);
  214. },
  215. /**
  216. * Registers new global logger transport to the library logging framework.
  217. *
  218. * @param globalTransport
  219. * @see Logger.addGlobalTransport
  220. */
  221. addGlobalLogTransport(globalTransport) {
  222. Logger.addGlobalTransport(globalTransport);
  223. },
  224. /**
  225. * Removes global logging transport from the library logging framework.
  226. *
  227. * @param globalTransport
  228. * @see Logger.removeGlobalTransport
  229. */
  230. removeGlobalLogTransport(globalTransport) {
  231. Logger.removeGlobalTransport(globalTransport);
  232. },
  233. /**
  234. * Sets global options which will be used by all loggers. Changing these
  235. * works even after other loggers are created.
  236. *
  237. * @param options
  238. * @see Logger.setGlobalOptions
  239. */
  240. setGlobalLogOptions(options) {
  241. Logger.setGlobalOptions(options);
  242. },
  243. /**
  244. * Creates the media tracks and returns them trough the callback.
  245. *
  246. * @param options Object with properties / settings specifying the tracks
  247. * which should be created. should be created or some additional
  248. * configurations about resolution for example.
  249. * @param {Array} options.effects optional effects array for the track
  250. * @param {boolean} options.firePermissionPromptIsShownEvent - if event
  251. * JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN should be fired
  252. * @param {boolean} options.fireSlowPromiseEvent - if event
  253. * JitsiMediaDevicesEvents.USER_MEDIA_SLOW_PROMISE_TIMEOUT should be fired
  254. * @param {Array} options.devices the devices that will be requested
  255. * @param {string} options.resolution resolution constraints
  256. * @param {string} options.cameraDeviceId
  257. * @param {string} options.micDeviceId
  258. * @param {intiger} interval - the interval (in ms) for
  259. * checking whether the desktop sharing extension is installed or not
  260. * @param {Function} checkAgain - returns boolean. While checkAgain()==true
  261. * createLocalTracks will wait and check on every "interval" ms for the
  262. * extension. If the desktop extension is not install and checkAgain()==true
  263. * createLocalTracks will finish with rejected Promise.
  264. * @param {Function} listener - The listener will be called to notify the
  265. * user of lib-jitsi-meet that createLocalTracks is starting external
  266. * extension installation process.
  267. * NOTE: If the inline installation process is not possible and external
  268. * installation is enabled the listener property will be called to notify
  269. * the start of external installation process. After that createLocalTracks
  270. * will start to check for the extension on every interval ms until the
  271. * plugin is installed or until checkAgain return false. If the extension
  272. * is found createLocalTracks will try to get the desktop sharing track and
  273. * will finish the execution. If checkAgain returns false, createLocalTracks
  274. * will finish the execution with rejected Promise.
  275. *
  276. * @deprecated old firePermissionPromptIsShownEvent
  277. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise
  278. * that returns an array of created JitsiTracks if resolved, or a
  279. * JitsiConferenceError if rejected.
  280. */
  281. createLocalTracks(options: ICreateLocalTrackOptions = {}, oldfirePermissionPromptIsShownEvent) {
  282. let promiseFulfilled = false;
  283. const { firePermissionPromptIsShownEvent, fireSlowPromiseEvent, ...restOptions } = options;
  284. const firePermissionPrompt = firePermissionPromptIsShownEvent || oldfirePermissionPromptIsShownEvent;
  285. if (firePermissionPrompt && !RTC.arePermissionsGrantedForAvailableDevices()) {
  286. // @ts-ignore
  287. JitsiMediaDevices.emit(JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN, browser.getName());
  288. } else if (fireSlowPromiseEvent) {
  289. window.setTimeout(() => {
  290. if (!promiseFulfilled) {
  291. JitsiMediaDevices.emit(JitsiMediaDevicesEvents.SLOW_GET_USER_MEDIA);
  292. }
  293. }, USER_MEDIA_SLOW_PROMISE_TIMEOUT);
  294. }
  295. let isFirstGUM = false;
  296. let startTS = window.performance.now();
  297. if (!window.connectionTimes) {
  298. window.connectionTimes = {};
  299. }
  300. if (!hasGUMExecuted) {
  301. hasGUMExecuted = true;
  302. isFirstGUM = true;
  303. window.connectionTimes['firstObtainPermissions.start'] = startTS;
  304. }
  305. window.connectionTimes['obtainPermissions.start'] = startTS;
  306. return RTC.obtainAudioAndVideoPermissions(restOptions)
  307. .then(tracks => {
  308. promiseFulfilled = true;
  309. let endTS = window.performance.now();
  310. window.connectionTimes['obtainPermissions.end'] = endTS;
  311. if (isFirstGUM) {
  312. window.connectionTimes['firstObtainPermissions.end'] = endTS;
  313. }
  314. Statistics.sendAnalytics(
  315. createGetUserMediaEvent(
  316. 'success',
  317. getAnalyticsAttributesFromOptions(restOptions)));
  318. if (this.isCollectingLocalStats()) {
  319. for (let i = 0; i < tracks.length; i++) {
  320. const track = tracks[i];
  321. if (track.getType() === MediaType.AUDIO) {
  322. Statistics.startLocalStats(track,
  323. track.setAudioLevel.bind(track));
  324. }
  325. }
  326. }
  327. // set real device ids
  328. const currentlyAvailableMediaDevices
  329. = RTC.getCurrentlyAvailableMediaDevices();
  330. if (currentlyAvailableMediaDevices) {
  331. for (let i = 0; i < tracks.length; i++) {
  332. const track = tracks[i];
  333. track._setRealDeviceIdFromDeviceList(
  334. currentlyAvailableMediaDevices);
  335. }
  336. }
  337. return tracks;
  338. })
  339. .catch(error => {
  340. promiseFulfilled = true;
  341. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  342. Statistics.sendAnalytics(
  343. createGetUserMediaEvent(
  344. 'warning',
  345. {
  346. reason: 'extension install user canceled'
  347. }));
  348. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  349. const attributes
  350. = getAnalyticsAttributesFromOptions(options);
  351. attributes.reason = 'device not found';
  352. attributes.devices = error.gum.devices.join('.');
  353. Statistics.sendAnalytics(
  354. createGetUserMediaEvent('error', attributes));
  355. } else {
  356. const attributes
  357. = getAnalyticsAttributesFromOptions(options);
  358. attributes.reason = error.name;
  359. Statistics.sendAnalytics(
  360. createGetUserMediaEvent('error', attributes));
  361. }
  362. let endTS = window.performance.now();
  363. window.connectionTimes['obtainPermissions.end'] = endTS;
  364. if (isFirstGUM) {
  365. window.connectionTimes['firstObtainPermissions.end'] = endTS;
  366. }
  367. return Promise.reject(error);
  368. });
  369. },
  370. /**
  371. * Manually create JitsiLocalTrack's from the provided track info, by exposing the RTC method
  372. *
  373. * @param {Array<ICreateLocalTrackFromMediaStreamOptions>} tracksInfo - array of track information
  374. * @returns {Array<JitsiLocalTrack>} - created local tracks
  375. */
  376. createLocalTracksFromMediaStreams(tracksInfo) {
  377. return RTC.createLocalTracks(tracksInfo.map((trackInfo) => {
  378. const tracks = trackInfo.stream.getTracks()
  379. .filter(track => track.kind === trackInfo.mediaType);
  380. if (!tracks || tracks.length === 0) {
  381. throw new JitsiTrackError(JitsiTrackErrors.TRACK_NO_STREAM_TRACKS_FOUND, null, null);
  382. }
  383. if (tracks.length > 1) {
  384. throw new JitsiTrackError(JitsiTrackErrors.TRACK_TOO_MANY_TRACKS_IN_STREAM, null, null);
  385. }
  386. trackInfo.track = tracks[0];
  387. return trackInfo;
  388. }));
  389. },
  390. /**
  391. * Create a TrackVADEmitter service that connects an audio track to an VAD (voice activity detection) processor in
  392. * order to obtain VAD scores for individual PCM audio samples.
  393. * @param {string} localAudioDeviceId - The target local audio device.
  394. * @param {number} sampleRate - Sample rate at which the emitter will operate. Possible values 256, 512, 1024,
  395. * 4096, 8192, 16384. Passing other values will default to closes neighbor.
  396. * I.e. Providing a value of 4096 means that the emitter will process 4096 PCM samples at a time, higher values mean
  397. * longer calls, lowers values mean more calls but shorter.
  398. * @param {Object} vadProcessor - VAD Processors that does the actual compute on a PCM sample.The processor needs
  399. * to implement the following functions:
  400. * - <tt>getSampleLength()</tt> - Returns the sample size accepted by calculateAudioFrameVAD.
  401. * - <tt>getRequiredPCMFrequency()</tt> - Returns the PCM frequency at which the processor operates.
  402. * i.e. (16KHz, 44.1 KHz etc.)
  403. * - <tt>calculateAudioFrameVAD(pcmSample)</tt> - Process a 32 float pcm sample of getSampleLength size.
  404. * @returns {Promise<TrackVADEmitter>}
  405. */
  406. createTrackVADEmitter(localAudioDeviceId, sampleRate, vadProcessor) {
  407. return TrackVADEmitter.create(localAudioDeviceId, sampleRate, vadProcessor);
  408. },
  409. /**
  410. * Create AudioMixer, which is essentially a wrapper over web audio ChannelMergerNode. It essentially allows the
  411. * user to mix multiple MediaStreams into a single one.
  412. *
  413. * @returns {AudioMixer}
  414. */
  415. createAudioMixer() {
  416. return new AudioMixer();
  417. },
  418. /**
  419. * Go through all audio devices on the system and return one that is active, i.e. has audio signal.
  420. *
  421. * @returns Promise<Object> - Object containing information about the found device.
  422. */
  423. getActiveAudioDevice() {
  424. return getActiveAudioDevice();
  425. },
  426. /**
  427. * Checks if its possible to enumerate available cameras/microphones.
  428. *
  429. * @returns {Promise<boolean>} a Promise which will be resolved only once
  430. * the WebRTC stack is ready, either with true if the device listing is
  431. * available available or with false otherwise.
  432. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  433. */
  434. isDeviceListAvailable() {
  435. logger.warn('This method is deprecated, use '
  436. + 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  437. return this.mediaDevices.isDeviceListAvailable();
  438. },
  439. /**
  440. * Returns true if changing the input (camera / microphone) or output
  441. * (audio) device is supported and false if not.
  442. *
  443. * @param {string} [deviceType] - type of device to change. Default is
  444. * {@code undefined} or 'input', 'output' - for audio output device change.
  445. * @returns {boolean} {@code true} if available; {@code false}, otherwise.
  446. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  447. */
  448. isDeviceChangeAvailable(deviceType) {
  449. logger.warn('This method is deprecated, use '
  450. + 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  451. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  452. },
  453. /**
  454. * Checks if the current environment supports having multiple audio
  455. * input devices in use simultaneously.
  456. *
  457. * @returns {boolean} True if multiple audio input devices can be used.
  458. */
  459. isMultipleAudioInputSupported() {
  460. return this.mediaDevices.isMultipleAudioInputSupported();
  461. },
  462. /**
  463. * Checks if local tracks can collect stats and collection is enabled.
  464. *
  465. * @param {boolean} True if stats are being collected for local tracks.
  466. */
  467. isCollectingLocalStats() {
  468. return Statistics.audioLevelsEnabled && LocalStatsCollector.isLocalStatsSupported();
  469. },
  470. /**
  471. * Executes callback with list of media devices connected.
  472. *
  473. * @param {function} callback
  474. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  475. */
  476. enumerateDevices(callback) {
  477. logger.warn('This method is deprecated, use '
  478. + 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  479. this.mediaDevices.enumerateDevices(callback);
  480. },
  481. /**
  482. * Informs lib-jitsi-meet about the current network status.
  483. *
  484. * @param {object} state - The network info state.
  485. * @param {boolean} state.isOnline - {@code true} if the internet connectivity is online or {@code false}
  486. * otherwise.
  487. */
  488. setNetworkInfo({ isOnline }) {
  489. NetworkInfo.updateNetworkInfo({ isOnline });
  490. },
  491. /**
  492. * Represents a hub/namespace for utility functionality which may be of
  493. * interest to lib-jitsi-meet clients.
  494. */
  495. util: {
  496. ScriptUtil,
  497. browser
  498. }
  499. };