You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiMeetJS.js 19KB

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