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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. Logger.setLogLevel(Logger.levels.INFO);
  131. // @ts-ignore
  132. logger.info(`This appears to be ${browser.getName()}, ver: ${browser.getVersion()}`);
  133. Settings.init(options.externalStorage);
  134. Statistics.init(options);
  135. // Initialize global window.connectionTimes
  136. // FIXME do not use 'window'
  137. if (!window.connectionTimes) {
  138. window.connectionTimes = {};
  139. }
  140. if (options.enableAnalyticsLogging !== true) {
  141. logger.warn('Analytics disabled, disposing.');
  142. this.analytics.dispose();
  143. }
  144. return RTC.init(options);
  145. },
  146. /**
  147. * Returns whether the desktop sharing is enabled or not.
  148. *
  149. * @returns {boolean}
  150. */
  151. isDesktopSharingEnabled() {
  152. return RTC.isDesktopSharingEnabled();
  153. },
  154. /**
  155. * Returns whether the current execution environment supports WebRTC (for
  156. * use within this library).
  157. *
  158. * @returns {boolean} {@code true} if WebRTC is supported in the current
  159. * execution environment (for use within this library); {@code false},
  160. * otherwise.
  161. */
  162. isWebRtcSupported() {
  163. return RTC.isWebRtcSupported();
  164. },
  165. setLogLevel(level) {
  166. Logger.setLogLevel(level);
  167. },
  168. /**
  169. * Expose rtcstats to the public API.
  170. */
  171. rtcstats: {
  172. /**
  173. * Sends identity data to the rtcstats server. This data is used
  174. * to identify the specifics of a particular client, it can be any object
  175. * and will show in the generated rtcstats dump under "identity" entries.
  176. *
  177. * @param {Object} identityData - Identity data to send.
  178. * @returns {void}
  179. */
  180. sendIdentityEntry(identityData) {
  181. RTCStats.sendIdentity(identityData);
  182. },
  183. /**
  184. * Sends a stats entry to rtcstats server.
  185. * @param {string} statsType - The type of stats to send.
  186. * @param {Object} data - The stats data to send.
  187. */
  188. sendStatsEntry(statsType, data) {
  189. RTCStats.sendStatsEntry(statsType, null, data);
  190. },
  191. /**
  192. * Events generated by rtcstats, such as PeerConnections state,
  193. * and websocket connection state.
  194. *
  195. * @param {RTCStatsEvents} event - The event name.
  196. * @param {function} handler - The event handler.
  197. */
  198. on(event, handler) {
  199. RTCStats.events.on(event, handler);
  200. }
  201. },
  202. /**
  203. * Sets the log level to the <tt>Logger</tt> instance with given id.
  204. *
  205. * @param {Logger.levels} level the logging level to be set
  206. * @param {string} id the logger id to which new logging level will be set.
  207. * Usually it's the name of the JavaScript source file including the path
  208. * ex. "modules/xmpp/ChatRoom.js"
  209. */
  210. setLogLevelById(level, id) {
  211. Logger.setLogLevelById(level, id);
  212. },
  213. /**
  214. * Registers new global logger transport to the library logging framework.
  215. *
  216. * @param globalTransport
  217. * @see Logger.addGlobalTransport
  218. */
  219. addGlobalLogTransport(globalTransport) {
  220. Logger.addGlobalTransport(globalTransport);
  221. },
  222. /**
  223. * Removes global logging transport from the library logging framework.
  224. *
  225. * @param globalTransport
  226. * @see Logger.removeGlobalTransport
  227. */
  228. removeGlobalLogTransport(globalTransport) {
  229. Logger.removeGlobalTransport(globalTransport);
  230. },
  231. /**
  232. * Sets global options which will be used by all loggers. Changing these
  233. * works even after other loggers are created.
  234. *
  235. * @param options
  236. * @see Logger.setGlobalOptions
  237. */
  238. setGlobalLogOptions(options) {
  239. Logger.setGlobalOptions(options);
  240. },
  241. /**
  242. * Creates local media tracks.
  243. *
  244. * @param options Object with properties / settings specifying the tracks
  245. * which should be created. should be created or some additional
  246. * configurations about resolution for example.
  247. * @param {Array} options.effects optional effects array for the track
  248. * @param {boolean} options.firePermissionPromptIsShownEvent - if event
  249. * JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN should be fired
  250. * @param {boolean} options.fireSlowPromiseEvent - if event
  251. * JitsiMediaDevicesEvents.USER_MEDIA_SLOW_PROMISE_TIMEOUT should be fired
  252. * @param {Array} options.devices the devices that will be requested
  253. * @param {string} options.resolution resolution constraints
  254. * @param {string} options.cameraDeviceId
  255. * @param {string} options.micDeviceId
  256. *
  257. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise
  258. * that returns an array of created JitsiTracks if resolved, or a
  259. * JitsiConferenceError if rejected.
  260. */
  261. createLocalTracks(options: ICreateLocalTrackOptions = {}) {
  262. let promiseFulfilled = false;
  263. const { firePermissionPromptIsShownEvent, fireSlowPromiseEvent, ...restOptions } = options;
  264. if (firePermissionPromptIsShownEvent && !RTC.arePermissionsGrantedForAvailableDevices()) {
  265. // @ts-ignore
  266. JitsiMediaDevices.emit(JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN, browser.getName());
  267. } else if (fireSlowPromiseEvent) {
  268. window.setTimeout(() => {
  269. if (!promiseFulfilled) {
  270. JitsiMediaDevices.emit(JitsiMediaDevicesEvents.SLOW_GET_USER_MEDIA);
  271. }
  272. }, USER_MEDIA_SLOW_PROMISE_TIMEOUT);
  273. }
  274. let isFirstGUM = false;
  275. let startTS = window.performance.now();
  276. if (!window.connectionTimes) {
  277. window.connectionTimes = {};
  278. }
  279. if (!hasGUMExecuted) {
  280. hasGUMExecuted = true;
  281. isFirstGUM = true;
  282. window.connectionTimes['firstObtainPermissions.start'] = startTS;
  283. }
  284. window.connectionTimes['obtainPermissions.start'] = startTS;
  285. return RTC.obtainAudioAndVideoPermissions(restOptions)
  286. .then(tracks => {
  287. promiseFulfilled = true;
  288. let endTS = window.performance.now();
  289. window.connectionTimes['obtainPermissions.end'] = endTS;
  290. if (isFirstGUM) {
  291. window.connectionTimes['firstObtainPermissions.end'] = endTS;
  292. }
  293. Statistics.sendAnalytics(
  294. createGetUserMediaEvent(
  295. 'success',
  296. getAnalyticsAttributesFromOptions(restOptions)));
  297. if (this.isCollectingLocalStats()) {
  298. for (let i = 0; i < tracks.length; i++) {
  299. const track = tracks[i];
  300. if (track.getType() === MediaType.AUDIO) {
  301. Statistics.startLocalStats(track,
  302. track.setAudioLevel.bind(track));
  303. }
  304. }
  305. }
  306. // set real device ids
  307. const currentlyAvailableMediaDevices
  308. = RTC.getCurrentlyAvailableMediaDevices();
  309. if (currentlyAvailableMediaDevices) {
  310. for (let i = 0; i < tracks.length; i++) {
  311. const track = tracks[i];
  312. track._setRealDeviceIdFromDeviceList(
  313. currentlyAvailableMediaDevices);
  314. }
  315. }
  316. return tracks;
  317. })
  318. .catch(error => {
  319. promiseFulfilled = true;
  320. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  321. Statistics.sendAnalytics(
  322. createGetUserMediaEvent(
  323. 'warning',
  324. {
  325. reason: 'extension install user canceled'
  326. }));
  327. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  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. const attributes
  336. = getAnalyticsAttributesFromOptions(options);
  337. attributes.reason = error.name;
  338. Statistics.sendAnalytics(
  339. createGetUserMediaEvent('error', attributes));
  340. }
  341. let endTS = window.performance.now();
  342. window.connectionTimes['obtainPermissions.end'] = endTS;
  343. if (isFirstGUM) {
  344. window.connectionTimes['firstObtainPermissions.end'] = endTS;
  345. }
  346. return Promise.reject(error);
  347. });
  348. },
  349. /**
  350. * Manually create JitsiLocalTrack's from the provided track info, by exposing the RTC method
  351. *
  352. * @param {Array<ICreateLocalTrackFromMediaStreamOptions>} tracksInfo - array of track information
  353. * @returns {Array<JitsiLocalTrack>} - created local tracks
  354. */
  355. createLocalTracksFromMediaStreams(tracksInfo) {
  356. return RTC.createLocalTracks(tracksInfo.map((trackInfo) => {
  357. const tracks = trackInfo.stream.getTracks()
  358. .filter(track => track.kind === trackInfo.mediaType);
  359. if (!tracks || tracks.length === 0) {
  360. throw new JitsiTrackError(JitsiTrackErrors.TRACK_NO_STREAM_TRACKS_FOUND, null, null);
  361. }
  362. if (tracks.length > 1) {
  363. throw new JitsiTrackError(JitsiTrackErrors.TRACK_TOO_MANY_TRACKS_IN_STREAM, null, null);
  364. }
  365. trackInfo.track = tracks[0];
  366. return trackInfo;
  367. }));
  368. },
  369. /**
  370. * Create a TrackVADEmitter service that connects an audio track to an VAD (voice activity detection) processor in
  371. * order to obtain VAD scores for individual PCM audio samples.
  372. * @param {string} localAudioDeviceId - The target local audio device.
  373. * @param {number} sampleRate - Sample rate at which the emitter will operate. Possible values 256, 512, 1024,
  374. * 4096, 8192, 16384. Passing other values will default to closes neighbor.
  375. * I.e. Providing a value of 4096 means that the emitter will process 4096 PCM samples at a time, higher values mean
  376. * longer calls, lowers values mean more calls but shorter.
  377. * @param {Object} vadProcessor - VAD Processors that does the actual compute on a PCM sample.The processor needs
  378. * to implement the following functions:
  379. * - <tt>getSampleLength()</tt> - Returns the sample size accepted by calculateAudioFrameVAD.
  380. * - <tt>getRequiredPCMFrequency()</tt> - Returns the PCM frequency at which the processor operates.
  381. * i.e. (16KHz, 44.1 KHz etc.)
  382. * - <tt>calculateAudioFrameVAD(pcmSample)</tt> - Process a 32 float pcm sample of getSampleLength size.
  383. * @returns {Promise<TrackVADEmitter>}
  384. */
  385. createTrackVADEmitter(localAudioDeviceId, sampleRate, vadProcessor) {
  386. return TrackVADEmitter.create(localAudioDeviceId, sampleRate, vadProcessor);
  387. },
  388. /**
  389. * Create AudioMixer, which is essentially a wrapper over web audio ChannelMergerNode. It essentially allows the
  390. * user to mix multiple MediaStreams into a single one.
  391. *
  392. * @returns {AudioMixer}
  393. */
  394. createAudioMixer() {
  395. return new AudioMixer();
  396. },
  397. /**
  398. * Go through all audio devices on the system and return one that is active, i.e. has audio signal.
  399. *
  400. * @returns Promise<Object> - Object containing information about the found device.
  401. */
  402. getActiveAudioDevice() {
  403. return getActiveAudioDevice();
  404. },
  405. /**
  406. * Checks if its possible to enumerate available cameras/microphones.
  407. *
  408. * @returns {Promise<boolean>} a Promise which will be resolved only once
  409. * the WebRTC stack is ready, either with true if the device listing is
  410. * available available or with false otherwise.
  411. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  412. */
  413. isDeviceListAvailable() {
  414. logger.warn('This method is deprecated, use '
  415. + 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  416. return this.mediaDevices.isDeviceListAvailable();
  417. },
  418. /**
  419. * Returns true if changing the input (camera / microphone) or output
  420. * (audio) device is supported and false if not.
  421. *
  422. * @param {string} [deviceType] - type of device to change. Default is
  423. * {@code undefined} or 'input', 'output' - for audio output device change.
  424. * @returns {boolean} {@code true} if available; {@code false}, otherwise.
  425. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  426. */
  427. isDeviceChangeAvailable(deviceType) {
  428. logger.warn('This method is deprecated, use '
  429. + 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  430. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  431. },
  432. /**
  433. * Checks if the current environment supports having multiple audio
  434. * input devices in use simultaneously.
  435. *
  436. * @returns {boolean} True if multiple audio input devices can be used.
  437. */
  438. isMultipleAudioInputSupported() {
  439. return this.mediaDevices.isMultipleAudioInputSupported();
  440. },
  441. /**
  442. * Checks if local tracks can collect stats and collection is enabled.
  443. *
  444. * @param {boolean} True if stats are being collected for local tracks.
  445. */
  446. isCollectingLocalStats() {
  447. return Statistics.audioLevelsEnabled && LocalStatsCollector.isLocalStatsSupported();
  448. },
  449. /**
  450. * Executes callback with list of media devices connected.
  451. *
  452. * @param {function} callback
  453. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  454. */
  455. enumerateDevices(callback) {
  456. logger.warn('This method is deprecated, use '
  457. + 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  458. this.mediaDevices.enumerateDevices(callback);
  459. },
  460. /**
  461. * Informs lib-jitsi-meet about the current network status.
  462. *
  463. * @param {object} state - The network info state.
  464. * @param {boolean} state.isOnline - {@code true} if the internet connectivity is online or {@code false}
  465. * otherwise.
  466. */
  467. setNetworkInfo({ isOnline }) {
  468. NetworkInfo.updateNetworkInfo({ isOnline });
  469. },
  470. /**
  471. * Represents a hub/namespace for utility functionality which may be of
  472. * interest to lib-jitsi-meet clients.
  473. */
  474. util: {
  475. ScriptUtil,
  476. browser
  477. }
  478. };