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: iframe document pip on tab switch (#17587)

Bandhan Majumder52d01b705fcd
diff --git a/Makefile b/Makefile
index b83da31f70..c29a1ee369 100644
--- a/Makefile
+++ b/Makefile
@@ -49,6 +49,8 @@ deploy-appbundle:
$(BUILD_DIR)/external_api.min.js.map \
$(BUILD_DIR)/alwaysontop.min.js \
$(BUILD_DIR)/alwaysontop.min.js.map \
+ $(BUILD_DIR)/documentpip.min.js \
+ $(BUILD_DIR)/documentpip.min.js.map \
$(BUILD_DIR)/face-landmarks-worker.min.js \
$(BUILD_DIR)/face-landmarks-worker.min.js.map \
$(BUILD_DIR)/noise-suppressor-worklet.min.js \
diff --git a/modules/API/API.js b/modules/API/API.js
index 3560178636..6fe18ad524 100755
--- a/modules/API/API.js
+++ b/modules/API/API.js
@@ -108,7 +108,14 @@ import {
open as openParticipantsPane
} from '../../react/features/participants-pane/actions';
import { getParticipantsPaneOpen } from '../../react/features/participants-pane/functions';
-import { hidePiP, showPiP } from '../../react/features/pip/actions';
+import {
+ handleHostDocumentPiPOpenFailed,
+ handleHostDocumentPiPOpened,
+ handleHostDocumentPiPSignal,
+ handleHostDocumentPiPWindowClosed,
+ hidePiP,
+ showPiP
+} from '../../react/features/pip/actions';
import {
setStartRecordingIntent,
setStopRecordingIntent,
@@ -1000,6 +1007,18 @@ function initCommands() {
},
'hide-pip': () => {
APP.store.dispatch(hidePiP());
+ },
+ 'document-pip-opened': () => {
+ APP.store.dispatch(handleHostDocumentPiPOpened());
+ },
+ 'document-pip-open-failed': () => {
+ APP.store.dispatch(handleHostDocumentPiPOpenFailed());
+ },
+ 'document-pip-closed': () => {
+ APP.store.dispatch(handleHostDocumentPiPWindowClosed());
+ },
+ 'document-pip-signal': signal => {
+ APP.store.dispatch(handleHostDocumentPiPSignal(signal));
}
};
transport.on('event', ({ data, name }) => {
@@ -2419,6 +2438,37 @@ class API {
});
}
+ /**
+ * Requests that the embedding page close Document PiP.
+ *
+ * @returns {void}
+ */
+ notifyDocumentPiPClose() {
+ this._sendEvent({ name: '_document-pip-close' });
+ }
+
+ /**
+ * Requests a host-owned Document PiP window.
+ *
+ * @returns {void}
+ */
+ notifyDocumentPiPRequested() {
+ this._sendEvent({ name: '_document-pip-requested' });
+ }
+
+ /**
+ * Sends one ordered WebRTC signal to the embedding page.
+ *
+ * @param {Object} signal - Offer, answer, candidate, mute, restart, or stop signal.
+ * @returns {void}
+ */
+ notifyDocumentPiPSignal(signal) {
+ this._sendEvent({
+ name: '_document-pip-signal',
+ signal
+ });
+ }
+
/**
* Notify external application (if API is enabled) that Picture-in-Picture was requested.
* Used by Electron to handle PiP requests with proper user gesture context.
diff --git a/modules/API/external/external_api.js b/modules/API/external/external_api.js
index 67cd12f110..bb2df9fecf 100644
--- a/modules/API/external/external_api.js
+++ b/modules/API/external/external_api.js
@@ -2,6 +2,7 @@ import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
import EventEmitter from 'events';
import { urlObjectToString } from '../../../react/features/base/util/uri';
+import DocumentPiPController from '../../../react/features/external-api/DocumentPiPController.web';
import { isPiPEnabled } from '../../../react/features/pip/external-api.shared';
import {
PostMessageTransportBackend,
@@ -109,6 +110,7 @@ const commands = {
* events expected by jitsi-meet.
*/
const events = {
+ '_document-pip-signal': '_documentPiPSignal',
'_pip-requested': '_pipRequested',
'pip-entered': 'pipEntered',
'pip-left': 'pipLeft',
@@ -340,14 +342,15 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
this._onload = onload;
this._tmpE2EEKey = e2eeKey;
- this._isLargeVideoVisible = false;
- this._isPrejoinVideoVisible = false;
+ this._largeVideoVisible = false;
+ this._prejoinVideoVisible = false;
this._numberOfParticipants = 0;
this._participants = {};
this._myUserID = undefined;
this._onStageParticipant = undefined;
this._iAmvisitor = undefined;
this._pipConfig = configOverwrite?.pip;
+ this._documentPiPController = undefined;
this._setupListeners();
id++;
}
@@ -454,6 +457,24 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
return this._onStageParticipant;
}
+ /**
+ * Returns whether the meeting's large video is currently visible.
+ *
+ * @returns {boolean}
+ */
+ _isLargeVideoVisible() {
+ return this._largeVideoVisible;
+ }
+
+ /**
+ * Returns whether the meeting's prejoin video is currently visible.
+ *
+ * @returns {boolean}
+ */
+ _isPrejoinVideoVisible() {
+ return this._prejoinVideoVisible;
+ }
+
/**
* Getter for the large video element in Jitsi Meet.
@@ -463,7 +484,7 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
_getLargeVideo() {
const iframe = this.getIFrame();
- if (!this._isLargeVideoVisible
+ if (!this._largeVideoVisible
|| !iframe
|| !iframe.contentWindow
|| !iframe.contentWindow.document) {
@@ -481,7 +502,7 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
_getPrejoinVideo() {
const iframe = this.getIFrame();
- if (!this._isPrejoinVideoVisible
+ if (!this._prejoinVideoVisible
|| !iframe
|| !iframe.contentWindow
|| !iframe.contentWindow.document) {
@@ -555,6 +576,8 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
// Fake the iframe onload event because it's not reliable.
this._onload?.();
+ // A reloaded meeting must not keep a stale PiP window alive.
+ this._documentPiPController?.close();
break;
}
case 'video-conference-joined': {
@@ -629,7 +652,7 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
this.emit('largeVideoChanged');
break;
case 'large-video-visibility-changed':
- this._isLargeVideoVisible = data.isVisible;
+ this._largeVideoVisible = data.isVisible;
this.emit('largeVideoChanged');
break;
case 'prejoin-screen-loaded':
@@ -639,7 +662,7 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
};
break;
case 'on-prejoin-video-changed':
- this._isPrejoinVideoVisible = data.isVisible;
+ this._prejoinVideoVisible = data.isVisible;
this.emit('prejoinVideoChanged');
break;
case 'video-conference-left':
@@ -649,6 +672,15 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
case 'video-quality-changed':
this._videoQuality = data.videoQuality;
break;
+ case '_document-pip-requested':
+ this._getDocumentPiPController().open()
+ .catch(error => console.error('Document PiP open failed:', error));
+
+ return true;
+ case '_document-pip-close':
+ this._documentPiPController?.close();
+
+ return true;
case 'breakout-rooms-updated':
this.updateNumberOfParticipants(data.rooms);
break;
@@ -733,6 +765,35 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
}
}
+ /**
+ * Returns this API instance's lazily created Document PiP controller.
+ *
+ * @returns {DocumentPiPController}
+ */
+ _getDocumentPiPController() {
+ if (!this._documentPiPController) {
+ this._documentPiPController = new DocumentPiPController({
+ api: this,
+ frame: this._frame,
+ transport: this._transport,
+ windowOptions: this._pipConfig?.documentPiP?.windowOptions,
+ meetingUrl: this._url
+ });
+ }
+
+ return this._documentPiPController;
+ }
+
+ /**
+ * Sends a media-cast signal from the Document PiP renderer to the meeting iframe.
+ *
+ * @param {Object} signal - Answer, candidate, restart, or stop signal.
+ * @returns {void}
+ */
+ _sendDocumentPiPSignal(signal) {
+ this._getDocumentPiPController().sendSignal(signal);
+ }
+
/**
* Update number of participants based on all rooms.
*
@@ -949,6 +1010,7 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
*/
dispose() {
this.emit('_willDispose');
+ this._documentPiPController?.close();
this._transport.dispose();
this.removeAllListeners();
this._teardownIntersectionObserver();
@@ -1666,6 +1728,7 @@ export default class JitsiMeetExternalAPI extends EventEmitter {
* @returns {void}
*/
hidePiP() {
+ this._documentPiPController?.close();
this.executeCommand('hidePiP');
}
diff --git a/react/features/always-on-top/AlwaysOnTop.tsx b/react/features/always-on-top/AlwaysOnTop.tsx
index 5ed8b36b65..6e508bd2d2 100644
--- a/react/features/always-on-top/AlwaysOnTop.tsx
+++ b/react/features/always-on-top/AlwaysOnTop.tsx
@@ -1,12 +1,6 @@
import React, { Component } from 'react';
-// We need to reference these files directly to avoid loading things that are not available
-// in this environment (e.g. JitsiMeetJS or interfaceConfig)
-import StatelessAvatar from '../base/avatar/components/web/StatelessAvatar';
-import { getAvatarColor, getInitials } from '../base/avatar/functions';
-import { DEFAULT_ICON } from '../base/icons/svg/constants';
-
-import Toolbar from './Toolbar';
+import AlwaysOnTopView from './AlwaysOnTopView';
const { api } = window.alwaysOnTop;
@@ -162,43 +156,6 @@ export default class AlwaysOnTop extends Component<any, IState> {
this._hovered = true;
}
- /**
- * Renders display name and avatar for the on stage participant.
- *
- * @returns {ReactElement}
- */
- _renderVideoNotAvailableScreen() {
- const {
- avatarURL,
- customAvatarBackgrounds,
- displayName,
- formattedDisplayName,
- isVideoDisplayed
- } = this.state;
-
- if (isVideoDisplayed) {
- return null;
- }
-
- return (
- <div id = 'videoNotAvailableScreen'>
- <div id = 'avatarContainer'>
- <StatelessAvatar
- color = { getAvatarColor(displayName, customAvatarBackgrounds) }
- iconUser = { DEFAULT_ICON.IconUser }
- id = 'avatar'
- initials = { getInitials(displayName) }
- url = { avatarURL } />)
- </div>
- <div
- className = 'displayname'
- id = 'displayname'>
- { formattedDisplayName }
- </div>
- </div>
- );
- }
-
/**
* Sets mouse move listener and initial toolbar timeout.
*
@@ -268,14 +225,25 @@ export default class AlwaysOnTop extends Component<any, IState> {
* @returns {ReactElement}
*/
override render() {
+ const {
+ avatarURL,
+ customAvatarBackgrounds,
+ displayName,
+ formattedDisplayName,
+ isVideoDisplayed,
+ visible
+ } = this.state;
+
return (
- <div id = 'alwaysOnTop'>
- <Toolbar
- className = { this.state.visible ? 'fadeIn' : 'fadeOut' }
- onMouseOut = { this._onMouseOut }
- onMouseOver = { this._onMouseOver } />
- { this._renderVideoNotAvailableScreen() }
- </div>
+ <AlwaysOnTopView
+ avatarURL = { avatarURL }
+ customAvatarBackgrounds = { customAvatarBackgrounds }
+ displayName = { displayName }
+ formattedDisplayName = { formattedDisplayName }
+ isVideoDisplayed = { isVideoDisplayed }
+ onMouseOut = { this._onMouseOut }
+ onMouseOver = { this._onMouseOver }
+ toolbarVisible = { visible } />
);
}
}
diff --git a/react/features/always-on-top/AlwaysOnTopView.tsx b/react/features/always-on-top/AlwaysOnTopView.tsx
new file mode 100644
index 0000000000..37006693a8
--- /dev/null
+++ b/react/features/always-on-top/AlwaysOnTopView.tsx
@@ -0,0 +1,85 @@
+import React, { ReactNode } from 'react';
+
+// We need to reference these files directly to avoid loading things that are not available
+// in this environment (e.g. JitsiMeetJS or interfaceConfig).
+import StatelessAvatar from '../base/avatar/components/web/StatelessAvatar';
+import { getAvatarColor, getInitials } from '../base/avatar/functions';
+import { DEFAULT_ICON } from '../base/icons/svg/constants';
+
+import Toolbar from './Toolbar';
+
+/**
+ * Props shared by the legacy Always-on-Top and dedicated Document PiP renderers.
+ */
+interface IProps {
+ /** Participant avatar URL. */
+ avatarURL: string;
+
+ /** Optional renderer-owned media element. */
+ children?: ReactNode;
+
+ /** Configured avatar background palette. */
+ customAvatarBackgrounds: string[];
+
+ /** Participant display name used for initials and avatar hashing. */
+ displayName: string;
+
+ /** Display name formatted for presentation. */
+ formattedDisplayName: string;
+
+ /** Whether media is visible instead of the avatar fallback. */
+ isVideoDisplayed: boolean;
+
+ /** Pointer-leave handler used by toolbar visibility management. */
+ onMouseOut: (event?: React.MouseEvent) => void;
+
+ /** Pointer-enter handler used by toolbar visibility management. */
+ onMouseOver: (event?: React.MouseEvent) => void;
+
+ /** Whether the shared toolbar is visible. */
+ toolbarVisible: boolean;
+}
+
+/**
+ * Shared presentation used by the legacy and Document PiP always-on-top renderers.
+ *
+ * @returns {ReactElement}
+ */
+export default function AlwaysOnTopView({
+ avatarURL,
+ children,
+ customAvatarBackgrounds,
+ displayName,
+ formattedDisplayName,
+ isVideoDisplayed,
+ onMouseOut,
+ onMouseOver,
+ toolbarVisible
+}: IProps) {
+ return (
+ <div id = 'alwaysOnTop'>
+ { children }
+ <Toolbar
+ className = { toolbarVisible ? 'fadeIn' : 'fadeOut' }
+ onMouseOut = { onMouseOut }
+ onMouseOver = { onMouseOver } />
+ { !isVideoDisplayed && (
+ <div id = 'videoNotAvailableScreen'>
+ <div id = 'avatarContainer'>
+ <StatelessAvatar
+ color = { getAvatarColor(displayName, customAvatarBackgrounds) }
+ iconUser = { DEFAULT_ICON.IconUser }
+ id = 'avatar'
+ initials = { getInitials(displayName) }
+ url = { avatarURL } />
+ </div>
+ <div
+ className = 'displayname'
+ id = 'displayname'>
+ { formattedDisplayName }
+ </div>
+ </div>
+ ) }
+ </div>
+ );
+}
diff --git a/react/features/always-on-top/DocumentPiP.tsx b/react/features/always-on-top/DocumentPiP.tsx
new file mode 100644
index 0000000000..b2ab115834
--- /dev/null
+++ b/react/features/always-on-top/DocumentPiP.tsx
@@ -0,0 +1,329 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+
+import MediaCastReceiver from '../base/media-cast/MediaCastReceiver';
+import type { MediaCastSignal, MediaCastSignalHandler } from '../base/media-cast/types.web';
+
+import AlwaysOnTopView from './AlwaysOnTopView';
+
+/**
+ * External API instance exposed to the dedicated Document PiP window.
+ */
+const { api } = window.alwaysOnTop;
+
+/**
+ * Delay in milliseconds before hiding the PiP toolbar after pointer activity stops.
+ */
+const TOOLBAR_TIMEOUT = 4000;
+
+/**
+ * Layout applied to the React-owned video element without cropping shared content.
+ */
+const VIDEO_STYLE: React.CSSProperties = {
+ height: '100%',
+ left: 0,
+ objectFit: 'contain',
+ position: 'absolute',
+ top: 0,
+ width: '100%'
+};
+
+/**
+ * Participant metadata rendered by the shared always-on-top presentation.
+ */
+interface IParticipantState {
+ /** Participant avatar URL. */
+ avatarURL: string;
+
+ /** Configured avatar background palette. */
+ customAvatarBackgrounds: string[];
+
+ /** Participant display name used for avatar hashing. */
+ displayName: string;
+
+ /** Participant display name formatted for presentation. */
+ formattedDisplayName: string;
+}
+
+/**
+ * Signals received from the meeting iframe before the media-cast receiver is ready are buffered
+ * here and flushed once the receiver registers itself. The host forwards signals through the
+ * embedder API, which is available from the moment this bundle executes, so buffering must start
+ * at module scope rather than on React mount.
+ */
+const pendingSignals: MediaCastSignal[] = [];
+
+/**
+ * The signal handler the media-cast receiver has registered, if any.
+ */
+let receiverSignalHandler: MediaCastSignalHandler | undefined;
+
+/**
+ * Whether the API signal listener is currently registered.
+ */
+let signalBridgeRegistered = false;
+
+/**
+ * Forwards one media-cast signal to the receiver, buffering it until the receiver is ready.
+ *
+ * @param {Object} payload - Event payload received from the embedder API.
+ * @param {MediaCastSignal} payload.signal - The signal to forward.
+ * @returns {void}
+ */
+const onSignal = ({ signal }: { signal: MediaCastSignal; }) => {
+ if (receiverSignalHandler) {
+ receiverSignalHandler(signal);
+ } else {
+ pendingSignals.push(signal);
+ }
+};
+
+/**
+ * Registers the media-cast receiver's signal handler, flushing any buffered signals, and returns
+ * a function that unregisters it.
+ *
+ * @param {MediaCastSignalHandler} handler - The receiver's signal handler.
+ * @returns {Function} Unregister function.
+ */
+const registerSignalHandler = (handler: MediaCastSignalHandler): (() => void) => {
+ receiverSignalHandler = handler;
+
+ for (const signal of pendingSignals.splice(0)) {
+ handler(signal);
+ }
+
+ return () => {
+ if (receiverSignalHandler === handler) {
+ receiverSignalHandler = undefined;
+ }
+ };
+};
+
+/**
+ * Registers the API listener at most once. It is invoked at module load so signals arriving before
+ * React mounts are buffered, and again on mount to tolerate development-only remounts.
+ *
+ * @returns {void}
+ */
+const registerSignalBridge = () => {
+ if (signalBridgeRegistered) {
+ return;
+ }
+
+ signalBridgeRegistered = true;
+ api.on('_documentPiPSignal', onSignal);
+};
+
+/**
+ * Removes the API listener and clears all receiver and buffered-signal references.
+ *
+ * @returns {void}
+ */
+const cleanupSignalBridge = () => {
+ if (signalBridgeRegistered) {
+ api.removeListener('_documentPiPSignal', onSignal);
+ signalBridgeRegistered = false;
+ }
+
+ receiverSignalHandler = undefined;
+ pendingSignals.length = 0;
+};
+
+registerSignalBridge();
+
+/**
+ * Document PiP renderer backed by a media-cast receiver.
+ *
+ * @returns {ReactElement}
+ */
+export default function DocumentPiP() {
+ const [ participant, setParticipant ] = useState<IParticipantState>({
+ avatarURL: '',
+ customAvatarBackgrounds: [],
+ displayName: '',
+ formattedDisplayName: ''
+ });
+ const [ sourceVisible, setSourceVisible ] = useState(
+ () => Boolean(api._isLargeVideoVisible() || api._isPrejoinVideoVisible()));
+ const [ toolbarVisible, setToolbarVisible ] = useState(true);
+ const [ track, setTrack ] = useState<MediaStreamTrack | null>(null);
+ const [ trackMuted, setTrackMuted ] = useState(true);
+ const hoveredRef = useRef(false);
+ const toolbarTimerRef = useRef<number | undefined>(undefined);
+ const videoRef = useRef<HTMLVideoElement>(null);
+
+ const updateParticipant = useCallback(() => {
+ const userID = api._getOnStageParticipant();
+
+ setParticipant(current => ({
+ ...current,
+ avatarURL: api.getAvatarURL(userID),
+ displayName: api.getDisplayName(userID),
+ formattedDisplayName: api._getFormattedDisplayName(userID)
+ }));
+
+ setSourceVisible(Boolean(api._isLargeVideoVisible() || api._isPrejoinVideoVisible()));
+ }, []);
+
+ const scheduleToolbarHide = useCallback(() => {
+ const hideWhenIdle = () => {
+ if (hoveredRef.current) {
+ toolbarTimerRef.current = window.setTimeout(hideWhenIdle, TOOLBAR_TIMEOUT);
+ } else {
+ setToolbarVisible(false);
+ }
+ };
+
+ window.clearTimeout(toolbarTimerRef.current);
+ toolbarTimerRef.current = window.setTimeout(hideWhenIdle, TOOLBAR_TIMEOUT);
+ }, []);
+ const onMouseOut = useCallback(() => {
+ hoveredRef.current = false;
+ }, []);
+ const onMouseOver = useCallback(() => {
+ hoveredRef.current = true;
+ }, []);
+
+ useEffect(() => {
+ let active = true;
+
+ registerSignalBridge();
+
+ const receiver = new MediaCastReceiver({
+ onError: error => console.error('Document PiP receiver failed', error),
+ onSignal: signal => api._sendDocumentPiPSignal(signal),
+ onTrack: nextTrack => {
+ if (active) {
+ setTrack(nextTrack);
+ }
+ }
+ });
+ const unregister = registerSignalHandler(signal => receiver.handleSignal(signal));
+
+ return () => {
+ active = false;
+ unregister();
+ receiver.dispose();
+ cleanupSignalBridge();
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!track) {
+ setTrackMuted(true);
+
+ return;
+ }
+
+ const updateMuted = () => setTrackMuted(track.muted || track.readyState !== 'live');
+
+ track.addEventListener('mute', updateMuted);
+ track.addEventListener('unmute', updateMuted);
+ track.addEventListener('ended', updateMuted);
+ updateMuted();
+
+ return () => {
+ track.removeEventListener('mute', updateMuted);
+ track.removeEventListener('unmute', updateMuted);
+ track.removeEventListener('ended', updateMuted);
+ };
+ }, [ track ]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+
+ if (!video) {
+ return;
+ }
+
+ video.srcObject = track ? new MediaStream([ track ]) : null;
+
+ return () => {
+ video.srcObject = null;
+ };
+ }, [ track ]);
+
+ useEffect(() => {
+ const avatarChanged = ({ avatarURL, id }: { avatarURL: string; id: string; }) => {
+ if (api._getOnStageParticipant() === id) {
+ setParticipant(current => ({
+ ...current,
+ avatarURL
+ }));
+ }
+ };
+ const displayNameChanged = ({ displayname, formattedDisplayName, id }: {
+ displayname: string;
+ formattedDisplayName: string;
+ id: string;
+ }) => {
+ if (api._getOnStageParticipant() === id) {
+ setParticipant(current => ({
+ ...current,
+ displayName: displayname,
+ formattedDisplayName
+ }));
+ }
+ };
+
+ api.on('avatarChanged', avatarChanged);
+ api.on('displayNameChange', displayNameChanged);
+ api.on('largeVideoChanged', updateParticipant);
+ api.on('prejoinVideoChanged', updateParticipant);
+ api.on('videoConferenceJoined', updateParticipant);
+ updateParticipant();
+
+ api.getCustomAvatarBackgrounds()
+ .then(({ avatarBackgrounds = [] }: { avatarBackgrounds?: string[]; }) => {
+ setParticipant(current => ({
+ ...current,
+ customAvatarBackgrounds: avatarBackgrounds
+ }));
+ })
+ .catch(console.error);
+
+ return () => {
+ api.removeListener('avatarChanged', avatarChanged);
+ api.removeListener('displayNameChange', displayNameChanged);
+ api.removeListener('largeVideoChanged', updateParticipant);
+ api.removeListener('prejoinVideoChanged', updateParticipant);
+ api.removeListener('videoConferenceJoined', updateParticipant);
+ };
+ }, [ updateParticipant ]);
+
+ useEffect(() => {
+ const onMouseMove = () => {
+ setToolbarVisible(true);
+ scheduleToolbarHide();
+ };
+
+ window.addEventListener('mousemove', onMouseMove);
+ scheduleToolbarHide();
+
+ return () => {
+ window.removeEventListener('mousemove', onMouseMove);
+ window.clearTimeout(toolbarTimerRef.current);
+ };
+ }, [ scheduleToolbarHide ]);
+
+ const isVideoDisplayed = Boolean(track && !trackMuted && sourceVisible);
+
+ return (
+ <AlwaysOnTopView
+ avatarURL = { participant.avatarURL }
+ customAvatarBackgrounds = { participant.customAvatarBackgrounds }
+ displayName = { participant.displayName }
+ formattedDisplayName = { participant.formattedDisplayName }
+ isVideoDisplayed = { isVideoDisplayed }
+ onMouseOut = { onMouseOut }
+ onMouseOver = { onMouseOver }
+ toolbarVisible = { toolbarVisible }>
+ <video
+ autoPlay = { true }
+ hidden = { !isVideoDisplayed }
+ muted = { true }
+ playsInline = { true }
+ ref = { videoRef }
+ style = { VIDEO_STYLE } />
+ </AlwaysOnTopView>
+ );
+}
diff --git a/react/features/always-on-top/document-pip-index.tsx b/react/features/always-on-top/document-pip-index.tsx
new file mode 100644
index 0000000000..8998ac1f72
--- /dev/null
+++ b/react/features/always-on-top/document-pip-index.tsx
@@ -0,0 +1,41 @@
+/**
+ * Entry point for the Document PiP window renderer.
+ *
+ * Bootstraps the React tree into the PiP window document and unmounts it when
+ * the window is closed or reloaded.
+ */
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+
+import DocumentPiP from './DocumentPiP';
+
+/**
+ * React root attached to the Document PiP window document.
+ */
+const root = createRoot(document.getElementById('react') as HTMLElement);
+
+root.render(<DocumentPiP />);
+
+/**
+ * Whether the renderer has already been cleaned up.
+ */
+let cleanedUp = false;
+
+/**
+ * Unmounts the Document PiP renderer before the PiP window is closed or reloaded.
+ *
+ * @returns {void}
+ */
+const cleanup = () => {
+ if (cleanedUp) {
+ return;
+ }
+
+ cleanedUp = true;
+ window.removeEventListener('beforeunload', cleanup);
+ window.removeEventListener('pagehide', cleanup);
+ root.unmount();
+};
+
+window.addEventListener('beforeunload', cleanup);
+window.addEventListener('pagehide', cleanup);
diff --git a/react/features/base/media-cast/MediaCastReceiver.web.ts b/react/features/base/media-cast/MediaCastReceiver.web.ts
new file mode 100644
index 0000000000..1a947eca83
--- /dev/null
+++ b/react/features/base/media-cast/MediaCastReceiver.web.ts
@@ -0,0 +1,317 @@
+import {
+ type IMediaCastReceiverOptions,
+ type IReceiverSession,
+ type MediaCastSignal,
+ type MediaCastSignalHandler,
+ isMediaCastSignal
+} from './types.web';
+
+/**
+ * The subset of {@link MediaCastSignal} that carries a new SDP offer.
+ */
+type OfferSignal = Extract<MediaCastSignal, { kind: 'offer'; }>;
+
+/**
+ * Receives one media track over a plain RTCPeerConnection.
+ *
+ * The receiver owns the connection lifecycle while the caller owns the received track:
+ * the current track is surfaced through the onTrack handler and released on close. Session
+ * state is versioned by a generation counter so signals from superseded sessions are ignored.
+ */
+export default class MediaCastReceiver {
+ /**
+ * Whether the receiver has been permanently disposed and must ignore further signals.
+ */
+ private _disposed = false;
+
+ /**
+ * The media track received by the current session, if any.
+ */
+ private _currentTrack: MediaStreamTrack | null = null;
+
+ /**
+ * The generation of the most recently negotiated session.
+ */
+ private _generation = 0;
+
+ /**
+ * Whether the sender is currently transmitting a null (muted) track.
+ */
+ private _muted = false;
+
+ /**
+ * Handler invoked when an asynchronous receiving error occurs.
+ */
+ private _onError: (error: unknown) => void;
+
+ /**
+ * Handler used to forward outgoing signals to the remote peer.
+ */
+ private _onSignal: MediaCastSignalHandler;
+
+ /**
+ * Handler invoked whenever the received media track changes.
+ */
+ private _onTrack: (track: MediaStreamTrack | null) => void;
+
+ /**
+ * Optional RTCPeerConnection configuration applied to new connections.
+ */
+ private _pcConfig?: RTCConfiguration;
+
+ /**
+ * The live incoming session, if any.
+ */
+ private _session?: IReceiverSession;
+
+ /**
+ * Promise chain enforcing transport ordering of incoming signals.
+ */
+ private _signalQueue = Promise.resolve();
+
+ /**
+ * Creates a media-cast receiver.
+ *
+ * @param {IMediaCastReceiverOptions} options - Configuration for the receiver.
+ */
+ constructor({
+ onError = () => undefined,
+ onSignal,
+ onTrack,
+ pcConfig
+ }: IMediaCastReceiverOptions) {
+ this._onError = onError;
+ this._onSignal = onSignal;
+ this._onTrack = onTrack;
+ this._pcConfig = pcConfig;
+ }
+
+ /**
+ * Processes one signal in transport order.
+ *
+ * @param {MediaCastSignal} signal - Signal received from the remote peer.
+ * @returns {void}
+ */
+ handleSignal(signal: MediaCastSignal): void {
+ if (!isMediaCastSignal(signal)) {
+ this._onError(new TypeError('Malformed media-cast signal received.'));
+
+ return;
+ }
+
+ const generation = signal.generation;
+
+ this._signalQueue = this._signalQueue
+ .then(() => this._processSignal(signal))
+ .catch(error => {
+ this._onError(error);
+ this._requestRestart(generation);
+ });
+ }
+
+ /**
+ * Stops the current session and resets generation tracking so this receiver can accept
+ * a new sender whose first offer starts again at generation one.
+ *
+ * @returns {void}
+ */
+ stop(): void {
+ if (this._disposed) {
+ return;
+ }
+
+ this._generation = 0;
+ this._closeSession();
+ }
+
+ /**
+ * Permanently disposes the receiver and ignores queued or future signals.
+ *
+ * @returns {void}
+ */
+ dispose(): void {
+ if (this._disposed) {
+ return;
+ }
+
+ this._disposed = true;
+ this._generation = 0;
+ this._closeSession();
+ }
+
+ /**
+ * Closes the current session's RTCPeerConnection and releases the received track.
+ *
+ * @returns {void}
+ */
+ private _closeSession(): void {
+ const session = this._session;
+
+ this._session = undefined;
+ this._currentTrack = null;
+ this._muted = false;
+ this._onTrack(null);
+
+ if (!session) {
+ return;
+ }
+
+ session.peerConnection.onconnectionstatechange = null;
+ session.peerConnection.onicecandidate = null;
+ session.peerConnection.ontrack = null;
+ session.peerConnection.close();
+ }
+
+ /**
+ * Applies one incoming signal to the current session, or handles a new offer.
+ *
+ * @param {MediaCastSignal} signal - Signal received from the remote peer.
+ * @returns {Promise<void>}
+ */
+ private async _processSignal(signal: MediaCastSignal): Promise<void> {
+ if (this._disposed) {
+ return;
+ }
+
+ if (signal.kind === 'offer') {
+ await this._handleOffer(signal);
+
+ return;
+ }
+
+ const session = this._session;
+
+ if (!session || signal.generation !== session.generation) {
+ return;
+ }
+
+ switch (signal.kind) {
+ case 'candidate':
+ await session.peerConnection.addIceCandidate(signal.candidate);
+ break;
+ case 'mute':
+ this._setMuted(signal.muted);
+ break;
+ case 'stop':
+ this.stop();
+ break;
+ }
+ }
+
+ /**
+ * Negotiates an answer for an incoming offer, replacing any previous session.
+ *
+ * @param {OfferSignal} signal - The received offer.
+ * @returns {Promise<void>}
+ */
+ private async _handleOffer(signal: OfferSignal): Promise<void> {
+ if (signal.generation <= this._generation) {
+ return;
+ }
+
+ this._closeSession();
+
+ const peerConnection = new RTCPeerConnection(this._pcConfig);
+ const session: IReceiverSession = {
+ answerSent: false,
+ generation: signal.generation,
+ peerConnection,
+ pendingCandidates: [],
+ restartSent: false
+ };
+
+ this._generation = signal.generation;
+ this._session = session;
+
+ peerConnection.ontrack = ({ track }) => {
+ if (this._session === session) {
+ this._currentTrack = track;
+ this._onTrack(this._muted ? null : track);
+ }
+ };
+ peerConnection.onicecandidate = ({ candidate }) => {
+ if (candidate && this._session === session) {
+ const candidateInit = candidate.toJSON();
+
+ if (!session.answerSent) {
+ session.pendingCandidates.push(candidateInit);
+
+ return;
+ }
+
+ this._onSignal({
+ candidate: candidateInit,
+ generation: session.generation,
+ kind: 'candidate'
+ });
+ }
+ };
+ peerConnection.onconnectionstatechange = () => {
+ if (this._session === session && peerConnection.connectionState === 'failed') {
+ this._requestRestart(session.generation);
+ }
+ };
+
+ await peerConnection.setRemoteDescription(signal.sdp);
+
+ const answer = await peerConnection.createAnswer();
+
+ await peerConnection.setLocalDescription(answer);
+
+ if (this._session !== session || !peerConnection.localDescription) {
+ return;
+ }
+
+ const { sdp, type } = peerConnection.localDescription;
+
+ this._onSignal({
+ generation: session.generation,
+ kind: 'answer',
+ sdp: {
+ sdp,
+ type
+ }
+ });
+ session.answerSent = true;
+
+ for (const candidate of session.pendingCandidates.splice(0)) {
+ this._onSignal({
+ candidate,
+ generation: session.generation,
+ kind: 'candidate'
+ });
+ }
+ }
+
+ /**
+ * Requests an ICE restart from the sender unless one is already pending for this session.
+ *
+ * @param {number} generation - The generation that is allowed to request a restart.
+ * @returns {void}
+ */
+ private _requestRestart(generation: number): void {
+ const session = this._session;
+
+ if (!session || session.generation !== generation || session.restartSent) {
+ return;
+ }
+
+ session.restartSent = true;
+ this._onSignal({
+ generation,
+ kind: 'restart'
+ });
+ }
+
+ /**
+ * Applies the sender's mute state, re-surfacing the held track when unmuted
+ * without waiting for a new ontrack event.
+ *
+ * @param {boolean} muted - Whether the sender is currently transmitting a null track.
+ * @returns {void}
+ */
+ private _setMuted(muted: boolean): void {
+ this._muted = muted;
+ this._onTrack(muted ? null : this._currentTrack);
+ }
+}
diff --git a/react/features/base/media-cast/MediaCastSender.web.ts b/react/features/base/media-cast/MediaCastSender.web.ts
new file mode 100644
index 0000000000..be3d64dc42
--- /dev/null
+++ b/react/features/base/media-cast/MediaCastSender.web.ts
@@ -0,0 +1,506 @@
+import {
+ type IMediaCastSenderOptions,
+ type ISenderSession,
+ type MediaCastSignal,
+ type MediaCastSignalHandler,
+ isMediaCastSignal
+} from './types.web';
+
+/**
+ * Delay in milliseconds before re-establishing the connection after a failure.
+ */
+const DEFAULT_RECONNECT_DELAY = 1000;
+
+/**
+ * Maximum time in milliseconds to wait for a newly offered connection to become connected.
+ */
+const DEFAULT_SETUP_TIMEOUT = 10000;
+
+/**
+ * Maximum consecutive reconnection attempts before giving up on a broken connection.
+ */
+const MAX_RECONNECT_ATTEMPTS = 3;
+
+/**
+ * Multiplier applied to the reconnect delay after each consecutive failed attempt.
+ */
+const RECONNECT_DELAY_MULTIPLIER = 2;
+
+/**
+ * Sends one replaceable video track over a plain RTCPeerConnection.
+ *
+ * The sender owns the connection lifecycle while the caller owns the track: starting or
+ * updating the track never stops or disposes the conference-owned source track. Session
+ * state is versioned by a generation counter so signals from superseded sessions are ignored.
+ */
+export default class MediaCastSender {
+ /**
+ * Whether the sender has been started and may maintain a connection.
+ */
+ private _active = false;
+
+ /**
+ * The generation of the most recently started session.
+ */
+ private _generation = 0;
+
+ /**
+ * Handler invoked when an asynchronous sending error occurs.
+ */
+ private _onError: (error: unknown) => void;
+
+ /**
+ * Handler used to forward outgoing signals to the remote peer.
+ */
+ private _onSignal: MediaCastSignalHandler;
+
+ /**
+ * Optional RTCPeerConnection configuration applied to new connections.
+ */
+ private _pcConfig?: RTCConfiguration;
+
+ /**
+ * Number of consecutive reconnection attempts made for the current connection.
+ */
+ private _reconnectAttempts = 0;
+
+ /**
+ * Delay in milliseconds before re-establishing the connection after a failure.
+ */
+ private _reconnectDelay: number;
+
+ /**
+ * Handle of the pending reconnection timer, if any.
+ */
+ private _reconnectTimer?: number;
+
+ /**
+ * The live outgoing session, if any.
+ */
+ private _session?: ISenderSession;
+
+ /**
+ * Handle of the timer that fails a session whose offer was never answered, if any.
+ */
+ private _setupTimer?: number;
+
+ /**
+ * Maximum time in milliseconds to wait for a newly offered connection to become connected.
+ */
+ private _setupTimeout: number;
+
+ /**
+ * Promise chain enforcing transport ordering of incoming signals.
+ */
+ private _signalQueue = Promise.resolve();
+
+ /**
+ * The track currently being transmitted, or null to send silence.
+ */
+ private _track: MediaStreamTrack | null = null;
+
+ /**
+ * Creates a media-cast sender.
+ *
+ * @param {IMediaCastSenderOptions} options - Configuration for the sender.
+ */
+ constructor({
+ onError = () => undefined,
+ onSignal,
+ pcConfig,
+ reconnectDelay = DEFAULT_RECONNECT_DELAY,
+ setupTimeout = DEFAULT_SETUP_TIMEOUT
+ }: IMediaCastSenderOptions) {
+ this._onError = onError;
+ this._onSignal = onSignal;
+ this._pcConfig = pcConfig;
+ this._reconnectDelay = reconnectDelay;
+ this._setupTimeout = setupTimeout;
+ }
+
+ /**
+ * Starts sending the supplied track. A null track keeps the negotiated video
+ * transceiver alive without sending media.
+ *
+ * @param {MediaStreamTrack|null} track - Conference-owned input track.
+ * @returns {void}
+ */
+ start(track: MediaStreamTrack | null): void {
+ if (this._active) {
+ void this.setTrack(track);
+
+ return;
+ }
+
+ this._active = true;
+ this._reconnectAttempts = 0;
+ this._track = track;
+ this._startSession();
+ }
+
+ /**
+ * Replaces the currently transmitted track without renegotiating.
+ *
+ * @param {MediaStreamTrack|null} track - Conference-owned input track.
+ * @returns {Promise<void>}
+ */
+ async setTrack(track: MediaStreamTrack | null): Promise<void> {
+ this._track = track;
+
+ const session = this._session;
+
+ if (!this._active || !session) {
+ return;
+ }
+
+ if (session.lastRequestedTrack === track) {
+ return;
+ }
+
+ session.lastRequestedTrack = track;
+
+ try {
+ await session.sender.replaceTrack(track);
+
+ // Only report the mute state once the offer has been sent: the receiver drops any
+ // signal for a session it does not know yet, and the final flush in _negotiate
+ // covers the state that changed while the offer was still being prepared.
+ if (this._session === session && session.offerSent) {
+ this._notifyMute(session);
+ }
+ } catch (error) {
+ if (this._session === session) {
+ this._reportError(error);
+ this._scheduleReconnect(session.generation);
+ }
+ }
+ }
+
+ /**
+ * Processes an answer, candidate, or restart request in transport order.
+ *
+ * @param {MediaCastSignal} signal - Signal received from the remote peer.
+ * @returns {void}
+ */
+ handleSignal(signal: MediaCastSignal): void {
+ if (!isMediaCastSignal(signal)) {
+ this._reportError(new TypeError('Malformed media-cast signal received.'));
+
+ return;
+ }
+
+ const generation = signal.generation;
+
+ this._signalQueue = this._signalQueue
+ .then(() => this._processSignal(signal))
+ .catch(error => {
+ this._reportError(error);
+ this._scheduleReconnect(generation);
+ });
+ }
+
+ /**
+ * Stops the sender without stopping or disposing the source track.
+ *
+ * @returns {void}
+ */
+ stop(): void {
+ this._stop(true);
+ }
+
+ /**
+ * Stops the sender, optionally notifying the remote peer with a stop signal.
+ *
+ * @param {boolean} notify - Whether to send a stop signal to the remote peer.
+ * @returns {void}
+ */
+ private _stop(notify: boolean): void {
+ if (!this._active && !this._session) {
+ return;
+ }
+
+ const generation = this._session?.generation ?? this._generation;
+
+ this._active = false;
+ this._track = null;
+ this._clearReconnectTimer();
+ this._closeSession();
+
+ if (notify && generation > 0) {
+ this._onSignal({
+ generation,
+ kind: 'stop'
+ });
+ }
+ }
+
+ /**
+ * Cancels any pending reconnection attempt.
+ *
+ * @returns {void}
+ */
+ private _clearReconnectTimer(): void {
+ if (this._reconnectTimer !== undefined) {
+ window.clearTimeout(this._reconnectTimer);
+ this._reconnectTimer = undefined;
+ }
+ }
+
+ /**
+ * Closes the current session's RTCPeerConnection and detaches its event handlers.
+ *
+ * @returns {void}
+ */
+ private _closeSession(): void {
+ const session = this._session;
+
+ this._session = undefined;
+ this._clearSetupTimer();
+
+ if (!session) {
+ return;
+ }
+
+ session.peerConnection.onconnectionstatechange = null;
+ session.peerConnection.onicecandidate = null;
+ session.peerConnection.close();
+ }
+
+ /**
+ * Applies one incoming signal to the current session if it is still current.
+ *
+ * @param {MediaCastSignal} signal - Signal received from the remote peer.
+ * @returns {Promise<void>}
+ */
+ private async _processSignal(signal: MediaCastSignal): Promise<void> {
+ const session = this._session;
+
+ if (!this._active || !session || signal.generation !== session.generation) {
+ return;
+ }
+
+ switch (signal.kind) {
+ case 'answer':
+ await session.peerConnection.setRemoteDescription(signal.sdp);
+ break;
+ case 'candidate':
+ await session.peerConnection.addIceCandidate(signal.candidate);
+ break;
+ case 'restart':
+ this._scheduleReconnect(signal.generation);
+ break;
+ case 'stop':
+ this._stop(false);
+ break;
+ }
+ }
+
+ /**
+ * Reports the current mute state to the remote peer when it changed.
+ *
+ * @param {ISenderSession} session - The session the mute state applies to.
+ * @returns {void}
+ */
+ private _notifyMute(session: ISenderSession): void {
+ const muted = this._track === null;
+
+ if (session.muteNotified === muted) {
+ return;
+ }
+
+ session.muteNotified = muted;
+ this._onSignal({
+ generation: session.generation,
+ kind: 'mute',
+ muted
+ });
+ }
+
+ /**
+ * Invokes the configured error handler.
+ *
+ * @param {unknown} error - The error that occurred.
+ * @returns {void}
+ */
+ private _reportError(error: unknown): void {
+ this._onError(error);
+ }
+
+ /**
+ * Schedules a reconnection for the given generation unless one is already pending, backing
+ * off after each failed attempt and giving up once MAX_RECONNECT_ATTEMPTS is reached.
+ *
+ * @param {number} expectedGeneration - The generation that is allowed to reconnect.
+ * @returns {void}
+ */
+ private _scheduleReconnect(expectedGeneration: number): void {
+ if (!this._active
+ || this._session?.generation !== expectedGeneration
+ || this._reconnectTimer !== undefined) {
+ return;
+ }
+
+ if (this._reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
+ if (this._reconnectAttempts === MAX_RECONNECT_ATTEMPTS) {
+ this._reconnectAttempts += 1;
+ this._reportError(new Error('Media-cast connection could not be re-established.'));
+ }
+
+ return;
+ }
+
+ const delay = this._reconnectDelay * (RECONNECT_DELAY_MULTIPLIER ** this._reconnectAttempts);
+
+ this._reconnectAttempts += 1;
+ this._reconnectTimer = window.setTimeout(() => {
+ this._reconnectTimer = undefined;
+
+ if (this._active && this._session?.generation === expectedGeneration) {
+ this._startSession();
+ }
+ }, delay);
+ }
+
+ /**
+ * Starts the timer that fails a session whose offer was never answered, retrying through
+ * _scheduleReconnect once the delay elapses with the connection still not connected.
+ *
+ * @param {ISenderSession} session - The session being set up.
+ * @returns {void}
+ */
+ private _armSetupTimeout(session: ISenderSession): void {
+ this._clearSetupTimer();
+
+ this._setupTimer = window.setTimeout(() => {
+ this._setupTimer = undefined;
+
+ if (this._session === session && session.peerConnection.connectionState !== 'connected') {
+ this._scheduleReconnect(session.generation);
+ }
+ }, this._setupTimeout);
+ }
+
+ /**
+ * Cancels the setup timeout for the current session, if any.
+ *
+ * @returns {void}
+ */
+ private _clearSetupTimer(): void {
+ if (this._setupTimer !== undefined) {
+ window.clearTimeout(this._setupTimer);
+ this._setupTimer = undefined;
+ }
+ }
+
+ /**
+ * Establishes a new send-only RTCPeerConnection and negotiates an offer with the remote peer.
+ *
+ * @returns {void}
+ */
+ private _startSession(): void {
+ this._clearReconnectTimer();
+ this._closeSession();
+
+ const peerConnection = new RTCPeerConnection(this._pcConfig);
+ const sender = peerConnection.addTransceiver('video', { direction: 'sendonly' }).sender;
+ const session: ISenderSession = {
+ generation: ++this._generation,
+ offerSent: false,
+ peerConnection,
+ pendingCandidates: [],
+ sender
+ };
+
+ this._session = session;
+
+ peerConnection.onicecandidate = ({ candidate }) => {
+ if (!candidate || this._session !== session) {
+ return;
+ }
+
+ const candidateInit = candidate.toJSON();
+
+ if (!session.offerSent) {
+ session.pendingCandidates.push(candidateInit);
+
+ return;
+ }
+
+ this._onSignal({
+ candidate: candidateInit,
+ generation: session.generation,
+ kind: 'candidate'
+ });
+ };
+ peerConnection.onconnectionstatechange = () => {
+ if (this._session !== session) {
+ return;
+ }
+
+ if (peerConnection.connectionState === 'connected') {
+ this._clearSetupTimer();
+ this._clearReconnectTimer();
+ this._reconnectAttempts = 0;
+ } else if (peerConnection.connectionState === 'failed') {
+ this._clearSetupTimer();
+ this._scheduleReconnect(session.generation);
+ }
+ };
+
+ this._armSetupTimeout(session);
+
+ void this._negotiate(session);
+ }
+
+ /**
+ * Creates and sends the offer for a session, flushing buffered ICE candidates afterwards.
+ *
+ * @param {ISenderSession} session - The session being negotiated.
+ * @returns {Promise<void>}
+ */
+ private async _negotiate(session: ISenderSession): Promise<void> {
+ try {
+ session.lastRequestedTrack = this._track;
+ await session.sender.replaceTrack(this._track);
+
+ if (this._session !== session) {
+ return;
+ }
+
+ const offer = await session.peerConnection.createOffer();
+
+ await session.peerConnection.setLocalDescription(offer);
+
+ if (this._session !== session || !session.peerConnection.localDescription) {
+ return;
+ }
+
+ const { sdp, type } = session.peerConnection.localDescription;
+
+ this._onSignal({
+ generation: session.generation,
+ kind: 'offer',
+ sdp: {
+ sdp,
+ type
+ }
+ });
+ session.offerSent = true;
+
+ for (const candidate of session.pendingCandidates.splice(0)) {
+ this._onSignal({
+ candidate,
+ generation: session.generation,
+ kind: 'candidate'
+ });
+ }
+
+ this._notifyMute(session);
+ } catch (error) {
+ if (this._session === session) {
+ this._reportError(error);
+ this._scheduleReconnect(session.generation);
+ }
+ }
+ }
+}
diff --git a/react/features/base/media-cast/types.web.ts b/react/features/base/media-cast/types.web.ts
new file mode 100644
index 0000000000..a6ac5a397f
--- /dev/null
+++ b/react/features/base/media-cast/types.web.ts
@@ -0,0 +1,197 @@
+/**
+ * Structured-clone-safe signalling exchanged by a media-cast sender and receiver.
+ */
+export type MediaCastSignal =
+ | { generation: number; kind: 'offer'; sdp: RTCSessionDescriptionInit; }
+ | { generation: number; kind: 'answer'; sdp: RTCSessionDescriptionInit; }
+ | { candidate: RTCIceCandidateInit; generation: number; kind: 'candidate'; }
+ | { generation: number; kind: 'mute'; muted: boolean; }
+ | { generation: number; kind: 'restart'; }
+ | { generation: number; kind: 'stop'; };
+
+/**
+ * Callback used to forward one media-cast signal over an application-owned transport.
+ */
+export type MediaCastSignalHandler = (signal: MediaCastSignal) => void;
+
+/**
+ * The media-cast signal kinds accepted over the transport.
+ */
+const MEDIA_CAST_SIGNAL_KINDS = new Set([
+ 'answer',
+ 'candidate',
+ 'mute',
+ 'offer',
+ 'restart',
+ 'stop'
+]);
+
+/**
+ * Checks whether an unknown value is a well-formed media-cast signal, so malformed messages
+ * received from the host are rejected before they reach the WebRTC layer.
+ *
+ * @param {unknown} value - Value received over the application transport.
+ * @returns {boolean} Whether the value is a well-formed media-cast signal.
+ */
+export function isMediaCastSignal(value: unknown): value is MediaCastSignal {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+
+ const signal = value as Record<string, unknown>;
+ const { kind } = signal;
+
+ if (typeof kind !== 'string' || !MEDIA_CAST_SIGNAL_KINDS.has(kind)) {
+ return false;
+ }
+
+ if (typeof signal.generation !== 'number') {
+ return false;
+ }
+
+ switch (kind) {
+ case 'answer':
+ case 'offer': {
+ const sdp = signal.sdp;
+
+ return typeof sdp === 'object' && sdp !== null
+ && typeof (sdp as { type?: unknown; }).type === 'string'
+ && typeof (sdp as { sdp?: unknown; }).sdp === 'string';
+ }
+ case 'candidate':
+ return typeof signal.candidate === 'object' && signal.candidate !== null;
+ case 'mute':
+ return typeof signal.muted === 'boolean';
+ case 'restart':
+ case 'stop':
+ return true;
+ default:
+ return false;
+ }
+}
+
+/**
+ * Options for constructing a {@link MediaCastSender}.
+ */
+export interface IMediaCastSenderOptions {
+ /**
+ * Optional handler invoked with any asynchronous error encountered while sending media.
+ */
+ onError?: (error: unknown) => void;
+
+ /**
+ * Handler used to forward outgoing signals (offer, candidates, mute, stop) to the remote peer.
+ */
+ onSignal: MediaCastSignalHandler;
+
+ /**
+ * Optional RTCPeerConnection configuration (e.g. custom ICE servers) applied to new connections.
+ */
+ pcConfig?: RTCConfiguration;
+
+ /**
+ * Delay in milliseconds before re-establishing the connection after a failure.
+ */
+ reconnectDelay?: number;
+
+ /**
+ * Maximum time in milliseconds to wait for a newly offered connection to become connected.
+ */
+ setupTimeout?: number;
+}
+
+/**
+ * State associated with one live outgoing RTCPeerConnection session.
+ */
+export interface ISenderSession {
+ /**
+ * Monotonically increasing session identifier used to discard stale signals.
+ */
+ generation: number;
+
+ /**
+ * The last track requested to be sent, so track updates are compared against what was
+ * requested instead of the possibly-stale sender.track value.
+ */
+ lastRequestedTrack?: MediaStreamTrack | null;
+
+ /**
+ * Whether the last transmitted mute state has already been reported to the remote peer.
+ */
+ muteNotified?: boolean;
+
+ /**
+ * Whether the initial offer has been sent; ICE candidates are buffered until then.
+ */
+ offerSent: boolean;
+
+ /**
+ * The active RTCPeerConnection sending the video track.
+ */
+ peerConnection: RTCPeerConnection;
+
+ /**
+ * ICE candidates gathered before the offer was sent, flushed once it is.
+ */
+ pendingCandidates: RTCIceCandidateInit[];
+
+ /**
+ * The RTCRtpSender transmitting the current track.
+ */
+ sender: RTCRtpSender;
+}
+
+/**
+ * Options for constructing a {@link MediaCastReceiver}.
+ */
+export interface IMediaCastReceiverOptions {
+ /**
+ * Optional handler invoked with any asynchronous error encountered while receiving media.
+ */
+ onError?: (error: unknown) => void;
+
+ /**
+ * Handler used to forward outgoing signals (answer, candidates, restart) to the remote peer.
+ */
+ onSignal: MediaCastSignalHandler;
+
+ /**
+ * Handler invoked whenever the received track changes; receives null when it is muted or closed.
+ */
+ onTrack: (track: MediaStreamTrack | null) => void;
+
+ /**
+ * Optional RTCPeerConnection configuration (e.g. custom ICE servers) applied to new connections.
+ */
+ pcConfig?: RTCConfiguration;
+}
+
+/**
+ * State associated with one live incoming RTCPeerConnection session.
+ */
+export interface IReceiverSession {
+ /**
+ * Whether the answer to the received offer has been sent; ICE candidates are buffered until then.
+ */
+ answerSent: boolean;
+
+ /**
+ * Monotonically increasing session identifier used to discard stale signals.
+ */
+ generation: number;
+
+ /**
+ * The active RTCPeerConnection receiving the negotiated media track.
+ */
+ peerConnection: RTCPeerConnection;
+
+ /**
+ * ICE candidates gathered before the answer was sent, flushed once it is.
+ */
+ pendingCandidates: RTCIceCandidateInit[];
+
+ /**
+ * Whether an ICE restart request has already been sent for this session.
+ */
+ restartSent: boolean;
+}
diff --git a/react/features/external-api/DocumentPiPController.web.ts b/react/features/external-api/DocumentPiPController.web.ts
new file mode 100644
index 0000000000..f1d91f1ec6
--- /dev/null
+++ b/react/features/external-api/DocumentPiPController.web.ts
@@ -0,0 +1,265 @@
+import type { MediaCastSignal } from '../base/media-cast/types.web';
+import { DEFAULT_DOCUMENT_PIP_HEIGHT, DEFAULT_DOCUMENT_PIP_WIDTH } from '../pip/constants';
+import type { IDocumentPictureInPictureOptions } from '../pip/types';
+
+/**
+ * Renderer bundle loaded into the host-owned Document PiP window.
+ */
+const DOCUMENT_PIP_SCRIPT = 'libs/documentpip.min.js';
+
+/**
+ * Application stylesheet loaded into the host-owned Document PiP window.
+ */
+const DOCUMENT_PIP_STYLESHEET = 'css/all.css';
+
+/**
+ * Options for constructing a {@link DocumentPiPController}.
+ */
+interface IDocumentPiPControllerOptions {
+ /**
+ * The JitsiMeetExternalAPI instance; exposed to the renderer bundle through window.alwaysOnTop.
+ */
+ api: any;
+
+ /**
+ * The iframe hosting the meeting; used to derive the renderer bundle base URL.
+ */
+ frame: HTMLIFrameElement;
+
+ /**
+ * The URL of the meeting iframe, used as the fallback base URL for the renderer bundle.
+ */
+ meetingUrl: string;
+
+ /**
+ * The transport used to send host commands back to the meeting iframe.
+ */
+ transport: any;
+
+ /**
+ * The Document PiP window options supplied by the embedder, if any.
+ */
+ windowOptions?: IDocumentPictureInPictureOptions;
+}
+
+/**
+ * Owns the top-level portion of embedded Document Picture-in-Picture.
+ *
+ * The iframe learns the outcome of every open request exclusively through the 'opened' or
+ * 'open-failed' host commands, so every exit path of {@link open} must answer with one of them.
+ */
+export default class DocumentPiPController {
+ /**
+ * The currently resolving Document PiP window request, if any.
+ */
+ private _pendingRequest?: Promise<Window>;
+
+ /**
+ * The currently open Document PiP window, if any.
+ */
+ private _pipWindow?: Window;
+
+ /**
+ * Whether the renderer bundle has loaded in the active Document PiP window.
+ */
+ private _rendererReady = false;
+
+ /**
+ * Immutable dependencies and configuration supplied by the owning External API instance.
+ */
+ private _options: IDocumentPiPControllerOptions;
+
+ /**
+ * Creates a controller with private per-API lifecycle state.
+ *
+ * @param {IDocumentPiPControllerOptions} options - Configuration for the controller.
+ */
+ constructor(options: IDocumentPiPControllerOptions) {
+ this._options = options;
+ }
+
+ /**
+ * Opens and initializes a Document PiP window. Every exit path answers the iframe with
+ * either the 'opened' or the 'open-failed' command so a request never goes unanswered.
+ *
+ * @returns {Promise<void>}
+ */
+ async open(): Promise<void> {
+ if (this._pendingRequest || this._pipWindow) {
+ // A session is already owned. Answer so the iframe never waits forever: a live
+ // ready window is 'opened'; an unresolved or initializing request is 'open-failed'.
+ this._sendCommand(this._pipWindow && this._rendererReady ? 'opened' : 'open-failed');
+
+ return;
+ }
+
+ const documentPiP = window.documentPictureInPicture;
+
+ if (!documentPiP) {
+ this._sendCommand('open-failed');
+
+ return;
+ }
+
+ let newPiPWindow: Window | undefined;
+ let request: Promise<Window> | undefined;
+
+ try {
+ // Toolbar clicks and Chrome's automatic PiP callback preserve activation across the
+ // iframe transport hop. Visibility-only IntersectionObserver requests may be rejected
+ // because scrolling does not create transient user activation; that failure is reported below.
+ request = documentPiP.requestWindow({
+ height: DEFAULT_DOCUMENT_PIP_HEIGHT,
+ width: DEFAULT_DOCUMENT_PIP_WIDTH,
+ ...this._options.windowOptions
+ });
+ this._pendingRequest = request;
+
+ newPiPWindow = await request;
+
+ if (this._pendingRequest !== request) {
+ // A close was requested while the window was resolving; closeSession() already
+ // acknowledged it with the 'closed' command, so do not double-acknowledge here.
+ newPiPWindow.close();
+
+ return;
+ }
+
+ this._pendingRequest = undefined;
+ this._pipWindow = newPiPWindow;
+ this._initializeWindow(newPiPWindow);
+ } catch (error) {
+ // A cleared pending request with no matching window means close() already cancelled
+ // and acknowledged this operation. Otherwise this request still owns the failure.
+ const ownsPendingRequest = !request || this._pendingRequest === request;
+ const ownsPiPWindow = Boolean(newPiPWindow && this._pipWindow === newPiPWindow);
+
+ if (ownsPendingRequest || ownsPiPWindow) {
+ this._pendingRequest = undefined;
+ this._closeSession(false);
+ this._sendCommand('open-failed');
+ }
+
+ throw error;
+ }
+ }
+
+ /**
+ * Closes an active or pending PiP session and acknowledges the close once.
+ *
+ * @returns {void}
+ */
+ close(): void {
+ this._closeSession(true);
+ }
+
+ /**
+ * Forwards a media-cast signal from the Document PiP renderer to the meeting iframe.
+ *
+ * @param {MediaCastSignal} signal - Answer, candidate, restart, or stop signal.
+ * @returns {void}
+ */
+ sendSignal(signal: MediaCastSignal): void {
+ this._sendCommand('signal', signal);
+ }
+
+ /**
+ * Sends an internal host command to the embedded meeting iframe.
+ *
+ * @param {string} name - Command name, e.g. 'opened', 'open-failed', 'closed' or 'signal'.
+ * @param {any} [data] - Optional command payload.
+ * @returns {void}
+ */
+ private _sendCommand(name: string, data?: any): void {
+ this._options.transport.sendEvent({
+ data: data === undefined ? [] : [ data ],
+ name: `document-pip-${name}`
+ });
+ }
+
+ /**
+ * Tears down the active or pending session, closing any live window and optionally
+ * acknowledging the close to the iframe.
+ *
+ * @param {boolean} notify - Whether to send the 'closed' command when a session existed.
+ * @returns {void}
+ */
+ private _closeSession(notify: boolean): void {
+ const hadSession = Boolean(this._pendingRequest || this._pipWindow);
+ const activeWindow = this._pipWindow;
+
+ this._pendingRequest = undefined;
+ this._pipWindow = undefined;
+ this._rendererReady = false;
+
+ if (activeWindow && !activeWindow.closed) {
+ activeWindow.close();
+ }
+
+ if (notify && hadSession) {
+ this._sendCommand('closed');
+ }
+ }
+
+ /**
+ * Initializes a freshly opened PiP window: copies the stylesheet, seeds the container markup,
+ * exposes the embedder API to the renderer bundle and loads libs/documentpip.min.js. The
+ * renderer's load success or failure is reported back as the 'opened' or 'open-failed' command.
+ *
+ * @param {Window} newPiPWindow - The Document PiP window to initialize.
+ * @returns {void}
+ */
+ private _initializeWindow(newPiPWindow: Window): void {
+ let baseURL = new URL('/', this._options.meetingUrl).href;
+
+ try {
+ // For a cross-origin meeting frame contentDocument is always null, so the URL-derived
+ // fallback is what we use in practice; the <base> lookup only matters for same-origin
+ // deployments. Deployments that serve files from a versioned CDN therefore load the
+ // fallback URL, so it must resolve to the same release as the iframe — otherwise the
+ // PiP window loads a 404 or a bundle from a different release.
+ const base = this._options.frame.contentDocument?.querySelector('base');
+
+ if (base) {
+ baseURL = base.href;
+ }
+ } catch {
+ // Cross-origin meeting iframes use the URL-derived fallback.
+ }
+
+ const pipDocument = newPiPWindow.document;
+ const link = pipDocument.createElement('link');
+ const script = pipDocument.createElement('script');
+
+ link.href = new URL(DOCUMENT_PIP_STYLESHEET, baseURL).href;
+ link.rel = 'stylesheet';
+ pipDocument.head.appendChild(link);
+
+ pipDocument.body.innerHTML
+ = '<div class="videocontainer" id="react" style="height:100%"></div>';
+
+ newPiPWindow.alwaysOnTop = { api: this._options.api };
+
+ newPiPWindow.addEventListener('pagehide', () => {
+ if (this._pipWindow === newPiPWindow) {
+ this._closeSession(true);
+ }
+ }, { once: true });
+
+ script.addEventListener('load', () => {
+ if (this._pipWindow === newPiPWindow) {
+ this._rendererReady = true;
+ this._sendCommand('opened');
+ }
+ }, { once: true });
+ script.addEventListener('error', () => {
+ if (this._pipWindow === newPiPWindow) {
+ this._closeSession(false);
+ this._sendCommand('open-failed');
+ console.error('Document PiP renderer failed to load.');
+ }
+ }, { once: true });
+ script.src = new URL(DOCUMENT_PIP_SCRIPT, baseURL).href;
+ pipDocument.body.appendChild(script);
+ }
+}
diff --git a/react/features/pip/actionTypes.ts b/react/features/pip/actionTypes.ts
index d6b1aebb2c..ad234c18ba 100644
--- a/react/features/pip/actionTypes.ts
+++ b/react/features/pip/actionTypes.ts
@@ -7,3 +7,19 @@ export const SET_PIP_ACTIVE = 'SET_PIP_ACTIVE';
* Action type to store the Document PiP window reference.
*/
export const SET_PIP_WINDOW = 'SET_PIP_WINDOW';
+
+/**
+ * Internal action signalling that the host confirmed a Document PiP window has opened.
+ */
+export const HOST_DOCUMENT_PIP_OPENED = 'HOST_DOCUMENT_PIP_OPENED';
+
+/**
+ * Internal action signalling that the host confirmed a Document PiP window has closed
+ * or that opening it failed.
+ */
+export const HOST_DOCUMENT_PIP_CLOSED = 'HOST_DOCUMENT_PIP_CLOSED';
+
+/**
+ * Internal action carrying an ordered WebRTC signal from the embedding page.
+ */
+export const HOST_DOCUMENT_PIP_SIGNAL_RECEIVED = 'HOST_DOCUMENT_PIP_SIGNAL_RECEIVED';
diff --git a/react/features/pip/actions.ts b/react/features/pip/actions.ts
index 92be75c3ce..84fb767832 100644
--- a/react/features/pip/actions.ts
+++ b/react/features/pip/actions.ts
@@ -1,11 +1,20 @@
import { IStore } from '../app/types';
+import { browser } from '../base/lib-jitsi-meet';
import { MEDIA_TYPE } from '../base/media/constants';
+import type { MediaCastSignal } from '../base/media-cast/types.web';
import { isLocalTrackMuted } from '../base/tracks/functions.any';
+import { isEmbedded } from '../base/util/embedUtils';
import { showErrorNotification } from '../notifications/actions';
import { handleToggleVideoMuted } from '../toolbox/actions.any';
import { muteLocal } from '../video-menu/actions.any';
-import { SET_PIP_ACTIVE, SET_PIP_WINDOW } from './actionTypes';
+import {
+ HOST_DOCUMENT_PIP_CLOSED,
+ HOST_DOCUMENT_PIP_OPENED,
+ HOST_DOCUMENT_PIP_SIGNAL_RECEIVED,
+ SET_PIP_ACTIVE,
+ SET_PIP_WINDOW
+} from './actionTypes';
import { DEFAULT_DOCUMENT_PIP_HEIGHT, DEFAULT_DOCUMENT_PIP_WIDTH } from './constants';
import {
cleanupMediaSessionHandlers,
@@ -20,6 +29,20 @@ import {
import logger from './logger';
import type { IOpenDocumentPiPOptions, IWebKitPictureInPictureVideoElement } from './types';
+/**
+ * Whether the current host-owned request should notify the user if opening fails.
+ */
+let hostDocumentPiPNotifyOnFailure = false;
+
+/**
+ * Clears the pending host-owned PiP request state.
+ *
+ * @returns {void}
+ */
+export function clearHostDocumentPiPPendingState() {
+ hostDocumentPiPNotifyOnFailure = false;
+}
+
/**
* Action to set Picture-in-Picture active state.
*
@@ -93,7 +116,9 @@ export function toggleVideoFromPiP() {
export function exitPiP() {
return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
logger.debug('exitPiP called');
+ clearHostDocumentPiPPendingState();
+ const wasActive = getState()['features/pip']?.isPiPActive;
const { pipWindow } = getState()['features/pip'];
if (pipWindow) {
@@ -106,6 +131,19 @@ export function exitPiP() {
}
}
+ if (isEmbedded() && isDocumentPiPSupported()) {
+ setDocumentPiPRequestPending(false);
+ APP.API.notifyDocumentPiPClose();
+
+ // hidePiP() may run while the host has not answered yet, in which case PiP never
+ // opened and emitting pipLeft without a matching pipEntered would be unbalanced.
+ if (wasActive) {
+ dispatch(handlePiPLeaveEvent());
+ }
+
+ return;
+ }
+
const webKitPiPVideo = document.getElementById('pipVideo') as IWebKitPictureInPictureVideoElement | null;
if (webKitPiPVideo?.webkitPresentationMode === 'picture-in-picture'
@@ -245,12 +283,17 @@ export function showPiP() {
*/
export function hidePiP() {
return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ clearHostDocumentPiPPendingState();
+
const state = getState();
const isPiPActive = state['features/pip']?.isPiPActive;
+ const embeddedRequestPending = isEmbedded()
+ && isDocumentPiPSupported()
+ && isDocumentPiPRequestPending();
logger.debug(`hidePiP called, isPiPActive=${isPiPActive}`);
- if (isPiPActive) {
+ if (isPiPActive || embeddedRequestPending) {
dispatch(exitPiP());
}
};
@@ -294,6 +337,8 @@ export function togglePip() {
/**
* Opens Document PiP from the toolbar or an automatic MediaSession request.
+ * Embedded meetings only request the host-owned window; the host config is the
+ * single source of truth for window options.
*
* @param {IOpenDocumentPiPOptions} options - Options controlling user-facing failure handling.
* @returns {Function}
@@ -307,9 +352,29 @@ export function openDocumentPiP(options: IOpenDocumentPiPOptions = {}) {
return;
}
+ // Electron must not change and must never ask the host for a Document PiP window; browsers
+ // without the Document PiP API fall back to the Video PiP element instead.
+ if (browser.isElectron() || !isDocumentPiPSupported()) {
+ logger.warn('Document Picture-in-Picture not supported');
+
+ return;
+ }
+
+ if (isEmbedded()) {
+ if (state['features/pip']?.isPiPActive || isDocumentPiPRequestPending()) {
+ return;
+ }
+
+ setDocumentPiPRequestPending(true);
+ hostDocumentPiPNotifyOnFailure = Boolean(options.notifyOnFailure);
+ APP.API.notifyDocumentPiPRequested();
+
+ return;
+ }
+
const docPiP = window.documentPictureInPicture;
- if (!isDocumentPiPSupported() || !docPiP) {
+ if (!docPiP) {
logger.warn('Document Picture-in-Picture not supported');
return;
@@ -388,3 +453,85 @@ export function openDocumentPiP(options: IOpenDocumentPiPOptions = {}) {
}
};
}
+
+/**
+ * Applies the host acknowledgement once the parent-owned document and the dedicated Document PiP
+ * renderer bundle are ready, and signals the sender to start streaming.
+ *
+ * @returns {Function}
+ */
+export function handleHostDocumentPiPOpened() {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ clearHostDocumentPiPPendingState();
+ setDocumentPiPRequestPending(false);
+
+ const state = getState();
+
+ if (!shouldShowPiP(state)) {
+ APP.API.notifyDocumentPiPClose();
+
+ return;
+ }
+
+ if (!state['features/pip']?.isPiPActive) {
+ dispatch(handlePipEnterEvent());
+ }
+
+ dispatch({ type: HOST_DOCUMENT_PIP_OPENED });
+ };
+}
+
+/**
+ * Clears the request guard after the host rejects requestWindow or resource setup.
+ *
+ * @returns {Function}
+ */
+export function handleHostDocumentPiPOpenFailed() {
+ return (dispatch: IStore['dispatch']) => {
+ const notifyOnFailure = hostDocumentPiPNotifyOnFailure;
+
+ logger.warn('Embedded Document PiP open failed.');
+ clearHostDocumentPiPPendingState();
+ setDocumentPiPRequestPending(false);
+ dispatch({ type: HOST_DOCUMENT_PIP_CLOSED });
+
+ if (notifyOnFailure) {
+ dispatch(showErrorNotification({
+ descriptionKey: 'notify.pipOpenFailedDescription',
+ titleKey: 'notify.pipOpenFailedTitle'
+ }));
+ }
+ };
+}
+
+/**
+ * Handles the authoritative close acknowledgement from the embedding page.
+ *
+ * @returns {Function}
+ */
+export function handleHostDocumentPiPWindowClosed() {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ const wasActive = getState()['features/pip']?.isPiPActive;
+
+ clearHostDocumentPiPPendingState();
+ setDocumentPiPRequestPending(false);
+ dispatch({ type: HOST_DOCUMENT_PIP_CLOSED });
+
+ if (wasActive) {
+ dispatch(handlePiPLeaveEvent());
+ }
+ };
+}
+
+/**
+ * Carries the one internal signaling union into the ordered sender queue.
+ *
+ * @param {MediaCastSignal} signal - WebRTC signal from the embedding page.
+ * @returns {Object}
+ */
+export function handleHostDocumentPiPSignal(signal: MediaCastSignal) {
+ return {
+ type: HOST_DOCUMENT_PIP_SIGNAL_RECEIVED,
+ signal
+ };
+}
diff --git a/react/features/pip/components/PiP.tsx b/react/features/pip/components/PiP.tsx
index 3b1adf1fd7..2eb67d891c 100644
--- a/react/features/pip/components/PiP.tsx
+++ b/react/features/pip/components/PiP.tsx
@@ -1,7 +1,10 @@
import React from 'react';
import { useSelector } from 'react-redux';
+import { browser } from '../../base/lib-jitsi-meet';
+import { isEmbedded } from '../../base/util/embedUtils';
import { isDocumentPiPSupported, shouldShowPiP } from '../functions';
+import { useDocumentPiPMediaSession } from '../hooks';
import PiPVideoElement from './PiPVideoElement';
import { DocumentPiPContent } from './web/DocumentPiPContent';
@@ -15,16 +18,26 @@ const IS_DOCUMENT_PIP_SUPPORTED = isDocumentPiPSupported();
/**
* Wrapper component that selects the appropriate PiP implementation.
* Uses Document PiP API when available, falls back to Video PiP.
+ * Embedded meetings defer to the host-owned Document PiP window.
*
* @returns {React.ReactElement | null}
*/
function PiP() {
+ useDocumentPiPMediaSession();
+
const showPiP = useSelector(shouldShowPiP);
if (!showPiP) {
return null;
}
+ if (isEmbedded()) {
+ // The host owns the Document PiP document. Electron stays on Video PiP and browsers
+ // without the Document PiP API fall back to the existing Video PiP element; everywhere
+ // else the embedded meeting renders nothing here.
+ return browser.isElectron() || !IS_DOCUMENT_PIP_SUPPORTED ? <PiPVideoElement /> : null;
+ }
+
if (IS_DOCUMENT_PIP_SUPPORTED) {
return <DocumentPiPContent />;
}
diff --git a/react/features/pip/components/web/DocumentPiPContent.tsx b/react/features/pip/components/web/DocumentPiPContent.tsx
index dfd89121a3..8955fe3816 100644
--- a/react/features/pip/components/web/DocumentPiPContent.tsx
+++ b/react/features/pip/components/web/DocumentPiPContent.tsx
@@ -6,7 +6,6 @@ import { useSelector } from 'react-redux';
import { IReduxState } from '../../../app/types';
import GlobalStyles from '../../../base/ui/components/GlobalStyles.web';
-import { useDocumentPiPMediaSession } from '../../hooks';
import { DocumentPiPView } from './DocumentPiPView';
@@ -16,8 +15,6 @@ import { DocumentPiPView } from './DocumentPiPView';
* @returns {React.ReactElement | null}
*/
export function DocumentPiPContent() {
- useDocumentPiPMediaSession();
-
const pipWindow = useSelector((state: IReduxState) => state['features/pip'].pipWindow);
const pipCache = useMemo(() => {
if (!pipWindow || pipWindow.closed) {
diff --git a/react/features/pip/hooks.ts b/react/features/pip/hooks.ts
index 72d747c0f2..a44e941b34 100644
--- a/react/features/pip/hooks.ts
+++ b/react/features/pip/hooks.ts
@@ -257,8 +257,13 @@ export function useDocumentPiPMediaSession() {
[ dispatch ]
);
+ const pipEnabled = useSelector(shouldShowPiP);
+ const documentPiPAvailable = pipEnabled && isDocumentPiPSupported();
+
useEffect(() => {
- if (!isDocumentPiPSupported()) {
+ if (!documentPiPAvailable
+ || !('mediaSession' in navigator)
+ || typeof navigator.mediaSession?.setActionHandler !== 'function') {
return;
}
@@ -286,10 +291,10 @@ export function useDocumentPiPMediaSession() {
return () => {
navigator.mediaSession.setActionHandler('enterpictureinpicture', null);
};
- }, [ openDocumentPip ]);
+ }, [ documentPiPAvailable, openDocumentPip ]);
useEffect(() => {
- if (!isDocumentPiPSupported()) {
+ if (!documentPiPAvailable) {
return;
}
@@ -306,7 +311,7 @@ export function useDocumentPiPMediaSession() {
return () => {
document.removeEventListener('visibilitychange', onVisibilityChange);
};
- }, [ dispatch ]);
+ }, [ dispatch, documentPiPAvailable ]);
}
/**
@@ -318,7 +323,8 @@ export function usePipToggleButton() {
const visible = useSelector((state: IReduxState) =>
state['features/base/config'].pip?.showToolbarButton !== false && shouldShowPiP(state));
- return !browser.isElectron() && visible && (isDocumentPiPSupported() || Boolean(document.pictureInPictureEnabled))
+ return !browser.isElectron() && visible
+ && (isDocumentPiPSupported() || Boolean(document.pictureInPictureEnabled))
? togglePiP
: undefined;
}
diff --git a/react/features/pip/middleware.ts b/react/features/pip/middleware.ts
index 1f1d0f71e9..3d51c35898 100644
--- a/react/features/pip/middleware.ts
+++ b/react/features/pip/middleware.ts
@@ -1,27 +1,117 @@
import { AnyAction } from 'redux';
-import { IStore } from '../app/types';
-import { CONFERENCE_FAILED, CONFERENCE_LEFT } from '../base/conference/actionTypes';
+import { IReduxState, IStore } from '../app/types';
+import { CONFERENCE_FAILED, CONFERENCE_LEFT, CONFERENCE_WILL_LEAVE } from '../base/conference/actionTypes';
+import { browser } from '../base/lib-jitsi-meet';
+import MediaCastSender from '../base/media-cast/MediaCastSender';
+import type { MediaCastSignal } from '../base/media-cast/types.web';
import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
+import StateListenerRegistry from '../base/redux/StateListenerRegistry';
+import { isEmbedded } from '../base/util/embedUtils';
+import { getLargeVideoParticipant } from '../large-video/functions';
+
+import {
+ HOST_DOCUMENT_PIP_CLOSED,
+ HOST_DOCUMENT_PIP_OPENED,
+ HOST_DOCUMENT_PIP_SIGNAL_RECEIVED
+} from './actionTypes';
+import { clearHostDocumentPiPPendingState, exitPiP } from './actions';
+import { getPiPVideoTrack, isDocumentPiPRequestPending, setDocumentPiPRequestPending } from './functions';
+import logger from './logger';
-import { exitPiP } from './actions';
import './subscriber';
/**
- * Middleware that intercepts conference termination actions and exits active Picture-in-Picture mode.
+ * Sender associated with the currently open host-owned Document PiP window.
+ */
+let mediaCastSender: MediaCastSender | undefined;
+
+/**
+ * Returns the live native video track selected for PiP without taking ownership of it.
+ *
+ * @param {IReduxState} state - Current Redux state.
+ * @returns {MediaStreamTrack|null}
+ */
+function getNativePiPTrack(state: IReduxState): MediaStreamTrack | null {
+ const videoTrack = getPiPVideoTrack(state, getLargeVideoParticipant(state));
+ const nativeTrack = videoTrack?.jitsiTrack?.getTrack();
+
+ return videoTrack?.muted || nativeTrack?.readyState !== 'live' ? null : nativeTrack;
+}
+
+/**
+ * Stops and releases the media-cast sender without stopping its conference-owned source track.
+ *
+ * @returns {void}
+ */
+function stopSender() {
+ mediaCastSender?.stop();
+ mediaCastSender = undefined;
+}
+
+/**
+ * Starts the media-cast sender or updates its current source track.
*
- * @param {Store} store - The Redux store.
- * @returns {Function}
+ * @param {IStore} store - Redux store used to select the initial track.
+ * @returns {void}
*/
+function startSender(store: IStore) {
+ if (mediaCastSender) {
+ void mediaCastSender.setTrack(getNativePiPTrack(store.getState()));
+
+ return;
+ }
+
+ mediaCastSender = new MediaCastSender({
+ onError: error => logger.error('Embedded Document PiP media sender failed:', error),
+ onSignal: signal => APP.API.notifyDocumentPiPSignal(signal)
+ });
+ mediaCastSender.start(getNativePiPTrack(store.getState()));
+}
+
+StateListenerRegistry.register(
+ /* selector */ (state: IReduxState) => {
+ const pipState = state['features/pip'];
+
+ return isEmbedded() && pipState?.isPiPActive
+ ? getNativePiPTrack(state)
+ : undefined;
+ },
+ /* listener */ (track: MediaStreamTrack | null | undefined) => {
+ if (track !== undefined) {
+ mediaCastSender?.setTrack(track)
+ .catch(error => logger.error('Failed to update embedded Document PiP track:', error));
+ }
+ }
+);
+
MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAction) => {
const result = next(action);
switch (action.type) {
+ case HOST_DOCUMENT_PIP_OPENED:
+ // Electron stays on Video PiP and never has a host receiver, so no sender is started.
+ if (!browser.isElectron()) {
+ startSender(store);
+ }
+ break;
+ case HOST_DOCUMENT_PIP_CLOSED:
+ stopSender();
+ break;
+ case HOST_DOCUMENT_PIP_SIGNAL_RECEIVED:
+ mediaCastSender?.handleSignal(action.signal as MediaCastSignal);
+ break;
+ case CONFERENCE_WILL_LEAVE:
case CONFERENCE_FAILED:
case CONFERENCE_LEFT:
- if (store.getState()['features/pip'].isPiPActive) {
+ clearHostDocumentPiPPendingState();
+ if (store.getState()['features/pip']?.isPiPActive) {
store.dispatch(exitPiP());
+ } else if (isDocumentPiPRequestPending()) {
+ setDocumentPiPRequestPending(false);
+ APP.API.notifyDocumentPiPClose();
}
+ stopSender();
break;
}
diff --git a/webpack.config.js b/webpack.config.js
index 600a35d247..54985658d0 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -358,6 +358,15 @@ module.exports = (_env, argv) => {
...getBundleAnalyzerPlugin(analyzeBundle, 'alwaysontop')
],
performance: getPerformanceHints(perfHintOptions, 800 * 1024) },
+ { ...config,
+ entry: {
+ 'documentpip': './react/features/always-on-top/document-pip-index.tsx'
+ },
+ plugins: [
+ ...config.plugins,
+ ...getBundleAnalyzerPlugin(analyzeBundle, 'documentpip')
+ ],
+ performance: getPerformanceHints(perfHintOptions, 800 * 1024) },
{ ...config,
entry: {
'close3': './static/close3.js'