Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiMeetJS.ts 17KB

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