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

JitsiMeetJS.ts 17KB

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