Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiMeetJS.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /* global __filename */
  2. import { createGetUserMediaEvent } from './service/statistics/AnalyticsEvents';
  3. import AuthUtil from './modules/util/AuthUtil';
  4. import * as ConnectionQualityEvents
  5. from './service/connectivity/ConnectionQualityEvents';
  6. import * as E2ePingEvents from './service/e2eping/E2ePingEvents';
  7. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  8. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  9. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  10. import JitsiConnection from './JitsiConnection';
  11. import * as JitsiConnectionErrors from './JitsiConnectionErrors';
  12. import * as JitsiConnectionEvents from './JitsiConnectionEvents';
  13. import JitsiMediaDevices from './JitsiMediaDevices';
  14. import * as JitsiMediaDevicesEvents from './JitsiMediaDevicesEvents';
  15. import JitsiTrackError from './JitsiTrackError';
  16. import * as JitsiTrackErrors from './JitsiTrackErrors';
  17. import * as JitsiTrackEvents from './JitsiTrackEvents';
  18. import * as JitsiTranscriptionStatus from './JitsiTranscriptionStatus';
  19. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  20. import Logger from 'jitsi-meet-logger';
  21. import * as MediaType from './service/RTC/MediaType';
  22. import Resolutions from './service/RTC/Resolutions';
  23. import { ParticipantConnectionStatus }
  24. from './modules/connectivity/ParticipantConnectionStatus';
  25. import RTC from './modules/RTC/RTC';
  26. import browser from './modules/browser';
  27. import ScriptUtil from './modules/util/ScriptUtil';
  28. import recordingConstants from './modules/recording/recordingConstants';
  29. import ProxyConnectionService
  30. from './modules/proxyconnection/ProxyConnectionService';
  31. import Statistics from './modules/statistics/statistics';
  32. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  33. const logger = Logger.getLogger(__filename);
  34. /**
  35. * The amount of time to wait until firing
  36. * {@link JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN} event.
  37. */
  38. const USER_MEDIA_PERMISSION_PROMPT_TIMEOUT = 1000;
  39. /**
  40. * Gets the next lowest desirable resolution to try for a camera. If the given
  41. * resolution is already the lowest acceptable resolution, returns {@code null}.
  42. *
  43. * @param resolution the current resolution
  44. * @return the next lowest resolution from the given one, or {@code null} if it
  45. * is already the lowest acceptable resolution.
  46. */
  47. function getLowerResolution(resolution) {
  48. if (!Resolutions[resolution]) {
  49. return null;
  50. }
  51. const order = Resolutions[resolution].order;
  52. let res = null;
  53. let resName = null;
  54. Object.keys(Resolutions).forEach(r => {
  55. const value = Resolutions[r];
  56. if (!res || (res.order < value.order && value.order < order)) {
  57. resName = r;
  58. res = value;
  59. }
  60. });
  61. if (resName === resolution) {
  62. resName = null;
  63. }
  64. return resName;
  65. }
  66. /**
  67. * Extracts from an 'options' objects with a specific format (TODO what IS the
  68. * format?) the attributes which are to be logged in analytics events.
  69. *
  70. * @param options gum options (???)
  71. * @returns {*} the attributes to attach to analytics events.
  72. */
  73. function getAnalyticsAttributesFromOptions(options) {
  74. const attributes = {
  75. 'audio_requested':
  76. options.devices.includes('audio'),
  77. 'video_requested':
  78. options.devices.includes('video'),
  79. 'screen_sharing_requested':
  80. options.devices.includes('desktop')
  81. };
  82. if (attributes.video_requested) {
  83. attributes.resolution = options.resolution;
  84. }
  85. return attributes;
  86. }
  87. /**
  88. * Tries to deal with the following problem: {@code JitsiMeetJS} is not only
  89. * this module, it's also a global (i.e. attached to {@code window}) namespace
  90. * for all globals of the projects in the Jitsi Meet family. If lib-jitsi-meet
  91. * is loaded through an HTML {@code script} tag, {@code JitsiMeetJS} will
  92. * automatically be attached to {@code window} by webpack. Unfortunately,
  93. * webpack's source code does not check whether the global variable has already
  94. * been assigned and overwrites it. Which is OK for the module
  95. * {@code JitsiMeetJS} but is not OK for the namespace {@code JitsiMeetJS}
  96. * because it may already contain the values of other projects in the Jitsi Meet
  97. * family. The solution offered here works around webpack by merging all
  98. * existing values of the namespace {@code JitsiMeetJS} into the module
  99. * {@code JitsiMeetJS}.
  100. *
  101. * @param {Object} module - The module {@code JitsiMeetJS} (which will be
  102. * exported and may be attached to {@code window} by webpack later on).
  103. * @private
  104. * @returns {Object} - A {@code JitsiMeetJS} module which contains all existing
  105. * value of the namespace {@code JitsiMeetJS} (if any).
  106. */
  107. function _mergeNamespaceAndModule(module) {
  108. return (
  109. typeof window.JitsiMeetJS === 'object'
  110. ? Object.assign({}, window.JitsiMeetJS, module)
  111. : module);
  112. }
  113. /**
  114. * The public API of the Jitsi Meet library (a.k.a. {@code JitsiMeetJS}).
  115. */
  116. export default _mergeNamespaceAndModule({
  117. version: '{#COMMIT_HASH#}',
  118. JitsiConnection,
  119. /**
  120. * {@code ProxyConnectionService} is used to connect a remote peer to a
  121. * local Jitsi participant without going through a Jitsi conference. It is
  122. * currently used for room integration development, specifically wireless
  123. * screensharing. Its API is experimental and will likely change; usage of
  124. * it is advised against.
  125. */
  126. ProxyConnectionService,
  127. constants: {
  128. participantConnectionStatus: ParticipantConnectionStatus,
  129. recording: recordingConstants,
  130. sipVideoGW: VideoSIPGWConstants,
  131. transcriptionStatus: JitsiTranscriptionStatus
  132. },
  133. events: {
  134. conference: JitsiConferenceEvents,
  135. connection: JitsiConnectionEvents,
  136. track: JitsiTrackEvents,
  137. mediaDevices: JitsiMediaDevicesEvents,
  138. connectionQuality: ConnectionQualityEvents,
  139. e2eping: E2ePingEvents
  140. },
  141. errors: {
  142. conference: JitsiConferenceErrors,
  143. connection: JitsiConnectionErrors,
  144. track: JitsiTrackErrors
  145. },
  146. errorTypes: {
  147. JitsiTrackError
  148. },
  149. logLevels: Logger.levels,
  150. mediaDevices: JitsiMediaDevices,
  151. analytics: Statistics.analytics,
  152. init(options = {}) {
  153. Statistics.init(options);
  154. // Initialize global window.connectionTimes
  155. // FIXME do not use 'window'
  156. if (!window.connectionTimes) {
  157. window.connectionTimes = {};
  158. }
  159. if (options.enableAnalyticsLogging !== true) {
  160. logger.warn('Analytics disabled, disposing.');
  161. this.analytics.dispose();
  162. }
  163. if (options.enableWindowOnErrorHandler) {
  164. GlobalOnErrorHandler.addHandler(
  165. this.getGlobalOnErrorHandler.bind(this));
  166. }
  167. // Log deployment-specific information, if available. Defined outside
  168. // the application by individual deployments
  169. const aprops = options.deploymentInfo;
  170. if (aprops && Object.keys(aprops).length > 0) {
  171. const logObject = {};
  172. for (const attr in aprops) {
  173. if (aprops.hasOwnProperty(attr)) {
  174. logObject[attr] = aprops[attr];
  175. }
  176. }
  177. logObject.id = 'deployment_info';
  178. Statistics.sendLog(JSON.stringify(logObject));
  179. }
  180. if (this.version) {
  181. const logObject = {
  182. id: 'component_version',
  183. component: 'lib-jitsi-meet',
  184. version: this.version
  185. };
  186. Statistics.sendLog(JSON.stringify(logObject));
  187. }
  188. return RTC.init(options);
  189. },
  190. /**
  191. * Returns whether the desktop sharing is enabled or not.
  192. *
  193. * @returns {boolean}
  194. */
  195. isDesktopSharingEnabled() {
  196. return RTC.isDesktopSharingEnabled();
  197. },
  198. /**
  199. * Returns whether the current execution environment supports WebRTC (for
  200. * use within this library).
  201. *
  202. * @returns {boolean} {@code true} if WebRTC is supported in the current
  203. * execution environment (for use within this library); {@code false},
  204. * otherwise.
  205. */
  206. isWebRtcSupported() {
  207. return RTC.isWebRtcSupported();
  208. },
  209. setLogLevel(level) {
  210. Logger.setLogLevel(level);
  211. },
  212. /**
  213. * Sets the log level to the <tt>Logger</tt> instance with given id.
  214. *
  215. * @param {Logger.levels} level the logging level to be set
  216. * @param {string} id the logger id to which new logging level will be set.
  217. * Usually it's the name of the JavaScript source file including the path
  218. * ex. "modules/xmpp/ChatRoom.js"
  219. */
  220. setLogLevelById(level, id) {
  221. Logger.setLogLevelById(level, id);
  222. },
  223. /**
  224. * Registers new global logger transport to the library logging framework.
  225. *
  226. * @param globalTransport
  227. * @see Logger.addGlobalTransport
  228. */
  229. addGlobalLogTransport(globalTransport) {
  230. Logger.addGlobalTransport(globalTransport);
  231. },
  232. /**
  233. * Removes global logging transport from the library logging framework.
  234. *
  235. * @param globalTransport
  236. * @see Logger.removeGlobalTransport
  237. */
  238. removeGlobalLogTransport(globalTransport) {
  239. Logger.removeGlobalTransport(globalTransport);
  240. },
  241. /**
  242. * Creates the media tracks and returns them trough the callback.
  243. *
  244. * @param options Object with properties / settings specifying the tracks
  245. * which should be created. should be created or some additional
  246. * configurations about resolution for example.
  247. * @param {Array} options.devices the devices that will be requested
  248. * @param {string} options.resolution resolution constraints
  249. * @param {string} options.cameraDeviceId
  250. * @param {string} options.micDeviceId
  251. * @param {object} options.desktopSharingExtensionExternalInstallation -
  252. * enables external installation process for desktop sharing extension if
  253. * the inline installation is not posible. The following properties should
  254. * be provided:
  255. * @param {intiger} interval - the interval (in ms) for
  256. * checking whether the desktop sharing extension is installed or not
  257. * @param {Function} checkAgain - returns boolean. While checkAgain()==true
  258. * createLocalTracks will wait and check on every "interval" ms for the
  259. * extension. If the desktop extension is not install and checkAgain()==true
  260. * createLocalTracks will finish with rejected Promise.
  261. * @param {Function} listener - The listener will be called to notify the
  262. * user of lib-jitsi-meet that createLocalTracks is starting external
  263. * extension installation process.
  264. * NOTE: If the inline installation process is not possible and external
  265. * installation is enabled the listener property will be called to notify
  266. * the start of external installation process. After that createLocalTracks
  267. * will start to check for the extension on every interval ms until the
  268. * plugin is installed or until checkAgain return false. If the extension
  269. * is found createLocalTracks will try to get the desktop sharing track and
  270. * will finish the execution. If checkAgain returns false, createLocalTracks
  271. * will finish the execution with rejected Promise.
  272. *
  273. * @param {boolean} (firePermissionPromptIsShownEvent) - if event
  274. * JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN should be fired
  275. * @param originalOptions - internal use only, to be able to store the
  276. * originally requested options.
  277. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise
  278. * that returns an array of created JitsiTracks if resolved, or a
  279. * JitsiConferenceError if rejected.
  280. */
  281. createLocalTracks(
  282. options = {}, firePermissionPromptIsShownEvent, originalOptions) {
  283. let promiseFulfilled = false;
  284. if (firePermissionPromptIsShownEvent === true) {
  285. window.setTimeout(() => {
  286. if (!promiseFulfilled) {
  287. JitsiMediaDevices.emitEvent(
  288. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  289. browser.getName());
  290. }
  291. }, USER_MEDIA_PERMISSION_PROMPT_TIMEOUT);
  292. }
  293. if (!window.connectionTimes) {
  294. window.connectionTimes = {};
  295. }
  296. window.connectionTimes['obtainPermissions.start']
  297. = window.performance.now();
  298. return RTC.obtainAudioAndVideoPermissions(options)
  299. .then(tracks => {
  300. promiseFulfilled = true;
  301. window.connectionTimes['obtainPermissions.end']
  302. = window.performance.now();
  303. Statistics.sendAnalytics(
  304. createGetUserMediaEvent(
  305. 'success',
  306. getAnalyticsAttributesFromOptions(options)));
  307. if (!RTC.options.disableAudioLevels) {
  308. for (let i = 0; i < tracks.length; i++) {
  309. const track = tracks[i];
  310. const mStream = track.getOriginalStream();
  311. if (track.getType() === MediaType.AUDIO) {
  312. Statistics.startLocalStats(mStream,
  313. track.setAudioLevel.bind(track));
  314. track.addEventListener(
  315. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  316. () => {
  317. Statistics.stopLocalStats(mStream);
  318. });
  319. }
  320. }
  321. }
  322. // set real device ids
  323. const currentlyAvailableMediaDevices
  324. = RTC.getCurrentlyAvailableMediaDevices();
  325. if (currentlyAvailableMediaDevices) {
  326. for (let i = 0; i < tracks.length; i++) {
  327. const track = tracks[i];
  328. track._setRealDeviceIdFromDeviceList(
  329. currentlyAvailableMediaDevices);
  330. }
  331. }
  332. return tracks;
  333. })
  334. .catch(error => {
  335. promiseFulfilled = true;
  336. if (error.name === JitsiTrackErrors.UNSUPPORTED_RESOLUTION
  337. && !browser.usesNewGumFlow()) {
  338. const oldResolution = options.resolution || '720';
  339. const newResolution = getLowerResolution(oldResolution);
  340. if (newResolution !== null) {
  341. options.resolution = newResolution;
  342. logger.debug(
  343. 'Retry createLocalTracks with resolution',
  344. newResolution);
  345. Statistics.sendAnalytics(createGetUserMediaEvent(
  346. 'warning',
  347. {
  348. 'old_resolution': oldResolution,
  349. 'new_resolution': newResolution,
  350. reason: 'unsupported resolution'
  351. }));
  352. return this.createLocalTracks(
  353. options,
  354. undefined,
  355. originalOptions || Object.assign({}, options));
  356. }
  357. // We tried everything. If there is a mandatory device id,
  358. // remove it and let gum find a device to use.
  359. if (originalOptions
  360. && error.gum.constraints
  361. && error.gum.constraints.video
  362. && error.gum.constraints.video.mandatory
  363. && error.gum.constraints.video.mandatory.sourceId) {
  364. originalOptions.cameraDeviceId = undefined;
  365. return this.createLocalTracks(originalOptions);
  366. }
  367. }
  368. if (error.name
  369. === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  370. // User cancelled action is not really an error, so only
  371. // log it as an event to avoid having conference classified
  372. // as partially failed
  373. const logObject = {
  374. id: 'chrome_extension_user_canceled',
  375. message: error.message
  376. };
  377. Statistics.sendLog(JSON.stringify(logObject));
  378. Statistics.sendAnalytics(
  379. createGetUserMediaEvent(
  380. 'warning',
  381. {
  382. reason: 'extension install user canceled'
  383. }));
  384. } else if (error.name === JitsiTrackErrors.NOT_FOUND) {
  385. // logs not found devices with just application log to cs
  386. const logObject = {
  387. id: 'usermedia_missing_device',
  388. status: error.gum.devices
  389. };
  390. Statistics.sendLog(JSON.stringify(logObject));
  391. const attributes
  392. = getAnalyticsAttributesFromOptions(options);
  393. attributes.reason = 'device not found';
  394. attributes.devices = error.gum.devices.join('.');
  395. Statistics.sendAnalytics(
  396. createGetUserMediaEvent('error', attributes));
  397. } else {
  398. // Report gUM failed to the stats
  399. Statistics.sendGetUserMediaFailed(error);
  400. const attributes
  401. = getAnalyticsAttributesFromOptions(options);
  402. attributes.reason = error.name;
  403. Statistics.sendAnalytics(
  404. createGetUserMediaEvent('error', attributes));
  405. }
  406. window.connectionTimes['obtainPermissions.end']
  407. = window.performance.now();
  408. return Promise.reject(error);
  409. });
  410. },
  411. /**
  412. * Checks if its possible to enumerate available cameras/microphones.
  413. *
  414. * @returns {Promise<boolean>} a Promise which will be resolved only once
  415. * the WebRTC stack is ready, either with true if the device listing is
  416. * available available or with false otherwise.
  417. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceListAvailable instead
  418. */
  419. isDeviceListAvailable() {
  420. logger.warn('This method is deprecated, use '
  421. + 'JitsiMeetJS.mediaDevices.isDeviceListAvailable instead');
  422. return this.mediaDevices.isDeviceListAvailable();
  423. },
  424. /**
  425. * Returns true if changing the input (camera / microphone) or output
  426. * (audio) device is supported and false if not.
  427. *
  428. * @param {string} [deviceType] - type of device to change. Default is
  429. * {@code undefined} or 'input', 'output' - for audio output device change.
  430. * @returns {boolean} {@code true} if available; {@code false}, otherwise.
  431. * @deprecated use JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead
  432. */
  433. isDeviceChangeAvailable(deviceType) {
  434. logger.warn('This method is deprecated, use '
  435. + 'JitsiMeetJS.mediaDevices.isDeviceChangeAvailable instead');
  436. return this.mediaDevices.isDeviceChangeAvailable(deviceType);
  437. },
  438. /**
  439. * Checks if the current environment supports having multiple audio
  440. * input devices in use simultaneously.
  441. *
  442. * @returns {boolean} True if multiple audio input devices can be used.
  443. */
  444. isMultipleAudioInputSupported() {
  445. return this.mediaDevices.isMultipleAudioInputSupported();
  446. },
  447. /**
  448. * Checks if local tracks can collect stats and collection is enabled.
  449. *
  450. * @param {boolean} True if stats are being collected for local tracks.
  451. */
  452. isCollectingLocalStats() {
  453. return Statistics.audioLevelsEnabled
  454. && LocalStatsCollector.isLocalStatsSupported();
  455. },
  456. /**
  457. * Executes callback with list of media devices connected.
  458. *
  459. * @param {function} callback
  460. * @deprecated use JitsiMeetJS.mediaDevices.enumerateDevices instead
  461. */
  462. enumerateDevices(callback) {
  463. logger.warn('This method is deprecated, use '
  464. + 'JitsiMeetJS.mediaDevices.enumerateDevices instead');
  465. this.mediaDevices.enumerateDevices(callback);
  466. },
  467. /* eslint-disable max-params */
  468. /**
  469. * @returns function that can be used to be attached to window.onerror and
  470. * if options.enableWindowOnErrorHandler is enabled returns
  471. * the function used by the lib.
  472. * (function(message, source, lineno, colno, error)).
  473. */
  474. getGlobalOnErrorHandler(message, source, lineno, colno, error) {
  475. logger.error(
  476. `UnhandledError: ${message}`,
  477. `Script: ${source}`,
  478. `Line: ${lineno}`,
  479. `Column: ${colno}`,
  480. 'StackTrace: ', error);
  481. Statistics.reportGlobalError(error);
  482. },
  483. /* eslint-enable max-params */
  484. /**
  485. * Represents a hub/namespace for utility functionality which may be of
  486. * interest to lib-jitsi-meet clients.
  487. */
  488. util: {
  489. AuthUtil,
  490. ScriptUtil,
  491. browser
  492. }
  493. });