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

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