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

JitsiMeetJS.js 21KB

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