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.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import {
  2. createTrackMutedEvent,
  3. sendAnalytics
  4. } from '../../analytics';
  5. import { JitsiTrackErrors, JitsiTrackEvents } from '../lib-jitsi-meet';
  6. import {
  7. CAMERA_FACING_MODE,
  8. MEDIA_TYPE,
  9. setAudioMuted,
  10. setVideoMuted
  11. } from '../media';
  12. import { getLocalParticipant } from '../participants';
  13. import {
  14. TOGGLE_SCREENSHARING,
  15. TRACK_ADDED,
  16. TRACK_CREATE_CANCELED,
  17. TRACK_CREATE_ERROR,
  18. TRACK_REMOVED,
  19. TRACK_UPDATED,
  20. TRACK_WILL_CREATE
  21. } from './actionTypes';
  22. import { createLocalTracksF } from './functions';
  23. const logger = require('jitsi-meet-logger').getLogger(__filename);
  24. /**
  25. * Requests the creating of the desired media type tracks. Desire is expressed
  26. * by base/media unless the function caller specifies desired media types
  27. * explicitly and thus override base/media. Dispatches a
  28. * {@code createLocalTracksA} action for the desired media types for which there
  29. * are no existing tracks yet.
  30. *
  31. * @returns {Function}
  32. */
  33. export function createDesiredLocalTracks(...desiredTypes) {
  34. return (dispatch, getState) => {
  35. const state = getState();
  36. if (desiredTypes.length === 0) {
  37. const { audio, video } = state['features/base/media'];
  38. audio.muted || desiredTypes.push(MEDIA_TYPE.AUDIO);
  39. video.muted || desiredTypes.push(MEDIA_TYPE.VIDEO);
  40. }
  41. const availableTypes
  42. = state['features/base/tracks']
  43. .filter(t => t.local)
  44. .map(t => t.mediaType);
  45. // We need to create the desired tracks which are not already available.
  46. const createTypes
  47. = desiredTypes.filter(type => availableTypes.indexOf(type) === -1);
  48. createTypes.length
  49. && dispatch(createLocalTracksA({ devices: createTypes }));
  50. };
  51. }
  52. /**
  53. * Request to start capturing local audio and/or video. By default, the user
  54. * facing camera will be selected.
  55. *
  56. * @param {Object} [options] - For info @see JitsiMeetJS.createLocalTracks.
  57. * @returns {Function}
  58. */
  59. export function createLocalTracksA(options = {}) {
  60. return (dispatch, getState) => {
  61. const devices
  62. = options.devices || [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ];
  63. const store = {
  64. dispatch,
  65. getState
  66. };
  67. // The following executes on React Native only at the time of this
  68. // writing. The effort to port Web's createInitialLocalTracksAndConnect
  69. // is significant and that's where the function createLocalTracksF got
  70. // born. I started with the idea a porting so that we could inherit the
  71. // ability to getUserMedia for audio only or video only if getUserMedia
  72. // for audio and video fails. Eventually though, I realized that on
  73. // mobile we do not have combined permission prompts implemented anyway
  74. // (either because there are no such prompts or it does not make sense
  75. // to implement them) and the right thing to do is to ask for each
  76. // device separately.
  77. for (const device of devices) {
  78. if (getState()['features/base/tracks']
  79. .find(t => t.local && t.mediaType === device)) {
  80. throw new Error(`Local track for ${device} already exists`);
  81. }
  82. const gumProcess
  83. = createLocalTracksF(
  84. {
  85. cameraDeviceId: options.cameraDeviceId,
  86. devices: [ device ],
  87. facingMode:
  88. options.facingMode || CAMERA_FACING_MODE.USER,
  89. micDeviceId: options.micDeviceId
  90. },
  91. /* firePermissionPromptIsShownEvent */ false,
  92. store)
  93. .then(
  94. localTracks => {
  95. // Because GUM is called for 1 device (which is actually
  96. // a media type 'audio', 'video', 'screen', etc.) we
  97. // should not get more than one JitsiTrack.
  98. if (localTracks.length !== 1) {
  99. throw new Error(
  100. `Expected exactly 1 track, but was given ${
  101. localTracks.length} tracks for device: ${
  102. device}.`);
  103. }
  104. if (gumProcess.canceled) {
  105. return _disposeTracks(localTracks)
  106. .then(() =>
  107. dispatch(_trackCreateCanceled(device)));
  108. }
  109. return dispatch(trackAdded(localTracks[0]));
  110. },
  111. reason =>
  112. dispatch(
  113. gumProcess.canceled
  114. ? _trackCreateCanceled(device)
  115. : _onCreateLocalTracksRejected(
  116. reason,
  117. device)));
  118. /**
  119. * Cancels the {@code getUserMedia} process represented by this
  120. * {@code Promise}.
  121. *
  122. * @returns {Promise} This {@code Promise} i.e. {@code gumProcess}.
  123. */
  124. gumProcess.cancel = () => {
  125. gumProcess.canceled = true;
  126. return gumProcess;
  127. };
  128. dispatch({
  129. type: TRACK_WILL_CREATE,
  130. track: {
  131. gumProcess,
  132. local: true,
  133. mediaType: device
  134. }
  135. });
  136. }
  137. };
  138. }
  139. /**
  140. * Calls JitsiLocalTrack#dispose() on all local tracks ignoring errors when
  141. * track is already disposed. After that signals tracks to be removed.
  142. *
  143. * @returns {Function}
  144. */
  145. export function destroyLocalTracks() {
  146. return (dispatch, getState) => {
  147. // First wait until any getUserMedia in progress is settled and then get
  148. // rid of all local tracks.
  149. _cancelGUMProcesses(getState)
  150. .then(() =>
  151. dispatch(
  152. _disposeAndRemoveTracks(
  153. getState()['features/base/tracks']
  154. .filter(t => t.local)
  155. .map(t => t.jitsiTrack))));
  156. };
  157. }
  158. /**
  159. * Signals that the local participant is ending screensharing or beginning the
  160. * screensharing flow.
  161. *
  162. * @returns {{
  163. * type: TOGGLE_SCREENSHARING,
  164. * }}
  165. */
  166. export function toggleScreensharing() {
  167. return {
  168. type: TOGGLE_SCREENSHARING
  169. };
  170. }
  171. /**
  172. * Replaces one track with another for one renegotiation instead of invoking
  173. * two renegotiations with a separate removeTrack and addTrack. Disposes the
  174. * removed track as well.
  175. *
  176. * @param {JitsiLocalTrack|null} oldTrack - The track to dispose.
  177. * @param {JitsiLocalTrack|null} newTrack - The track to use instead.
  178. * @param {JitsiConference} [conference] - The conference from which to remove
  179. * and add the tracks. If one is not provided, the conference in the redux store
  180. * will be used.
  181. * @returns {Function}
  182. */
  183. export function replaceLocalTrack(oldTrack, newTrack, conference) {
  184. return (dispatch, getState) => {
  185. conference
  186. // eslint-disable-next-line no-param-reassign
  187. || (conference = getState()['features/base/conference'].conference);
  188. return conference.replaceTrack(oldTrack, newTrack)
  189. .then(() => {
  190. // We call dispose after doing the replace because dispose will
  191. // try and do a new o/a after the track removes itself. Doing it
  192. // after means the JitsiLocalTrack.conference is already
  193. // cleared, so it won't try and do the o/a.
  194. const disposePromise
  195. = oldTrack
  196. ? dispatch(_disposeAndRemoveTracks([ oldTrack ]))
  197. : Promise.resolve();
  198. return disposePromise
  199. .then(() => {
  200. if (newTrack) {
  201. // The mute state of the new track should be
  202. // reflected in the app's mute state. For example,
  203. // if the app is currently muted and changing to a
  204. // new track that is not muted, the app's mute
  205. // state should be falsey. As such, emit a mute
  206. // event here to set up the app to reflect the
  207. // track's mute state. If this is not done, the
  208. // current mute state of the app will be reflected
  209. // on the track, not vice-versa.
  210. const setMuted
  211. = newTrack.isVideoTrack()
  212. ? setVideoMuted
  213. : setAudioMuted;
  214. const isMuted = newTrack.isMuted();
  215. sendAnalytics(createTrackMutedEvent(
  216. newTrack.getType(),
  217. 'track.replaced',
  218. isMuted));
  219. logger.log(`Replace ${newTrack.getType()} track - ${
  220. isMuted ? 'muted' : 'unmuted'}`);
  221. return dispatch(setMuted(isMuted));
  222. }
  223. })
  224. .then(() => {
  225. if (newTrack) {
  226. return dispatch(_addTracks([ newTrack ]));
  227. }
  228. });
  229. });
  230. };
  231. }
  232. /**
  233. * Create an action for when a new track has been signaled to be added to the
  234. * conference.
  235. *
  236. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  237. * @returns {{ type: TRACK_ADDED, track: Track }}
  238. */
  239. export function trackAdded(track) {
  240. return (dispatch, getState) => {
  241. track.on(
  242. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  243. () => dispatch(trackMutedChanged(track)));
  244. track.on(
  245. JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED,
  246. type => dispatch(trackVideoTypeChanged(track, type)));
  247. // participantId
  248. const local = track.isLocal();
  249. let participantId;
  250. if (local) {
  251. const participant = getLocalParticipant(getState);
  252. if (participant) {
  253. participantId = participant.id;
  254. }
  255. } else {
  256. participantId = track.getParticipantId();
  257. }
  258. return dispatch({
  259. type: TRACK_ADDED,
  260. track: {
  261. jitsiTrack: track,
  262. local,
  263. mediaType: track.getType(),
  264. mirror: _shouldMirror(track),
  265. muted: track.isMuted(),
  266. participantId,
  267. videoStarted: false,
  268. videoType: track.videoType
  269. }
  270. });
  271. };
  272. }
  273. /**
  274. * Create an action for when a track's muted state has been signaled to be
  275. * changed.
  276. *
  277. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  278. * @returns {{
  279. * type: TRACK_UPDATED,
  280. * track: Track
  281. * }}
  282. */
  283. export function trackMutedChanged(track) {
  284. return {
  285. type: TRACK_UPDATED,
  286. track: {
  287. jitsiTrack: track,
  288. muted: track.isMuted()
  289. }
  290. };
  291. }
  292. /**
  293. * Create an action for when a track has been signaled for removal from the
  294. * conference.
  295. *
  296. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  297. * @returns {{
  298. * type: TRACK_REMOVED,
  299. * track: Track
  300. * }}
  301. */
  302. export function trackRemoved(track) {
  303. track.removeAllListeners(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  304. track.removeAllListeners(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED);
  305. return {
  306. type: TRACK_REMOVED,
  307. track: {
  308. jitsiTrack: track
  309. }
  310. };
  311. }
  312. /**
  313. * Signal that track's video started to play.
  314. *
  315. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  316. * @returns {{
  317. * type: TRACK_UPDATED,
  318. * track: Track
  319. * }}
  320. */
  321. export function trackVideoStarted(track) {
  322. return {
  323. type: TRACK_UPDATED,
  324. track: {
  325. jitsiTrack: track,
  326. videoStarted: true
  327. }
  328. };
  329. }
  330. /**
  331. * Create an action for when participant video type changes.
  332. *
  333. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  334. * @param {VIDEO_TYPE|undefined} videoType - Video type.
  335. * @returns {{
  336. * type: TRACK_UPDATED,
  337. * track: Track
  338. * }}
  339. */
  340. export function trackVideoTypeChanged(track, videoType) {
  341. return {
  342. type: TRACK_UPDATED,
  343. track: {
  344. jitsiTrack: track,
  345. videoType
  346. }
  347. };
  348. }
  349. /**
  350. * Signals passed tracks to be added.
  351. *
  352. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  353. * @private
  354. * @returns {Function}
  355. */
  356. function _addTracks(tracks) {
  357. return dispatch => Promise.all(tracks.map(t => dispatch(trackAdded(t))));
  358. }
  359. /**
  360. * Cancels and waits for any {@code getUserMedia} process/currently in progress
  361. * to complete/settle.
  362. *
  363. * @param {Function} getState - The redux store {@code getState} function used
  364. * to obtain the state.
  365. * @private
  366. * @returns {Promise} - A {@code Promise} resolved once all
  367. * {@code gumProcess.cancel()} {@code Promise}s are settled because all we care
  368. * about here is to be sure that the {@code getUserMedia} callbacks have
  369. * completed (i.e. returned from the native side).
  370. */
  371. function _cancelGUMProcesses(getState) {
  372. const logError
  373. = error =>
  374. logger.error('gumProcess.cancel failed', JSON.stringify(error));
  375. return Promise.all(
  376. getState()['features/base/tracks']
  377. .filter(t => t.local)
  378. .map(({ gumProcess }) =>
  379. gumProcess && gumProcess.cancel().catch(logError)));
  380. }
  381. /**
  382. * Disposes passed tracks and signals them to be removed.
  383. *
  384. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  385. * @protected
  386. * @returns {Function}
  387. */
  388. export function _disposeAndRemoveTracks(tracks) {
  389. return dispatch =>
  390. _disposeTracks(tracks)
  391. .then(() =>
  392. Promise.all(tracks.map(t => dispatch(trackRemoved(t)))));
  393. }
  394. /**
  395. * Disposes passed tracks.
  396. *
  397. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  398. * @private
  399. * @returns {Promise} - A Promise resolved once {@link JitsiTrack.dispose()} is
  400. * done for every track from the list.
  401. */
  402. function _disposeTracks(tracks) {
  403. return Promise.all(
  404. tracks.map(t =>
  405. t.dispose()
  406. .catch(err => {
  407. // Track might be already disposed so ignore such an error.
  408. // Of course, re-throw any other error(s).
  409. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  410. throw err;
  411. }
  412. })));
  413. }
  414. /**
  415. * Implements the {@code Promise} rejection handler of
  416. * {@code createLocalTracksA} and {@code createLocalTracksF}.
  417. *
  418. * @param {Object} reason - The {@code Promise} rejection reason.
  419. * @param {string} device - The device/{@code MEDIA_TYPE} associated with the
  420. * rejection.
  421. * @private
  422. * @returns {Function}
  423. */
  424. function _onCreateLocalTracksRejected({ gum }, device) {
  425. return dispatch => {
  426. // If permissions are not allowed, alert the user.
  427. if (gum) {
  428. const { error } = gum;
  429. if (error) {
  430. // FIXME For whatever reason (which is probably an
  431. // implementation fault), react-native-webrtc will give the
  432. // error in one of the following formats depending on whether it
  433. // is attached to a remote debugger or not. (The remote debugger
  434. // scenario suggests that react-native-webrtc is at fault
  435. // because the remote debugger is Google Chrome and then its
  436. // JavaScript engine will define DOMException. I suspect I wrote
  437. // react-native-webrtc to return the error in the alternative
  438. // format if DOMException is not defined.)
  439. let trackPermissionError;
  440. switch (error.name) {
  441. case 'DOMException':
  442. trackPermissionError = error.message === 'NotAllowedError';
  443. break;
  444. case 'NotAllowedError':
  445. trackPermissionError = error instanceof DOMException;
  446. break;
  447. }
  448. dispatch({
  449. type: TRACK_CREATE_ERROR,
  450. permissionDenied: trackPermissionError,
  451. trackType: device
  452. });
  453. }
  454. }
  455. };
  456. }
  457. /**
  458. * Returns true if the provided {@code JitsiTrack} should be rendered as a
  459. * mirror.
  460. *
  461. * We only want to show a video in mirrored mode when:
  462. * 1) The video source is local, and not remote.
  463. * 2) The video source is a camera, not a desktop (capture).
  464. * 3) The camera is capturing the user, not the environment.
  465. *
  466. * TODO Similar functionality is part of lib-jitsi-meet. This function should be
  467. * removed after https://github.com/jitsi/lib-jitsi-meet/pull/187 is merged.
  468. *
  469. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  470. * @private
  471. * @returns {boolean}
  472. */
  473. function _shouldMirror(track) {
  474. return (
  475. track
  476. && track.isLocal()
  477. && track.isVideoTrack()
  478. // XXX The type of the return value of JitsiLocalTrack's
  479. // getCameraFacingMode happens to be named CAMERA_FACING_MODE as
  480. // well, it's defined by lib-jitsi-meet. Note though that the type
  481. // of the value on the right side of the equality check is defined
  482. // by jitsi-meet. The type definitions are surely compatible today
  483. // but that may not be the case tomorrow.
  484. && track.getCameraFacingMode() === CAMERA_FACING_MODE.USER);
  485. }
  486. /**
  487. * Signals that track create operation for given media track has been canceled.
  488. * Will clean up local track stub from the redux state which holds the
  489. * {@code gumProcess} reference.
  490. *
  491. * @param {MEDIA_TYPE} mediaType - The type of the media for which the track was
  492. * being created.
  493. * @private
  494. * @returns {{
  495. * type,
  496. * trackType: MEDIA_TYPE
  497. * }}
  498. */
  499. function _trackCreateCanceled(mediaType) {
  500. return {
  501. type: TRACK_CREATE_CANCELED,
  502. trackType: mediaType
  503. };
  504. }