您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiMeetJS.ts 18KB

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