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.

actions.any.ts 29KB

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