Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

VideoContainer.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. /* global APP, interfaceConfig */
  2. /* eslint-disable no-unused-vars */
  3. import Logger from '@jitsi/logger';
  4. import $ from 'jquery';
  5. import React from 'react';
  6. import ReactDOM from 'react-dom';
  7. import { browser } from '../../../react/features/base/lib-jitsi-meet';
  8. import { FILMSTRIP_BREAKPOINT } from '../../../react/features/filmstrip/constants';
  9. import { setLargeVideoDimensions } from '../../../react/features/large-video/actions.any';
  10. import { LargeVideoBackground, ORIENTATION } from '../../../react/features/large-video/components/LargeVideoBackground';
  11. import { LAYOUTS } from '../../../react/features/video-layout/constants';
  12. import { getCurrentLayout } from '../../../react/features/video-layout/functions.any';
  13. /* eslint-enable no-unused-vars */
  14. import UIUtil from '../util/UIUtil';
  15. import Filmstrip from './Filmstrip';
  16. import LargeContainer from './LargeContainer';
  17. // FIXME should be 'video'
  18. export const VIDEO_CONTAINER_TYPE = 'camera';
  19. // Corresponds to animation duration from the animatedFadeIn and animatedFadeOut CSS classes.
  20. const FADE_DURATION_MS = 300;
  21. const logger = Logger.getLogger(__filename);
  22. /**
  23. * Returns an array of the video dimensions, so that it keeps it's aspect
  24. * ratio and fits available area with it's larger dimension. This method
  25. * ensures that whole video will be visible and can leave empty areas.
  26. *
  27. * @param videoWidth the width of the video to position
  28. * @param videoHeight the height of the video to position
  29. * @param videoSpaceWidth the width of the available space
  30. * @param videoSpaceHeight the height of the available space
  31. * @param subtractFilmstrip whether to subtract the filmstrip or not
  32. * @return an array with 2 elements, the video width and the video height
  33. */
  34. function computeDesktopVideoSize( // eslint-disable-line max-params
  35. videoWidth,
  36. videoHeight,
  37. videoSpaceWidth,
  38. videoSpaceHeight,
  39. subtractFilmstrip) {
  40. if (videoWidth === 0 || videoHeight === 0 || videoSpaceWidth === 0 || videoSpaceHeight === 0) {
  41. // Avoid NaN values caused by division by 0.
  42. return [ 0, 0 ];
  43. }
  44. const aspectRatio = videoWidth / videoHeight;
  45. let availableWidth = Math.max(videoWidth, videoSpaceWidth);
  46. let availableHeight = Math.max(videoHeight, videoSpaceHeight);
  47. if (interfaceConfig.VERTICAL_FILMSTRIP) {
  48. if (subtractFilmstrip) {
  49. // eslint-disable-next-line no-param-reassign
  50. videoSpaceWidth -= Filmstrip.getVerticalFilmstripWidth();
  51. }
  52. } else {
  53. // eslint-disable-next-line no-param-reassign
  54. videoSpaceHeight -= Filmstrip.getFilmstripHeight();
  55. }
  56. if (availableWidth / aspectRatio >= videoSpaceHeight) {
  57. availableHeight = videoSpaceHeight;
  58. availableWidth = availableHeight * aspectRatio;
  59. }
  60. if (availableHeight * aspectRatio >= videoSpaceWidth) {
  61. availableWidth = videoSpaceWidth;
  62. availableHeight = availableWidth / aspectRatio;
  63. }
  64. return [ availableWidth, availableHeight ];
  65. }
  66. /**
  67. * Returns an array of the video dimensions. It respects the
  68. * VIDEO_LAYOUT_FIT config, to fit the video to the screen, by hiding some parts
  69. * of it, or to fit it to the height or width.
  70. *
  71. * @param videoWidth the original video width
  72. * @param videoHeight the original video height
  73. * @param videoSpaceWidth the width of the video space
  74. * @param videoSpaceHeight the height of the video space
  75. * @return an array with 2 elements, the video width and the video height
  76. */
  77. function computeCameraVideoSize( // eslint-disable-line max-params
  78. videoWidth,
  79. videoHeight,
  80. videoSpaceWidth,
  81. videoSpaceHeight,
  82. videoLayoutFit) {
  83. if (videoWidth === 0 || videoHeight === 0 || videoSpaceWidth === 0 || videoSpaceHeight === 0) {
  84. // Avoid NaN values caused by division by 0.
  85. return [ 0, 0 ];
  86. }
  87. const aspectRatio = videoWidth / videoHeight;
  88. const videoSpaceRatio = videoSpaceWidth / videoSpaceHeight;
  89. switch (videoLayoutFit) {
  90. case 'height':
  91. return [ videoSpaceHeight * aspectRatio, videoSpaceHeight ];
  92. case 'width':
  93. return [ videoSpaceWidth, videoSpaceWidth / aspectRatio ];
  94. case 'nocrop':
  95. return computeCameraVideoSize(
  96. videoWidth,
  97. videoHeight,
  98. videoSpaceWidth,
  99. videoSpaceHeight,
  100. videoSpaceRatio < aspectRatio ? 'width' : 'height');
  101. case 'both': {
  102. const maxZoomCoefficient = interfaceConfig.MAXIMUM_ZOOMING_COEFFICIENT
  103. || Infinity;
  104. if (videoSpaceRatio === aspectRatio) {
  105. return [ videoSpaceWidth, videoSpaceHeight ];
  106. }
  107. let [ width, height ] = computeCameraVideoSize(
  108. videoWidth,
  109. videoHeight,
  110. videoSpaceWidth,
  111. videoSpaceHeight,
  112. videoSpaceRatio < aspectRatio ? 'height' : 'width');
  113. const maxWidth = videoSpaceWidth * maxZoomCoefficient;
  114. const maxHeight = videoSpaceHeight * maxZoomCoefficient;
  115. if (width > maxWidth) {
  116. width = maxWidth;
  117. height = width / aspectRatio;
  118. } else if (height > maxHeight) {
  119. height = maxHeight;
  120. width = height * aspectRatio;
  121. }
  122. return [ width, height ];
  123. }
  124. default:
  125. return [ videoWidth, videoHeight ];
  126. }
  127. }
  128. /**
  129. * Returns an array of the video horizontal and vertical indents,
  130. * so that if fits its parent.
  131. *
  132. * @return an array with 2 elements, the horizontal indent and the vertical
  133. * indent
  134. */
  135. function getCameraVideoPosition( // eslint-disable-line max-params
  136. videoWidth,
  137. videoHeight,
  138. videoSpaceWidth,
  139. videoSpaceHeight) {
  140. // Parent height isn't completely calculated when we position the video in
  141. // full screen mode and this is why we use the screen height in this case.
  142. // Need to think it further at some point and implement it properly.
  143. if (UIUtil.isFullScreen()) {
  144. // eslint-disable-next-line no-param-reassign
  145. videoSpaceHeight = window.innerHeight;
  146. }
  147. const horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  148. const verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  149. return { horizontalIndent,
  150. verticalIndent };
  151. }
  152. /**
  153. * Container for user video.
  154. */
  155. export class VideoContainer extends LargeContainer {
  156. /**
  157. *
  158. */
  159. get video() {
  160. return document.getElementById('largeVideo');
  161. }
  162. /**
  163. *
  164. */
  165. get id() {
  166. return this.userId;
  167. }
  168. /**
  169. * Creates new VideoContainer instance.
  170. * @param resizeContainer {Function} function that takes care of the size
  171. * of the video container.
  172. */
  173. constructor(resizeContainer) {
  174. super();
  175. this.stream = null;
  176. this.userId = null;
  177. this.videoType = null;
  178. this.localFlipX = true;
  179. this.resizeContainer = resizeContainer;
  180. /**
  181. * Whether the background should fit the height of the container
  182. * (portrait) or fit the width of the container (landscape).
  183. *
  184. * @private
  185. * @type {string|null}
  186. */
  187. this._backgroundOrientation = null;
  188. /**
  189. * Flag indicates whether or not the background should be rendered.
  190. * If the background will not be visible then it is hidden to save
  191. * on performance.
  192. * @type {boolean}
  193. */
  194. this._hideBackground = true;
  195. this._isHidden = false;
  196. /**
  197. * Flag indicates whether or not the avatar is currently displayed.
  198. * @type {boolean}
  199. */
  200. this.avatarDisplayed = false;
  201. this.avatar = document.getElementById('dominantSpeaker');
  202. /**
  203. * The HTMLElements of the remote connection message.
  204. * @type {HTMLElement}
  205. */
  206. this.remoteConnectionMessage = document.getElementById('remoteConnectionMessage');
  207. this.remotePresenceMessage = document.getElementById('remotePresenceMessage');
  208. this.$wrapper = $('#largeVideoWrapper');
  209. this.wrapperParent = document.getElementById('largeVideoElementsContainer');
  210. this.avatarHeight = document.getElementById('dominantSpeakerAvatarContainer').getBoundingClientRect().height;
  211. this.video.onplaying = function(event) {
  212. if (typeof resizeContainer === 'function') {
  213. resizeContainer(event);
  214. }
  215. };
  216. /**
  217. * A Set of functions to invoke when the video element resizes.
  218. *
  219. * @private
  220. */
  221. this._resizeListeners = new Set();
  222. this.video.onresize = this._onResize.bind(this);
  223. }
  224. /**
  225. * Adds a function to the known subscribers of video element resize
  226. * events.
  227. *
  228. * @param {Function} callback - The subscriber to notify when the video
  229. * element resizes.
  230. * @returns {void}
  231. */
  232. addResizeListener(callback) {
  233. this._resizeListeners.add(callback);
  234. }
  235. /**
  236. * Obtains media stream ID of the underlying {@link JitsiTrack}.
  237. * @return {string|null}
  238. */
  239. getStreamID() {
  240. return this.stream ? this.stream.getId() : null;
  241. }
  242. /**
  243. * Get size of video element.
  244. * @returns {{width, height}}
  245. */
  246. getStreamSize() {
  247. const video = this.video;
  248. return {
  249. width: video.videoWidth,
  250. height: video.videoHeight
  251. };
  252. }
  253. /**
  254. * Calculate optimal video size for specified container size.
  255. * @param {number} containerWidth container width
  256. * @param {number} containerHeight container height
  257. * @param {number} verticalFilmstripWidth current width of the vertical filmstrip
  258. * @returns {{availableWidth, availableHeight}}
  259. */
  260. _getVideoSize(containerWidth, containerHeight, verticalFilmstripWidth) {
  261. const { width, height } = this.getStreamSize();
  262. if (this.stream && this.isScreenSharing()) {
  263. return computeDesktopVideoSize(width,
  264. height,
  265. containerWidth,
  266. containerHeight,
  267. verticalFilmstripWidth < FILMSTRIP_BREAKPOINT);
  268. }
  269. return computeCameraVideoSize(width,
  270. height,
  271. containerWidth,
  272. containerHeight,
  273. interfaceConfig.VIDEO_LAYOUT_FIT);
  274. }
  275. /* eslint-disable max-params */
  276. /**
  277. * Calculate optimal video position (offset for top left corner)
  278. * for specified video size and container size.
  279. * @param {number} width video width
  280. * @param {number} height video height
  281. * @param {number} containerWidth container width
  282. * @param {number} containerHeight container height
  283. * @param {number} verticalFilmstripWidth current width of the vertical filmstrip
  284. * @returns {{horizontalIndent, verticalIndent}}
  285. */
  286. getVideoPosition(width, height, containerWidth, containerHeight, verticalFilmstripWidth) {
  287. let containerWidthToUse = containerWidth;
  288. /* eslint-enable max-params */
  289. if (this.stream && this.isScreenSharing()) {
  290. if (interfaceConfig.VERTICAL_FILMSTRIP && verticalFilmstripWidth < FILMSTRIP_BREAKPOINT) {
  291. containerWidthToUse -= Filmstrip.getVerticalFilmstripWidth();
  292. }
  293. return getCameraVideoPosition(width,
  294. height,
  295. containerWidthToUse,
  296. containerHeight);
  297. }
  298. return getCameraVideoPosition(width,
  299. height,
  300. containerWidthToUse,
  301. containerHeight);
  302. }
  303. /**
  304. * Updates the positioning of the remote connection presence message and the
  305. * connection status message which escribes that the remote user is having
  306. * connectivity issues.
  307. *
  308. * @returns {void}
  309. */
  310. positionRemoteStatusMessages() {
  311. this._positionParticipantStatus(this.remoteConnectionMessage);
  312. this._positionParticipantStatus(this.remotePresenceMessage);
  313. }
  314. /**
  315. * Modifies the position of the passed in jQuery object so it displays
  316. * in the middle of the video container or below the avatar.
  317. *
  318. * @private
  319. * @returns {void}
  320. */
  321. _positionParticipantStatus(element) {
  322. if (this.avatarDisplayed) {
  323. const avatarImage = document.getElementById('dominantSpeakerAvatarContainer').getBoundingClientRect();
  324. element.style.top = avatarImage.top + avatarImage.height + 10;
  325. } else {
  326. const height = element.getBoundingClientRect().height;
  327. const parentHeight = element.parentElement.getBoundingClientRect().height;
  328. element.style.top = (parentHeight / 2) - (height / 2);
  329. }
  330. }
  331. /**
  332. *
  333. */
  334. resize(containerWidth, containerHeight, animate = false) {
  335. // XXX Prevent TypeError: undefined is not an object when the Web
  336. // browser does not support WebRTC (yet).
  337. if (!this.video) {
  338. return;
  339. }
  340. const state = APP.store.getState();
  341. const currentLayout = getCurrentLayout(state);
  342. const verticalFilmstripWidth = state['features/filmstrip'].width?.current;
  343. if (currentLayout === LAYOUTS.TILE_VIEW || currentLayout === LAYOUTS.STAGE_FILMSTRIP_VIEW) {
  344. // We don't need to resize the large video since it won't be displayed and we'll resize when returning back
  345. // to stage view.
  346. return;
  347. }
  348. this.positionRemoteStatusMessages();
  349. const [ width, height ] = this._getVideoSize(containerWidth, containerHeight, verticalFilmstripWidth);
  350. if (width === 0 || height === 0) {
  351. // We don't need to set 0 for width or height since the visibility is controlled by the visibility css prop
  352. // on the largeVideoElementsContainer. Also if the width/height of the video element is 0 the attached
  353. // stream won't be played. Normally if we attach a new stream we won't resize the video element until the
  354. // stream has been played. But setting width/height to 0 will prevent the video from playing.
  355. return;
  356. }
  357. if ((containerWidth > width) || (containerHeight > height)) {
  358. this._backgroundOrientation = containerWidth > width ? ORIENTATION.LANDSCAPE : ORIENTATION.PORTRAIT;
  359. this._hideBackground = false;
  360. } else {
  361. this._hideBackground = true;
  362. }
  363. this._updateBackground();
  364. const { horizontalIndent, verticalIndent }
  365. = this.getVideoPosition(width, height, containerWidth, containerHeight, verticalFilmstripWidth);
  366. APP.store.dispatch(setLargeVideoDimensions(height, width));
  367. this.$wrapper.animate({
  368. width,
  369. height,
  370. top: verticalIndent,
  371. bottom: verticalIndent,
  372. left: horizontalIndent,
  373. right: horizontalIndent
  374. }, {
  375. queue: false,
  376. duration: animate ? 500 : 0
  377. });
  378. }
  379. /**
  380. * Removes a function from the known subscribers of video element resize
  381. * events.
  382. *
  383. * @param {Function} callback - The callback to remove from known
  384. * subscribers of video resize events.
  385. * @returns {void}
  386. */
  387. removeResizeListener(callback) {
  388. this._resizeListeners.delete(callback);
  389. }
  390. /**
  391. * Update video stream.
  392. * @param {string} userID
  393. * @param {JitsiTrack?} stream new stream
  394. * @param {string} videoType video type
  395. */
  396. setStream(userID, stream, videoType) {
  397. this.userId = userID;
  398. if (this.stream === stream && !stream?.forceStreamToReattach) {
  399. // Handles the use case for the remote participants when the
  400. // videoType is received with delay after turning on/off the
  401. // desktop sharing.
  402. if (this.videoType !== videoType) {
  403. this.videoType = videoType;
  404. this.resizeContainer();
  405. }
  406. return;
  407. }
  408. if (stream?.forceStreamToReattach) {
  409. delete stream.forceStreamToReattach;
  410. }
  411. // detach old stream
  412. if (this.stream && this.video) {
  413. this.stream.detach(this.video);
  414. }
  415. this.stream = stream;
  416. this.videoType = videoType;
  417. if (!stream) {
  418. return;
  419. }
  420. if (this.video) {
  421. stream.attach(this.video).catch(error => {
  422. logger.error(`Attaching the remote track ${stream} has failed with `, error);
  423. });
  424. // Ensure large video gets play() called on it when a new stream is attached to it. This is necessary in the
  425. // case of Safari as autoplay doesn't kick-in automatically on Safari 15 and newer versions.
  426. browser.isWebKitBased() && this.video.play();
  427. const flipX = stream.isLocal() && this.localFlipX && !this.isScreenSharing();
  428. this.video.style.transform = flipX ? 'scaleX(-1)' : 'none';
  429. this._updateBackground();
  430. }
  431. }
  432. /**
  433. * Changes the flipX state of the local video.
  434. * @param val {boolean} true if flipped.
  435. */
  436. setLocalFlipX(val) {
  437. this.localFlipX = val;
  438. if (!this.video || !this.stream || !this.stream.isLocal() || this.isScreenSharing()) {
  439. return;
  440. }
  441. this.video.style.transform = this.localFlipX ? 'scaleX(-1)' : 'none';
  442. this._updateBackground();
  443. }
  444. /**
  445. * Check if current video stream is screen sharing.
  446. * @returns {boolean}
  447. */
  448. isScreenSharing() {
  449. return this.videoType === 'desktop';
  450. }
  451. /**
  452. * Show or hide user avatar.
  453. * @param {boolean} show
  454. */
  455. showAvatar(show) {
  456. this.avatar.style.visibility = show ? 'visible' : 'hidden';
  457. this.avatarDisplayed = show;
  458. APP.API.notifyLargeVideoVisibilityChanged(show);
  459. }
  460. /**
  461. * Show video container.
  462. */
  463. show() {
  464. return new Promise(resolve => {
  465. this.wrapperParent.style.visibility = 'visible';
  466. this.wrapperParent.classList.remove('animatedFadeOut');
  467. this.wrapperParent.classList.add('animatedFadeIn');
  468. setTimeout(() => {
  469. this._isHidden = false;
  470. this._updateBackground();
  471. resolve();
  472. }, FADE_DURATION_MS);
  473. });
  474. }
  475. /**
  476. * Hide video container.
  477. */
  478. hide() {
  479. // as the container is hidden/replaced by another container
  480. // hide its avatar
  481. this.showAvatar(false);
  482. return new Promise(resolve => {
  483. this.wrapperParent.classList.remove('animatedFadeIn');
  484. this.wrapperParent.classList.add('animatedFadeOut');
  485. setTimeout(() => {
  486. this.wrapperParent.style.visibility = 'hidden';
  487. this._isHidden = true;
  488. this._updateBackground();
  489. resolve();
  490. }, FADE_DURATION_MS);
  491. });
  492. }
  493. /**
  494. * @return {boolean} switch on dominant speaker event if on stage.
  495. */
  496. stayOnStage() {
  497. return false;
  498. }
  499. /**
  500. * Callback invoked when the video element changes dimensions.
  501. *
  502. * @private
  503. * @returns {void}
  504. */
  505. _onResize() {
  506. this._resizeListeners.forEach(callback => callback());
  507. }
  508. /**
  509. * Attaches and/or updates a React Component to be used as a background for
  510. * the large video, to display blurred video and fill up empty space not
  511. * taken up by the large video.
  512. *
  513. * @private
  514. * @returns {void}
  515. */
  516. _updateBackground() {
  517. // Do not the background display on browsers that might experience
  518. // performance issues from the presence of the background or if
  519. // explicitly disabled.
  520. if (interfaceConfig.DISABLE_VIDEO_BACKGROUND
  521. || browser.isFirefox()
  522. || browser.isWebKitBased()) {
  523. return;
  524. }
  525. ReactDOM.render(
  526. <LargeVideoBackground
  527. hidden = { this._hideBackground || this._isHidden }
  528. mirror = {
  529. this.stream
  530. && this.stream.isLocal()
  531. && this.localFlipX
  532. }
  533. orientationFit = { this._backgroundOrientation }
  534. videoElement = { this.video }
  535. videoTrack = { this.stream } />,
  536. document.getElementById('largeVideoBackgroundContainer')
  537. );
  538. }
  539. }