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.

functions.js 15KB

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