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 17KB

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