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 16KB

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