Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat(multi-screen): shared video as a second-screen source (#17615)

Abhay Madan722731dcfc27
diff --git a/lang/main.json b/lang/main.json
index 7bda7c5ef9..9d6cc1e0fc 100644
--- a/lang/main.json
+++ b/lang/main.json
@@ -839,6 +839,8 @@
"me": "me",
"multiScreen": {
"noParticipants": "No participants",
+ "sharedVideoError": "The shared video could not be played on this screen",
+ "sharedVideoInactive": "Share a video in the meeting to show it on the second screen",
"showOnStage": "Show {{name}} on the second screen",
"unpinFromStage": "Stop featuring {{name}} on the second screen",
"whiteboardInactive": "Open the whiteboard in the meeting to show it on the second screen",
diff --git a/react/features/multi-screen/components/SecondScreenSharedVideo.web.tsx b/react/features/multi-screen/components/SecondScreenSharedVideo.web.tsx
new file mode 100644
index 0000000000..3ebc65fe0f
--- /dev/null
+++ b/react/features/multi-screen/components/SecondScreenSharedVideo.web.tsx
@@ -0,0 +1,130 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useSelector } from 'react-redux';
+import { makeStyles } from 'tss-react/mui';
+
+import { IReduxState } from '../../app/types';
+import VideoManager from '../../shared-video/components/web/VideoManager';
+import YoutubeVideoManager from '../../shared-video/components/web/YoutubeVideoManager';
+import { isSharedVideoEnabled, isVideoPlaying } from '../../shared-video/functions';
+import logger from '../logger';
+
+/**
+ * The type of the React {@code Component} props of {@link SecondScreenSharedVideo}.
+ */
+interface IProps {
+
+ /**
+ * The id of the second-screen window this view renders into.
+ */
+ id: string;
+}
+
+/**
+ * The styles, injected into the second window via its own Emotion cache.
+ */
+const useStyles = makeStyles()(() => {
+ return {
+ container: {
+ width: '100%',
+ height: '100%',
+ backgroundColor: '#040404',
+
+ // The follower player is view-only: a local pause here would not
+ // be reflected in the meeting and would silently desync until the
+ // owner's next update.
+ pointerEvents: 'none',
+
+ // react-youtube renders the player inside a plain wrapper div;
+ // stretch it (and the player itself) to fill the window.
+ '& > div, & iframe, & video': {
+ width: '100%',
+ height: '100%'
+ }
+ },
+ placeholder: {
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: '#040404'
+ },
+ message: {
+ fontSize: 16,
+ color: 'rgba(255, 255, 255, 0.5)'
+ }
+ };
+});
+
+/**
+ * Renders the video (e.g. YouTube) shared in the meeting on a second screen.
+ * The player is the same manager the meeting window uses, mounted as a
+ * follower: it tracks the shared playback state (play/pause/seek) but never
+ * acts as the controlling player, and plays no audio; the audio stays with
+ * the main window's player. Like the whiteboard, this is the kind of
+ * non-video content a plain {@code <video>} second screen cannot host.
+ * Requires a video to be shared in the meeting; otherwise a hint is shown.
+ *
+ * @param {IProps} props - The component props.
+ * @returns {ReactElement}
+ */
+const SecondScreenSharedVideo = ({ id }: IProps) => {
+ const { classes } = useStyles();
+ const { t } = useTranslation();
+ const sharedVideoEnabled = useSelector(isSharedVideoEnabled);
+ const videoShared = useSelector(isVideoPlaying);
+ const videoUrl = useSelector((state: IReduxState) => state['features/shared-video'].videoUrl);
+ const [ failed, setFailed ] = useState(false);
+
+ // A failure belongs to the video that caused it: a newly shared one gets a
+ // fresh attempt.
+ useEffect(() => setFailed(false), [ videoUrl ]);
+
+ // The player itself cannot report this: a follower must not stop the
+ // meeting's shared video, so without this the window just stays black.
+ const onFollowerError = useCallback((code?: any) => {
+ logger.error(`Shared video failed on second screen "${id}"`, code);
+ APP.API?.notifySecondScreenError?.({ id, error: 'shared-video-error' });
+ setFailed(true);
+ }, [ id ]);
+
+ if (!sharedVideoEnabled || !videoShared || !videoUrl) {
+ return (
+ <div className = { classes.placeholder }>
+ <div className = { classes.message }>
+ { t('multiScreen.sharedVideoInactive') }
+ </div>
+ </div>
+ );
+ }
+
+ if (failed) {
+ return (
+ <div className = { classes.placeholder }>
+ <div className = { classes.message }>
+ { t('multiScreen.sharedVideoError') }
+ </div>
+ </div>
+ );
+ }
+
+ // The same manager split as the meeting's SharedVideo component: direct
+ // http(s) links get the plain <video> manager, anything else is a
+ // YouTube video id.
+ return (
+ <div className = { classes.container }>
+ { videoUrl.match(/http/)
+ ? <VideoManager
+ follower = { true }
+ onFollowerError = { onFollowerError }
+ videoId = { videoUrl } />
+ : <YoutubeVideoManager
+ follower = { true }
+ onFollowerError = { onFollowerError }
+ videoId = { videoUrl } /> }
+ </div>
+ );
+};
+
+export default SecondScreenSharedVideo;
diff --git a/react/features/multi-screen/components/SecondScreenView.web.tsx b/react/features/multi-screen/components/SecondScreenView.web.tsx
index c58fd5acd4..f20e064664 100644
--- a/react/features/multi-screen/components/SecondScreenView.web.tsx
+++ b/react/features/multi-screen/components/SecondScreenView.web.tsx
@@ -4,6 +4,7 @@ import { useSelector } from 'react-redux';
import { IReduxState } from '../../app/types';
import SecondScreenGallery from './SecondScreenGallery';
+import SecondScreenSharedVideo from './SecondScreenSharedVideo';
import SecondScreenSingle from './SecondScreenSingle';
import SecondScreenStage from './SecondScreenStage';
import SecondScreenWhiteboard from './SecondScreenWhiteboard';
@@ -27,12 +28,14 @@ interface IProps {
/**
* Routes a single second-screen window to a layout from its redux source
* descriptor. A {@code whiteboard} source renders the {@link SecondScreenWhiteboard}
- * iframe; a {@code tile} source renders the {@link SecondScreenGallery} grid; a
- * stage or participant source renders the {@link SecondScreenStage} layout
- * (featured participant plus filmstrip); any other source renders the single
- * track/avatar via {@link SecondScreenSingle}. Each layout resolves its own state,
- * so the potentially expensive {@code resolveSource} selector only runs where it is
- * needed. Portaled into the second window by {@link SecondScreenPortals}.
+ * iframe; a {@code sharedvideo} source renders the meeting's shared video via
+ * {@link SecondScreenSharedVideo}; a {@code tile} source renders the
+ * {@link SecondScreenGallery} grid; a stage or participant source renders the
+ * {@link SecondScreenStage} layout (featured participant plus filmstrip); any
+ * other source renders the single track/avatar via {@link SecondScreenSingle}.
+ * Each layout resolves its own state, so the potentially expensive
+ * {@code resolveSource} selector only runs where it is needed. Portaled into
+ * the second window by {@link SecondScreenPortals}.
*
* @param {IProps} props - The component props.
* @returns {ReactElement}
@@ -44,6 +47,13 @@ const SecondScreenView = ({ id, win }: IProps) => {
return <SecondScreenWhiteboard />;
}
+ if (source?.role === 'sharedvideo') {
+ return (
+ <SecondScreenSharedVideo
+ id = { id } />
+ );
+ }
+
if (source?.role === 'tile') {
return (
<SecondScreenGallery
diff --git a/react/features/multi-screen/functions.web.ts b/react/features/multi-screen/functions.web.ts
index 4f90f68c22..3062ee6ebb 100644
--- a/react/features/multi-screen/functions.web.ts
+++ b/react/features/multi-screen/functions.web.ts
@@ -1,6 +1,7 @@
import createCache, { EmotionCache } from '@emotion/cache';
import { IReduxState, IStore } from '../app/types';
+import { getURLWithoutParams } from '../base/connection/utils';
import { MEDIA_TYPE, VIDEO_TYPE } from '../base/media/constants';
import { getParticipantById, isScreenShareParticipant } from '../base/participants/functions';
import { IParticipant } from '../base/participants/types';
@@ -34,6 +35,29 @@ const SECOND_SCREEN_CACHE_KEY = 'secondscreen';
const SECOND_SCREEN_FONT_FAMILY
= '-apple-system, BlinkMacSystemFont, open_sanslight, \'Helvetica Neue\', Helvetica, Arial, sans-serif';
+/**
+ * How long to wait for a second-screen window to load its shell page before
+ * giving up on it and closing it.
+ */
+const SECOND_SCREEN_LOAD_TIMEOUT = 10000;
+
+/**
+ * How often the load wait re-checks whether the window was closed. A window
+ * closed mid-load fires no {@code load} event, so without polling the wait would
+ * only end on the timeout above.
+ */
+const SECOND_SCREEN_LOAD_POLL_INTERVAL = 250;
+
+/**
+ * The name of the {@code meta} marker carried by the shell page (see
+ * {@link getSecondScreenPageUrl}). A {@code load} event only says that
+ * *something* was served, so the marker is what tells the shell apart from a 404
+ * body, an SSO/CDN redirect landing, or (in dev) a proxied response from the
+ * dev-server target. Without it the handle would be built on that document and
+ * the portal root would silently paint over it.
+ */
+const SECOND_SCREEN_MARKER = 'jitsi-second-screen';
+
/**
* The live, non-serializable handle backing a single second-screen window. It is
* stored on the redux entry (typed opaquely there as {@code unknown} because the
@@ -191,6 +215,29 @@ export function getGalleryGridDimensions(count: number, maxColumns: number): { c
return { columns, rows };
}
+/**
+ * Builds the URL of the static shell page a second-screen window loads
+ * ({@code static/secondScreen.html}). Derived from the canonical meeting
+ * location the same way the whiteboard page URL is, so tenant paths keep
+ * working; falls back to {@code window.location} before the connection is up.
+ *
+ * The window loads a real same-origin page instead of {@code about:blank}
+ * because embeds rendered inside it (e.g. the YouTube shared-video player)
+ * require the embedding page to send a valid referrer, which an
+ * {@code about:blank} document cannot (YouTube fails with error 153).
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {string}
+ */
+function getSecondScreenPageUrl(state: IReduxState): string {
+ const locationURL = state['features/base/connection'].locationURL;
+ const href = locationURL
+ ? getURLWithoutParams(locationURL).href
+ : `${window.location.origin}${window.location.pathname}`;
+
+ return `${href.substring(0, href.lastIndexOf('/'))}/static/secondScreen.html`;
+}
+
/**
* Computes the {@code window.open} features string, placing the window on a
* physical screen via the Window Management API. Rejects if the API is
@@ -209,6 +256,122 @@ async function computeFeatures(screenId?: number): Promise<string> {
return `popup,left=${target.left},top=${target.top},width=${target.width},height=${target.height}`;
}
+/**
+ * Whether the document currently in a second-screen window is the shell page,
+ * identified by its {@code meta} marker (see {@link SECOND_SCREEN_MARKER}) rather
+ * than by its URL: the URL is only what was requested, while the marker is proof
+ * of what was actually served. Also covers the initial empty document, which
+ * carries no marker.
+ *
+ * @param {Window} win - The opened window.
+ * @returns {boolean}
+ */
+function hasShellMarker(win: Window): boolean {
+ try {
+ return Boolean(win.document.querySelector(`meta[name="${SECOND_SCREEN_MARKER}"]`));
+ } catch (_e) {
+ // Unreadable document: mid-navigation, or cross-origin after a redirect
+ // of the shell URL, which makes every document access throw.
+ return false;
+ }
+}
+
+/**
+ * The URL a second-screen window actually ended up on, for diagnostics, or
+ * {@code undefined} when it cannot be read (a cross-origin document).
+ *
+ * @param {Window} win - The opened window.
+ * @returns {string | undefined}
+ */
+function readWindowLocation(win: Window): string | undefined {
+ try {
+ return win.location.href;
+ } catch (_e) {
+ return undefined;
+ }
+}
+
+/**
+ * Whether a second-screen window has already loaded its shell page, in which
+ * case waiting for its {@code load} event would never resolve (the event has
+ * already fired). Happens when a window is opened again for an id whose window
+ * is still open, since {@code window.open} reuses the window with the same name.
+ *
+ * @param {Window} win - The opened window.
+ * @returns {boolean}
+ */
+function isShellPageLoaded(win: Window): boolean {
+ try {
+ return win.document.readyState === 'complete' && hasShellMarker(win);
+ } catch (_e) {
+ // Mid-navigation (or an unreadable document); treat it as not loaded and wait.
+ return false;
+ }
+}
+
+/**
+ * How a wait for a second-screen window's shell page ended: the shell loaded,
+ * the window was closed while it was loading, the load timed out, or something
+ * other than the shell page was served. They are reported differently: only the
+ * last two are errors, and a window the user closed mid-load is the same user
+ * action as closing it a moment later, so it must produce the same event.
+ */
+type SecondScreenLoadResult = 'loaded' | 'closed' | 'timeout' | 'wrong-page';
+
+/**
+ * Waits for a freshly opened second-screen window to load its shell page (see
+ * {@link getSecondScreenPageUrl}), so the handle (root, Emotion cache,
+ * listeners) is built on the real document and not wiped by the navigation. The
+ * Window object is reused for this first navigation, so the listener attached
+ * here survives it and fires on the page load.
+ *
+ * Resolves with how the wait ended (see {@link SecondScreenLoadResult}). A
+ * window closed mid-load, or a navigation that stalls, fires no {@code load} at
+ * all, so the wait is bounded by a poll for {@code win.closed} and a timeout.
+ * Without them the promise would stay pending forever: the caller's
+ * {@code .catch} cannot fire, the redux entry keeps a source with no handle that
+ * nothing reconciles, and a window that did open is stranded on the external
+ * display with no handle in state for anything to close it by. A {@code load}
+ * that delivered something other than the shell page is reported separately,
+ * since the event fires for any served response.
+ *
+ * @param {Window} win - The opened window.
+ * @returns {Promise<SecondScreenLoadResult>}
+ */
+function awaitSecondScreenLoad(win: Window): Promise<SecondScreenLoadResult> {
+ if (isShellPageLoaded(win)) {
+ return Promise.resolve('loaded');
+ }
+
+ return new Promise<SecondScreenLoadResult>(resolve => {
+ let poll = 0;
+ let timeout = 0;
+ let settled = false;
+
+ const finish = (result: SecondScreenLoadResult) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ window.clearInterval(poll);
+ window.clearTimeout(timeout);
+ resolve(result);
+ };
+
+ // The marker is checked here, on load, rather than by the caller: this is
+ // the document the handle would be built on, and a later navigation
+ // (which nothing else triggers) would not change the verdict.
+ win.addEventListener('load', () => finish(hasShellMarker(win) ? 'loaded' : 'wrong-page'), { once: true });
+
+ poll = window.setInterval(() => {
+ if (win.closed) {
+ finish('closed');
+ }
+ }, SECOND_SCREEN_LOAD_POLL_INTERVAL);
+ timeout = window.setTimeout(() => finish('timeout'), SECOND_SCREEN_LOAD_TIMEOUT);
+ });
+}
+
/**
* Builds the (empty) second-screen document: a full-bleed root on black that
* React portals the window's content into. Uses element styles (not a
@@ -307,6 +470,52 @@ function handleWindowClosed(store: IStore, id: string) {
store.dispatch(removeSecondScreen(id));
}
+/**
+ * The ids whose windows are currently being opened, i.e. the calls that are past
+ * the handle check below but have not stored a handle yet.
+ */
+const opening = new Set<string>();
+
+/**
+ * Tears down a second-screen open that failed: closes the window if one is still
+ * open, tells the embedder why, and drops the redux entry. Every failure path
+ * runs all three, so none of them can leave a window on the external display
+ * with no handle in state (nothing else would be able to close it, not even the
+ * end of the conference) or an entry holding a source with no window.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} id - The window id.
+ * @param {string} error - The error reported to the embedder.
+ * @param {Window} win - The window to close, if it was opened at all.
+ * @returns {void}
+ */
+function failSecondScreenOpen(store: IStore, id: string, error: string, win?: Window | null) {
+ if (win && !win.closed) {
+ win.close();
+ }
+
+ APP.API?.notifySecondScreenError?.({ id, error });
+ store.dispatch(removeSecondScreen(id));
+}
+
+/**
+ * Handles an unexpected rejection from {@link openOrUpdateSecondScreen}, which is
+ * otherwise all-catching. Reading the popup's document can throw now that it
+ * loads a real page instead of {@code about:blank} (a cross-origin redirect of
+ * the shell URL makes every access raise a {@code SecurityError}), so this runs
+ * the same teardown as the handled failures rather than only logging, which would
+ * land right back on the orphaned-window-plus-inert-entry state.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} id - The window id.
+ * @param {any} e - The error.
+ * @returns {void}
+ */
+export function handleSecondScreenOpenError(store: IStore, id: string, e: any) {
+ logger.error(`Failed to open second screen "${id}"`, e);
+ failSecondScreenOpen(store, id, 'window-setup-failed', getHandle(store.getState(), id)?.win);
+}
+
/**
* Opens a new second-screen window (or updates an existing one) to render its
* configured source. The window is placed on a physical screen via the Window
@@ -333,6 +542,40 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen
return;
}
+ // A second request for the same id can arrive while the first one is still
+ // opening its window: the handle above is the only other reentrancy guard and
+ // it stays empty until the page has loaded. Letting a second call through
+ // would reach window.open with the same window name and re-navigate (or, on
+ // the initial empty document, share) the window the first call is building
+ // on, which orphans load listeners, duplicates roots and pagehide listeners,
+ // and can close a window that was just set up. Nothing is lost by returning:
+ // the source lives in redux, so the open already in flight picks up the
+ // newest one when it applies it at the end. A screenId that changed in the
+ // meantime is ignored, exactly as it is for a window that is already open.
+ if (opening.has(id)) {
+ return;
+ }
+
+ opening.add(id);
+
+ try {
+ await openSecondScreenWindow(store, id, screenId);
+ } finally {
+ opening.delete(id);
+ }
+}
+
+/**
+ * Opens and sets up the window for an id, having established that it has no live
+ * window and no other open in flight (see {@link openOrUpdateSecondScreen}).
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} id - The window id.
+ * @param {number} screenId - Optional target screen index.
+ * @returns {Promise<void>}
+ */
+async function openSecondScreenWindow(store: IStore, id: string, screenId?: number): Promise<void> {
+
// If a previous window was closed without notifying us, its handle is
// overwritten below and React unmounts its portal content (stopping the cloned
// track and its Emotion cache) on its own, so there is nothing to tear down.
@@ -343,27 +586,91 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen
features = await computeFeatures(screenId);
} catch (e) {
logger.warn(`Window Management API unavailable; cannot place second-screen window "${id}"`, e);
- APP.API?.notifySecondScreenError?.({ id, error: 'window-management-unavailable' });
- store.dispatch(removeSecondScreen(id));
+ failSecondScreenOpen(store, id, 'window-management-unavailable');
return;
}
- const win = window.open('', `jitsiSecondScreen_${id}`, features);
+ const url = getSecondScreenPageUrl(store.getState());
+ const win = window.open(url, `jitsiSecondScreen_${id}`, features);
if (!win) {
logger.warn(`Failed to open second-screen window "${id}" (popup blocked?)`);
- APP.API?.notifySecondScreenError?.({ id, error: 'popup-blocked' });
+ failSecondScreenOpen(store, id, 'popup-blocked');
+
+ return;
+ }
+
+ // Wait for the shell page to replace the popup's initial empty document
+ // before building the handle on it.
+ const result = win.closed ? 'closed' : await awaitSecondScreenLoad(win);
+
+ if (result === 'closed' || win.closed) {
+
+ // The user closed the popup while it was loading. That is the same action
+ // as closing it a moment later, so it reports the same event rather than
+ // an error, and there is no window left to close.
+ logger.debug(`Second-screen window "${id}" was closed while loading`);
store.dispatch(removeSecondScreen(id));
+ APP.API?.notifySecondScreenClosed?.({ id });
return;
}
- const handle: ISecondScreenHandle = {
- cache: createCache({ container: win.document.head, key: SECOND_SCREEN_CACHE_KEY }),
- root: buildWindow(win),
- win
- };
+ if (result !== 'loaded') {
+
+ // Close the window on the way out: a navigation that stalled, or one that
+ // served something other than the shell page, still leaves a window on the
+ // external display, and it never reaches state, so nothing else would ever
+ // be able to close it. Log where it actually ended up: the requested URL
+ // says nothing about what a proxy, a redirect or a 404 returned.
+ if (result === 'timeout') {
+ logger.warn(`Second-screen window "${id}" did not load "${url}" within `
+ + `${SECOND_SCREEN_LOAD_TIMEOUT}ms`);
+ } else {
+ logger.warn(`Second-screen window "${id}" loaded "${readWindowLocation(win) ?? '<unreadable>'}" `
+ + `instead of the shell page "${url}"`);
+ }
+
+ failSecondScreenOpen(store, id, 'window-load-failed', win);
+
+ return;
+ }
+
+ // A removal (or a conference end) can land while the window is loading. Its
+ // handle is not in state yet, so closeSecondScreenHandle had nothing to
+ // close: close the window here instead of building a handle for an entry
+ // that is gone, which the reducer would drop anyway. Everything from here to
+ // setSecondScreenWindow is synchronous, so no dispatch can interleave.
+ if (!store.getState()['features/multi-screen'].screens[id]) {
+ win.close();
+ APP.API?.notifySecondScreenClosed?.({ id });
+
+ return;
+ }
+
+ let handle: ISecondScreenHandle;
+
+ try {
+ handle = {
+ cache: createCache({ container: win.document.head, key: SECOND_SCREEN_CACHE_KEY }),
+ root: buildWindow(win),
+ win
+ };
+ } catch (e) {
+
+ // Reading the popup's document can throw now that it loads a real page
+ // instead of about:blank: a cross-origin redirect of the shell URL makes
+ // head/body raise a SecurityError. The marker check above already turns
+ // most of those into 'wrong-page', so this is the last resort for one that
+ // still gets here, and it tears down rather than leaving a live window
+ // behind an entry with no handle.
+ logger.warn(`Could not build the second-screen document for "${id}" at `
+ + `"${readWindowLocation(win) ?? '<unreadable>'}"`, e);
+ failSecondScreenOpen(store, id, 'window-setup-failed', win);
+
+ return;
+ }
store.dispatch(setSecondScreenWindow(id, handle));
win.addEventListener('pagehide', () => handleWindowClosed(store, id), { once: true });
diff --git a/react/features/multi-screen/middleware.web.ts b/react/features/multi-screen/middleware.web.ts
index a279c78826..b1b87c3d5f 100644
--- a/react/features/multi-screen/middleware.web.ts
+++ b/react/features/multi-screen/middleware.web.ts
@@ -4,8 +4,13 @@ import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
import { REMOVE_SECOND_SCREEN, RESET_SECOND_SCREENS, SET_SECOND_SCREEN } from './actionTypes';
import { resetSecondScreens } from './actions.web';
-import { closeAllSecondScreens, closeSecondScreenHandle, getHandle, openOrUpdateSecondScreen } from './functions.web';
-import logger from './logger';
+import {
+ closeAllSecondScreens,
+ closeSecondScreenHandle,
+ getHandle,
+ handleSecondScreenOpenError,
+ openOrUpdateSecondScreen
+} from './functions.web';
import './subscriber.web';
@@ -38,7 +43,7 @@ MiddlewareRegistry.register((store: IStore) => {
const result = next(action);
openOrUpdateSecondScreen(store, action.id, action.screenId)
- .catch(e => logger.error('Failed to open second screen', e));
+ .catch(e => handleSecondScreenOpenError(store, action.id, e));
return result;
}
diff --git a/react/features/multi-screen/types.ts b/react/features/multi-screen/types.ts
index 0ff623befd..c3b84b481c 100644
--- a/react/features/multi-screen/types.ts
+++ b/react/features/multi-screen/types.ts
@@ -19,9 +19,10 @@ export interface ISecondScreenSource {
/**
* What the window shows: the active-speaker stage, the current screenshare,
- * a tile grid of every participant, or the shared whiteboard.
+ * a tile grid of every participant, the shared whiteboard, or the video
+ * (e.g. YouTube) shared in the meeting.
*/
- role?: 'stage' | 'screenshare' | 'tile' | 'whiteboard';
+ role?: 'stage' | 'screenshare' | 'tile' | 'whiteboard' | 'sharedvideo';
}
/**
diff --git a/react/features/shared-video/components/web/AbstractVideoManager.ts b/react/features/shared-video/components/web/AbstractVideoManager.ts
index bda9eb6fe3..d903135740 100644
--- a/react/features/shared-video/components/web/AbstractVideoManager.ts
+++ b/react/features/shared-video/components/web/AbstractVideoManager.ts
@@ -102,12 +102,34 @@ export interface IProps {
*/
_videoUrl?: string;
+ /**
+ * Whether this player is a passive follower (e.g. on a second-screen
+ * window): it follows the shared playback state but never acts as the
+ * controlling player, even when the local participant owns the shared
+ * video, reports no analytics or status updates, and plays no audio (the
+ * audio stays with the main window's player).
+ */
+ follower?: boolean;
+
+ /**
+ * Called when a follower player fails. A follower must not tear down the
+ * meeting's shared video, so its host is notified instead and surfaces the
+ * failure in place of the (black) player. Ignored for a non-follower.
+ */
+ onFollowerError?: (code?: any) => void;
+
/**
* The video id.
*/
videoId: string;
}
+/**
+ * The props a manager takes from its host, as opposed to the ones it maps from
+ * the redux state below.
+ */
+type IOwnProps = Pick<IProps, 'follower' | 'onFollowerError' | 'videoId'>;
+
/**
* Manager of shared video.
*/
@@ -126,7 +148,9 @@ class AbstractVideoManager extends PureComponent<IProps> {
this.throttledFireUpdateSharedVideoEvent = throttle(this.fireUpdateSharedVideoEvent.bind(this), 5000);
// selenium tests handler
- window._sharedVideoPlayer = this;
+ if (!props.follower) {
+ window._sharedVideoPlayer = this;
+ }
}
/**
@@ -135,8 +159,12 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @inheritdoc
*/
override componentDidMount() {
- this.props._dockToolbox(true);
- this.processUpdatedProps();
+ if (this.props.follower) {
+ this.syncFollower();
+ } else {
+ this.props._dockToolbox(true);
+ this.processUpdatedProps();
+ }
}
/**
@@ -145,9 +173,9 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @inheritdoc
*/
override componentDidUpdate(prevProps: IProps) {
- const { _videoUrl } = this.props;
+ const { _videoUrl, follower } = this.props;
- if (prevProps._videoUrl !== _videoUrl) {
+ if (!follower && prevProps._videoUrl !== _videoUrl) {
sendAnalytics(createEvent('started'));
}
@@ -160,13 +188,14 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @inheritdoc
*/
override componentWillUnmount() {
- sendAnalytics(createEvent('stopped'));
+ if (!this.props.follower) {
+ sendAnalytics(createEvent('stopped'));
+ this.props._dockToolbox(false);
+ }
if (this.dispose) {
this.dispose();
}
-
- this.props._dockToolbox(false);
}
/**
@@ -175,7 +204,7 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @returns {void}
*/
processUpdatedProps() {
- const { _status, _time, _isOwner, _muted } = this.props;
+ const { _status, _time, _isOwner, _muted, follower } = this.props;
if (_isOwner) {
return;
@@ -197,7 +226,14 @@ class AbstractVideoManager extends PureComponent<IProps> {
}
}
- if (this.isMuted() !== _muted) {
+ if (follower) {
+ // A follower plays no audio (the audio stays with the main
+ // window's player), so it is kept muted instead of following the
+ // shared muted state.
+ if (!this.isMuted()) {
+ this.mute();
+ }
+ } else if (this.isMuted() !== _muted) {
if (_muted) {
this.mute();
} else {
@@ -206,6 +242,29 @@ class AbstractVideoManager extends PureComponent<IProps> {
}
}
+ /**
+ * Starts a follower player in sync with the meeting's shared state. A
+ * follower must not start playing a video the meeting has paused: doing so
+ * desyncs silently, because a paused video sends no further status updates
+ * and nothing would ever correct it. Everything else (seeking to the shared
+ * position, staying muted) is left to processUpdatedProps.
+ *
+ * Called both on mount and, for players created asynchronously (the YouTube
+ * iframe API), once the player is ready; it is safe to run twice.
+ *
+ * @returns {void}
+ */
+ syncFollower() {
+ // Not PLAYING vs. PAUSED: a video that was just shared is in the
+ // "start" state, which processUpdatedProps does not act on, and a
+ // follower opened at that moment should play.
+ if (this.props._status !== PLAYBACK_STATUSES.PAUSED) {
+ this.play();
+ }
+
+ this.processUpdatedProps();
+ }
+
/**
* Handle video error.
*
@@ -213,8 +272,28 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @returns {void}
*/
onError(e?: any) {
- logger.error('Error in the video player', e?.data,
+ const { follower, onFollowerError, videoId } = this.props;
+
+ // The YouTube API reports its error code in `data`; a <video> element
+ // fires a DOM event instead, whose target carries the MediaError and the
+ // source that actually failed to load.
+ const code = e?.data ?? e?.target?.error?.code;
+ const src = e?.target?.currentSrc;
+
+ logger.error(`Error in the ${follower ? 'follower ' : ''}video player for "${videoId}"`,
+ code, src ?? '',
e?.data ? 'Check error code at https://developers.google.com/youtube/iframe_api_reference#onError' : '');
+
+ // An error in a follower player must not tear down the shared video
+ // for the whole meeting (stopSharedVideo resets it when the local
+ // participant is the owner); its host reports it instead, so the
+ // failure does not read as an unexplained black screen.
+ if (follower) {
+ onFollowerError?.(code);
+
+ return;
+ }
+
this.props._stopSharedVideo();
this.props._displayWarning();
}
@@ -225,6 +304,12 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @returns {void}
*/
onPlay() {
+ // A follower only observes: no analytics, no status updates, no
+ // mic-mute side effects.
+ if (this.props.follower) {
+ return;
+ }
+
this.smartAudioMute();
sendAnalytics(createEvent('play'));
this.fireUpdateSharedVideoEvent();
@@ -236,6 +321,10 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @returns {void}
*/
onPause() {
+ if (this.props.follower) {
+ return;
+ }
+
sendAnalytics(createEvent('paused'));
this.fireUpdateSharedVideoEvent();
}
@@ -246,6 +335,10 @@ class AbstractVideoManager extends PureComponent<IProps> {
* @returns {void}
*/
onVolumeChange() {
+ if (this.props.follower) {
+ return;
+ }
+
const volume = this.getVolume();
const muted = this.isMuted();
@@ -436,9 +529,10 @@ export default AbstractVideoManager;
* Maps part of the Redux store to the props of this component.
*
* @param {Object} state - The Redux state.
+ * @param {Object} ownProps - The component's own props.
* @returns {IProps}
*/
-export function _mapStateToProps(state: IReduxState) {
+export function _mapStateToProps(state: IReduxState, ownProps: IOwnProps) {
const { ownerId, status, time, videoUrl, muted } = state['features/shared-video'];
const localParticipant = getLocalParticipant(state);
const _isLocalAudioMuted = isLocalTrackMuted(state['features/base/tracks'], MEDIA_TYPE.AUDIO);
@@ -446,7 +540,12 @@ export function _mapStateToProps(state: IReduxState) {
return {
_conference: getCurrentConference(state),
_isLocalAudioMuted,
- _isOwner: ownerId === localParticipant?.id,
+
+ // A follower never acts as the controlling player, even when the
+ // local participant owns the shared video: ownership stays with the
+ // main window's player, and the follower tracks the shared state like
+ // any remote participant.
+ _isOwner: !ownProps.follower && ownerId === localParticipant?.id,
_muted: muted,
_ownerId: ownerId,
_status: status,
diff --git a/react/features/shared-video/components/web/VideoManager.tsx b/react/features/shared-video/components/web/VideoManager.tsx
index 45b4196c6f..13c143c81f 100644
--- a/react/features/shared-video/components/web/VideoManager.tsx
+++ b/react/features/shared-video/components/web/VideoManager.tsx
@@ -143,13 +143,22 @@ class VideoManager extends AbstractVideoManager {
* @returns {void}
*/
getPlayerOptions() {
- const { _isOwner, videoId } = this.props;
+ const { _isOwner, follower, videoId } = this.props;
let options: any = {
- autoPlay: true,
+ // A follower starts itself from the meeting's shared state
+ // (see syncFollower), so it must not autoplay a paused video.
+ autoPlay: !follower,
src: videoId,
controls: _isOwner,
- onError: () => this.onError(),
+
+ // A follower plays no audio; starting it muted also keeps the
+ // browser from blocking the autoplay.
+ muted: follower,
+ // Forwarded rather than dropped: the event's target carries the
+ // MediaError and the resolved source, which is the only diagnostic
+ // behind the message a follower shows on a second screen.
+ onError: (e: any) => this.onError(e),
onPlay: () => this.onPlay(),
onVolumeChange: () => this.onVolumeChange()
};
diff --git a/react/features/shared-video/components/web/YoutubeVideoManager.tsx b/react/features/shared-video/components/web/YoutubeVideoManager.tsx
index 8eecf90db2..478cc12583 100644
--- a/react/features/shared-video/components/web/YoutubeVideoManager.tsx
+++ b/react/features/shared-video/components/web/YoutubeVideoManager.tsx
@@ -93,7 +93,12 @@ class YoutubeVideoManager extends AbstractVideoManager {
* @returns {void}
*/
override seek(time: number) {
- return this.player?.seekTo(time);
+ // allowSeekAhead, so a seek outside the buffered range is honoured
+ // instead of being deferred. A follower is the first caller to reach this
+ // on a player that has not started (opened while the meeting's video is
+ // paused), where the default would leave it on the thumbnail rather than
+ // at the shared position.
+ return this.player?.seekTo(time, true);
}
/**
@@ -167,7 +172,7 @@ class YoutubeVideoManager extends AbstractVideoManager {
* @returns {void}
*/
onPlayerReady = (event: any) => {
- const { _isOwner } = this.props;
+ const { _isOwner, follower } = this.props;
this.player = event.target;
@@ -179,6 +184,15 @@ class YoutubeVideoManager extends AbstractVideoManager {
this.player.addEventListener('onVideoProgress', this.throttledFireUpdateSharedVideoEvent);
}
+ if (follower) {
+ // The player only exists now, so this is where a follower first
+ // gets to reconcile with the meeting's shared state; it also stays
+ // muted, since a follower plays no audio.
+ this.syncFollower();
+
+ return;
+ }
+
this.play();
// sometimes youtube can get muted state from previous videos played in the browser
@@ -189,7 +203,7 @@ class YoutubeVideoManager extends AbstractVideoManager {
};
getPlayerOptions = () => {
- const { _isOwner, videoId } = this.props;
+ const { _isOwner, follower, videoId } = this.props;
const showControls = _isOwner ? 1 : 0;
const options = {
@@ -202,7 +216,11 @@ class YoutubeVideoManager extends AbstractVideoManager {
'fs': '0',
'autoplay': 0,
'controls': showControls,
- 'rel': 0
+ 'rel': 0,
+
+ // A follower plays no audio; starting it muted also keeps
+ // the browser from blocking its (scripted) playback.
+ ...follower ? { 'mute': 1 } : {}
}
},
onError: (e: any) => this.onError(e),
diff --git a/static/secondScreen.html b/static/secondScreen.html
new file mode 100644
index 0000000000..97c2cbe6b5
--- /dev/null
+++ b/static/secondScreen.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<html style="height: 100%;">
+
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <!--
+ Marks this document as the second-screen shell. The meeting window checks
+ for it before building anything in the popup, because a load event only
+ means that something was served: a 404 body, a redirect landing or a
+ dev-server proxy response would otherwise be treated as this page and
+ silently painted over. Keep in sync with SECOND_SCREEN_MARKER in
+ react/features/multi-screen/functions.web.ts.
+ -->
+ <meta name="jitsi-second-screen" content="1">
+ <title>Jitsi Meet</title>
+</head>
+
+<body style="margin: 0; height: 100%; background: #000; overflow: hidden;">
+ <!--
+ Intentionally empty: this page is the shell for a second-screen window
+ (react/features/multi-screen). The meeting window portals the window's
+ content into it. It exists so the popup has a real same-origin URL
+ instead of about:blank: embeds rendered inside the window (e.g. the
+ YouTube shared-video player) require the page to send a valid referrer,
+ which an about:blank window cannot (YouTube fails with error 153).
+ -->
+</body>
+
+</html>
diff --git a/webpack.config.js b/webpack.config.js
index 04097afe6e..600a35d247 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -70,6 +70,12 @@ function devServerProxyBypass({ path }) {
tpath = tpath.replace(/\/v1\/_cdn\/[^/]+\//, '/');
}
+ // A page opened from a tenant meeting URL asks for its static assets under
+ // that tenant (e.g. /tenant/static/secondScreen.html), which would otherwise
+ // be proxied to the dev target and serve that deployment's copy, or a 404 for
+ // a file that only exists locally.
+ tpath = tpath.replace(/^\/[^/]+\/static\//, '/static/');
+
if (tpath.startsWith('/css/')
|| tpath.startsWith('/doc/')
|| tpath.startsWith('/fonts/')