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

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