Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

actions.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import { sendEvent } 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. sendEvent(`replacetrack.${newTrack.getType()}.${
  147. isMuted ? 'muted' : 'unmuted'}`);
  148. logger.log(`Replace ${newTrack.getType()} track - ${
  149. isMuted ? 'muted' : 'unmuted'}`);
  150. return dispatch(setMuted());
  151. }
  152. })
  153. .then(() => {
  154. if (newTrack) {
  155. return dispatch(_addTracks([ newTrack ]));
  156. }
  157. });
  158. });
  159. };
  160. }
  161. /**
  162. * Create an action for when a new track has been signaled to be added to the
  163. * conference.
  164. *
  165. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  166. * @returns {{ type: TRACK_ADDED, track: Track }}
  167. */
  168. export function trackAdded(track) {
  169. return (dispatch, getState) => {
  170. track.on(
  171. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  172. () => dispatch(trackMutedChanged(track)));
  173. track.on(
  174. JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED,
  175. type => dispatch(trackVideoTypeChanged(track, type)));
  176. // participantId
  177. const local = track.isLocal();
  178. let participantId;
  179. if (local) {
  180. const participant = getLocalParticipant(getState);
  181. if (participant) {
  182. participantId = participant.id;
  183. }
  184. } else {
  185. participantId = track.getParticipantId();
  186. }
  187. return dispatch({
  188. type: TRACK_ADDED,
  189. track: {
  190. jitsiTrack: track,
  191. local,
  192. mediaType: track.getType(),
  193. mirror: _shouldMirror(track),
  194. muted: track.isMuted(),
  195. participantId,
  196. videoStarted: false,
  197. videoType: track.videoType
  198. }
  199. });
  200. };
  201. }
  202. /**
  203. * Create an action for when a track's muted state has been signaled to be
  204. * changed.
  205. *
  206. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  207. * @returns {{
  208. * type: TRACK_UPDATED,
  209. * track: Track
  210. * }}
  211. */
  212. export function trackMutedChanged(track) {
  213. return {
  214. type: TRACK_UPDATED,
  215. track: {
  216. jitsiTrack: track,
  217. muted: track.isMuted()
  218. }
  219. };
  220. }
  221. /**
  222. * Create an action for when a track has been signaled for removal from the
  223. * conference.
  224. *
  225. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  226. * @returns {{
  227. * type: TRACK_REMOVED,
  228. * track: Track
  229. * }}
  230. */
  231. export function trackRemoved(track) {
  232. track.removeAllListeners(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  233. track.removeAllListeners(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED);
  234. return {
  235. type: TRACK_REMOVED,
  236. track: {
  237. jitsiTrack: track
  238. }
  239. };
  240. }
  241. /**
  242. * Signal that track's video started to play.
  243. *
  244. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  245. * @returns {{
  246. * type: TRACK_UPDATED,
  247. * track: Track
  248. * }}
  249. */
  250. export function trackVideoStarted(track) {
  251. return {
  252. type: TRACK_UPDATED,
  253. track: {
  254. jitsiTrack: track,
  255. videoStarted: true
  256. }
  257. };
  258. }
  259. /**
  260. * Create an action for when participant video type changes.
  261. *
  262. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  263. * @param {VIDEO_TYPE|undefined} videoType - Video type.
  264. * @returns {{
  265. * type: TRACK_UPDATED,
  266. * track: Track
  267. * }}
  268. */
  269. export function trackVideoTypeChanged(track, videoType) {
  270. return {
  271. type: TRACK_UPDATED,
  272. track: {
  273. jitsiTrack: track,
  274. videoType
  275. }
  276. };
  277. }
  278. /**
  279. * Signals passed tracks to be added.
  280. *
  281. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  282. * @private
  283. * @returns {Function}
  284. */
  285. function _addTracks(tracks) {
  286. return dispatch => Promise.all(tracks.map(t => dispatch(trackAdded(t))));
  287. }
  288. /**
  289. * Disposes passed tracks and signals them to be removed.
  290. *
  291. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  292. * @protected
  293. * @returns {Function}
  294. */
  295. export function _disposeAndRemoveTracks(tracks) {
  296. return dispatch =>
  297. Promise.all(
  298. tracks.map(t =>
  299. t.dispose()
  300. .catch(err => {
  301. // Track might be already disposed so ignore such an
  302. // error. Of course, re-throw any other error(s).
  303. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  304. throw err;
  305. }
  306. })
  307. ))
  308. .then(Promise.all(tracks.map(t => dispatch(trackRemoved(t)))));
  309. }
  310. /**
  311. * Finds the first {@code JitsiLocalTrack} in a specific array/list of
  312. * {@code JitsiTrack}s which is of a specific {@code MEDIA_TYPE}.
  313. *
  314. * @param {JitsiTrack[]} tracks - The array/list of {@code JitsiTrack}s to look
  315. * through.
  316. * @param {MEDIA_TYPE} mediaType - The {@code MEDIA_TYPE} of the first
  317. * {@code JitsiLocalTrack} to be returned.
  318. * @private
  319. * @returns {JitsiLocalTrack} The first {@code JitsiLocalTrack}, if any, in the
  320. * specified {@code tracks} of the specified {@code mediaType}.
  321. */
  322. function _getLocalTrack(tracks, mediaType) {
  323. return tracks.find(track =>
  324. track.isLocal()
  325. // XXX JitsiTrack#getType() returns a MEDIA_TYPE value in the terms
  326. // of lib-jitsi-meet while mediaType is in the terms of jitsi-meet.
  327. && track.getType() === mediaType);
  328. }
  329. /**
  330. * Determines which local media tracks should be added and which removed.
  331. *
  332. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} currentTracks - List of
  333. * current/existing media tracks.
  334. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} newTracks - List of new media
  335. * tracks.
  336. * @private
  337. * @returns {{
  338. * tracksToAdd: JitsiLocalTrack[],
  339. * tracksToRemove: JitsiLocalTrack[]
  340. * }}
  341. */
  342. function _getLocalTracksToChange(currentTracks, newTracks) {
  343. const tracksToAdd = [];
  344. const tracksToRemove = [];
  345. for (const mediaType of [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ]) {
  346. const newTrack = _getLocalTrack(newTracks, mediaType);
  347. if (newTrack) {
  348. const currentTrack = _getLocalTrack(currentTracks, mediaType);
  349. tracksToAdd.push(newTrack);
  350. currentTrack && tracksToRemove.push(currentTrack);
  351. }
  352. }
  353. return {
  354. tracksToAdd,
  355. tracksToRemove
  356. };
  357. }
  358. /**
  359. * Implements the {@code Promise} rejection handler of
  360. * {@code createLocalTracksA} and {@code createLocalTracksF}.
  361. *
  362. * @param {Object} reason - The {@code Promise} rejection reason.
  363. * @param {string} device - The device/{@code MEDIA_TYPE} associated with the
  364. * rejection.
  365. * @private
  366. * @returns {Function}
  367. */
  368. function _onCreateLocalTracksRejected({ gum }, device) {
  369. return dispatch => {
  370. // If permissions are not allowed, alert the user.
  371. if (gum) {
  372. const { error } = gum;
  373. if (error) {
  374. // FIXME For whatever reason (which is probably an
  375. // implementation fault), react-native-webrtc will give the
  376. // error in one of the following formats depending on whether it
  377. // is attached to a remote debugger or not. (The remote debugger
  378. // scenario suggests that react-native-webrtc is at fault
  379. // because the remote debugger is Google Chrome and then its
  380. // JavaScript engine will define DOMException. I suspect I wrote
  381. // react-native-webrtc to return the error in the alternative
  382. // format if DOMException is not defined.)
  383. let trackPermissionError;
  384. switch (error.name) {
  385. case 'DOMException':
  386. trackPermissionError = error.message === 'NotAllowedError';
  387. break;
  388. case 'NotAllowedError':
  389. trackPermissionError = error instanceof DOMException;
  390. break;
  391. }
  392. trackPermissionError && dispatch({
  393. type: TRACK_PERMISSION_ERROR,
  394. trackType: device
  395. });
  396. }
  397. }
  398. };
  399. }
  400. /**
  401. * Returns true if the provided JitsiTrack should be rendered as a mirror.
  402. *
  403. * We only want to show a video in mirrored mode when:
  404. * 1) The video source is local, and not remote.
  405. * 2) The video source is a camera, not a desktop (capture).
  406. * 3) The camera is capturing the user, not the environment.
  407. *
  408. * TODO Similar functionality is part of lib-jitsi-meet. This function should be
  409. * removed after https://github.com/jitsi/lib-jitsi-meet/pull/187 is merged.
  410. *
  411. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  412. * @private
  413. * @returns {boolean}
  414. */
  415. function _shouldMirror(track) {
  416. return (
  417. track
  418. && track.isLocal()
  419. && track.isVideoTrack()
  420. // XXX The type of the return value of JitsiLocalTrack's
  421. // getCameraFacingMode happens to be named CAMERA_FACING_MODE as
  422. // well, it's defined by lib-jitsi-meet. Note though that the type
  423. // of the value on the right side of the equality check is defined
  424. // by jitsi-meet. The type definitions are surely compatible today
  425. // but that may not be the case tomorrow.
  426. && track.getCameraFacingMode() === CAMERA_FACING_MODE.USER);
  427. }
  428. /**
  429. * Set new local tracks replacing any existing tracks that were previously
  430. * available. Currently only one audio and one video local tracks are allowed.
  431. *
  432. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} [newTracks=[]] - List of new
  433. * media tracks.
  434. * @private
  435. * @returns {Function}
  436. */
  437. function _updateLocalTracks(newTracks = []) {
  438. return (dispatch, getState) => {
  439. const tracks
  440. = getState()['features/base/tracks'].map(t => t.jitsiTrack);
  441. const { tracksToAdd, tracksToRemove }
  442. = _getLocalTracksToChange(tracks, newTracks);
  443. return dispatch(_disposeAndRemoveTracks(tracksToRemove))
  444. .then(() => dispatch(_addTracks(tracksToAdd)));
  445. };
  446. }