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

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