Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

actions.any.ts 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. import { createTrackMutedEvent } from '../../analytics/AnalyticsEvents';
  2. import { sendAnalytics } from '../../analytics/functions';
  3. import { IStore } from '../../app/types';
  4. import { showErrorNotification, showNotification } from '../../notifications/actions';
  5. import { NOTIFICATION_TIMEOUT, NOTIFICATION_TIMEOUT_TYPE } from '../../notifications/constants';
  6. import { getCurrentConference } from '../conference/functions';
  7. import { IJitsiConference } from '../conference/reducer';
  8. import { getMultipleVideoSendingSupportFeatureFlag, getMultipleVideoSupportFeatureFlag } from '../config/functions.any';
  9. import { JitsiTrackErrors, JitsiTrackEvents } from '../lib-jitsi-meet';
  10. import { createLocalTrack } from '../lib-jitsi-meet/functions.any';
  11. import { setAudioMuted, setScreenshareMuted, setVideoMuted } from '../media/actions';
  12. import {
  13. CAMERA_FACING_MODE,
  14. MEDIA_TYPE,
  15. MediaType,
  16. VIDEO_MUTISM_AUTHORITY,
  17. VIDEO_TYPE,
  18. VideoType
  19. } from '../media/constants';
  20. import { getLocalParticipant } from '../participants/functions';
  21. import { updateSettings } from '../settings/actions';
  22. import {
  23. SET_NO_SRC_DATA_NOTIFICATION_UID,
  24. TRACK_ADDED,
  25. TRACK_CREATE_CANCELED,
  26. TRACK_CREATE_ERROR,
  27. TRACK_MUTE_UNMUTE_FAILED,
  28. TRACK_NO_DATA_FROM_SOURCE,
  29. TRACK_REMOVED,
  30. TRACK_STOPPED,
  31. TRACK_UPDATED,
  32. TRACK_UPDATE_LAST_VIDEO_MEDIA_EVENT,
  33. TRACK_WILL_CREATE
  34. } from './actionTypes';
  35. import {
  36. createLocalTracksF,
  37. getLocalTrack,
  38. getLocalTracks,
  39. getLocalVideoTrack,
  40. getTrackByJitsiTrack
  41. } from './functions';
  42. import logger from './logger';
  43. import { ITrackOptions } from './types';
  44. /**
  45. * Add a given local track to the conference.
  46. *
  47. * @param {JitsiLocalTrack} newTrack - The local track to be added to the conference.
  48. * @returns {Function}
  49. */
  50. export function addLocalTrack(newTrack: any) {
  51. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  52. const conference = getCurrentConference(getState());
  53. if (conference) {
  54. await conference.addTrack(newTrack);
  55. }
  56. const setMuted = newTrack.isVideoTrack()
  57. ? getMultipleVideoSendingSupportFeatureFlag(getState())
  58. && newTrack.getVideoType() === VIDEO_TYPE.DESKTOP
  59. ? setScreenshareMuted
  60. : setVideoMuted
  61. : setAudioMuted;
  62. const isMuted = newTrack.isMuted();
  63. logger.log(`Adding ${newTrack.getType()} track - ${isMuted ? 'muted' : 'unmuted'}`);
  64. await dispatch(setMuted(isMuted));
  65. return dispatch(_addTracks([ newTrack ]));
  66. };
  67. }
  68. /**
  69. * Requests the creating of the desired media type tracks. Desire is expressed
  70. * by base/media unless the function caller specifies desired media types
  71. * explicitly and thus override base/media. Dispatches a
  72. * {@code createLocalTracksA} action for the desired media types for which there
  73. * are no existing tracks yet.
  74. *
  75. * @returns {Function}
  76. */
  77. export function createDesiredLocalTracks(...desiredTypes: any) {
  78. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  79. const state = getState();
  80. dispatch(destroyLocalDesktopTrackIfExists());
  81. if (desiredTypes.length === 0) {
  82. const { video } = state['features/base/media'];
  83. // XXX: Always create the audio track early, even if it will be muted.
  84. // This fixes a timing issue when adding the track to the conference which
  85. // manifests primarily on iOS 15.
  86. desiredTypes.push(MEDIA_TYPE.AUDIO);
  87. // XXX When the app is coming into the foreground from the
  88. // background in order to handle a URL, it may realize the new
  89. // background state soon after it has tried to create the local
  90. // tracks requested by the URL. Ignore
  91. // VIDEO_MUTISM_AUTHORITY.BACKGROUND and create the local video
  92. // track if no other VIDEO_MUTISM_AUTHORITY has muted it. The local
  93. // video track will be muted until the app realizes the new
  94. // background state.
  95. // eslint-disable-next-line no-bitwise
  96. (video.muted & ~VIDEO_MUTISM_AUTHORITY.BACKGROUND)
  97. || desiredTypes.push(MEDIA_TYPE.VIDEO);
  98. }
  99. const availableTypes
  100. = getLocalTracks(
  101. state['features/base/tracks'],
  102. /* includePending */ true)
  103. .map(t => t.mediaType);
  104. // We need to create the desired tracks which are not already available.
  105. const createTypes
  106. = desiredTypes.filter((type: MediaType) => availableTypes.indexOf(type) === -1);
  107. createTypes.length
  108. && dispatch(createLocalTracksA({ devices: createTypes }));
  109. };
  110. }
  111. /**
  112. * Request to start capturing local audio and/or video. By default, the user
  113. * facing camera will be selected.
  114. *
  115. * @param {Object} [options] - For info @see JitsiMeetJS.createLocalTracks.
  116. * @returns {Function}
  117. */
  118. export function createLocalTracksA(options: ITrackOptions = {}) {
  119. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  120. const devices
  121. = options.devices || [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ];
  122. const store = {
  123. dispatch,
  124. getState
  125. };
  126. // The following executes on React Native only at the time of this
  127. // writing. The effort to port Web's createInitialLocalTracksAndConnect
  128. // is significant and that's where the function createLocalTracksF got
  129. // born. I started with the idea a porting so that we could inherit the
  130. // ability to getUserMedia for audio only or video only if getUserMedia
  131. // for audio and video fails. Eventually though, I realized that on
  132. // mobile we do not have combined permission prompts implemented anyway
  133. // (either because there are no such prompts or it does not make sense
  134. // to implement them) and the right thing to do is to ask for each
  135. // device separately.
  136. for (const device of devices) {
  137. if (getLocalTrack(
  138. getState()['features/base/tracks'],
  139. device as MediaType,
  140. /* includePending */ true)) {
  141. throw new Error(`Local track for ${device} already exists`);
  142. }
  143. const gumProcess
  144. = createLocalTracksF(
  145. {
  146. cameraDeviceId: options.cameraDeviceId,
  147. devices: [ device ],
  148. facingMode:
  149. options.facingMode || CAMERA_FACING_MODE.USER,
  150. micDeviceId: options.micDeviceId
  151. },
  152. store)
  153. .then(
  154. (localTracks: any[]) => {
  155. // Because GUM is called for 1 device (which is actually
  156. // a media type 'audio', 'video', 'screen', etc.) we
  157. // should not get more than one JitsiTrack.
  158. if (localTracks.length !== 1) {
  159. throw new Error(
  160. `Expected exactly 1 track, but was given ${
  161. localTracks.length} tracks for device: ${
  162. device}.`);
  163. }
  164. if (gumProcess.canceled) {
  165. return _disposeTracks(localTracks)
  166. .then(() =>
  167. dispatch(_trackCreateCanceled(device as MediaType)));
  168. }
  169. return dispatch(trackAdded(localTracks[0]));
  170. },
  171. (reason: Error) =>
  172. dispatch(
  173. gumProcess.canceled
  174. ? _trackCreateCanceled(device as MediaType)
  175. : _onCreateLocalTracksRejected(
  176. reason,
  177. device)));
  178. /**
  179. * Cancels the {@code getUserMedia} process represented by this
  180. * {@code Promise}.
  181. *
  182. * @returns {Promise} This {@code Promise} i.e. {@code gumProcess}.
  183. */
  184. gumProcess.cancel = () => {
  185. gumProcess.canceled = true;
  186. return gumProcess;
  187. };
  188. dispatch({
  189. type: TRACK_WILL_CREATE,
  190. track: {
  191. gumProcess,
  192. local: true,
  193. mediaType: device
  194. }
  195. });
  196. }
  197. };
  198. }
  199. /**
  200. * Calls JitsiLocalTrack#dispose() on the given track or on all local tracks (if none are passed) ignoring errors if
  201. * track is already disposed. After that signals tracks to be removed.
  202. *
  203. * @param {JitsiLocalTrack|null} [track] - The local track that needs to be destroyed.
  204. * @returns {Function}
  205. */
  206. export function destroyLocalTracks(track: any = null) {
  207. if (track) {
  208. return (dispatch: IStore['dispatch']) => {
  209. dispatch(_disposeAndRemoveTracks([ track ]));
  210. };
  211. }
  212. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  213. // First wait until any getUserMedia in progress is settled and then get
  214. // rid of all local tracks.
  215. _cancelGUMProcesses(getState)
  216. .then(() =>
  217. dispatch(
  218. _disposeAndRemoveTracks(
  219. getState()['features/base/tracks']
  220. .filter(t => t.local)
  221. .map(t => t.jitsiTrack))));
  222. };
  223. }
  224. /**
  225. * Signals that the passed JitsiLocalTrack has triggered a no data from source event.
  226. *
  227. * @param {JitsiLocalTrack} track - The track.
  228. * @returns {{
  229. * type: TRACK_NO_DATA_FROM_SOURCE,
  230. * track: Track
  231. * }}
  232. */
  233. export function noDataFromSource(track: any) {
  234. return {
  235. type: TRACK_NO_DATA_FROM_SOURCE,
  236. track
  237. };
  238. }
  239. /**
  240. * Displays a no data from source video error if needed.
  241. *
  242. * @param {JitsiLocalTrack} jitsiTrack - The track.
  243. * @returns {Function}
  244. */
  245. export function showNoDataFromSourceVideoError(jitsiTrack: any) {
  246. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  247. let notificationInfo;
  248. const track = getTrackByJitsiTrack(getState()['features/base/tracks'], jitsiTrack);
  249. if (!track) {
  250. return;
  251. }
  252. if (track.isReceivingData) {
  253. notificationInfo = undefined;
  254. } else {
  255. const notificationAction = await dispatch(showErrorNotification({
  256. descriptionKey: 'dialog.cameraNotSendingData',
  257. titleKey: 'dialog.cameraNotSendingDataTitle'
  258. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  259. notificationInfo = {
  260. uid: notificationAction?.uid
  261. };
  262. }
  263. dispatch(trackNoDataFromSourceNotificationInfoChanged(jitsiTrack, notificationInfo));
  264. };
  265. }
  266. /**
  267. * Replaces one track with another for one renegotiation instead of invoking
  268. * two renegotiations with a separate removeTrack and addTrack. Disposes the
  269. * removed track as well.
  270. *
  271. * @param {JitsiLocalTrack|null} oldTrack - The track to dispose.
  272. * @param {JitsiLocalTrack|null} newTrack - The track to use instead.
  273. * @param {JitsiConference} [conference] - The conference from which to remove
  274. * and add the tracks. If one is not provided, the conference in the redux store
  275. * will be used.
  276. * @returns {Function}
  277. */
  278. export function replaceLocalTrack(oldTrack: any, newTrack: any, conference?: IJitsiConference) {
  279. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  280. conference
  281. // eslint-disable-next-line no-param-reassign
  282. || (conference = getState()['features/base/conference'].conference);
  283. if (conference) {
  284. await conference.replaceTrack(oldTrack, newTrack);
  285. }
  286. return dispatch(replaceStoredTracks(oldTrack, newTrack));
  287. };
  288. }
  289. /**
  290. * Replaces a stored track with another.
  291. *
  292. * @param {JitsiLocalTrack|null} oldTrack - The track to dispose.
  293. * @param {JitsiLocalTrack|null} newTrack - The track to use instead.
  294. * @returns {Function}
  295. */
  296. function replaceStoredTracks(oldTrack: any, newTrack: any) {
  297. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  298. // We call dispose after doing the replace because dispose will
  299. // try and do a new o/a after the track removes itself. Doing it
  300. // after means the JitsiLocalTrack.conference is already
  301. // cleared, so it won't try and do the o/a.
  302. if (oldTrack) {
  303. await dispatch(_disposeAndRemoveTracks([ oldTrack ]));
  304. }
  305. if (newTrack) {
  306. // The mute state of the new track should be reflected in the app's mute state. For example, if the
  307. // app is currently muted and changing to a new track that is not muted, the app's mute state
  308. // should be falsey. As such, emit a mute event here to set up the app to reflect the track's mute
  309. // state. If this is not done, the current mute state of the app will be reflected on the track,
  310. // not vice-versa.
  311. const setMuted = newTrack.isVideoTrack()
  312. ? getMultipleVideoSendingSupportFeatureFlag(getState())
  313. && newTrack.getVideoType() === VIDEO_TYPE.DESKTOP
  314. ? setScreenshareMuted
  315. : setVideoMuted
  316. : setAudioMuted;
  317. const isMuted = newTrack.isMuted();
  318. sendAnalytics(createTrackMutedEvent(newTrack.getType(), 'track.replaced', isMuted));
  319. logger.log(`Replace ${newTrack.getType()} track - ${isMuted ? 'muted' : 'unmuted'}`);
  320. await dispatch(setMuted(isMuted));
  321. await dispatch(_addTracks([ newTrack ]));
  322. }
  323. };
  324. }
  325. /**
  326. * Create an action for when a new track has been signaled to be added to the
  327. * conference.
  328. *
  329. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  330. * @returns {Function}
  331. */
  332. export function trackAdded(track: any) {
  333. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  334. track.on(
  335. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  336. () => dispatch(trackMutedChanged(track)));
  337. track.on(
  338. JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED,
  339. (type: VideoType) => dispatch(trackVideoTypeChanged(track, type)));
  340. const local = track.isLocal();
  341. const isVirtualScreenshareParticipantCreated = local
  342. ? getMultipleVideoSendingSupportFeatureFlag(getState())
  343. : getMultipleVideoSupportFeatureFlag(getState());
  344. const mediaType = track.getVideoType() === VIDEO_TYPE.DESKTOP && isVirtualScreenshareParticipantCreated
  345. ? MEDIA_TYPE.SCREENSHARE
  346. : track.getType();
  347. let isReceivingData, noDataFromSourceNotificationInfo, participantId;
  348. if (local) {
  349. // Reset the no data from src notification state when we change the track, as it's context is set
  350. // on a per device basis.
  351. dispatch(setNoSrcDataNotificationUid());
  352. const participant = getLocalParticipant(getState);
  353. if (participant) {
  354. participantId = participant.id;
  355. }
  356. isReceivingData = track.isReceivingData();
  357. track.on(JitsiTrackEvents.NO_DATA_FROM_SOURCE, () => dispatch(noDataFromSource({ jitsiTrack: track })));
  358. if (!isReceivingData) {
  359. if (mediaType === MEDIA_TYPE.AUDIO) {
  360. const notificationAction = await dispatch(showNotification({
  361. descriptionKey: 'dialog.micNotSendingData',
  362. titleKey: 'dialog.micNotSendingDataTitle'
  363. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  364. // Set the notification ID so that other parts of the application know that this was
  365. // displayed in the context of the current device.
  366. // I.E. The no-audio-signal notification shouldn't be displayed if this was already shown.
  367. dispatch(setNoSrcDataNotificationUid(notificationAction?.uid));
  368. noDataFromSourceNotificationInfo = { uid: notificationAction?.uid };
  369. } else {
  370. const timeout = setTimeout(() => dispatch(
  371. showNoDataFromSourceVideoError(track)),
  372. NOTIFICATION_TIMEOUT.MEDIUM);
  373. noDataFromSourceNotificationInfo = { timeout };
  374. }
  375. }
  376. track.on(JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  377. () => dispatch({
  378. type: TRACK_STOPPED,
  379. track: {
  380. jitsiTrack: track
  381. }
  382. }));
  383. } else {
  384. participantId = track.getParticipantId();
  385. isReceivingData = true;
  386. }
  387. return dispatch({
  388. type: TRACK_ADDED,
  389. track: {
  390. jitsiTrack: track,
  391. isReceivingData,
  392. local,
  393. mediaType,
  394. mirror: _shouldMirror(track),
  395. muted: track.isMuted(),
  396. noDataFromSourceNotificationInfo,
  397. participantId,
  398. videoStarted: false,
  399. videoType: track.videoType
  400. }
  401. });
  402. };
  403. }
  404. /**
  405. * Create an action for when a track's muted state has been signaled to be
  406. * changed.
  407. *
  408. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  409. * @returns {{
  410. * type: TRACK_UPDATED,
  411. * track: Track
  412. * }}
  413. */
  414. export function trackMutedChanged(track: any): {
  415. track: {
  416. jitsiTrack: any;
  417. muted: boolean;
  418. };
  419. type: 'TRACK_UPDATED';
  420. } {
  421. return {
  422. type: TRACK_UPDATED,
  423. track: {
  424. jitsiTrack: track,
  425. muted: track.isMuted()
  426. }
  427. };
  428. }
  429. /**
  430. * Create an action for when a track's muted state change action has failed. This could happen because of
  431. * {@code getUserMedia} errors during unmute or replace track errors at the peerconnection level.
  432. *
  433. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  434. * @param {boolean} wasMuting - If the operation that failed was a mute operation or an unmute operation.
  435. * @returns {{
  436. * type: TRACK_MUTE_UNMUTE_FAILED,
  437. * track: Track
  438. * }}
  439. */
  440. export function trackMuteUnmuteFailed(track: any, wasMuting: boolean): {
  441. track: any;
  442. type: 'TRACK_MUTE_UNMUTE_FAILED';
  443. wasMuting: boolean;
  444. } {
  445. return {
  446. type: TRACK_MUTE_UNMUTE_FAILED,
  447. track,
  448. wasMuting
  449. };
  450. }
  451. /**
  452. * Create an action for when a track's no data from source notification information changes.
  453. *
  454. * @param {JitsiLocalTrack} track - JitsiTrack instance.
  455. * @param {Object} noDataFromSourceNotificationInfo - Information about no data from source notification.
  456. * @returns {{
  457. * type: TRACK_UPDATED,
  458. * track: Track
  459. * }}
  460. */
  461. export function trackNoDataFromSourceNotificationInfoChanged(track: any, noDataFromSourceNotificationInfo?: Object) {
  462. return {
  463. type: TRACK_UPDATED,
  464. track: {
  465. jitsiTrack: track,
  466. noDataFromSourceNotificationInfo
  467. }
  468. };
  469. }
  470. /**
  471. * Create an action for when a track has been signaled for removal from the
  472. * conference.
  473. *
  474. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  475. * @returns {{
  476. * type: TRACK_REMOVED,
  477. * track: Track
  478. * }}
  479. */
  480. export function trackRemoved(track: any): {
  481. track: {
  482. jitsiTrack: any;
  483. };
  484. type: 'TRACK_REMOVED';
  485. } {
  486. track.removeAllListeners(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  487. track.removeAllListeners(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED);
  488. track.removeAllListeners(JitsiTrackEvents.NO_DATA_FROM_SOURCE);
  489. return {
  490. type: TRACK_REMOVED,
  491. track: {
  492. jitsiTrack: track
  493. }
  494. };
  495. }
  496. /**
  497. * Signal that track's video started to play.
  498. *
  499. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  500. * @returns {{
  501. * type: TRACK_UPDATED,
  502. * track: Track
  503. * }}
  504. */
  505. export function trackVideoStarted(track: any): {
  506. track: {
  507. jitsiTrack: any;
  508. videoStarted: true;
  509. };
  510. type: 'TRACK_UPDATED';
  511. } {
  512. return {
  513. type: TRACK_UPDATED,
  514. track: {
  515. jitsiTrack: track,
  516. videoStarted: true
  517. }
  518. };
  519. }
  520. /**
  521. * Create an action for when participant video type changes.
  522. *
  523. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  524. * @param {VIDEO_TYPE|undefined} videoType - Video type.
  525. * @returns {{
  526. * type: TRACK_UPDATED,
  527. * track: Track
  528. * }}
  529. */
  530. export function trackVideoTypeChanged(track: any, videoType: VideoType) {
  531. return {
  532. type: TRACK_UPDATED,
  533. track: {
  534. jitsiTrack: track,
  535. videoType
  536. }
  537. };
  538. }
  539. /**
  540. * Create an action for when track streaming status changes.
  541. *
  542. * @param {(JitsiRemoteTrack)} track - JitsiTrack instance.
  543. * @param {string} streamingStatus - The new streaming status of the track.
  544. * @returns {{
  545. * type: TRACK_UPDATED,
  546. * track: Track
  547. * }}
  548. */
  549. export function trackStreamingStatusChanged(track: any, streamingStatus: string): {
  550. track: {
  551. jitsiTrack: any;
  552. streamingStatus: string;
  553. };
  554. type: 'TRACK_UPDATED';
  555. } {
  556. return {
  557. type: TRACK_UPDATED,
  558. track: {
  559. jitsiTrack: track,
  560. streamingStatus
  561. }
  562. };
  563. }
  564. /**
  565. * Signals passed tracks to be added.
  566. *
  567. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  568. * @private
  569. * @returns {Function}
  570. */
  571. function _addTracks(tracks: any[]) {
  572. return (dispatch: IStore['dispatch']) => Promise.all(tracks.map(t => dispatch(trackAdded(t))));
  573. }
  574. /**
  575. * Cancels and waits for any {@code getUserMedia} process/currently in progress
  576. * to complete/settle.
  577. *
  578. * @param {Function} getState - The redux store {@code getState} function used
  579. * to obtain the state.
  580. * @private
  581. * @returns {Promise} - A {@code Promise} resolved once all
  582. * {@code gumProcess.cancel()} {@code Promise}s are settled because all we care
  583. * about here is to be sure that the {@code getUserMedia} callbacks have
  584. * completed (i.e. Returned from the native side).
  585. */
  586. function _cancelGUMProcesses(getState: IStore['getState']): Promise<any> {
  587. const logError
  588. = (error: Error) =>
  589. logger.error('gumProcess.cancel failed', JSON.stringify(error));
  590. return Promise.all(
  591. getState()['features/base/tracks']
  592. .filter(t => t.local)
  593. .map(({ gumProcess }: any) =>
  594. gumProcess?.cancel().catch(logError)));
  595. }
  596. /**
  597. * Disposes passed tracks and signals them to be removed.
  598. *
  599. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  600. * @protected
  601. * @returns {Function}
  602. */
  603. export function _disposeAndRemoveTracks(tracks: any[]) {
  604. return (dispatch: IStore['dispatch']) =>
  605. _disposeTracks(tracks)
  606. .then(() =>
  607. Promise.all(tracks.map(t => dispatch(trackRemoved(t)))));
  608. }
  609. /**
  610. * Disposes passed tracks.
  611. *
  612. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  613. * @private
  614. * @returns {Promise} - A Promise resolved once {@link JitsiTrack.dispose()} is
  615. * done for every track from the list.
  616. */
  617. function _disposeTracks(tracks: any[]): Promise<any> {
  618. return Promise.all(
  619. tracks.map(t =>
  620. t.dispose()
  621. .catch((err: Error) => {
  622. // Track might be already disposed so ignore such an error.
  623. // Of course, re-throw any other error(s).
  624. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  625. throw err;
  626. }
  627. })));
  628. }
  629. /**
  630. * Implements the {@code Promise} rejection handler of
  631. * {@code createLocalTracksA} and {@code createLocalTracksF}.
  632. *
  633. * @param {Object} error - The {@code Promise} rejection reason.
  634. * @param {string} device - The device/{@code MEDIA_TYPE} associated with the
  635. * rejection.
  636. * @private
  637. * @returns {Function}
  638. */
  639. function _onCreateLocalTracksRejected(error?: Error, device?: string) {
  640. return (dispatch: IStore['dispatch']) => {
  641. // If permissions are not allowed, alert the user.
  642. dispatch({
  643. type: TRACK_CREATE_ERROR,
  644. permissionDenied: error?.name === 'SecurityError',
  645. trackType: device
  646. });
  647. };
  648. }
  649. /**
  650. * Returns true if the provided {@code JitsiTrack} should be rendered as a
  651. * mirror.
  652. *
  653. * We only want to show a video in mirrored mode when:
  654. * 1) The video source is local, and not remote.
  655. * 2) The video source is a camera, not a desktop (capture).
  656. * 3) The camera is capturing the user, not the environment.
  657. *
  658. * TODO Similar functionality is part of lib-jitsi-meet. This function should be
  659. * removed after https://github.com/jitsi/lib-jitsi-meet/pull/187 is merged.
  660. *
  661. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  662. * @private
  663. * @returns {boolean}
  664. */
  665. function _shouldMirror(track: any): boolean {
  666. return (
  667. track?.isLocal()
  668. && track?.isVideoTrack()
  669. // XXX The type of the return value of JitsiLocalTrack's
  670. // getCameraFacingMode happens to be named CAMERA_FACING_MODE as
  671. // well, it's defined by lib-jitsi-meet. Note though that the type
  672. // of the value on the right side of the equality check is defined
  673. // by jitsi-meet. The type definitions are surely compatible today
  674. // but that may not be the case tomorrow.
  675. && track?.getCameraFacingMode() === CAMERA_FACING_MODE.USER);
  676. }
  677. /**
  678. * Signals that track create operation for given media track has been canceled.
  679. * Will clean up local track stub from the redux state which holds the
  680. * {@code gumProcess} reference.
  681. *
  682. * @param {MEDIA_TYPE} mediaType - The type of the media for which the track was
  683. * being created.
  684. * @private
  685. * @returns {{
  686. * type,
  687. * trackType: MEDIA_TYPE
  688. * }}
  689. */
  690. function _trackCreateCanceled(mediaType: MediaType): {
  691. trackType: MediaType;
  692. type: 'TRACK_CREATE_CANCELED';
  693. } {
  694. return {
  695. type: TRACK_CREATE_CANCELED,
  696. trackType: mediaType
  697. };
  698. }
  699. /**
  700. * If the local track if of type Desktop, it calls _disposeAndRemoveTracks) on it.
  701. *
  702. * @returns {Function}
  703. */
  704. export function destroyLocalDesktopTrackIfExists() {
  705. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  706. const videoTrack = getLocalVideoTrack(getState()['features/base/tracks']);
  707. const isDesktopTrack = videoTrack && videoTrack.videoType === VIDEO_TYPE.DESKTOP;
  708. if (isDesktopTrack) {
  709. dispatch(_disposeAndRemoveTracks([ videoTrack.jitsiTrack ]));
  710. }
  711. };
  712. }
  713. /**
  714. * Sets UID of the displayed no data from source notification. Used to track
  715. * if the notification was previously displayed in this context.
  716. *
  717. * @param {number} uid - Notification UID.
  718. * @returns {{
  719. * type: SET_NO_AUDIO_SIGNAL_UID,
  720. * uid: string
  721. * }}
  722. */
  723. export function setNoSrcDataNotificationUid(uid?: string) {
  724. return {
  725. type: SET_NO_SRC_DATA_NOTIFICATION_UID,
  726. uid
  727. };
  728. }
  729. /**
  730. * Updates the last media event received for a video track.
  731. *
  732. * @param {JitsiRemoteTrack} track - JitsiTrack instance.
  733. * @param {string} name - The current media event name for the video.
  734. * @returns {{
  735. * type: TRACK_UPDATE_LAST_VIDEO_MEDIA_EVENT,
  736. * track: Track,
  737. * name: string
  738. * }}
  739. */
  740. export function updateLastTrackVideoMediaEvent(track: any, name: string): {
  741. name: string;
  742. track: any;
  743. type: 'TRACK_UPDATE_LAST_VIDEO_MEDIA_EVENT';
  744. } {
  745. return {
  746. type: TRACK_UPDATE_LAST_VIDEO_MEDIA_EVENT,
  747. track,
  748. name
  749. };
  750. }
  751. /**
  752. * Toggles the facingMode constraint on the video stream.
  753. *
  754. * @returns {Function}
  755. */
  756. export function toggleCamera() {
  757. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  758. const state = getState();
  759. const tracks = state['features/base/tracks'];
  760. const localVideoTrack = getLocalVideoTrack(tracks)?.jitsiTrack;
  761. const currentFacingMode = localVideoTrack.getCameraFacingMode();
  762. /**
  763. * FIXME: Ideally, we should be dispatching {@code replaceLocalTrack} here,
  764. * but it seems to not trigger the re-rendering of the local video on Chrome;
  765. * could be due to a plan B vs unified plan issue. Therefore, we use the legacy
  766. * method defined in conference.js that manually takes care of updating the local
  767. * video as well.
  768. */
  769. await APP.conference.useVideoStream(null);
  770. const targetFacingMode = currentFacingMode === CAMERA_FACING_MODE.USER
  771. ? CAMERA_FACING_MODE.ENVIRONMENT
  772. : CAMERA_FACING_MODE.USER;
  773. // Update the flipX value so the environment facing camera is not flipped, before the new track is created.
  774. dispatch(updateSettings({ localFlipX: targetFacingMode === CAMERA_FACING_MODE.USER }));
  775. const newVideoTrack = await createLocalTrack('video', null, null, { facingMode: targetFacingMode });
  776. // FIXME: See above.
  777. await APP.conference.useVideoStream(newVideoTrack);
  778. };
  779. }