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

JitsiMeetJS.ts 18KB

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