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.

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