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.

LargeVideoManager.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /* global $, APP */
  2. /* eslint-disable no-unused-vars */
  3. import Logger from 'jitsi-meet-logger';
  4. import React from 'react';
  5. import ReactDOM from 'react-dom';
  6. import { I18nextProvider } from 'react-i18next';
  7. import { Provider } from 'react-redux';
  8. import { Avatar } from '../../../react/features/base/avatar';
  9. import { i18next } from '../../../react/features/base/i18n';
  10. import {
  11. JitsiParticipantConnectionStatus
  12. } from '../../../react/features/base/lib-jitsi-meet';
  13. import { VIDEO_TYPE } from '../../../react/features/base/media';
  14. import { CHAT_SIZE } from '../../../react/features/chat';
  15. import {
  16. updateKnownLargeVideoResolution
  17. } from '../../../react/features/large-video';
  18. import { PresenceLabel } from '../../../react/features/presence-status';
  19. /* eslint-enable no-unused-vars */
  20. import UIEvents from '../../../service/UI/UIEvents';
  21. import { createDeferred } from '../../util/helpers';
  22. import AudioLevels from '../audio_levels/AudioLevels';
  23. import { VideoContainer, VIDEO_CONTAINER_TYPE } from './VideoContainer';
  24. const logger = Logger.getLogger(__filename);
  25. const DESKTOP_CONTAINER_TYPE = 'desktop';
  26. /**
  27. * Manager for all Large containers.
  28. */
  29. export default class LargeVideoManager {
  30. /**
  31. * Checks whether given container is a {@link VIDEO_CONTAINER_TYPE}.
  32. * FIXME currently this is a workaround for the problem where video type is
  33. * mixed up with container type.
  34. * @param {string} containerType
  35. * @return {boolean}
  36. */
  37. static isVideoContainer(containerType) {
  38. return containerType === VIDEO_CONTAINER_TYPE
  39. || containerType === DESKTOP_CONTAINER_TYPE;
  40. }
  41. /**
  42. *
  43. */
  44. constructor(emitter) {
  45. /**
  46. * The map of <tt>LargeContainer</tt>s where the key is the video
  47. * container type.
  48. * @type {Object.<string, LargeContainer>}
  49. */
  50. this.containers = {};
  51. this.eventEmitter = emitter;
  52. this.state = VIDEO_CONTAINER_TYPE;
  53. // FIXME: We are passing resizeContainer as parameter which is calling
  54. // Container.resize. Probably there's better way to implement this.
  55. this.videoContainer = new VideoContainer(
  56. () => this.resizeContainer(VIDEO_CONTAINER_TYPE), emitter);
  57. this.addContainer(VIDEO_CONTAINER_TYPE, this.videoContainer);
  58. // use the same video container to handle desktop tracks
  59. this.addContainer(DESKTOP_CONTAINER_TYPE, this.videoContainer);
  60. this.width = 0;
  61. this.height = 0;
  62. /**
  63. * Cache the aspect ratio of the video displayed to detect changes to
  64. * the aspect ratio on video resize events.
  65. *
  66. * @type {number}
  67. */
  68. this._videoAspectRatio = 0;
  69. this.$container = $('#largeVideoContainer');
  70. this.$container.css({
  71. display: 'inline-block'
  72. });
  73. this.$container.hover(
  74. e => this.onHoverIn(e),
  75. e => this.onHoverOut(e)
  76. );
  77. // Bind event handler so it is only bound once for every instance.
  78. this._onVideoResolutionUpdate
  79. = this._onVideoResolutionUpdate.bind(this);
  80. this.videoContainer.addResizeListener(this._onVideoResolutionUpdate);
  81. this._dominantSpeakerAvatarContainer
  82. = document.getElementById('dominantSpeakerAvatarContainer');
  83. }
  84. /**
  85. * Removes any listeners registered on child components, including
  86. * React Components.
  87. *
  88. * @returns {void}
  89. */
  90. destroy() {
  91. this.videoContainer.removeResizeListener(
  92. this._onVideoResolutionUpdate);
  93. this.removePresenceLabel();
  94. ReactDOM.unmountComponentAtNode(this._dominantSpeakerAvatarContainer);
  95. this.$container.css({ display: 'none' });
  96. }
  97. /**
  98. *
  99. */
  100. onHoverIn(e) {
  101. if (!this.state) {
  102. return;
  103. }
  104. const container = this.getCurrentContainer();
  105. container.onHoverIn(e);
  106. }
  107. /**
  108. *
  109. */
  110. onHoverOut(e) {
  111. if (!this.state) {
  112. return;
  113. }
  114. const container = this.getCurrentContainer();
  115. container.onHoverOut(e);
  116. }
  117. /**
  118. *
  119. */
  120. get id() {
  121. const container = this.getCurrentContainer();
  122. // If a user switch for large video is in progress then provide what
  123. // will be the end result of the update.
  124. if (this.updateInProcess
  125. && this.newStreamData
  126. && this.newStreamData.id !== container.id) {
  127. return this.newStreamData.id;
  128. }
  129. return container.id;
  130. }
  131. /**
  132. *
  133. */
  134. scheduleLargeVideoUpdate() {
  135. if (this.updateInProcess || !this.newStreamData) {
  136. return;
  137. }
  138. this.updateInProcess = true;
  139. // Include hide()/fadeOut only if we're switching between users
  140. // eslint-disable-next-line eqeqeq
  141. const container = this.getCurrentContainer();
  142. const isUserSwitch = this.newStreamData.id !== container.id;
  143. const preUpdate = isUserSwitch ? container.hide() : Promise.resolve();
  144. preUpdate.then(() => {
  145. const { id, stream, videoType, resolve } = this.newStreamData;
  146. // FIXME this does not really make sense, because the videoType
  147. // (camera or desktop) is a completely different thing than
  148. // the video container type (Etherpad, SharedVideo, VideoContainer).
  149. const isVideoContainer
  150. = LargeVideoManager.isVideoContainer(videoType);
  151. this.newStreamData = null;
  152. logger.info(`hover in ${id}`);
  153. this.state = videoType;
  154. // eslint-disable-next-line no-shadow
  155. const container = this.getCurrentContainer();
  156. container.setStream(id, stream, videoType);
  157. // change the avatar url on large
  158. this.updateAvatar();
  159. // If the user's connection is disrupted then the avatar will be
  160. // displayed in case we have no video image cached. That is if
  161. // there was a user switch (image is lost on stream detach) or if
  162. // the video was not rendered, before the connection has failed.
  163. const wasUsersImageCached
  164. = !isUserSwitch && container.wasVideoRendered;
  165. const isVideoMuted = !stream || stream.isMuted();
  166. const connectionStatus
  167. = APP.conference.getParticipantConnectionStatus(id);
  168. const isVideoRenderable
  169. = !isVideoMuted
  170. && (APP.conference.isLocalId(id)
  171. || connectionStatus
  172. === JitsiParticipantConnectionStatus.ACTIVE
  173. || wasUsersImageCached);
  174. const showAvatar
  175. = isVideoContainer
  176. && ((APP.conference.isAudioOnly() && videoType !== VIDEO_TYPE.DESKTOP) || !isVideoRenderable);
  177. let promise;
  178. // do not show stream if video is muted
  179. // but we still should show watermark
  180. if (showAvatar) {
  181. this.showWatermark(true);
  182. // If the intention of this switch is to show the avatar
  183. // we need to make sure that the video is hidden
  184. promise = container.hide();
  185. } else {
  186. promise = container.show();
  187. }
  188. // show the avatar on large if needed
  189. container.showAvatar(showAvatar);
  190. // Clean up audio level after previous speaker.
  191. if (showAvatar) {
  192. this.updateLargeVideoAudioLevel(0);
  193. }
  194. const messageKey
  195. = connectionStatus === JitsiParticipantConnectionStatus.INACTIVE ? 'connection.LOW_BANDWIDTH' : null;
  196. // Do not show connection status message in the audio only mode,
  197. // because it's based on the video playback status.
  198. const overrideAndHide = APP.conference.isAudioOnly();
  199. this.updateParticipantConnStatusIndication(
  200. id,
  201. !overrideAndHide && messageKey);
  202. // Change the participant id the presence label is listening to.
  203. this.updatePresenceLabel(id);
  204. this.videoContainer.positionRemoteStatusMessages();
  205. // resolve updateLargeVideo promise after everything is done
  206. promise.then(resolve);
  207. return promise;
  208. }).then(() => {
  209. // after everything is done check again if there are any pending
  210. // new streams.
  211. this.updateInProcess = false;
  212. this.eventEmitter.emit(UIEvents.LARGE_VIDEO_ID_CHANGED, this.id);
  213. this.scheduleLargeVideoUpdate();
  214. });
  215. }
  216. /**
  217. * Shows/hides notification about participant's connectivity issues to be
  218. * shown on the large video area.
  219. *
  220. * @param {string} id the id of remote participant(MUC nickname)
  221. * @param {string|null} messageKey the i18n key of the message which will be
  222. * displayed on the large video or <tt>null</tt> to hide it.
  223. *
  224. * @private
  225. */
  226. updateParticipantConnStatusIndication(id, messageKey) {
  227. if (messageKey) {
  228. // Get user's display name
  229. const displayName
  230. = APP.conference.getParticipantDisplayName(id);
  231. this._setRemoteConnectionMessage(
  232. messageKey,
  233. { displayName });
  234. // Show it now only if the VideoContainer is on top
  235. this.showRemoteConnectionMessage(
  236. LargeVideoManager.isVideoContainer(this.state));
  237. } else {
  238. // Hide the message
  239. this.showRemoteConnectionMessage(false);
  240. }
  241. }
  242. /**
  243. * Update large video.
  244. * Switches to large video even if previously other container was visible.
  245. * @param userID the userID of the participant associated with the stream
  246. * @param {JitsiTrack?} stream new stream
  247. * @param {string?} videoType new video type
  248. * @returns {Promise}
  249. */
  250. updateLargeVideo(userID, stream, videoType) {
  251. if (this.newStreamData) {
  252. this.newStreamData.reject();
  253. }
  254. this.newStreamData = createDeferred();
  255. this.newStreamData.id = userID;
  256. this.newStreamData.stream = stream;
  257. this.newStreamData.videoType = videoType;
  258. this.scheduleLargeVideoUpdate();
  259. return this.newStreamData.promise;
  260. }
  261. /**
  262. * Update container size.
  263. */
  264. updateContainerSize(width, height) {
  265. let widthToUse = width ?? (this.width > 0 ? this.width : window.innerWidth);
  266. const { isOpen } = APP.store.getState()['features/chat'];
  267. /**
  268. * If chat state is open, we re-compute the container width by subtracting the default width of
  269. * the chat. We re-compute the width again after the chat window is closed. This is needed when
  270. * custom styling is configured on the large video container through the iFrame API.
  271. */
  272. if (isOpen) {
  273. widthToUse -= CHAT_SIZE;
  274. this.resizedForChat = true;
  275. } else if (this.resizedForChat) {
  276. this.resizedForChat = false;
  277. widthToUse += CHAT_SIZE;
  278. }
  279. this.width = widthToUse;
  280. this.height = height ?? (this.height > 0 ? this.height : window.innerHeight);
  281. }
  282. /**
  283. * Resize Large container of specified type.
  284. * @param {string} type type of container which should be resized.
  285. * @param {boolean} [animate=false] if resize process should be animated.
  286. */
  287. resizeContainer(type, animate = false) {
  288. const container = this.getContainer(type);
  289. container.resize(this.width, this.height, animate);
  290. }
  291. /**
  292. * Resize all Large containers.
  293. * @param {boolean} animate if resize process should be animated.
  294. */
  295. resize(animate) {
  296. // resize all containers
  297. Object.keys(this.containers)
  298. .forEach(type => this.resizeContainer(type, animate));
  299. }
  300. /**
  301. * Updates the src of the dominant speaker avatar
  302. */
  303. updateAvatar() {
  304. ReactDOM.render(
  305. <Provider store = { APP.store }>
  306. <Avatar
  307. id = "dominantSpeakerAvatar"
  308. participantId = { this.id }
  309. size = { 200 } />
  310. </Provider>,
  311. this._dominantSpeakerAvatarContainer
  312. );
  313. }
  314. /**
  315. * Updates the audio level indicator of the large video.
  316. *
  317. * @param lvl the new audio level to set
  318. */
  319. updateLargeVideoAudioLevel(lvl) {
  320. AudioLevels.updateLargeVideoAudioLevel('dominantSpeaker', lvl);
  321. }
  322. /**
  323. * Displays a message of the passed in participant id's presence status. The
  324. * message will not display if the remote connection message is displayed.
  325. *
  326. * @param {string} id - The participant ID whose associated user's presence
  327. * status should be displayed.
  328. * @returns {void}
  329. */
  330. updatePresenceLabel(id) {
  331. const isConnectionMessageVisible
  332. = $('#remoteConnectionMessage').is(':visible');
  333. if (isConnectionMessageVisible) {
  334. this.removePresenceLabel();
  335. return;
  336. }
  337. const presenceLabelContainer = $('#remotePresenceMessage');
  338. if (presenceLabelContainer.length) {
  339. ReactDOM.render(
  340. <Provider store = { APP.store }>
  341. <I18nextProvider i18n = { i18next }>
  342. <PresenceLabel
  343. participantID = { id }
  344. className = 'presence-label' />
  345. </I18nextProvider>
  346. </Provider>,
  347. presenceLabelContainer.get(0));
  348. }
  349. }
  350. /**
  351. * Removes the messages about the displayed participant's presence status.
  352. *
  353. * @returns {void}
  354. */
  355. removePresenceLabel() {
  356. const presenceLabelContainer = $('#remotePresenceMessage');
  357. if (presenceLabelContainer.length) {
  358. ReactDOM.unmountComponentAtNode(presenceLabelContainer.get(0));
  359. }
  360. }
  361. /**
  362. * Show or hide watermark.
  363. * @param {boolean} show
  364. */
  365. showWatermark(show) {
  366. $('.watermark').css('visibility', show ? 'visible' : 'hidden');
  367. }
  368. /**
  369. * Shows hides the "avatar" message which is to be displayed either in
  370. * the middle of the screen or below the avatar image.
  371. *
  372. * @param {boolean|undefined} [show=undefined] <tt>true</tt> to show
  373. * the avatar message or <tt>false</tt> to hide it. If not provided then
  374. * the connection status of the user currently on the large video will be
  375. * obtained form "APP.conference" and the message will be displayed if
  376. * the user's connection is either interrupted or inactive.
  377. */
  378. showRemoteConnectionMessage(show) {
  379. if (typeof show !== 'boolean') {
  380. const connStatus
  381. = APP.conference.getParticipantConnectionStatus(this.id);
  382. // eslint-disable-next-line no-param-reassign
  383. show = !APP.conference.isLocalId(this.id)
  384. && (connStatus === JitsiParticipantConnectionStatus.INTERRUPTED
  385. || connStatus
  386. === JitsiParticipantConnectionStatus.INACTIVE);
  387. }
  388. if (show) {
  389. $('#remoteConnectionMessage').css({ display: 'block' });
  390. } else {
  391. $('#remoteConnectionMessage').hide();
  392. }
  393. }
  394. /**
  395. * Updates the text which describes that the remote user is having
  396. * connectivity issues.
  397. *
  398. * @param {string} msgKey the translation key which will be used to get
  399. * the message text.
  400. * @param {object} msgOptions translation options object.
  401. *
  402. * @private
  403. */
  404. _setRemoteConnectionMessage(msgKey, msgOptions) {
  405. if (msgKey) {
  406. $('#remoteConnectionMessage')
  407. .attr('data-i18n', msgKey)
  408. .attr('data-i18n-options', JSON.stringify(msgOptions));
  409. APP.translation.translateElement(
  410. $('#remoteConnectionMessage'), msgOptions);
  411. }
  412. }
  413. /**
  414. * Add container of specified type.
  415. * @param {string} type container type
  416. * @param {LargeContainer} container container to add.
  417. */
  418. addContainer(type, container) {
  419. if (this.containers[type]) {
  420. throw new Error(`container of type ${type} already exist`);
  421. }
  422. this.containers[type] = container;
  423. this.resizeContainer(type);
  424. }
  425. /**
  426. * Get Large container of specified type.
  427. * @param {string} type container type.
  428. * @returns {LargeContainer}
  429. */
  430. getContainer(type) {
  431. const container = this.containers[type];
  432. if (!container) {
  433. throw new Error(`container of type ${type} doesn't exist`);
  434. }
  435. return container;
  436. }
  437. /**
  438. * Returns {@link LargeContainer} for the current {@link state}
  439. *
  440. * @return {LargeContainer}
  441. *
  442. * @throws an <tt>Error</tt> if there is no container for the current
  443. * {@link state}.
  444. */
  445. getCurrentContainer() {
  446. return this.getContainer(this.state);
  447. }
  448. /**
  449. * Returns type of the current {@link LargeContainer}
  450. * @return {string}
  451. */
  452. getCurrentContainerType() {
  453. return this.state;
  454. }
  455. /**
  456. * Remove Large container of specified type.
  457. * @param {string} type container type.
  458. */
  459. removeContainer(type) {
  460. if (!this.containers[type]) {
  461. throw new Error(`container of type ${type} doesn't exist`);
  462. }
  463. delete this.containers[type];
  464. }
  465. /**
  466. * Show Large container of specified type.
  467. * Does nothing if such container is already visible.
  468. * @param {string} type container type.
  469. * @returns {Promise}
  470. */
  471. showContainer(type) {
  472. if (this.state === type) {
  473. return Promise.resolve();
  474. }
  475. const oldContainer = this.containers[this.state];
  476. // FIXME when video is being replaced with other content we need to hide
  477. // companion icons/messages. It would be best if the container would
  478. // be taking care of it by itself, but that is a bigger refactoring
  479. if (LargeVideoManager.isVideoContainer(this.state)) {
  480. this.showWatermark(false);
  481. this.showRemoteConnectionMessage(false);
  482. }
  483. oldContainer.hide();
  484. this.state = type;
  485. const container = this.getContainer(type);
  486. return container.show().then(() => {
  487. if (LargeVideoManager.isVideoContainer(type)) {
  488. // FIXME when video appears on top of other content we need to
  489. // show companion icons/messages. It would be best if
  490. // the container would be taking care of it by itself, but that
  491. // is a bigger refactoring
  492. this.showWatermark(true);
  493. // "avatar" and "video connection" can not be displayed both
  494. // at the same time, but the latter is of higher priority and it
  495. // will hide the avatar one if will be displayed.
  496. this.showRemoteConnectionMessage(/* fetch the current state */);
  497. }
  498. });
  499. }
  500. /**
  501. * Changes the flipX state of the local video.
  502. * @param val {boolean} true if flipped.
  503. */
  504. onLocalFlipXChange(val) {
  505. this.videoContainer.setLocalFlipX(val);
  506. }
  507. /**
  508. * Dispatches an action to update the known resolution state of the large video and adjusts container sizes when the
  509. * resolution changes.
  510. *
  511. * @private
  512. * @returns {void}
  513. */
  514. _onVideoResolutionUpdate() {
  515. const { height, width } = this.videoContainer.getStreamSize();
  516. const { resolution } = APP.store.getState()['features/large-video'];
  517. if (height !== resolution) {
  518. APP.store.dispatch(updateKnownLargeVideoResolution(height));
  519. }
  520. const currentAspectRatio = height === 0 ? 0 : width / height;
  521. if (this._videoAspectRatio !== currentAspectRatio) {
  522. this._videoAspectRatio = currentAspectRatio;
  523. this.resize();
  524. }
  525. }
  526. }