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

JitsiMeetJS.ts 17KB

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