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

JitsiMeetJS.js 17KB

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