Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat: document pip (#17707)
Hristo Terezov504af9b13e16
diff --git a/config.js b/config.jsindex e89277f170..8915cce855 100644--- a/config.js+++ b/config.js@@ -829,6 +829,31 @@ var config = {// The client id for the google APIs used for the calendar integration, youtube livestreaming, etc.// googleApiApplicationClientID: '<client_id>',+ // Picture-in-Picture configuration.+ // pip: {+ // // Enable Picture-in-Picture for browser meetings. Opt-in, defaults to false.+ // enableBrowserPiP: false,+ // // Disable Picture-in-Picture entirely. Defaults to false.+ // disabled: false,+ // // Allow Picture-in-Picture on the prejoin page. Defaults to false.+ // showOnPrejoin: false,+ // // Show the Picture-in-Picture toolbar button when supported. Defaults to true.+ // showToolbarButton: true,+ // documentPiP: {+ // windowOptions: {+ // // Hide the browser control that returns to the opener. Defaults to false.+ // disallowReturnToOpener: false,+ // // Initial window height in pixels. Defaults to 160.+ // height: 160,+ // // Prefer the default initial placement instead of reusing the previous position and size.+ // // Defaults to false.+ // preferInitialWindowPlacement: false,+ // // Initial window width in pixels. Defaults to 284.+ // width: 284+ // }+ // }+ // },+// Configs for prejoin page.// prejoinConfig: {// // When 'true', it shows an intermediate page before joining, where the user can configure their devices.diff --git a/globals.d.ts b/globals.d.tsindex 2fd283ea4f..95f4a504fb 100644--- a/globals.d.ts+++ b/globals.d.ts@@ -1,5 +1,11 @@import { IStore } from "./react/features/app/types";import { IConfig } from "./react/features/base/config/configType";+import {+ DocumentPiPMediaSessionActionHandler,+ ExtendedMediaSessionAction,+ ExtendedMediaSessionActionHandler,+ IDocumentPictureInPicture+} from "./react/features/pip/types";export {};@@ -47,6 +53,18 @@ declare global {// selenium tests handler_sharedVideoPlayer: any;alwaysOnTop: { api: any };+ documentPictureInPicture?: IDocumentPictureInPicture;+ }++ interface MediaSession {+ setActionHandler(+ action: ExtendedMediaSessionAction,+ handler: ExtendedMediaSessionActionHandler | null+ ): void;+ setActionHandler(+ action: 'enterpictureinpicture',+ handler: DocumentPiPMediaSessionActionHandler | null+ ): void;}interface Document {diff --git a/lang/main.json b/lang/main.jsonindex bf998415da..166c113324 100644--- a/lang/main.json+++ b/lang/main.json@@ -939,6 +939,8 @@"participantsWantToJoin": "Want to join the meeting","passwordRemovedRemotely": "$t(lockRoomPasswordUppercase) removed by another participant","passwordSetRemotely": "$t(lockRoomPasswordUppercase) set by another participant",+ "pipOpenFailedDescription": "Your browser did not allow the Picture-in-Picture window to open.",+ "pipOpenFailedTitle": "Couldn't open Picture-in-Picture","raiseHandAction": "Raise hand","raisedHand": "Would like to participate.","raisedHands": "{{participantName}} and {{raisedHands}} more people",@@ -1428,7 +1430,8 @@"noiseSuppression": "Extra noise suppression","openChat": "Open chat","participants": "Open participants panel. {{participantsCount}} participants",- "pip": "Toggle Picture-in-Picture mode",+ "pip": "Enter Picture-in-Picture mode",+ "pipClose": "Close Picture-in-Picture mode","privateMessage": "Send private message","profile": "Edit your profile","raiseHand": "Raise your hand",@@ -1544,6 +1547,7 @@"openReactionsMenu": "Open reactions menu","participants": "Participants","pip": "Enter Picture-in-Picture mode",+ "pipClose": "Close Picture-in-Picture mode","polls": "Polls","privateMessage": "Send private message","profile": "Edit your profile",diff --git a/react/features/base/config/configType.ts b/react/features/base/config/configType.tsindex 5ee70da145..52427000c6 100644--- a/react/features/base/config/configType.ts+++ b/react/features/base/config/configType.ts@@ -609,7 +609,29 @@ export interface IConfig {peopleSearchUrl?: string;pip?: {disabled?: boolean;+ /**+ * Document Picture-in-Picture configuration.+ *+ * @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture#methods+ */+ documentPiP?: {+ windowOptions?: {+ disallowReturnToOpener?: boolean;+ height?: number;+ preferInitialWindowPlacement?: boolean;+ width?: number;+ };+ };+ /**+ * Whether Picture-in-Picture is enabled for browser (non-Electron) meetings.+ * Opt-in: defaults to false.+ */+ enableBrowserPiP?: boolean;showOnPrejoin?: boolean;+ /**+ * Whether to show the Picture-in-Picture toolbar button when supported.+ */+ showToolbarButton?: boolean;};preferBosh?: boolean;preferVisitor?: boolean;diff --git a/react/features/base/icons/svg/constants.ts b/react/features/base/icons/svg/constants.tsindex 7f254b29eb..f1ace57d20 100644--- a/react/features/base/icons/svg/constants.ts+++ b/react/features/base/icons/svg/constants.ts@@ -68,6 +68,7 @@ import { default as IconPerformance } from './performance.svg';import { default as IconPhoneRinging } from './phone-ringing.svg';import { default as IconPin } from './pin.svg';import { default as IconPinned } from './pinned.svg';+import { default as IconPip } from './pip.svg';import { default as IconPlay } from './play.svg';import { default as IconPlus } from './plus.svg';import { default as IconRaiseHand } from './raise-hand.svg';@@ -181,6 +182,7 @@ export const DEFAULT_ICON: Record<string, any> = {IconPhoneRinging,IconPin,IconPinned,+ IconPip,IconPlay,IconPlus,IconRaiseHand,diff --git a/react/features/base/icons/svg/index.ts b/react/features/base/icons/svg/index.tsindex aaf9a617d7..d16d30b6fd 100644--- a/react/features/base/icons/svg/index.ts+++ b/react/features/base/icons/svg/index.ts@@ -70,6 +70,7 @@ const {IconPhoneRinging,IconPin,IconPinned,+ IconPip,IconPlay,IconPlus,IconRaiseHand,@@ -192,6 +193,7 @@ export {IconPhoneRinging,IconPin,IconPinned,+ IconPip,IconPlay,IconPlus,IconRaiseHand,diff --git a/react/features/base/icons/svg/pip.svg b/react/features/base/icons/svg/pip.svgnew file mode 100644index 0000000000..88bbee337a--- /dev/null+++ b/react/features/base/icons/svg/pip.svg@@ -0,0 +1,3 @@+<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path fill-rule="evenodd" clip-rule="evenodd" d="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14z"/>+</svg>diff --git a/react/features/base/toolbox/components/AbstractButton.tsx b/react/features/base/toolbox/components/AbstractButton.tsxindex 45f007b788..1eef518b0a 100644--- a/react/features/base/toolbox/components/AbstractButton.tsx+++ b/react/features/base/toolbox/components/AbstractButton.tsx@@ -37,6 +37,11 @@ export interface IProps extends WithTranslation {*/customClass?: string;+ /**+ * Whether to suppress the tooltip while preserving the accessibility label.+ */+ disableTooltip?: boolean;+/*** Extra styles which will be applied in conjunction with `styles` or* `toggledStyles` when the button is disabled;.diff --git a/react/features/base/toolbox/components/AbstractToolboxItem.tsx b/react/features/base/toolbox/components/AbstractToolboxItem.tsxindex 31c6e760e5..b652499d8f 100644--- a/react/features/base/toolbox/components/AbstractToolboxItem.tsx+++ b/react/features/base/toolbox/components/AbstractToolboxItem.tsx@@ -42,6 +42,11 @@ export interface IProps extends WithTranslation {*/customClass?: string;+ /**+ * Whether to suppress the tooltip while preserving the accessibility label.+ */+ disableTooltip?: boolean;+/*** Whether this item is disabled or not. When disabled, clicking an the item* has no effect, and it may reflect on its style.diff --git a/react/features/base/toolbox/components/ToolboxItem.web.tsx b/react/features/base/toolbox/components/ToolboxItem.web.tsxindex fbac9b8890..07f68e01c2 100644--- a/react/features/base/toolbox/components/ToolboxItem.web.tsx+++ b/react/features/base/toolbox/components/ToolboxItem.web.tsx@@ -74,10 +74,11 @@ export default class ToolboxItem extends AbstractToolboxItem<IProps> {const {backgroundColor,contextMenu,- isMenuButton,disabled,+ disableTooltip,elementAfter,icon,+ isMenuButton,onClick,onKeyDown,showLabel,@@ -99,7 +100,7 @@ export default class ToolboxItem extends AbstractToolboxItem<IProps> {};const elementType = showLabel ? 'li' : 'div';- const useTooltip = this.tooltip && this.tooltip.length > 0;+ const useTooltip = !disableTooltip && this.tooltip && this.tooltip.length > 0;if (contextMenu) {return (diff --git a/react/features/pip/actionTypes.ts b/react/features/pip/actionTypes.tsindex 6c8f2c36a2..d6b1aebb2c 100644--- a/react/features/pip/actionTypes.ts+++ b/react/features/pip/actionTypes.ts@@ -2,3 +2,8 @@* Action type to set Picture-in-Picture active state.*/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';diff --git a/react/features/pip/actions.ts b/react/features/pip/actions.tsindex e43802bffc..92be75c3ce 100644--- a/react/features/pip/actions.ts+++ b/react/features/pip/actions.ts@@ -1,17 +1,24 @@import { IStore } from '../app/types';import { MEDIA_TYPE } from '../base/media/constants';import { isLocalTrackMuted } from '../base/tracks/functions.any';+import { showErrorNotification } from '../notifications/actions';import { handleToggleVideoMuted } from '../toolbox/actions.any';import { muteLocal } from '../video-menu/actions.any';-import { SET_PIP_ACTIVE } from './actionTypes';+import { SET_PIP_ACTIVE, SET_PIP_WINDOW } from './actionTypes';+import { DEFAULT_DOCUMENT_PIP_HEIGHT, DEFAULT_DOCUMENT_PIP_WIDTH } from './constants';import {cleanupMediaSessionHandlers,- enterPiP,+ enterVideoPiP,+ initPiPWindow,+ isDocumentPiPRequestPending,+ isDocumentPiPSupported,+ setDocumentPiPRequestPending,setupMediaSessionHandlers,- shouldShowPiP+ shouldShowPiP,} from './functions';import logger from './logger';+import type { IOpenDocumentPiPOptions, IWebKitPictureInPictureVideoElement } from './types';/*** Action to set Picture-in-Picture active state.@@ -29,6 +36,22 @@ export function setPiPActive(isPiPActive: boolean) {};}+/**+ * Action to store the Document PiP window reference.+ *+ * @param {Window|null} pipWindow - The open Document PiP window, or null when none is open.+ * @returns {{+ * type: SET_PIP_WINDOW,+ * pipWindow: (Window|null)+ * }}+ */+export function setPiPWindow(pipWindow: Window | null) {+ return {+ type: SET_PIP_WINDOW,+ pipWindow+ };+}+/*** Toggles audio mute from PiP MediaSession controls.* Uses exact same logic as toolbar audio button including GUM pending state.@@ -63,21 +86,43 @@ export function toggleVideoFromPiP() {/*** Action to exit Picture-in-Picture mode.+ * Handles both Document PiP and Video PiP.** @returns {Function}*/export function exitPiP() {- return (dispatch: IStore['dispatch']) => {+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {logger.debug('exitPiP called');- if (document.pictureInPictureElement) {+ const { pipWindow } = getState()['features/pip'];++ if (pipWindow) {+ // Clear the reference before close() so the window's pagehide listener runs against+ // the already-cleared state, mirroring the browser-initiated close flow.+ dispatch(setPiPWindow(null));++ if (!pipWindow.closed) {+ pipWindow.close();+ }+ }++ const webKitPiPVideo = document.getElementById('pipVideo') as IWebKitPictureInPictureVideoElement | null;++ if (webKitPiPVideo?.webkitPresentationMode === 'picture-in-picture'+ && typeof webKitPiPVideo.webkitSetPresentationMode === 'function') {+ try {+ webKitPiPVideo.webkitSetPresentationMode('inline');+ } catch (error) {+ logger.error('Error while exiting WebKit PiP:', error);+ }+ } else if (document.pictureInPictureElement) {document.exitPictureInPicture()- .then(() => {- logger.debug('Exited Picture-in-Picture mode');- })- .catch((err: Error) => {- logger.error(`Error while exiting PiP: ${err.message}`);- });+ .then(() => {+ logger.debug('Exited Picture-in-Picture mode');+ })+ .catch((err: Error) => {+ logger.error(`Error while exiting PiP: ${err.message}`);+ });}dispatch(setPiPActive(false));@@ -100,7 +145,7 @@ export function handleWindowBlur(videoElement: HTMLVideoElement) {logger.debug(`Window blur detected, isPiPActive=${isPiPActive}`);if (!isPiPActive) {- enterPiP(videoElement);+ enterVideoPiP(videoElement);}};}@@ -163,7 +208,7 @@ export function handlePipEnterEvent() {* @returns {Function}*/export function showPiP() {- return (_dispatch: IStore['dispatch'], getState: IStore['getState']) => {+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {const state = getState();const isPiPActive = state['features/pip']?.isPiPActive;const _shouldShowPip = shouldShowPiP(state);@@ -175,15 +220,19 @@ export function showPiP() {}if (!isPiPActive) {- const videoElement = document.getElementById('pipVideo') as HTMLVideoElement;+ if (isDocumentPiPSupported()) {+ dispatch(openDocumentPiP());+ } else {+ const videoElement = document.getElementById('pipVideo') as HTMLVideoElement;- if (!videoElement) {- logger.warn('showPiP: pipVideo element not found');+ if (!videoElement) {+ logger.warn('showPiP: pipVideo element not found');- return;- }+ return;+ }- enterPiP(videoElement);+ enterVideoPiP(videoElement);+ }}};}@@ -206,3 +255,136 @@ export function hidePiP() {}};}++/**+ * Toggles PiP based on the current state and browser support.+ *+ * @returns {Function}+ */++export function togglePip() {+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {+ const state = getState();+ const isPiPActive = state['features/pip']?.isPiPActive;+ const _shouldShowPip = shouldShowPiP(state);++ logger.debug(`togglePip called, shouldShow=${_shouldShowPip}, isPiPActive=${isPiPActive}`);++ if (!_shouldShowPip) {+ return;+ }++ if (isPiPActive) {+ dispatch(exitPiP());++ return;+ }++ if (isDocumentPiPSupported()) {+ dispatch(openDocumentPiP({ notifyOnFailure: true }));+ } else {+ const videoElement = document.getElementById('pipVideo') as HTMLVideoElement;++ if (videoElement) {+ enterVideoPiP(videoElement);+ }+ }+ };+}++/**+ * Opens Document PiP from the toolbar or an automatic MediaSession request.+ *+ * @param {IOpenDocumentPiPOptions} options - Options controlling user-facing failure handling.+ * @returns {Function}+ */+export function openDocumentPiP(options: IOpenDocumentPiPOptions = {}) {+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {+ const state = getState();+ const _shouldShowPip = shouldShowPiP(state);++ if (!_shouldShowPip) {+ return;+ }++ const docPiP = window.documentPictureInPicture;++ if (!isDocumentPiPSupported() || !docPiP) {+ logger.warn('Document Picture-in-Picture not supported');++ return;+ }++ const pipConfig = state['features/base/config']?.pip;+ const docPiPConfig = pipConfig?.documentPiP?.windowOptions;+ const docPiPWindow = docPiP.window;+ const storedWindow = state['features/pip'].pipWindow;++ // Two sources can diverge: storedWindow is the window this feature opened and initialized, while+ // docPiP.window is the browser's view of any Document PiP window open for this page. Only one Document PiP+ // window may exist per page and requestWindow() closes an existing one, so do not open if either is active.+ const isPiPWindowAlreadyOpen = Boolean(+ (storedWindow && !storedWindow.closed) || (docPiPWindow && !docPiPWindow.closed));++ if (isPiPWindowAlreadyOpen) {+ logger.debug('Document PiP is already open');++ return;+ }++ if (storedWindow?.closed) {+ dispatch(setPiPWindow(null));+ }++ if (isDocumentPiPRequestPending()) {+ logger.debug('Document PiP request already pending, skipping duplicate request');++ return;+ }++ setDocumentPiPRequestPending(true);++ const handleError = (error: unknown) => {+ logger.error('Failed to open Document PiP:', error);++ if (options.notifyOnFailure) {+ dispatch(showErrorNotification({+ descriptionKey: 'notify.pipOpenFailedDescription',+ titleKey: 'notify.pipOpenFailedTitle'+ }));+ }+ };++ try {+ return docPiP.requestWindow({+ width: docPiPConfig?.width ?? DEFAULT_DOCUMENT_PIP_WIDTH,+ height: docPiPConfig?.height ?? DEFAULT_DOCUMENT_PIP_HEIGHT,+ disallowReturnToOpener: docPiPConfig?.disallowReturnToOpener ?? false,+ preferInitialWindowPlacement: docPiPConfig?.preferInitialWindowPlacement ?? false,+ })+ .then((pipWindow: Window) => {+ // The window can be closed before this resolves; nothing has been stored or+ // dispatched for it yet, so simply do not initialize it.+ if (pipWindow.closed) {+ return;+ }++ pipWindow.addEventListener('pagehide', () => {+ dispatch(setPiPWindow(null));+ dispatch(handlePiPLeaveEvent());+ });++ initPiPWindow(pipWindow);+ dispatch(setPiPWindow(pipWindow));+ dispatch(handlePipEnterEvent());+ })+ .catch(handleError)+ .finally(() => {+ setDocumentPiPRequestPending(false);+ });+ } catch (error) {+ setDocumentPiPRequestPending(false);+ handleError(error);+ }+ };+}diff --git a/react/features/pip/components/PiP.tsx b/react/features/pip/components/PiP.tsxindex c8863733f7..3b1adf1fd7 100644--- a/react/features/pip/components/PiP.tsx+++ b/react/features/pip/components/PiP.tsx@@ -1,13 +1,20 @@import React from 'react';import { useSelector } from 'react-redux';-import { shouldShowPiP } from '../functions';+import { isDocumentPiPSupported, shouldShowPiP } from '../functions';import PiPVideoElement from './PiPVideoElement';+import { DocumentPiPContent } from './web/DocumentPiPContent';/**- * Wrapper component that conditionally renders PiPVideoElement.- * Prevents mounting when PiP is disabled or on prejoin without showOnPrejoin flag.+ * Document PiP support cannot change during the page lifetime, so it is computed once at module+ * load instead of on every render.+ */+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.** @returns {React.ReactElement | null}*/@@ -18,6 +25,10 @@ function PiP() {return null;}+ if (IS_DOCUMENT_PIP_SUPPORTED) {+ return <DocumentPiPContent />;+ }+return <PiPVideoElement />;}diff --git a/react/features/pip/components/PiPVideoElement.tsx b/react/features/pip/components/PiPVideoElement.tsxindex 14d92f06f1..a6500368b7 100644--- a/react/features/pip/components/PiPVideoElement.tsx+++ b/react/features/pip/components/PiPVideoElement.tsx@@ -4,27 +4,56 @@ import { makeStyles } from 'tss-react/mui';import { IReduxState, IStore } from '../../app/types';import { getAvatarFont, getAvatarInitialsColor } from '../../base/avatar/components/web/styles';+import { browser } from '../../base/lib-jitsi-meet';import { getLocalParticipant, getParticipantDisplayName } from '../../base/participants/functions';-import { isTrackStreamingStatusActive } from '../../connection-indicator/functions';import { getDisplayNameColor } from '../../display-name/components/web/styles';import { getThumbnailBackgroundColor } from '../../filmstrip/functions.web';import { getLargeVideoParticipant } from '../../large-video/functions';import { isPrejoinPageVisible } from '../../prejoin/functions.any';import { handlePiPLeaveEvent, handlePipEnterEvent, handleWindowBlur, handleWindowFocus } from '../actions';-import { getPiPVideoTrack } from '../functions';+import { getPiPVideoTrack, shouldShowPiPAvatar } from '../functions';import { useCanvasAvatar } from '../hooks';import logger from '../logger';+import type { IWebKitPictureInPictureVideoElement } from '../types';++/**+ * Electron-only delay before reacting to window focus, so that the browser's+ * leavepictureinpicture event is processed first (see the comment at the usage site).+ */+const FOCUS_CHECK_DELAY_MS = 100;++/**+ * Interval between canvas frame re-publish attempts while WebKit asynchronously wires the video+ * element to the canvas stream (see the comment at the usage site for why polling is needed).+ */+const WEBKIT_REPUBLISH_INTERVAL_MS = 50;++/**+ * Cap on canvas frame re-publish attempts (a ~1.25 s total budget). One attempt has been enough+ * in practice (Safari 26.6); the bound only prevents polling forever against a dead stream.+ */+const WEBKIT_REPUBLISH_MAX_ATTEMPTS = 25;++const baseVideoStyle = {+ width: '1px',+ height: '1px',+ pointerEvents: 'none' as const,+ opacity: 0,+ position: 'absolute' as const+};const useStyles = makeStyles()(() => {return {hiddenVideo: {- position: 'absolute' as const,- width: '1px',- height: '1px',- opacity: 0,- pointerEvents: 'none' as const,+ ...baseVideoStyle,left: '-9999px',top: '-9999px'+ },+ // Safari 26.5.2 was observed to produce black PiP content when this video was positioned offscreen.+ webKitVideo: {+ ...baseVideoStyle,+ left: 0,+ top: 0}};});@@ -41,6 +70,11 @@ const PiPVideoElement: React.FC = () => {const videoRef = useRef<HTMLVideoElement>(null);const previousTrackRef = useRef<any>(null);+ // True only when PiP was dismissed while the tab was still hidden; reset once the tab becomes+ // visible again. Safari 26.5.2 fires `playing` after such a dismissal, which would immediately+ // reopen PiP, so automatic re-entry is suppressed while this is set.+ const webKitPiPDismissedWhileHiddenRef = useRef(false);+// Redux selectors.const isOnPrejoin = useSelector(isPrejoinPageVisible);const localParticipant = useSelector(getLocalParticipant);@@ -67,21 +101,19 @@ const PiPVideoElement: React.FC = () => {const fontFamily = (avatarFont as any).fontFamily ?? 'Inter, sans-serif';const initialsColor = getAvatarInitialsColor(theme);const displayNameColor = getDisplayNameColor(theme);- const { canvasStreamRef } = useCanvasAvatar({+ const shouldShowAvatar = shouldShowPiPAvatar(videoTrack);++ const { canvasStreamRef, publishFrame } = useCanvasAvatar({participant,displayName,customAvatarBackgrounds,backgroundColor: getThumbnailBackgroundColor(theme),fontFamily,initialsColor,- displayNameColor+ displayNameColor,+ shouldShowAvatar});- // Determine if we should show avatar instead of video.- const shouldShowAvatar = !videoTrack- || videoTrack.muted- || (!videoTrack.local && !isTrackStreamingStatusActive(videoTrack));-/*** Effect: Handle switching between real video track and canvas avatar stream.*/@@ -93,6 +125,7 @@ const PiPVideoElement: React.FC = () => {}const previousTrack = previousTrackRef.current;+ let republishInterval: number | undefined;// Detach previous track.if (previousTrack?.jitsiTrack) {@@ -111,6 +144,36 @@ const PiPVideoElement: React.FC = () => {// Only set srcObject if it's different to avoid interrupting playback.if (canvasStream && videoElement.srcObject !== canvasStream) {videoElement.srcObject = canvasStream;+ publishFrame();++ // Safari wires the element to a new srcObject asynchronously and silently drops canvas+ // frames published before that completes: streams never buffer for late sinks (W3C+ // resolution in w3c/mediacapture-transform#114) and the media-provider fetch runs+ // "in parallel" per the HTML spec, so no readiness event exists — republishing until+ // the element itself reports data is the only reliable strategy. Chromium captures+ // synchronously on requestFrame() and redelivers the current frame to late sinks,+ // so it needs no retry.+ if (browser.isWebKitBased()) {+ let attempts = 0;++ republishInterval = window.setInterval(() => {+ const done = videoElement.readyState >= videoElement.HAVE_CURRENT_DATA+ || videoElement.srcObject !== canvasStream;++ if (done || ++attempts > WEBKIT_REPUBLISH_MAX_ATTEMPTS) {+ window.clearInterval(republishInterval);+ republishInterval = undefined;++ if (!done) {+ logger.warn('Canvas stream produced no data after repeated frame requests');+ }++ return;+ }++ publishFrame();+ }, WEBKIT_REPUBLISH_INTERVAL_MS);+ }}} else if (videoTrack?.jitsiTrack) {// Attach real video track.@@ -124,6 +187,9 @@ const PiPVideoElement: React.FC = () => {// Cleanup on unmount or track change.return () => {+ if (republishInterval) {+ window.clearInterval(republishInterval);+ }if (videoTrack?.jitsiTrack && videoElement) {try {videoTrack.jitsiTrack.detach(videoElement);@@ -132,16 +198,147 @@ const PiPVideoElement: React.FC = () => {}}};- }, [ videoTrack, shouldShowAvatar ]);+ }, [ videoTrack, shouldShowAvatar, publishFrame ]);++ /**+ * Effect: Use WebKit presentation modes to enter and leave Video PiP on tab switches.+ *+ */+ useEffect(() => {+ const videoElement = videoRef.current as IWebKitPictureInPictureVideoElement | null;++ if (!videoElement+ || !browser.isWebKitBased()+ || typeof videoElement.webkitSupportsPresentationMode !== 'function'+ || typeof videoElement.webkitSetPresentationMode !== 'function') {+ return;+ }++ let enteringWebKitPiP = false;+ let isPiPActive = false;++ const resumeWebKitPiPPlayback = () => {+ if (videoElement.webkitPresentationMode !== 'picture-in-picture'+ || !videoElement.paused) {+ return;+ }++ // A muted live-MediaStream mirror has no meaningful paused state: any pause while in PiP+ // (Safari's hidden-tab interruption churn around the PiP transition, media keys) just+ // freezes the PiP frame, so playback is always resumed.+ videoElement.play()+ .catch(error => logger.warn('Failed to resume WebKit Picture-in-Picture video:', error));+ };+ const onEnterPiP = () => {+ if (!isPiPActive) {+ isPiPActive = true;+ dispatch(handlePipEnterEvent());+ }+ };+ const onLeavePiP = () => {+ if (!isPiPActive) {+ return;+ }++ isPiPActive = false;+ dispatch(handlePiPLeaveEvent());+ webKitPiPDismissedWhileHiddenRef.current = document.hidden;++ };+ const enterWebKitPiP = async () => {+ if (enteringWebKitPiP || videoElement.webkitPresentationMode === 'picture-in-picture') {+ return;+ }+ enteringWebKitPiP = true;++ try {+ if (videoElement.paused) {+ // Safari pauses hidden MediaStream videos, but a rejected play() (autoplay policy)+ // must not prevent the PiP entry attempt — WebKit does the final eligibility check+ // and the playback recovery below resumes playback once PiP is entered.+ await videoElement.play()+ .catch(error => logger.warn('Failed to play video before entering WebKit PiP:', error));+ }++ // The tab may have become visible or PiP may have been dismissed while play() was pending.+ if (!document.hidden || webKitPiPDismissedWhileHiddenRef.current) {+ return;+ }++ const hasCurrentMedia = !videoElement.ended+ && videoElement.readyState >= videoElement.HAVE_CURRENT_DATA;++ if (hasCurrentMedia+ && videoElement.webkitSupportsPresentationMode?.('picture-in-picture')) {+ videoElement.webkitSetPresentationMode?.('picture-in-picture');+ }+ } catch (error) {+ logger.warn('Failed to enter WebKit Picture-in-Picture:', error);+ } finally {+ enteringWebKitPiP = false;+ }+ };+ const exitWebKitPiP = () => {+ if (videoElement.webkitPresentationMode !== 'picture-in-picture') {+ return;+ }++ try {+ videoElement.webkitSetPresentationMode?.('inline');+ } catch (error) {+ logger.warn('Failed to exit WebKit Picture-in-Picture:', error);+ }+ };+ const onVisibilityChange = (event: Event) => {+ if (!event.isTrusted) {+ return;+ }++ if (document.hidden) {+ if (!webKitPiPDismissedWhileHiddenRef.current) {+ void enterWebKitPiP();+ }+ } else {+ webKitPiPDismissedWhileHiddenRef.current = false;+ exitWebKitPiP();+ }+ };+ const onPlaying = (event: Event) => {+ if (event.isTrusted && document.hidden && !webKitPiPDismissedWhileHiddenRef.current) {+ void enterWebKitPiP();+ }+ };+ const onWebKitPresentationModeChanged = () => {+ if (videoElement.webkitPresentationMode === 'picture-in-picture') {+ resumeWebKitPiPPlayback();+ onEnterPiP();+ } else {+ onLeavePiP();+ }+ };++ document.addEventListener('visibilitychange', onVisibilityChange);+ videoElement.addEventListener('pause', resumeWebKitPiPPlayback);+ videoElement.addEventListener('playing', onPlaying);+ videoElement.addEventListener('webkitpresentationmodechanged', onWebKitPresentationModeChanged);++ return () => {+ document.removeEventListener('visibilitychange', onVisibilityChange);+ videoElement.removeEventListener('pause', resumeWebKitPiPPlayback);+ videoElement.removeEventListener('playing', onPlaying);+ videoElement.removeEventListener('webkitpresentationmodechanged', onWebKitPresentationModeChanged);+ exitWebKitPiP();+ };+ }, [ dispatch ]);/**- * Effect: Window blur/focus and visibility change listeners.- * Enters PiP on blur, exits on focus (matches old AOT behavior).+ * Effect: Electron-only window blur/focus and visibility change listeners.+ * Enters PiP on blur and exits on focus, matching the old AOT behavior.*/useEffect(() => {const videoElement = videoRef.current;- if (!videoElement) {+ if (!videoElement || !browser.isElectron()) {return;}@@ -156,7 +353,7 @@ const PiPVideoElement: React.FC = () => {// is triggered after the leavepictureinpicture event and everything seems to work well.setTimeout(() => {dispatch(handleWindowFocus());- }, 100);+ }, FOCUS_CHECK_DELAY_MS);};const onVisibilityChange = () => {if (document.hidden) {@@ -199,7 +396,7 @@ const PiPVideoElement: React.FC = () => {useEffect(() => {const videoElement = videoRef.current;- if (!videoElement) {+ if (!videoElement || browser.isWebKitBased()) {return;}@@ -222,7 +419,7 @@ const PiPVideoElement: React.FC = () => {return (<videoautoPlay = { true }- className = { classes.hiddenVideo }+ className = { browser.isWebKitBased() ? classes.webKitVideo : classes.hiddenVideo }id = 'pipVideo'muted = { true }playsInline = { true }diff --git a/react/features/pip/components/web/DocumentPiPContent.tsx b/react/features/pip/components/web/DocumentPiPContent.tsxnew file mode 100644index 0000000000..dfd89121a3--- /dev/null+++ b/react/features/pip/components/web/DocumentPiPContent.tsx@@ -0,0 +1,50 @@+import createCache from '@emotion/cache';+import { CacheProvider } from '@emotion/react';+import React, { useEffect, useMemo } from 'react';+import { createPortal } from 'react-dom';+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';++/**+ * Inner component for the Document PiP.+ *+ * @returns {React.ReactElement | null}+ */+export function DocumentPiPContent() {+ useDocumentPiPMediaSession();++ const pipWindow = useSelector((state: IReduxState) => state['features/pip'].pipWindow);+ const pipCache = useMemo(() => {+ if (!pipWindow || pipWindow.closed) {+ return null;+ }++ return createCache({+ key: 'jitsi-pip',+ container: pipWindow.document.head+ });+ }, [ pipWindow ]);++ useEffect(() => () => {+ pipCache?.sheet.flush();+ }, [ pipCache ]);++ const pipRoot = pipWindow?.document.getElementById('pip-root');++ if (!pipCache || !pipRoot) {+ return null;+ }++ return createPortal(+ <CacheProvider value = { pipCache }>+ <GlobalStyles />+ <DocumentPiPView />+ </CacheProvider>,+ pipRoot+ );+}diff --git a/react/features/pip/components/web/DocumentPiPView.tsx b/react/features/pip/components/web/DocumentPiPView.tsxnew file mode 100644index 0000000000..aac589f348--- /dev/null+++ b/react/features/pip/components/web/DocumentPiPView.tsx@@ -0,0 +1,180 @@+import React, { useEffect, useRef } from 'react';+import { useSelector } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IReduxState } from '../../../app/types';+import Avatar from '../../../base/avatar/components/Avatar';+import { getLocalParticipant, getParticipantDisplayName } from '../../../base/participants/functions';+import DisplayNameBadge from '../../../display-name/components/web/DisplayNameBadge';+import { getStageParticipantTypography } from '../../../display-name/components/web/styles';+import { getLargeVideoParticipant } from '../../../large-video/functions';+import { isPrejoinPageVisible } from '../../../prejoin/functions.any';+import HangupButton from '../../../toolbox/components/HangupButton';+import AudioMuteButton from '../../../toolbox/components/web/AudioMuteButton';+import VideoMuteButton from '../../../toolbox/components/web/VideoMuteButton';+import { getPiPVideoTrack, shouldShowPiPAvatar } from '../../functions';+import logger from '../../logger';++const useStyles = makeStyles<void, 'controls'>()((theme, _params, classes) => {+ return {+ container: {+ backgroundColor: theme.palette.largeVideoBackground,+ color: theme.palette.text01,+ height: '100vh',+ overflow: 'hidden',+ position: 'relative',+ userSelect: 'none',+ width: '100vw',++ '& *, & *::before, & *::after': {+ boxSizing: 'border-box'+ }+ },+ videoArea: {+ alignItems: 'center',+ backgroundColor: theme.palette.largeVideoBackground,+ display: 'flex',+ height: '100%',+ justifyContent: 'center',+ overflow: 'hidden',+ position: 'relative',+ width: '100%',++ [`&:hover .${classes.controls}`]: {+ opacity: 1,+ pointerEvents: 'auto'+ }+ },+ videoElement: {+ backgroundColor: theme.palette.largeVideoBackground,+ height: '100%',+ objectFit: 'contain',+ width: '100%'+ },+ avatarPlaceholder: {+ alignItems: 'center',+ backgroundColor: theme.palette.largeVideoPlaceholder,+ display: 'flex',+ height: '100%',+ justifyContent: 'center',+ width: '100%'+ },+ floatingControls: {+ alignItems: 'center',+ bottom: theme.spacing(4),+ display: 'flex',+ flexDirection: 'column',+ gap: theme.spacing(2),+ left: 0,+ pointerEvents: 'none',+ position: 'absolute',+ width: '100%',+ zIndex: 10+ },+ participantName: {+ ...getStageParticipantTypography(theme),+ display: 'flex',+ justifyContent: 'center',+ pointerEvents: 'none',+ width: '100%'+ },+ controls: {+ opacity: 0,+ pointerEvents: 'none',+ transition: 'opacity 0.3s ease',++ '& .toolbox-icon.hangup-button': {+ backgroundColor: theme.palette.actionDanger,++ '@media (hover: hover) and (pointer: fine)': {+ '&:hover': {+ backgroundColor: theme.palette.actionDangerHover+ },++ '&:active': {+ backgroundColor: theme.palette.actionDangerActive+ }+ },++ '& svg': {+ fill: theme.palette.icon01+ }+ }+ }+ };+});++/**+ * Renders the participant video, avatar fallback, display name and controls inside the Document PiP window.+ *+ * @returns {React.ReactElement}+ */+export function DocumentPiPView() {+ const { classes, cx } = useStyles();+ const videoRef = useRef<HTMLVideoElement>(null);+ const isOnPrejoin = useSelector(isPrejoinPageVisible);+ const localParticipant = useSelector((state: IReduxState) => getLocalParticipant(state));+ const largeVideoParticipant = useSelector(getLargeVideoParticipant);+ const participant = isOnPrejoin ? localParticipant : largeVideoParticipant;+ const videoTrack = useSelector((state: IReduxState) => getPiPVideoTrack(state, participant));+ const participantName = useSelector((state: IReduxState) =>+ participant?.id ? getParticipantDisplayName(state, participant.id) : '');+ const shouldShowAvatar = shouldShowPiPAvatar(videoTrack);++ useEffect(() => {+ const video = videoRef.current;++ if (!video || shouldShowAvatar || !videoTrack?.jitsiTrack) {+ return;+ }++ videoTrack.jitsiTrack.attach(video).catch((error: Error) => {+ logger.error('Failed to attach video track in Document PiP:', error);+ });++ return () => {+ try {+ videoTrack.jitsiTrack.detach(video);+ } catch (error) {+ logger.error('Failed to detach video track in Document PiP:', error);+ }+ };+ }, [ videoTrack, shouldShowAvatar ]);++ return (+ <div className = { classes.container }>+ <div className = { classes.videoArea }>+ {shouldShowAvatar ? (+ <div className = { classes.avatarPlaceholder }>+ <Avatar+ participantId = { participant?.id }+ size = { 120 } />+ </div>+ ) : (+ <video+ autoPlay = { true }+ className = { classes.videoElement }+ muted = { true }+ playsInline = { true }+ ref = { videoRef } />+ )}+ <div className = { classes.floatingControls }>+ {participantName && <div className = { classes.participantName }>+ <DisplayNameBadge name = { participantName } />+ </div>}+ <div className = { cx(classes.controls, 'toolbox-content-items') }>+ <AudioMuteButton+ disableTooltip = { true }+ registerKeyboardShortcut = { false } />+ <VideoMuteButton+ disableTooltip = { true }+ registerKeyboardShortcut = { false } />+ <HangupButton+ customClass = 'hangup-button'+ disableTooltip = { true } />+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/react/features/pip/components/web/PiPTriggerButton.tsx b/react/features/pip/components/web/PiPTriggerButton.tsxnew file mode 100644index 0000000000..d9b97a2612--- /dev/null+++ b/react/features/pip/components/web/PiPTriggerButton.tsx@@ -0,0 +1,65 @@+import { connect } from 'react-redux';++import { createToolbarEvent } from '../../../analytics/AnalyticsEvents';+import { sendAnalytics } from '../../../analytics/functions';+import { IReduxState } from '../../../app/types';+import { translate } from '../../../base/i18n/functions';+import { IconPip } from '../../../base/icons/svg';+import AbstractButton, { IProps as AbstractButtonProps } from '../../../base/toolbox/components/AbstractButton';+import { togglePip } from '../../actions';++interface IProps extends AbstractButtonProps {++ /**+ * Whether Picture-in-Picture is active.+ */+ _isPiPActive: boolean;+}++/**+ * Opens or closes Picture-in-Picture using the implementation supported by the browser.+ */+class PiPTriggerButton extends AbstractButton<IProps> {+ override accessibilityLabel = 'toolbar.accessibilityLabel.pip';+ override toggledAccessibilityLabel = 'toolbar.accessibilityLabel.pipClose';+ override label = 'toolbar.pip';+ override toggledLabel = 'toolbar.pipClose';+ override tooltip = 'toolbar.pip';+ override toggledTooltip = 'toolbar.pipClose';+ override icon = IconPip;++ /**+ * Indicates whether the button is toggled.+ *+ * @returns {boolean}+ */+ override _isToggled(): boolean {+ return Boolean(this.props._isPiPActive);+ }++ /**+ * Handles toggling Picture-in-Picture.+ *+ * @returns {void}+ */+ override _handleClick() {+ const { dispatch } = this.props;++ sendAnalytics(createToolbarEvent('toggle.pip', { enable: !this._isToggled() }));+ dispatch(togglePip());+ }+}++/**+ * Maps Redux state to component props.+ *+ * @param {IReduxState} state - Redux state.+ * @returns {Object}+ */+function mapStateToProps(state: IReduxState) {+ return {+ _isPiPActive: Boolean(state['features/pip']?.isPiPActive)+ };+}++export default translate(connect(mapStateToProps)(PiPTriggerButton));diff --git a/react/features/pip/constants.ts b/react/features/pip/constants.tsnew file mode 100644index 0000000000..6f2b630192--- /dev/null+++ b/react/features/pip/constants.ts@@ -0,0 +1,9 @@+/**+ * Default WIDTH for the Document Picture-in-Picture window.+ */+export const DEFAULT_DOCUMENT_PIP_WIDTH = 284;++/**+ * Default HEIGHT for the Document Picture-in-Picture window.+ */+export const DEFAULT_DOCUMENT_PIP_HEIGHT = 160;diff --git a/react/features/pip/external-api.shared.ts b/react/features/pip/external-api.shared.tsindex feb6e5bfe2..f29cbc853b 100644--- a/react/features/pip/external-api.shared.ts+++ b/react/features/pip/external-api.shared.ts@@ -19,13 +19,30 @@ function isElectron(): boolean {/*** Checks if PiP is enabled based on config and environment.*+ * Honors the config it is given, but when `enableBrowserPiP` is absent it deliberately stays+ * permissive: the external API evaluates this against only the embedder-provided config, never+ * the deployment's server-side config, so applying the opt-in default here would silently+ * disable embedded auto-PiP for deployments that opt in server-side. The authoritative opt-in+ * default (an absent flag counts as disabled) is applied by `shouldShowPiP()` inside the client,+ * where the merged config is available — an over-approximating embedder only costs a no-op+ * show-PiP request that the client refuses.+ ** @param {Object} pipConfig - The pip config object.* @returns {boolean} - True if PiP is enabled.*/-export function isPiPEnabled(pipConfig?: { disabled?: boolean; }): boolean {+export function isPiPEnabled(pipConfig?: { disabled?: boolean; enableBrowserPiP?: boolean; }): boolean {if (pipConfig?.disabled) {return false;}- return isElectron();+ if (isElectron()) {+ return true;+ }++ if (pipConfig?.enableBrowserPiP === false) {+ return false;+ }++ return 'documentPictureInPicture' in window+ || Boolean(document.pictureInPictureEnabled);}diff --git a/react/features/pip/functions.ts b/react/features/pip/functions.tsindex 119e777e7c..9a41eab73a 100644--- a/react/features/pip/functions.ts+++ b/react/features/pip/functions.ts@@ -6,24 +6,55 @@ import { browser } from '../base/lib-jitsi-meet';import { IParticipant } from '../base/participants/types';import { getLocalVideoTrack } from '../base/tracks/functions.any';import { getVideoTrackByParticipant } from '../base/tracks/functions.web';+import { ITrack } from '../base/tracks/types';+import { isTrackStreamingStatusActive } from '../connection-indicator/functions';import { isPrejoinPageVisible } from '../prejoin/functions.any';import { toggleAudioFromPiP, toggleVideoFromPiP } from './actions';import { isPiPEnabled } from './external-api.shared';import logger from './logger';-import { IMediaSessionState } from './types';+import {+ ExtendedMediaSessionAction,+ ExtendedMediaSessionActionHandler,+ IMediaSessionState+} from './types';/*** Flag to track if a PiP request is currently pending (requested but not yet entered).** This prevents duplicate PiP entry requests that can occur on macOS when minimizing* a window. On minimize, both the 'blur' event and 'visibilitychange' event fire in- * rapid succession (within ~10ms), each triggering enterPiP(). Without this guard,+ * rapid succession (within ~10ms), each triggering enterVideoPiP(). Without this guard,* Electron receives two PiP requests before the first one completes, causing the* first PiP to immediately exit and triggering a pip leave event that will cause the window to be restored.*/let pipRequestPending = false;+/**+ * Flag to track if a Document PiP request is currently pending.+ * Prevents duplicate requestWindow() calls before the first one resolves.+ */+let docPiPRequestPending = false;++/**+ * Returns whether a Document PiP request is currently pending.+ *+ * @returns {boolean}+ */+export function isDocumentPiPRequestPending() {+ return docPiPRequestPending;+}++/**+ * Updates the pending state of the Document PiP request.+ *+ * @param {boolean} pending - Whether a Document PiP request is pending.+ * @returns {void}+ */+export function setDocumentPiPRequestPending(pending: boolean) {+ docPiPRequestPending = pending;+}+/*** Gets the appropriate video track for PiP based on prejoin state.* During prejoin, returns local video track. In conference, returns large video participant's track.@@ -40,6 +71,18 @@ export function getPiPVideoTrack(state: IReduxState, participant: IParticipant |: getVideoTrackByParticipant(state, participant);}+/**+ * Returns whether PiP should show an avatar instead of the selected video track.+ *+ * @param {ITrack | undefined} videoTrack - The selected PiP video track.+ * @returns {boolean} Whether the avatar should be shown.+ */+export function shouldShowPiPAvatar(videoTrack: ITrack | undefined): boolean {+ return !videoTrack+ || videoTrack.muted+ || (!videoTrack.local && !isTrackStreamingStatusActive(videoTrack));+}+/*** Determines if PiP should be shown based on config and current app state.* Checks if PiP is enabled and handles prejoin page visibility.@@ -50,11 +93,21 @@ export function getPiPVideoTrack(state: IReduxState, participant: IParticipant |export function shouldShowPiP(state: IReduxState): boolean {const pipConfig = state['features/base/config'].pip;- // Check if PiP is enabled at all.+ // Covers the global kill switch (disabled), an explicit enableBrowserPiP: false and browser+ // API support.if (!isPiPEnabled(pipConfig)) {return false;}+ // Browser PiP is opt-in: it stays disabled unless the deployment explicitly sets+ // enableBrowserPiP: true (Electron is unaffected). This authoritative default lives here+ // rather than in isPiPEnabled() because the external API evaluates isPiPEnabled() against+ // only the embedder-provided config, without the deployment's config.js — it must stay+ // permissive when the flag is absent (see isPiPEnabled()).+ if (!browser.isElectron() && pipConfig?.enableBrowserPiP !== true) {+ return false;+ }+// Check prejoin state.const isOnPrejoin = isPrejoinPageVisible(state);const showOnPrejoin = pipConfig?.showOnPrejoin ?? false;@@ -295,11 +348,13 @@ export function requestPictureInPicture() {if (!video) {logger.error('PiP video element (#pipVideo) not found');+ pipRequestPending = false;return;}if (document.pictureInPictureElement) {logger.warn('Already in PiP mode');+ pipRequestPending = false;return;}@@ -309,11 +364,36 @@ export function requestPictureInPicture() {if (video.readyState < 1) {logger.warn('Video metadata not loaded yet, waiting...');- // Wait for metadata to load before requesting PiP.+ // Two known limitations of this deferred request, deliberately not handled for now:+ //+ // 1. 'loadedmetadata' may never fire (e.g. the avatar image fetch stalls forever, so the+ // canvas captureStream(0) never produces a frame, or a video track never delivers a+ // frame). pipRequestPending then stays true and PiP is blocked until page reload.+ // If reports of a permanently dead PiP button ever come in, bound the wait:+ //+ // const onMetadata = () => {+ // clearTimeout(timer);+ // // ...existing requestPictureInPicture() logic...+ // };+ // const timer = setTimeout(() => {+ // video.removeEventListener('loadedmetadata', onMetadata);+ // logger.warn('Timed out waiting for video metadata, resetting PiP request state.');+ // pipRequestPending = false;+ // }, 5000);+ // video.addEventListener('loadedmetadata', onMetadata, { once: true });+ //+ // 2. TODO: In browsers, by the time 'loadedmetadata' fires the click's transient activation+ // has expired, so requestPictureInPicture() below rejects with NotAllowedError and the+ // click fails silently; clicking again once media is flowing works. This only happens+ // when the click lands in a readyState < 1 window: the brief moment right after mount,+ // the ~100ms srcObject swap when the large-video participant changes or the camera is+ // toggled, or while a slow avatar image fetch delays the first canvas frame — so it is+ // rare in practice. Revisit if it shows up in reports (e.g. a short bounded wait within+ // the activation window). The Electron flow is unaffected: it requests PiP from the main+ // process with userGesture: true, and its behavior here is pre-existing.video.addEventListener('loadedmetadata', () => {logger.debug(`Calling video.requestPictureInPicture(), readyState=${video.readyState}`);- // @ts-ignore - requestPictureInPicture is not yet in all TypeScript definitions.video.requestPictureInPicture().then(() => {logger.debug('video.requestPictureInPicture() succeeded');}).catch((err: Error) => {@@ -332,7 +412,6 @@ export function requestPictureInPicture() {logger.debug(`Calling video.requestPictureInPicture(), readyState=${video.readyState}`);- // @ts-ignore - requestPictureInPicture is not yet in all TypeScript definitions.video.requestPictureInPicture().then(() => {logger.debug('video.requestPictureInPicture() succeeded');}).catch((err: Error) => {@@ -353,7 +432,7 @@ export function requestPictureInPicture() {* @param {HTMLVideoElement} videoElement - The video element to call requestPictureInPicuture on.* @returns {void}*/-export function enterPiP(videoElement: HTMLVideoElement | undefined | null) {+export function enterVideoPiP(videoElement: HTMLVideoElement | undefined | null) {if (!videoElement) {logger.error('PiP video element not found');@@ -400,15 +479,32 @@ export function enterPiP(videoElement: HTMLVideoElement | undefined | null) {return;}- // TODO: Enable PiP for browsers:- // In browsers, we should directly call requestPictureInPicture.- // @ts-ignore - requestPictureInPicture is not yet in all TypeScript definitions.- // requestPictureInPicture();+ // In browsers, directly request Video PiP.+ pipRequestPending = true;+ requestPictureInPicture();} catch (error) {+ pipRequestPending = false;logger.error('Error entering Picture-in-Picture:', error);}}+/**+ * Sets an extended MediaSession action handler when supported by the browser.+ *+ * @param {ExtendedMediaSessionAction} action - The MediaSession action to configure.+ * @param {ExtendedMediaSessionActionHandler | null} handler - The action handler, or null to clear it.+ * @returns {void}+ */+function setExtendedMediaSessionActionHandler(+ action: ExtendedMediaSessionAction,+ handler: ExtendedMediaSessionActionHandler | null) {+ try {+ navigator.mediaSession.setActionHandler(action, handler);+ } catch (error) {+ logger.debug(`MediaSession action '${action}' is not supported:`, error);+ }+}+/*** Sets up MediaSession API action handlers for controlling the conference.* Handlers dispatch actions that query fresh Redux state, avoiding stale closures.@@ -417,33 +513,25 @@ export function enterPiP(videoElement: HTMLVideoElement | undefined | null) {* @returns {void}*/export function setupMediaSessionHandlers(dispatch: IStore['dispatch']) {- // @ts-ignore - MediaSession API is not fully typed in all environments.- if ('mediaSession' in navigator && navigator.mediaSession?.setActionHandler) {- try {- // Set up audio mute toggle handler.- // Dispatch action that will query current state and toggle.- // @ts-ignore - togglemicrophone is a newer MediaSession action.- navigator.mediaSession.setActionHandler('togglemicrophone', () => {- dispatch(toggleAudioFromPiP());- });-- // Set up video mute toggle handler.- // Dispatch action that will query current state and toggle.- // @ts-ignore - togglecamera is a newer MediaSession action.- navigator.mediaSession.setActionHandler('togglecamera', () => {- dispatch(toggleVideoFromPiP());- });-- // Set up hangup handler.- // @ts-ignore - hangup is a newer MediaSession action.- navigator.mediaSession.setActionHandler('hangup', () => {- dispatch(leaveConference());- });-- logger.log('MediaSession API handlers registered for PiP controls');- } catch (error) {- logger.warn('Some MediaSession actions not supported:', error);- }+ if ('mediaSession' in navigator && typeof navigator.mediaSession?.setActionHandler === 'function') {+ // Set up audio mute toggle handler.+ // Dispatch action that will query current state and toggle.+ setExtendedMediaSessionActionHandler('togglemicrophone', () => {+ dispatch(toggleAudioFromPiP());+ });++ // Set up video mute toggle handler.+ // Dispatch action that will query current state and toggle.+ setExtendedMediaSessionActionHandler('togglecamera', () => {+ dispatch(toggleVideoFromPiP());+ });++ // Set up hangup handler.+ setExtendedMediaSessionActionHandler('hangup', () => {+ dispatch(leaveConference());+ });++ logger.log('MediaSession API handlers registered for supported PiP controls');} else {logger.warn('MediaSession API not supported in this browser');}@@ -457,18 +545,27 @@ export function setupMediaSessionHandlers(dispatch: IStore['dispatch']) {* @returns {void}*/export function updateMediaSessionState(state: IMediaSessionState) {+ // Safari requires user activation when setting MediaSession capture state.+ // This runs from a Redux subscriber outside the initiating user gesture,+ // so Safari rejects the request. Skip state synchronization for Safari.+ // observed behavior in v26.5.2+ if (browser.isSafari()) {+ return;+ }+if ('mediaSession' in navigator) {+ const mediaSession = navigator.mediaSession as MediaSession & {+ setCameraActive?: (active: boolean) => void;+ setMicrophoneActive?: (active: boolean) => void;+ };+try {- // @ts-ignore - setMicrophoneActive is a newer MediaSession method.- if (navigator.mediaSession.setMicrophoneActive) {- // @ts-ignore- navigator.mediaSession.setMicrophoneActive(state.microphoneActive);+ if (mediaSession.setMicrophoneActive) {+ mediaSession.setMicrophoneActive(state.microphoneActive);}- // @ts-ignore - setCameraActive is a newer MediaSession method.- if (navigator.mediaSession.setCameraActive) {- // @ts-ignore- navigator.mediaSession.setCameraActive(state.cameraActive);+ if (mediaSession.setCameraActive) {+ mediaSession.setCameraActive(state.cameraActive);}logger.log('MediaSession state updated:', state);@@ -485,22 +582,98 @@ export function updateMediaSessionState(state: IMediaSessionState) {*/export function cleanupMediaSessionHandlers() {if ('mediaSession' in navigator) {+ setExtendedMediaSessionActionHandler('togglemicrophone', null);+ setExtendedMediaSessionActionHandler('togglecamera', null);+ setExtendedMediaSessionActionHandler('hangup', null);+ logger.log('Supported MediaSession API handlers cleaned up');+ }+}++/**+ * Applies initial stylings of the main window to PiP window.+ * Creates the container for the PiP window.+ *+ * The reference to the opened window lives in the pip Redux state (see setPiPWindow), not here,+ * so that every change to it is observable by React.+ *+ * @param {Window} pipWindow - Current window.+ * @returns {void}+ */+export function initPiPWindow(pipWindow: Window) {+ copyStylesheets(pipWindow);+ createPiPContainer(pipWindow);+}++/**+ * Applies stylesheet links and inline styles from the originating window.+ *+ * @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture#copy_style_sheets_to_pip+ * @param {Window} pipWindow - Current window.+ * @returns {void}+ */+function copyStylesheets(pipWindow: Window) {+ const { document: pipDoc } = pipWindow;++ document.head.querySelectorAll('link[rel="stylesheet"], style').forEach(node => {try {- // Note: Setting handlers to null is commented out as it may cause issues- // in some browsers. The handlers will be overwritten when entering PiP again.- // @ts-ignore - togglemicrophone is a newer MediaSession action.- navigator.mediaSession.setActionHandler('togglemicrophone', null);- // @ts-ignore - togglecamera is a newer MediaSession action.- navigator.mediaSession.setActionHandler('togglecamera', null);- // @ts-ignore - hangup is a newer MediaSession action.- navigator.mediaSession.setActionHandler('hangup', null);- logger.log('MediaSession API handlers cleaned up');+ if (node instanceof HTMLStyleElement) {+ pipDoc.head.appendChild(pipDoc.importNode(node, true));++ return;+ }++ if (!(node instanceof HTMLLinkElement) || !node.href) {+ return;+ }++ const link = pipDoc.createElement('link');++ Array.from(node.attributes).forEach(attribute => {+ if (attribute.name !== 'href' && (attribute.name !== 'type' || attribute.value)) {+ link.setAttribute(attribute.name, attribute.value);+ }+ });+ link.href = node.href;++ pipDoc.head.appendChild(link);} catch (error) {- logger.error('Error cleaning up MediaSession handlers:', error);+ logger.warn('Failed to copy stylesheet:', error);}- }+ });+}++/**+ * Creates container for pip. Helpful for react portals.+ *+ * @see https://react.dev/reference/react-dom/createPortal+ * @param {Window} pipWindow - Current window.+ * @returns {void}+ */+function createPiPContainer(pipWindow: Window) {+ const pipDoc = pipWindow.document;++ // The copied stylesheets load asynchronously; until they land, the UA default body margin+ // and overflow would make the 100vw/100vh container overflow and flash scrollbars on every+ // open, so reset them synchronously.+ pipDoc.body.style.margin = '0';+ pipDoc.body.style.overflow = 'hidden';++ const container = pipDoc.createElement('div');++ container.id = 'pip-root';+ container.style.cssText = 'margin: 0; padding: 0; overflow: hidden; height: 100vh; width: 100vw;';+ pipDoc.body.appendChild(container);+}++/**+ * Checks if the Document Picture-in-Picture API is supported.+ * Keeps Electron on its existing Video PiP implementation.+ *+ * @returns {boolean} True if Document PiP is supported.+ */+export function isDocumentPiPSupported(): boolean {+ return !browser.isElectron() && 'documentPictureInPicture' in window;}// Re-export from shared file for external use.export { isPiPEnabled };-diff --git a/react/features/pip/hooks.ts b/react/features/pip/hooks.tsindex bcee6b1225..72d747c0f2 100644--- a/react/features/pip/hooks.ts+++ b/react/features/pip/hooks.ts@@ -1,10 +1,19 @@-import React, { useEffect, useRef } from 'react';+import React, { useCallback, useEffect, useRef } from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { IReduxState, IStore } from '../app/types';import IconUserSVG from '../base/icons/svg/user.svg?raw';+import { browser } from '../base/lib-jitsi-meet';import { IParticipant } from '../base/participants/types';import { TILE_ASPECT_RATIO } from '../filmstrip/constants';-import { renderAvatarOnCanvas } from './functions';+import { hidePiP, openDocumentPiP } from './actions';+import PiPTriggerButton from './components/web/PiPTriggerButton';+import {+ isDocumentPiPSupported,+ renderAvatarOnCanvas,+ shouldShowPiP,+} from './functions';import logger from './logger';/**@@ -19,6 +28,12 @@ const CANVAS_HEIGHT = Math.floor(CANVAS_WIDTH / TILE_ASPECT_RATIO);*/const CANVAS_FRAME_RATE = 0;+const togglePiP = {+ key: 'toggle-pip',+ Content: PiPTriggerButton,+ group: 2+};+/*** Options for the useCanvasAvatar hook.*/@@ -30,15 +45,17 @@ interface IUseCanvasAvatarOptions {fontFamily: string;initialsColor: string;participant: IParticipant | undefined;+ shouldShowAvatar: boolean;}/*** Result returned by the useCanvasAvatar hook.- * Returns a ref object so consumers can access .current inside effects- * (the stream is created in an effect and won't be available at render time).+ * The stream ref is populated in an effect, while publishFrame lets consumers+ * explicitly deliver the current canvas after attaching it to a video element.*/interface IUseCanvasAvatarResult {canvasStreamRef: React.MutableRefObject<MediaStream | null>;+ publishFrame: () => void;}/**@@ -75,10 +92,11 @@ function createDefaultIconImage(): HTMLImageElement {/*** Custom hook that manages canvas-based avatar rendering for Picture-in-Picture.* Creates and maintains a canvas element with a MediaStream that can be used- * as a video source when the participant's video is unavailable.+ * as a video source when the participant's video is unavailable. Avatar rendering+ * is gated by shouldShowAvatar, while hidden content is cleared to avoid stale identity frames.** @param {IUseCanvasAvatarOptions} options - The hook options.- * @returns {IUseCanvasAvatarResult} The canvas stream for use as video source.+ * @returns {IUseCanvasAvatarResult} The canvas stream and frame publication callback.*/export function useCanvasAvatar(options: IUseCanvasAvatarOptions): IUseCanvasAvatarResult {const {@@ -88,7 +106,8 @@ export function useCanvasAvatar(options: IUseCanvasAvatarOptions): IUseCanvasAvabackgroundColor,fontFamily,initialsColor,- displayNameColor+ displayNameColor,+ shouldShowAvatar} = options;const refs = useRef<ICanvasRefs>({@@ -105,6 +124,40 @@ export function useCanvasAvatar(options: IUseCanvasAvatarOptions): IUseCanvasAva// changes when the stream is set, and consumers would add it to their effect deps.const streamRef = useRef<MediaStream | null>(null);+ /**+ * Publishes the canvas's current contents to its on-demand capture stream.+ *+ * @returns {void}+ */+ const publishFrame = useCallback(() => {+ const track = streamRef.current?.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void; };+ const canvas = refs.current.canvas;++ if (!track?.requestFrame || !canvas) {+ return;+ }++ track.requestFrame();++ // WebKit emits a canvas-capture frame only when the canvas is painted AFTER requestFrame()+ // has armed the capture — a bare requestFrame() on a static canvas produces nothing and the+ // PiP video stays at readyState 0 (verified on Safari 26.6). Nudge the canvas with an+ // imperceptible 1px draw so an emission paint always follows the arm. Chromium captures+ // the current canvas contents immediately on requestFrame(), so it needs no nudge.+ if (browser.isWebKitBased()) {+ const ctx = canvas.getContext('2d');++ if (ctx) {+ ctx.save();+ ctx.globalAlpha = 0.01;+ ctx.fillRect(0, 0, 1, 1);+ ctx.restore();+ }+ }++ logger.log('Canvas frame requested');+ }, []);+/*** Initialize canvas, stream, and default icon on mount.*/@@ -137,7 +190,7 @@ export function useCanvasAvatar(options: IUseCanvasAvatarOptions): IUseCanvasAva}, []);/**- * Re-render avatar when participant or display name changes.+ * Renders the avatar when it should be shown and clears stale participant content otherwise.*/useEffect(() => {const { canvas, defaultIcon } = refs.current;@@ -154,6 +207,14 @@ export function useCanvasAvatar(options: IUseCanvasAvatarOptions): IUseCanvasAvareturn;}+ // Clear participant identity synchronously before the canvas can be attached to a new sink.+ ctx.fillStyle = backgroundColor;+ ctx.fillRect(0, 0, canvas.width, canvas.height);++ if (!shouldShowAvatar) {+ return;+ }+renderAvatarOnCanvas(canvas,ctx,@@ -165,19 +226,99 @@ export function useCanvasAvatar(options: IUseCanvasAvatarOptions): IUseCanvasAvafontFamily,initialsColor,displayNameColor- ).then(() => {- // Request a frame capture after drawing.- // For captureStream(0), we need to manually trigger frame capture.- const track = streamRef.current?.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void; };-- if (track?.requestFrame) {- track.requestFrame();- logger.log('Canvas frame requested after render');- }- }).catch((error: Error) => logger.error('Error rendering avatar on canvas:', error));- }, [ participant?.loadableAvatarUrl, participant?.name, displayName, customAvatarBackgrounds, backgroundColor, fontFamily, initialsColor, displayNameColor ]);+ ).then(publishFrame)+ .catch((error: Error) => logger.error('Error rendering avatar on canvas:', error));+ }, [ participant?.loadableAvatarUrl, participant?.loadableAvatarUrlUseCORS, participant?.name, displayName, customAvatarBackgrounds, backgroundColor, fontFamily, initialsColor, displayNameColor, shouldShowAvatar, publishFrame ]);return {- canvasStreamRef: streamRef+ canvasStreamRef: streamRef,+ publishFrame};}++/**+ * Manages Document Picture-in-Picture via the MediaSession API in browsers that support its+ * enterpictureinpicture action. WebKit automatic Video PiP on tab switches is managed separately by PiPVideoElement+ * through the presentation-mode API.+ * Closes the PiP window when the tab becomes visible again.+ *+ * MediaSession playback state is kept in sync by the subscriber in+ * subscriber.ts, so this hook only handles the window lifecycle.+ *+ * @see https://googlechrome.github.io/samples/media-session/video-conferencing.html+ *+ * @returns {void}+ */+export function useDocumentPiPMediaSession() {+ const dispatch: IStore['dispatch'] = useDispatch();++ const openDocumentPip = useCallback(+ (notifyOnFailure: boolean) => dispatch(openDocumentPiP({ notifyOnFailure })),+ [ dispatch ]+ );++ useEffect(() => {+ if (!isDocumentPiPSupported()) {+ return;+ }++ try {+ navigator.mediaSession.setActionHandler('enterpictureinpicture', details => {+ const reason = details?.enterPictureInPictureReason;++ if (reason === 'useraction') {+ logger.log('User clicked Enter Picture-in-Picture icon.');+ } else if (reason === 'contentoccluded') {+ logger.log('Automatically enter picture-in-picture.');+ }++ // The browser invokes this handler fire-and-forget, so nothing may leak a+ // rejection here. openDocumentPiP() reports every failure internally: it always+ // logs, and for user-initiated entries it also shows the same error notification+ // as the toolbar button; automatic entries stay silent to avoid nagging on every+ // tab switch.+ openDocumentPip(reason === 'useraction');+ });+ } catch (error) {+ logger.warn('enterpictureinpicture MediaSession action not supported:', error);+ }++ return () => {+ navigator.mediaSession.setActionHandler('enterpictureinpicture', null);+ };+ }, [ openDocumentPip ]);++ useEffect(() => {+ if (!isDocumentPiPSupported()) {+ return;+ }++ const onVisibilityChange = () => {+ // hidePiP() checks the current PiP state inside the thunk, so the handler needs no+ // state in its closure and the listener registers once for the lifetime of the mount.+ if (!document.hidden) {+ dispatch(hidePiP());+ }+ };++ document.addEventListener('visibilitychange', onVisibilityChange);++ return () => {+ document.removeEventListener('visibilitychange', onVisibilityChange);+ };+ }, [ dispatch ]);+}++/**+ * Returns the PiP toggle button when PiP is enabled and supported by the browser.+ *+ * @returns {Object | undefined} The PiP toggle button or undefined.+ */+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))+ ? togglePiP+ : undefined;+}diff --git a/react/features/pip/middleware.ts b/react/features/pip/middleware.tsindex a77cbdf81b..1f1d0f71e9 100644--- a/react/features/pip/middleware.ts+++ b/react/features/pip/middleware.ts@@ -1 +1,29 @@+import { AnyAction } from 'redux';++import { IStore } from '../app/types';+import { CONFERENCE_FAILED, CONFERENCE_LEFT } from '../base/conference/actionTypes';+import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';++import { exitPiP } from './actions';import './subscriber';++/**+ * Middleware that intercepts conference termination actions and exits active Picture-in-Picture mode.+ *+ * @param {Store} store - The Redux store.+ * @returns {Function}+ */+MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: AnyAction) => {+ const result = next(action);++ switch (action.type) {+ case CONFERENCE_FAILED:+ case CONFERENCE_LEFT:+ if (store.getState()['features/pip'].isPiPActive) {+ store.dispatch(exitPiP());+ }+ break;+ }++ return result;+});diff --git a/react/features/pip/reducer.ts b/react/features/pip/reducer.tsindex 5cfad96f74..90d29e8649 100644--- a/react/features/pip/reducer.ts+++ b/react/features/pip/reducer.ts@@ -1,16 +1,32 @@import ReducerRegistry from '../base/redux/ReducerRegistry';-import { SET_PIP_ACTIVE } from './actionTypes';+import { SET_PIP_ACTIVE, SET_PIP_WINDOW } from './actionTypes';/*** The default state for the pip feature.*/const DEFAULT_STATE = {- isPiPActive: false+ isPiPActive: false,+ pipWindow: null};export interface IPipState {isPiPActive: boolean;++ /**+ * The Document PiP window this feature opened and initialized (stylesheets copied, #pip-root+ * container created), or null when none is open. This differs from+ * window.documentPictureInPicture.window, which is the browser's view of any Document PiP+ * window open for the page regardless of who opened it. Kept in Redux so that every change+ * to the reference is observable by React.+ *+ * The ts-ignore mirrors web-hid's HIDDevice: the pip feature is excluded from the native+ * TypeScript config, which has no DOM lib defining Window, but this interface still reaches+ * the native check through IReduxState. Types are erased at build time, so the suppression+ * only affects the type check and nothing on native ever reads this field.+ */+ // @ts-ignore+ pipWindow: Window | null;}/**@@ -24,6 +40,12 @@ ReducerRegistry.register<IPipState>('features/pip', (state = DEFAULT_STATE, actiisPiPActive: action.isPiPActive};+ case SET_PIP_WINDOW:+ return {+ ...state,+ pipWindow: action.pipWindow+ };+default:return state;}diff --git a/react/features/pip/subscriber.ts b/react/features/pip/subscriber.tsindex 68c16486dd..91bc4f8c36 100644--- a/react/features/pip/subscriber.ts+++ b/react/features/pip/subscriber.ts@@ -1,4 +1,5 @@import { IReduxState } from '../app/types';+import { browser } from '../base/lib-jitsi-meet';import { MEDIA_TYPE } from '../base/media/constants';import StateListenerRegistry from '../base/redux/StateListenerRegistry';import { isLocalTrackMuted } from '../base/tracks/functions.any';@@ -44,21 +45,23 @@ StateListenerRegistry.register(});-StateListenerRegistry.register(- /* selector */ shouldShowPiP,- /* listener */ (_shouldShowPiP: boolean) => {- const electronNS = getElectronGlobalNS();+if (browser.isElectron()) {+ StateListenerRegistry.register(+ /* selector */ shouldShowPiP,+ /* listener */ (_shouldShowPiP: boolean) => {+ const electronNS = getElectronGlobalNS();- if (_shouldShowPiP) {- // Expose requestPictureInPicture for Electron main process.- if (!electronNS.requestPictureInPicture) {- logger.debug('Exposing requestPictureInPicture to Electron namespace');- electronNS.requestPictureInPicture = requestPictureInPicture;+ if (_shouldShowPiP) {+ // Expose requestPictureInPicture for Electron main process.+ if (!electronNS.requestPictureInPicture) {+ logger.debug('Exposing requestPictureInPicture to Electron namespace');+ electronNS.requestPictureInPicture = requestPictureInPicture;+ }+ } else if (typeof electronNS.requestPictureInPicture === 'function') {+ logger.debug('Removing requestPictureInPicture from Electron namespace (PiP disabled)');+ delete electronNS.requestPictureInPicture;}- } else if (typeof electronNS.requestPictureInPicture === 'function') {- logger.debug('Removing requestPictureInPicture from Electron namespace (PiP disabled)');- delete electronNS.requestPictureInPicture;}- }-);+ );+}diff --git a/react/features/pip/types.ts b/react/features/pip/types.tsindex 26c99aae07..290a43742e 100644--- a/react/features/pip/types.ts+++ b/react/features/pip/types.ts@@ -12,3 +12,140 @@ export interface IMediaSessionState {*/microphoneActive: boolean;}++/**+ * Details supplied when MediaSession requests entering Document PiP.+ */+export interface IDocumentPiPMediaSessionActionDetails {+ /**+ * The MediaSession action being handled.+ */+ action: 'enterpictureinpicture';++ /**+ * The reason Document PiP was requested.+ */+ enterPictureInPictureReason?: 'contentoccluded' | 'useraction';+}++/**+ * Handles a MediaSession request to enter Document PiP.+ */+export type DocumentPiPMediaSessionActionHandler = (+ details: IDocumentPiPMediaSessionActionDetails+) => void;++/**+ * Options controlling user-facing failure handling when opening Document PiP.+ */+export interface IOpenDocumentPiPOptions {+ /**+ * Whether to show an error notification when opening the PiP window fails.+ */+ notifyOnFailure?: boolean;+}++/**+ * The browser's Document Picture-in-Picture API.+ */+export interface IDocumentPictureInPicture {+ /**+ * Registers a listener for Document PiP lifecycle events.+ */+ addEventListener: (+ type: 'enter' | 'leave',+ listener: ((event: IDocumentPictureInPictureEvent) => void) | ((event: Event) => void)+ ) => void;++ /**+ * Opens a Document PiP window using the supplied window options.+ */+ requestWindow: (options?: IDocumentPictureInPictureOptions) => Promise<Window>;++ /**+ * The currently open Document PiP window, if any.+ */+ readonly window: Window | null;+}++/**+ * Options used when requesting a Document PiP window.+ */+export interface IDocumentPictureInPictureOptions {+ /**+ * Whether the browser should hide its control for returning to the opener tab.+ */+ disallowReturnToOpener?: boolean;++ /**+ * The requested initial window height in CSS pixels.+ */+ height?: number;++ /**+ * Whether the browser should prefer the default placement over reusing the previous window position and size.+ */+ preferInitialWindowPlacement?: boolean;++ /**+ * The requested initial window width in CSS pixels.+ */+ width?: number;+}++/**+ * A Document PiP lifecycle event containing the associated PiP window.+ */+export interface IDocumentPictureInPictureEvent extends Event {+ /**+ * The Document PiP window associated with the event.+ */+ readonly window: Window;+}++/**+ * MediaSession actions supported by the PiP controls in addition to the standard action set.+ */+export type ExtendedMediaSessionAction = 'hangup' | 'togglecamera' | 'togglemicrophone';++/**+ * Details supplied to an extended MediaSession action handler.+ */+export interface IExtendedMediaSessionActionDetails {+ /**+ * The extended MediaSession action being handled.+ */+ action: ExtendedMediaSessionAction;+}++/**+ * Handles an extended MediaSession action used by the PiP controls.+ */+export type ExtendedMediaSessionActionHandler = (+ details: IExtendedMediaSessionActionDetails+) => void;++/**+ * WebKit video presentation modes used to enter and leave Safari's native Video PiP.+ */+export type WebKitPresentationMode = 'inline' | 'picture-in-picture';++/**+ * Safari's non-standard Video PiP additions to HTMLVideoElement.+ */+export interface IWebKitPictureInPictureVideoElement extends HTMLVideoElement {+ /**+ * The video's current WebKit presentation mode.+ */+ webkitPresentationMode?: WebKitPresentationMode;++ /**+ * Changes the video's WebKit presentation mode.+ */+ webkitSetPresentationMode?: (mode: WebKitPresentationMode) => void;++ /**+ * Returns whether the video currently supports the requested WebKit presentation mode.+ */+ webkitSupportsPresentationMode?: (mode: WebKitPresentationMode) => boolean;+}diff --git a/react/features/toolbox/components/web/AudioMuteButton.tsx b/react/features/toolbox/components/web/AudioMuteButton.tsxindex 1511fc7739..a4e945be01 100644--- a/react/features/toolbox/components/web/AudioMuteButton.tsx+++ b/react/features/toolbox/components/web/AudioMuteButton.tsx@@ -41,6 +41,10 @@ interface IProps extends AbstractAudioMuteButtonProps {*/classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;+ /**+ * Whether this instance should manage the global audio-mute keyboard shortcut.+ */+ registerKeyboardShortcut?: boolean;}/**@@ -71,11 +75,13 @@ class AudioMuteButton extends AbstractAudioMuteButton<IProps> {* @returns {void}*/override componentDidMount() {- this.props.dispatch(registerShortcut({- character: 'M',- helpDescription: 'keyboardShortcuts.mute',- handler: this._onKeyboardShortcut- }));+ if (this.props.registerKeyboardShortcut !== false) {+ this.props.dispatch(registerShortcut({+ character: 'M',+ helpDescription: 'keyboardShortcuts.mute',+ handler: this._onKeyboardShortcut+ }));+ }}/**@@ -85,7 +91,9 @@ class AudioMuteButton extends AbstractAudioMuteButton<IProps> {* @returns {void}*/override componentWillUnmount() {- this.props.dispatch(unregisterShortcut('M'));+ if (this.props.registerKeyboardShortcut !== false) {+ this.props.dispatch(unregisterShortcut('M'));+ }}/**diff --git a/react/features/toolbox/components/web/VideoMuteButton.tsx b/react/features/toolbox/components/web/VideoMuteButton.tsxindex 09ac33a3d4..a2a72a80ac 100644--- a/react/features/toolbox/components/web/VideoMuteButton.tsx+++ b/react/features/toolbox/components/web/VideoMuteButton.tsx@@ -40,6 +40,11 @@ export interface IProps extends AbstractVideoMuteButtonProps {* An object containing the CSS classes.*/classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;++ /**+ * Whether this instance should manage the global video-mute keyboard shortcut.+ */+ registerKeyboardShortcut?: boolean;}/**@@ -70,11 +75,13 @@ class VideoMuteButton extends AbstractVideoMuteButton<IProps> {* @returns {void}*/override componentDidMount() {- this.props.dispatch(registerShortcut({- character: 'V',- helpDescription: 'keyboardShortcuts.videoMute',- handler: this._onKeyboardShortcut- }));+ if (this.props.registerKeyboardShortcut !== false) {+ this.props.dispatch(registerShortcut({+ character: 'V',+ helpDescription: 'keyboardShortcuts.videoMute',+ handler: this._onKeyboardShortcut+ }));+ }}/**@@ -84,7 +91,9 @@ class VideoMuteButton extends AbstractVideoMuteButton<IProps> {* @returns {void}*/override componentWillUnmount() {- this.props.dispatch(unregisterShortcut('V'));+ if (this.props.registerKeyboardShortcut !== false) {+ this.props.dispatch(unregisterShortcut('V'));+ }}/**diff --git a/react/features/toolbox/constants.ts b/react/features/toolbox/constants.tsindex 0398e1d607..53cd1a4b12 100644--- a/react/features/toolbox/constants.ts+++ b/react/features/toolbox/constants.ts@@ -182,6 +182,7 @@ export const TOOLBAR_BUTTONS: ToolbarButton[] = ['stats','tileview','toggle-camera',+ 'toggle-pip','videoquality','whiteboard'];diff --git a/react/features/toolbox/hooks.web.ts b/react/features/toolbox/hooks.web.tsindex 6988bfde2a..0500139826 100644--- a/react/features/toolbox/hooks.web.ts+++ b/react/features/toolbox/hooks.web.ts@@ -37,6 +37,7 @@ import {isParticipantsPaneEnabled} from '../participants-pane/functions';import { useParticipantPaneButton } from '../participants-pane/hooks.web';+import { usePipToggleButton } from '../pip/hooks';import { usePollsButton } from '../polls/hooks.web';import { addReactionToBuffer } from '../reactions/actions.any';import { toggleReactionsMenuVisibility } from '../reactions/actions.web';@@ -311,6 +312,7 @@ export function useToolboxButtons(const _help = useHelpButton();const _invite = useInviteButton();const customPanel = useCustomPanelButton();+ const togglePiPButton = usePipToggleButton();const buttons: { [key in ToolbarButton]?: IToolboxButton; } = {microphone,@@ -324,6 +326,7 @@ export function useToolboxButtons(invite: _invite,tileview,'toggle-camera': toggleCameraButton,+ 'toggle-pip': togglePiPButton,videoquality: videoQuality,fullscreen: _fullscreen,security,diff --git a/react/features/toolbox/types.ts b/react/features/toolbox/types.tsindex d23fe2ce51..9c692c4102 100644--- a/react/features/toolbox/types.ts+++ b/react/features/toolbox/types.ts@@ -54,6 +54,7 @@ export type ToolbarButton = 'audiotranslation' |'stats' |'tileview' |'toggle-camera' |+ 'toggle-pip' |'videoquality' |'whiteboard' |'__end';