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

functions.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /* global APP */
  2. import JitsiMeetJS, { JitsiTrackErrors, browser } from '../lib-jitsi-meet';
  3. import { MEDIA_TYPE, VIDEO_TYPE, setAudioMuted } from '../media';
  4. import {
  5. getUserSelectedCameraDeviceId,
  6. getUserSelectedMicDeviceId
  7. } from '../settings';
  8. import loadEffects from './loadEffects';
  9. import logger from './logger';
  10. /**
  11. * Creates a local video track for presenter. The constraints are computed based
  12. * on the height of the desktop that is being shared.
  13. *
  14. * @param {Object} options - The options with which the local presenter track
  15. * is to be created.
  16. * @param {string|null} [options.cameraDeviceId] - Camera device id or
  17. * {@code undefined} to use app's settings.
  18. * @param {number} desktopHeight - The height of the desktop that is being
  19. * shared.
  20. * @returns {Promise<JitsiLocalTrack>}
  21. */
  22. export async function createLocalPresenterTrack(options, desktopHeight) {
  23. const { cameraDeviceId } = options;
  24. // compute the constraints of the camera track based on the resolution
  25. // of the desktop screen that is being shared.
  26. const cameraHeights = [ 180, 270, 360, 540, 720 ];
  27. const proportion = 5;
  28. const result = cameraHeights.find(
  29. height => (desktopHeight / proportion) < height);
  30. const constraints = {
  31. video: {
  32. aspectRatio: 4 / 3,
  33. height: {
  34. ideal: result
  35. }
  36. }
  37. };
  38. const [ videoTrack ] = await JitsiMeetJS.createLocalTracks(
  39. {
  40. cameraDeviceId,
  41. constraints,
  42. devices: [ 'video' ]
  43. });
  44. videoTrack.type = MEDIA_TYPE.PRESENTER;
  45. return videoTrack;
  46. }
  47. /**
  48. * Create local tracks of specific types.
  49. *
  50. * @param {Object} options - The options with which the local tracks are to be
  51. * created.
  52. * @param {string|null} [options.cameraDeviceId] - Camera device id or
  53. * {@code undefined} to use app's settings.
  54. * @param {string[]} options.devices - Required track types such as 'audio'
  55. * and/or 'video'.
  56. * @param {string|null} [options.micDeviceId] - Microphone device id or
  57. * {@code undefined} to use app's settings.
  58. * @param {number|undefined} [oprions.timeout] - A timeout for JitsiMeetJS.createLocalTracks used to create the tracks.
  59. * @param {boolean} [firePermissionPromptIsShownEvent] - Whether lib-jitsi-meet
  60. * should check for a {@code getUserMedia} permission prompt and fire a
  61. * corresponding event.
  62. * @param {Object} store - The redux store in the context of which the function
  63. * is to execute and from which state such as {@code config} is to be retrieved.
  64. * @returns {Promise<JitsiLocalTrack[]>}
  65. */
  66. export function createLocalTracksF(options = {}, firePermissionPromptIsShownEvent, store) {
  67. let { cameraDeviceId, micDeviceId } = options;
  68. const { desktopSharingSourceDevice, desktopSharingSources, timeout } = options;
  69. if (typeof APP !== 'undefined') {
  70. // TODO The app's settings should go in the redux store and then the
  71. // reliance on the global variable APP will go away.
  72. store || (store = APP.store); // eslint-disable-line no-param-reassign
  73. const state = store.getState();
  74. if (typeof cameraDeviceId === 'undefined' || cameraDeviceId === null) {
  75. cameraDeviceId = getUserSelectedCameraDeviceId(state);
  76. }
  77. if (typeof micDeviceId === 'undefined' || micDeviceId === null) {
  78. micDeviceId = getUserSelectedMicDeviceId(state);
  79. }
  80. }
  81. const state = store.getState();
  82. const {
  83. desktopSharingFrameRate,
  84. firefox_fake_device, // eslint-disable-line camelcase
  85. resolution
  86. } = state['features/base/config'];
  87. const constraints = options.constraints ?? state['features/base/config'].constraints;
  88. return (
  89. loadEffects(store).then(effectsArray => {
  90. // Filter any undefined values returned by Promise.resolve().
  91. const effects = effectsArray.filter(effect => Boolean(effect));
  92. return JitsiMeetJS.createLocalTracks(
  93. {
  94. cameraDeviceId,
  95. constraints,
  96. desktopSharingFrameRate,
  97. desktopSharingSourceDevice,
  98. desktopSharingSources,
  99. // Copy array to avoid mutations inside library.
  100. devices: options.devices.slice(0),
  101. effects,
  102. firefox_fake_device, // eslint-disable-line camelcase
  103. micDeviceId,
  104. resolution,
  105. timeout
  106. },
  107. firePermissionPromptIsShownEvent)
  108. .catch(err => {
  109. logger.error('Failed to create local tracks', options.devices, err);
  110. return Promise.reject(err);
  111. });
  112. }));
  113. }
  114. /**
  115. * Returns an object containing a promise which resolves with the created tracks &
  116. * the errors resulting from that process.
  117. *
  118. * @returns {Promise<JitsiLocalTrack>}
  119. *
  120. * @todo Refactor to not use APP
  121. */
  122. export function createPrejoinTracks() {
  123. const errors = {};
  124. const initialDevices = [ 'audio' ];
  125. const requestedAudio = true;
  126. let requestedVideo = false;
  127. const { startAudioOnly, startWithAudioMuted, startWithVideoMuted } = APP.store.getState()['features/base/settings'];
  128. // Always get a handle on the audio input device so that we have statistics even if the user joins the
  129. // conference muted. Previous implementation would only acquire the handle when the user first unmuted,
  130. // which would results in statistics ( such as "No audio input" or "Are you trying to speak?") being available
  131. // only after that point.
  132. if (startWithAudioMuted) {
  133. APP.store.dispatch(setAudioMuted(true));
  134. }
  135. if (!startWithVideoMuted && !startAudioOnly) {
  136. initialDevices.push('video');
  137. requestedVideo = true;
  138. }
  139. let tryCreateLocalTracks;
  140. if (!requestedAudio && !requestedVideo) {
  141. // Resolve with no tracks
  142. tryCreateLocalTracks = Promise.resolve([]);
  143. } else {
  144. tryCreateLocalTracks = createLocalTracksF({ devices: initialDevices }, true)
  145. .catch(err => {
  146. if (requestedAudio && requestedVideo) {
  147. // Try audio only...
  148. errors.audioAndVideoError = err;
  149. return (
  150. createLocalTracksF({ devices: [ 'audio' ] }, true));
  151. } else if (requestedAudio && !requestedVideo) {
  152. errors.audioOnlyError = err;
  153. return [];
  154. } else if (requestedVideo && !requestedAudio) {
  155. errors.videoOnlyError = err;
  156. return [];
  157. }
  158. logger.error('Should never happen');
  159. })
  160. .catch(err => {
  161. // Log this just in case...
  162. if (!requestedAudio) {
  163. logger.error('The impossible just happened', err);
  164. }
  165. errors.audioOnlyError = err;
  166. // Try video only...
  167. return requestedVideo
  168. ? createLocalTracksF({ devices: [ 'video' ] }, true)
  169. : [];
  170. })
  171. .catch(err => {
  172. // Log this just in case...
  173. if (!requestedVideo) {
  174. logger.error('The impossible just happened', err);
  175. }
  176. errors.videoOnlyError = err;
  177. return [];
  178. });
  179. }
  180. return {
  181. tryCreateLocalTracks,
  182. errors
  183. };
  184. }
  185. /**
  186. * Returns local audio track.
  187. *
  188. * @param {Track[]} tracks - List of all tracks.
  189. * @returns {(Track|undefined)}
  190. */
  191. export function getLocalAudioTrack(tracks) {
  192. return getLocalTrack(tracks, MEDIA_TYPE.AUDIO);
  193. }
  194. /**
  195. * Returns local track by media type.
  196. *
  197. * @param {Track[]} tracks - List of all tracks.
  198. * @param {MEDIA_TYPE} mediaType - Media type.
  199. * @param {boolean} [includePending] - Indicates whether a local track is to be
  200. * returned if it is still pending. A local track is pending if
  201. * {@code getUserMedia} is still executing to create it and, consequently, its
  202. * {@code jitsiTrack} property is {@code undefined}. By default a pending local
  203. * track is not returned.
  204. * @returns {(Track|undefined)}
  205. */
  206. export function getLocalTrack(tracks, mediaType, includePending = false) {
  207. return (
  208. getLocalTracks(tracks, includePending)
  209. .find(t => t.mediaType === mediaType));
  210. }
  211. /**
  212. * Returns an array containing the local tracks with or without a (valid)
  213. * {@code JitsiTrack}.
  214. *
  215. * @param {Track[]} tracks - An array containing all local tracks.
  216. * @param {boolean} [includePending] - Indicates whether a local track is to be
  217. * returned if it is still pending. A local track is pending if
  218. * {@code getUserMedia} is still executing to create it and, consequently, its
  219. * {@code jitsiTrack} property is {@code undefined}. By default a pending local
  220. * track is not returned.
  221. * @returns {Track[]}
  222. */
  223. export function getLocalTracks(tracks, includePending = false) {
  224. // XXX A local track is considered ready only once it has its `jitsiTrack`
  225. // property set by the `TRACK_ADDED` action. Until then there is a stub
  226. // added just before the `getUserMedia` call with a cancellable
  227. // `gumInProgress` property which then can be used to destroy the track that
  228. // has not yet been added to the redux store. Once GUM is cancelled, it will
  229. // never make it to the store nor there will be any
  230. // `TRACK_ADDED`/`TRACK_REMOVED` actions dispatched for it.
  231. return tracks.filter(t => t.local && (t.jitsiTrack || includePending));
  232. }
  233. /**
  234. * Returns local video track.
  235. *
  236. * @param {Track[]} tracks - List of all tracks.
  237. * @returns {(Track|undefined)}
  238. */
  239. export function getLocalVideoTrack(tracks) {
  240. return getLocalTrack(tracks, MEDIA_TYPE.VIDEO);
  241. }
  242. /**
  243. * Returns the media type of the local video, presenter or video.
  244. *
  245. * @param {Track[]} tracks - List of all tracks.
  246. * @returns {MEDIA_TYPE}
  247. */
  248. export function getLocalVideoType(tracks) {
  249. const presenterTrack = getLocalTrack(tracks, MEDIA_TYPE.PRESENTER);
  250. return presenterTrack ? MEDIA_TYPE.PRESENTER : MEDIA_TYPE.VIDEO;
  251. }
  252. /**
  253. * Returns the stored local video track.
  254. *
  255. * @param {Object} state - The redux state.
  256. * @returns {Object}
  257. */
  258. export function getLocalJitsiVideoTrack(state) {
  259. const track = getLocalVideoTrack(state['features/base/tracks']);
  260. return track?.jitsiTrack;
  261. }
  262. /**
  263. * Returns the stored local audio track.
  264. *
  265. * @param {Object} state - The redux state.
  266. * @returns {Object}
  267. */
  268. export function getLocalJitsiAudioTrack(state) {
  269. const track = getLocalAudioTrack(state['features/base/tracks']);
  270. return track?.jitsiTrack;
  271. }
  272. /**
  273. * Returns track of specified media type for specified participant id.
  274. *
  275. * @param {Track[]} tracks - List of all tracks.
  276. * @param {MEDIA_TYPE} mediaType - Media type.
  277. * @param {string} participantId - Participant ID.
  278. * @returns {(Track|undefined)}
  279. */
  280. export function getTrackByMediaTypeAndParticipant(
  281. tracks,
  282. mediaType,
  283. participantId) {
  284. return tracks.find(
  285. t => t.participantId === participantId && t.mediaType === mediaType
  286. );
  287. }
  288. /**
  289. * Returns the track if any which corresponds to a specific instance
  290. * of JitsiLocalTrack or JitsiRemoteTrack.
  291. *
  292. * @param {Track[]} tracks - List of all tracks.
  293. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} jitsiTrack - JitsiTrack instance.
  294. * @returns {(Track|undefined)}
  295. */
  296. export function getTrackByJitsiTrack(tracks, jitsiTrack) {
  297. return tracks.find(t => t.jitsiTrack === jitsiTrack);
  298. }
  299. /**
  300. * Returns tracks of specified media type.
  301. *
  302. * @param {Track[]} tracks - List of all tracks.
  303. * @param {MEDIA_TYPE} mediaType - Media type.
  304. * @returns {Track[]}
  305. */
  306. export function getTracksByMediaType(tracks, mediaType) {
  307. return tracks.filter(t => t.mediaType === mediaType);
  308. }
  309. /**
  310. * Checks if the local video camera track in the given set of tracks is muted.
  311. *
  312. * @param {Track[]} tracks - List of all tracks.
  313. * @returns {Track[]}
  314. */
  315. export function isLocalCameraTrackMuted(tracks) {
  316. const presenterTrack = getLocalTrack(tracks, MEDIA_TYPE.PRESENTER);
  317. const videoTrack = getLocalTrack(tracks, MEDIA_TYPE.VIDEO);
  318. // Make sure we check the mute status of only camera tracks, i.e.,
  319. // presenter track when it exists, camera track when the presenter
  320. // track doesn't exist.
  321. if (presenterTrack) {
  322. return isLocalTrackMuted(tracks, MEDIA_TYPE.PRESENTER);
  323. } else if (videoTrack) {
  324. return videoTrack.videoType === 'camera'
  325. ? isLocalTrackMuted(tracks, MEDIA_TYPE.VIDEO) : true;
  326. }
  327. return true;
  328. }
  329. /**
  330. * Checks if the first local track in the given tracks set is muted.
  331. *
  332. * @param {Track[]} tracks - List of all tracks.
  333. * @param {MEDIA_TYPE} mediaType - The media type of tracks to be checked.
  334. * @returns {boolean} True if local track is muted or false if the track is
  335. * unmuted or if there are no local tracks of the given media type in the given
  336. * set of tracks.
  337. */
  338. export function isLocalTrackMuted(tracks, mediaType) {
  339. const track = getLocalTrack(tracks, mediaType);
  340. return !track || track.muted;
  341. }
  342. /**
  343. * Checks if the local video track is of type DESKtOP.
  344. *
  345. * @param {Object} state - The redux state.
  346. * @returns {boolean}
  347. */
  348. export function isLocalVideoTrackDesktop(state) {
  349. const videoTrack = getLocalVideoTrack(state['features/base/tracks']);
  350. return videoTrack && videoTrack.videoType === VIDEO_TYPE.DESKTOP;
  351. }
  352. /**
  353. * Returns true if the remote track of the given media type and the given
  354. * participant is muted, false otherwise.
  355. *
  356. * @param {Track[]} tracks - List of all tracks.
  357. * @param {MEDIA_TYPE} mediaType - The media type of tracks to be checked.
  358. * @param {*} participantId - Participant ID.
  359. * @returns {boolean}
  360. */
  361. export function isRemoteTrackMuted(tracks, mediaType, participantId) {
  362. const track = getTrackByMediaTypeAndParticipant(
  363. tracks, mediaType, participantId);
  364. return !track || track.muted;
  365. }
  366. /**
  367. * Returns whether or not the current environment needs a user interaction with
  368. * the page before any unmute can occur.
  369. *
  370. * @param {Object} state - The redux state.
  371. * @returns {boolean}
  372. */
  373. export function isUserInteractionRequiredForUnmute(state) {
  374. return browser.isUserInteractionRequiredForUnmute()
  375. && window
  376. && window.self !== window.top
  377. && !state['features/base/user-interaction'].interacted;
  378. }
  379. /**
  380. * Mutes or unmutes a specific {@code JitsiLocalTrack}. If the muted state of
  381. * the specified {@code track} is already in accord with the specified
  382. * {@code muted} value, then does nothing.
  383. *
  384. * @param {JitsiLocalTrack} track - The {@code JitsiLocalTrack} to mute or
  385. * unmute.
  386. * @param {boolean} muted - If the specified {@code track} is to be muted, then
  387. * {@code true}; otherwise, {@code false}.
  388. * @returns {Promise}
  389. */
  390. export function setTrackMuted(track, muted) {
  391. muted = Boolean(muted); // eslint-disable-line no-param-reassign
  392. if (track.isMuted() === muted) {
  393. return Promise.resolve();
  394. }
  395. const f = muted ? 'mute' : 'unmute';
  396. return track[f]().catch(error => {
  397. // Track might be already disposed so ignore such an error.
  398. if (error.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  399. // FIXME Emit mute failed, so that the app can show error dialog.
  400. logger.error(`set track ${f} failed`, error);
  401. }
  402. });
  403. }