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

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