Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

26.9 KB
Raw Blame
// Hosts the native D3D preview canvas (the sole pixel source) plus the
// interactive-only DOM overlays (zoom gimbal, annotations, webcam drag) that
// still need real hitboxes. The shared source of truth is `useEditorSettings`,
// so toggling a slider here updates both the live preview (via the pushed
// scene) and the eventual native export.
//
// Architecture (matches the legacy `compositeLayout.computeCompositeLayout`,
// which this file still uses to POSITION the interactive overlays/hitboxes —
// the actual pixels come from the native canvas, not from this layout):
//   .previewFrame           → canvas (wallpaper bg; never receives padding
//                             from the slider directly).
//   .screenStage            → sizes/positions the zoom overlay by the
//                             composite-layout math (PiP/dual/stack/no-cam);
//                             its own <video> is CSS-hidden (decode/clock only).
//   .webcamSlot             → drag-to-reposition hitbox for the webcam PiP,
//                             positioned by the same math; its <video> is
//                             CSS-hidden too.
//   AnnotationLayer         → the whole frame: annotations are placed on it,
//                             a blur on the footage rect inside it.
//
// The composite layout is computed from `.previewFrame`'s actual rendered
// size (via ResizeObserver), so the camera + screen both resize correctly
// as the user resizes the workbench.

import type { PointerEvent as ReactPointerEvent } from "react";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import {
	type CameraFullscreenRegion,
	type CropRegion,
	DEFAULT_CROP_REGION,
	type WebcamLayoutPreset,
	type WebcamMaskShape,
	type ZoomFocus,
} from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import { materializeLayouts, sampleLayoutRegionsAt } from "@/lib/ai-edition/document/layout";
import {
	isFormatFillActive,
	resolveAspectRatioValue,
} from "@/lib/ai-edition/document/outputFormat";
import type {
	AxcutAnnotationRegion,
	AxcutAudioTrack,
	AxcutClip,
	AxcutTranscript,
	AxcutTrimRange,
	AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import { resolveActiveCameraTrack } from "@/lib/ai-edition/timeline/camera";
import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";
import {
	computeCameraFullscreenRect,
	computeCompositeLayout,
	interpolateCompositeLayout,
	paddedContentSize,
	resolveWebcamLayoutPreset,
	type WebcamCompositeLayout,
} from "@/lib/compositeLayout";
import { webcamAnchorAt } from "@/lib/projectDefaults";
import { wallpaperStyle } from "@/lib/wallpaper";
import { getCssClipPath } from "@/lib/webcamMaskShapes";
import { computeCameraFullscreenProgress } from "@/lib/zoomMath/cameraFullscreenUtils";
import { webcamBoxSourceSize } from "@/native/sceneDescription";
import {
	getWebcamNativeSize,
	getWebcamNativeSizeRevision,
	subscribeWebcamNativeSize,
} from "@/native/webcamSizeCache";
import { AnnotationLayer } from "./AnnotationLayer";
import { NativeCompositorOverlay } from "./NativeCompositorOverlay";
import styles from "./NewEditorShell.module.css";
import { type VideoSource, VirtualPreview } from "./VirtualPreview";
import { WebcamOverlay } from "./WebcamOverlay";
import { ZoomFocusOverlay } from "./ZoomFocusOverlay";

type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;

interface PreviewCanvasProps {
	videoSources: VideoSource[];
	/** Imported audio tracks + their asset URLs (issue #350), forwarded to
	 *  VirtualPreview. */
	audioTracks?: AxcutAudioTrack[];
	audioSources?: VideoSource[];
	clips: AxcutClip[];
	zoomRegions?: AxcutZoomRegion[];
	speedRegions?: SpeedRegion[];
	playUneditedTimeline?: boolean;
	cameraFullscreenRegions?: CameraFullscreenRegion[];
	trimRanges?: AxcutTrimRange[];
	/** Relayed to `VirtualPreview` so a clip carrying added words plays their extensions. */
	transcripts?: AxcutTranscript[];
	selectedZoomRegionId?: string | null;
	onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;
	onZoomFocusCommit?: () => void;
	annotationRegions?: AxcutAnnotationRegion[];
	selectedAnnotationId?: string | null;
	onSelectAnnotation?: (id: string) => void;
	/** Live edit of an annotation's geometry (and, for a text, its size) during a gesture. */
	onAnnotationChange?: (id: string, patch: Partial<AxcutAnnotationRegion>) => void;
	onAnnotationBlurDataChange?: (id: string, blurData: BlurData) => void;
	onAnnotationCommit?: () => void;
	seekTarget: { timeSec: number; requestId: number; preservePlayback?: boolean } | null;
	onTimeChange: (sec: number) => void;
	onSeek: (sec: number) => void;
	onLoadedMetadata: (sec: number, assetId: string) => void;
	onVideoElement: (el: HTMLVideoElement | null) => void;
	currentTimeSec: number;
	/** Receives the id of the asset whose <video> gave up, plus the MediaError
	 *  detail for the card. Transient failures are reloaded inside VirtualPreview
	 *  and never reach here (see Preview.tsx). */
	onVideoError?: (assetId: string, detail: string) => void;
	/** The mounted source decoded a frame again — see VirtualPreview. */
	onVideoRecovered?: (assetId: string) => void;
	/** Bumped to force a reload of the mounted source (the Retry button). */
	retryToken?: number;
}

// ponytail: fallback only — used until the active source's <video> reports
// its real intrinsic size via onLoadedMetadata. Nothing in the import/record
// pipeline ever probes/stores a recording's actual resolution (AxcutAsset's
// `video.width/height` is never populated), so without this the composite
// layout always assumed 16:9 regardless of the real capture — a recording at
// any other aspect then letterboxed a SECOND time inside its own screenRect
// (the <video> contain-fits its true ratio within a box sized for the wrong
// one), on top of the intentional `settings.padding` margin.
const SCREEN_SOURCE_SIZE = { width: 1920, height: 1080 };
const NO_SPEED_REGIONS: SpeedRegion[] = [];

export function PreviewCanvas(props: PreviewCanvasProps) {
	const te = useScopedT("editor");
	const { settings, setLive, commit } = useEditorSettings();
	// Captions are derived from the transcript, not passed down as regions — the
	// preview reads them from the same façade the inspector writes to.
	const document = useProjectStore((s) => s.document);
	const assets = document?.assets ?? [];
	const frameRef = useRef<HTMLDivElement | null>(null);
	const webcamSlotRef = useRef<HTMLDivElement | null>(null);
	// Real dimensions of the active source, from the <video>'s own
	// onLoadedMetadata (videoWidth/videoHeight) — null until the first source
	// loads, then falls back to SCREEN_SOURCE_SIZE.
	const [screenNativeSize, setScreenNativeSize] = useState<{
		width: number;
		height: number;
	} | null>(null);
	// ponytail: contain-fit the frame within its wrapper ourselves. CSS
	// `aspect-ratio` + `width: 100%` + `max-height: 100%` only clamps height —
	// it never shrinks width back down to match, so portrait ratios (9:16 etc)
	// silently overflowed/stretched instead of fitting. Measuring the parent
	// (not the frame, which we're about to size) lets us compute an explicit
	// pixel box that actually respects the ratio on both axes.
	const [containerSize, setContainerSize] = useState({ width: 1280, height: 720 });
	// ponytail: StrictMode's dev-only mount→cleanup→remount double-invoke
	// creates a fresh ResizeObserver, disconnects it, then creates ANOTHER
	// fresh one observing the same element in the same tick. Chromium
	// silently drops all FUTURE notifications for that element when this
	// exact disconnect-then-immediately-recreate pattern happens (confirmed
	// live: a raw counter in the callback never incremented past the initial
	// synchronous calls, even across a real viewport resize) — the frame
	// would freeze at its first-paint size and never resize again. Holding
	// the observer instance in a ref (surviving the double-invoke, since
	// only the effect body reruns) and just toggling observe/unobserve on it
	// avoids ever recreating the instance, which sidesteps the bug.
	const containerObserverRef = useRef<ResizeObserver | null>(null);

	useEffect(() => {
		const el = frameRef.current?.parentElement;
		if (!el) return;
		// ponytail: measure the parent's content box, not its border box —
		// clientWidth/clientHeight include any padding, and sizing the frame to
		// the full padded box while it's centered in the smaller content area
		// pushed it past the padding edge, where overflow:hidden clipped the
		// video. The parent (.previewWrap) is currently zero-padding, but
		// subtracting computed padding keeps this correct if that ever changes.
		const update = () => {
			const cs = getComputedStyle(el);
			const paddingX = Number.parseFloat(cs.paddingLeft) + Number.parseFloat(cs.paddingRight);
			const paddingY = Number.parseFloat(cs.paddingTop) + Number.parseFloat(cs.paddingBottom);
			setContainerSize({
				width: (el.clientWidth || 1280) - (Number.isFinite(paddingX) ? paddingX : 0),
				height: (el.clientHeight || 720) - (Number.isFinite(paddingY) ? paddingY : 0),
			});
		};
		update();
		if (typeof ResizeObserver === "undefined") return;
		if (!containerObserverRef.current) {
			containerObserverRef.current = new ResizeObserver(update);
		}
		const observer = containerObserverRef.current;
		observer.observe(el);
		return () => observer.unobserve(el);
	}, []);

	// ponytail: `canvasSize` used to be a SEPARATE DOM measurement of `frameRef` (its own
	// ResizeObserver, watching the frame element after it's sized). That was a second source
	// of truth for the exact same number `frameSize` below already computes synchronously from
	// `containerSize` + the aspect ratio -- and being observer-driven, it could go stale
	// relative to `frameSize` (this file's own comment above documents a known Chromium
	// ResizeObserver double-observe/freeze failure mode; a remount of the frame element would
	// leave this second observer watching a detached node forever). That staleness meant the
	// webcam-position math below (which needs to agree with the frame's ACTUAL rendered size)
	// could clamp against a WRONG canvas size after switching aspect ratio -- manifesting as
	// "can't drag the webcam flush to the edge" at non-default ratios. `frameSize` is already
	// exactly what the frame is styled to (`width: frameSize.width` a few lines below), so it's
	// used directly everywhere `canvasSize` used to be — one source of truth, no separate
	// observer that can desync from it.
	// `resolveAspectRatioValue`, not bare `getAspectRatioValue`: the latter has no document to
	// resolve the legacy "native" selection against and answers 16/9 for it, so a project saved
	// with "native" over portrait footage framed the preview 16:9 while `pickOutputDims` handed
	// the compositor a portrait `output` — preview and export disagreed on the frame's shape.
	const frameSize = useMemo(() => {
		const ratio = resolveAspectRatioValue(document, settings.aspectRatio);
		const { width: containerWidth, height: containerHeight } = containerSize;
		if (containerWidth <= 0 || containerHeight <= 0)
			return { width: containerWidth, height: containerHeight };
		if (containerWidth / containerHeight > ratio) {
			const height = containerHeight;
			return { width: Math.round(height * ratio), height: Math.round(height) };
		}
		const width = containerWidth;
		return { width: Math.round(width), height: Math.round(width / ratio) };
	}, [containerSize, settings.aspectRatio, document]);

	// Crop is per-clip (see clipSchema.cropRegion) — resolve it from whichever
	// clip the playhead is currently inside, the same lookup VirtualPreview
	// itself uses to map playback position back to a clip. `undefined` (no
	// crop stored) normalises to the identity region.
	const activeClip = useMemo(
		() => locateVirtualPosition(props.clips, props.currentTimeSec)?.clip ?? null,
		[props.clips, props.currentTimeSec],
	);
	const cropRegion: CropRegion = activeClip?.cropRegion ?? DEFAULT_CROP_REGION;

	// P4 — the layout preset is global (one panel for the whole timeline) but the camera
	// is per clip, so the layout has to be resolved against the clip under the playhead.
	const activeCameraTrack = useMemo(
		() => resolveActiveCameraTrack(assets, props.clips, props.currentTimeSec),
		[assets, props.clips, props.currentTimeSec],
	);
	const activeClipHasCamera = Boolean(activeCameraTrack?.visible && activeCameraTrack.sourcePath);
	// The drag box takes the camera's real proportions, the ones the native canvas draws
	// (a portrait camera in "Original" is a portrait box), not a fixed 4:3.
	const webcamSizeRevision = useSyncExternalStore(
		subscribeWebcamNativeSize,
		getWebcamNativeSizeRevision,
		() => 0,
	);
	// biome-ignore lint/correctness/useExhaustiveDependencies: the revision re-reads the probed-size cache
	const webcamSourceSize = useMemo(
		() =>
			webcamBoxSourceSize(
				activeCameraTrack,
				activeCameraTrack?.sourcePath ? getWebcamNativeSize(activeCameraTrack.sourcePath) : null,
				settings.webcamCropRegion,
			),
		[activeCameraTrack, settings.webcamCropRegion, webcamSizeRevision],
	);
	const layoutRegions = useMemo(() => (document ? materializeLayouts(document) : []), [document]);
	const sample = useMemo(
		() => sampleLayoutRegionsAt(layoutRegions, props.currentTimeSec, settings.webcamLayoutPreset),
		[layoutRegions, props.currentTimeSec, settings.webcamLayoutPreset],
	);
	const activePreset = resolveWebcamLayoutPreset(sample.preset, activeClipHasCamera);

	const formatFill = useMemo(() => (document ? isFormatFillActive(document) : false), [document]);
	const layout = useMemo(() => {
		// A clip with no camera lays out as "no-webcam", whatever the panel says. Hiding
		// only the webcam slot is not enough: the block presets size the SCREEN off the
		// block, so the screen stayed squeezed into its half with nothing beside it.
		const preset = activePreset;
		const mask = settings.webcamMaskShape as WebcamMaskShape;
		// Padding shrinks the available content area for ALL layouts (PiP/dual/stack),
		// through the same `paddedContentSize` the scene description uses.
		const maxContentSize = paddedContentSize(
			frameSize,
			settings.padding,
			settings.aspectRatio === "auto",
		);
		// The screen box must be fit to the CROPPED aspect ratio, not the full
		// source frame's — otherwise VirtualPreview's crop math (which assumes
		// its container is already correctly proportioned for the crop) would
		// stretch the video to fill a mis-shaped box.
		const fullScreenSize = screenNativeSize ?? SCREEN_SOURCE_SIZE;
		const croppedScreenSize = {
			width: Math.max(1, Math.round(fullScreenSize.width * cropRegion.width)),
			height: Math.max(1, Math.round(fullScreenSize.height * cropRegion.height)),
		};
		const compute = (layoutPreset: WebcamLayoutPreset) =>
			computeCompositeLayout({
				canvasSize: frameSize,
				maxContentSize,
				// Same box as the scene: a filled format gives the screen the whole padded area.
				screenSize: formatFill ? maxContentSize : croppedScreenSize,
				webcamSize: layoutPreset === "no-webcam" ? null : webcamSourceSize,
				layoutPreset,
				webcamSizePreset: settings.webcamSizePreset,
				// Picture-in-picture only: the block layouts place and round their own camera.
				webcamAnchor: settings.webcamAnchor,
				webcamMaskShape: mask,
				webcamRoundness: settings.webcamRoundness,
				frame: settings.frame,
			});
		const target = compute(preset);
		const from =
			sample.fromPreset && sample.progress < 1
				? compute(resolveWebcamLayoutPreset(sample.fromPreset, activeClipHasCamera))
				: null;
		return target && from ? interpolateCompositeLayout(from, target, sample.progress) : target;
	}, [
		frameSize,
		screenNativeSize,
		cropRegion,
		activeClipHasCamera,
		webcamSourceSize,
		settings.webcamMaskShape,
		settings.webcamSizePreset,
		settings.webcamAnchor,
		settings.webcamRoundness,
		settings.padding,
		settings.aspectRatio,
		formatFill,
		settings.frame,
		activePreset,
		sample.fromPreset,
		sample.progress,
	]);

	// Full Camera: during a cameraFullscreen region the webcam takes the whole
	// frame and eases back. Same `computeCameraFullscreenRect` call as both
	// exporters and the native compositor, so all four animate identically.
	const cameraFullscreenSpeedRegions = props.playUneditedTimeline
		? NO_SPEED_REGIONS
		: props.speedRegions;
	const cameraFullscreenProgress = useMemo(
		() =>
			computeCameraFullscreenProgress(
				props.cameraFullscreenRegions ?? [],
				Math.round(props.currentTimeSec * 1000),
				cameraFullscreenSpeedRegions,
			),
		[props.cameraFullscreenRegions, props.currentTimeSec, cameraFullscreenSpeedRegions],
	);
	const effectiveLayout = useMemo<WebcamCompositeLayout | null>(() => {
		if (!layout?.webcamRect || cameraFullscreenProgress <= 0) return layout;
		return {
			...layout,
			webcamRect: computeCameraFullscreenRect(
				layout.webcamRect,
				frameSize,
				cameraFullscreenProgress,
			),
		};
	}, [layout, cameraFullscreenProgress, frameSize]);

	// The stage hosting the interactive overlays is the CONTENT rect: the compositor draws the
	// frame around it (grown outward, or laid out beside the camera in a block layout), so every
	// handle (annotations, privacy blur, zoom focus) sits on `layout`.
	const frameStyle = useMemo(() => wallpaperStyle(settings.wallpaper), [settings.wallpaper]);
	const screenStyle = useMemo(
		() => buildScreenStyle(layout, settings, frameSize),
		[layout, settings, frameSize],
	);
	const webcamStyle = useMemo(
		() => buildWebcamStyle(effectiveLayout, settings, frameSize),
		[effectiveLayout, settings, frameSize],
	);
	// `layout` already resolves to "no-webcam" (hence `webcamRect: null`) for a
	// camera-less clip, so this is belt-and-braces rather than the only guard.
	const showWebcamSlot = Boolean(layout?.webcamRect && activeClipHasCamera);
	const [isPlaying, setIsPlaying] = useState(false);
	const handleVideoElement = useMemo(() => props.onVideoElement, [props.onVideoElement]);
	// L'élément `<video>` lui-même n'est plus retenu : il ne servait qu'à échantillonner des pixels
	// pour la mosaïque dessinée en DOM, que le compositeur natif rend désormais.
	const relayIsPlaying = (el: HTMLVideoElement | null) => {
		handleVideoElement(el);
		setIsPlaying(!el?.paused);
	};
	const relayLoadedMetadata = (
		durationSec: number,
		assetId: string,
		videoWidth: number,
		videoHeight: number,
	) => {
		if (videoWidth > 0 && videoHeight > 0) {
			setScreenNativeSize((prev) =>
				prev?.width === videoWidth && prev?.height === videoHeight
					? prev
					: { width: videoWidth, height: videoHeight },
			);
		}
		props.onLoadedMetadata(durationSec, assetId);
	};
	const relayProps = {
		...props,
		onVideoElement: relayIsPlaying,
		onLoadedMetadata: relayLoadedMetadata,
		cropRegion,
	};

	const handleWebcamPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
		if (
			activePreset !== "picture-in-picture" ||
			sample.progress < 1 ||
			cameraFullscreenProgress > 0
		)
			return;
		if (isPlaying) return;
		const slot = webcamSlotRef.current;
		if (!slot) return;
		const slotRect = slot.getBoundingClientRect();
		const frameRect = frameRef.current?.getBoundingClientRect();
		if (!frameRect) return;
		event.preventDefault();
		event.stopPropagation();
		const offsetX = event.clientX - (slotRect.left + slotRect.width / 2);
		const offsetY = event.clientY - (slotRect.top + slotRect.height / 2);
		slot.setPointerCapture(event.pointerId);

		// The camera snaps to the anchor nearest where it would sit if it followed the pointer,
		// so it is always somewhere it can be left: a corner or an edge middle.
		let anchor = settings.webcamAnchor;
		const handleMove = (e: PointerEvent) => {
			const frameNow = frameRef.current?.getBoundingClientRect();
			if (!frameNow) return;
			const next = webcamAnchorAt(
				(e.clientX - offsetX - frameNow.left) / frameNow.width,
				(e.clientY - offsetY - frameNow.top) / frameNow.height,
			);
			if (next === anchor) return;
			anchor = next;
			setLive({ webcamAnchor: next });
		};
		const handleUp = () => {
			slot.removeEventListener("pointermove", handleMove);
			slot.removeEventListener("pointerup", handleUp);
			slot.removeEventListener("pointercancel", handleUp);
			try {
				slot.releasePointerCapture(event.pointerId);
			} catch {
				// pointer already released
			}
			void commit();
		};
		slot.addEventListener("pointermove", handleMove);
		slot.addEventListener("pointerup", handleUp);
		slot.addEventListener("pointercancel", handleUp);
	};

	const isPipGrab =
		activePreset === "picture-in-picture" && sample.progress >= 1 && cameraFullscreenProgress <= 0;

	const selectedZoomRegion = props.selectedZoomRegionId
		? (props.zoomRegions?.find((z) => z.id === props.selectedZoomRegionId) ?? null)
		: null;

	return (
		<div
			ref={frameRef}
			className={styles.previewFrame}
			style={{ ...frameStyle, width: frameSize.width, height: frameSize.height }}
		>
			{/* Sole pixel source: the D3D-composited frame (wallpaper + screen + webcam +
			    cursor), streamed into a canvas. The <video> elements below are CSS-hidden
			    (visibility only — they stay mounted as the playback clock and for metadata,
			    since the native compositor doesn't drive playback itself), and the
			    interactive-only layers (ZoomFocusOverlay, AnnotationLayer, webcam drag
			    hitbox) still render on top as normal DOM so they stay clickable. No more
			    dual preview path. */}
			<NativeCompositorOverlay playUneditedTimeline={props.playUneditedTimeline} />
			{layout?.screenRect ? (
				<div className={styles.screenStage} style={screenStyle}>
					{(() => {
						// ponytail: PreviewCompositor (Pixi v8) regressed the screen
						// preview — the `<video>` is `visibility: hidden` while it's
						// the decode source for a Pixi VideoSource, and the
						// combination of `setPixiReady` + `canvasSize === {0,0}` on
						// mount produces a 1x1 canvas that the resize effect never
						// widens (the user reports either an empty stage showing
						// the wallpaper through, or a black rectangle where the
						// screen recording should be). Falling back to the legacy
						// VirtualPreview path — CSS-transformed <video> + measure
						// on ResizeObserver — until the Pixi path is hardened
						// behind a flag with its own tests.
						// See technical-documentation/architecture/preview.md
						// (todo) for the failure write-up.
						return (
							<VirtualPreview
								{...relayProps}
								videoStyle={videoBorderRadiusStyle(layout, settings)}
							/>
						);
					})()}
					{selectedZoomRegion && props.onZoomFocusChange ? (
						<ZoomFocusOverlay
							region={selectedZoomRegion}
							isPlaying={isPlaying}
							onFocusChange={props.onZoomFocusChange}
							onFocusCommit={props.onZoomFocusCommit}
						/>
					) : null}
				</div>
			) : null}
			{layout?.webcamRect && showWebcamSlot ? (
				<div
					ref={webcamSlotRef}
					className={styles.webcamSlot}
					style={{
						...webcamStyle,
						cursor: isPipGrab && !isPlaying ? "grab" : "default",
						touchAction: "none",
					}}
					onPointerDown={isPipGrab ? handleWebcamPointerDown : undefined}
					aria-label={te("preview.webcamPreview")}
				>
					<WebcamOverlay clips={props.clips} currentTimeSec={props.currentTimeSec} />
				</div>
			) : null}
			{/* Last, so a selected annotation over the camera takes the pointer before the
			    camera's drag hitbox does. It spans the frame: text, images and arrows move
			    anywhere in it, over the padding too. */}
			{layout?.screenRect &&
			props.annotationRegions &&
			props.onSelectAnnotation &&
			props.onAnnotationChange &&
			props.onAnnotationCommit ? (
				<AnnotationLayer
					annotations={props.annotationRegions}
					selectedAnnotationId={props.selectedAnnotationId ?? null}
					currentTimeSec={props.currentTimeSec}
					frameWidth={frameSize.width}
					frameHeight={frameSize.height}
					footage={layout.screenRect}
					onSelectAnnotation={props.onSelectAnnotation}
					onChange={props.onAnnotationChange}
					onCommit={props.onAnnotationCommit}
				/>
			) : null}
		</div>
	);
}

// Screen stage: rectangle from the composite layout, converted to percentages
// of the canvas. Positions/sizes the zoom overlay hosted inside it and the
// CSS-hidden <video> (decode/clock only) — no borderRadius/boxShadow here: the native canvas already draws its
// own rounded corners + shadow for this exact rect, and this container sits
// on TOP of it (z-index for the interactive layers). Duplicating the same
// decoration in CSS produced a visible "double rounded corner" — two
// slightly-offset rounded edges (native's + this container's own) instead of
// one.
function buildScreenStyle(
	layout: WebcamCompositeLayout | null,
	_settings: ReturnType<typeof useEditorSettings>["settings"],
	canvasSize: { width: number; height: number },
): React.CSSProperties {
	if (!layout?.screenRect) return { display: "none" };
	const r = layout.screenRect;
	return {
		position: "absolute",
		left: `${(r.x / canvasSize.width) * 100}%`,
		top: `${(r.y / canvasSize.height) * 100}%`,
		width: `${(r.width / canvasSize.width) * 100}%`,
		height: `${(r.height / canvasSize.height) * 100}%`,
		overflow: "hidden",
		display: "flex",
	};
}

function videoBorderRadiusStyle(
	layout: WebcamCompositeLayout | null,
	settings: ReturnType<typeof useEditorSettings>["settings"],
): React.CSSProperties {
	const borderRadius = layout?.screenBorderRadius ?? settings.borderRadius;
	return { borderRadius: `${borderRadius}px` };
}

// Webcam slot: full composite-layout rect — sizes/positions the drag hitbox
// (handleWebcamPointerDown) and the CSS-hidden webcam <video> (decode/clock
// only). No borderRadius/boxShadow: the native canvas already draws its own
// rounded/circular shape + shadow for this exact rect (duplicating it here
// produced a visible "double rounded corner"). `clipPath` is kept — unlike
// borderRadius/boxShadow it's not just decoration, it also shapes the
// hitbox's actual pointer-event area (e.g. "circle" mask), which should still
// match the native-drawn shape.
function buildWebcamStyle(
	layout: WebcamCompositeLayout | null,
	settings: ReturnType<typeof useEditorSettings>["settings"],
	canvasSize: { width: number; height: number },
): React.CSSProperties {
	if (!layout?.webcamRect) return { display: "none" };
	const r = layout.webcamRect;
	// The RECT's own shape, not the setting: Full Camera flattens the mask to a
	// rectangle as it takes the frame, and the hitbox must follow (a circular
	// clip-path over a full-screen camera would swallow clicks everywhere but a
	// disc in the middle).
	const mask = r.maskShape ?? (settings.webcamMaskShape as WebcamMaskShape);
	const clipPath = getCssClipPath(mask);
	const base: React.CSSProperties = {
		position: "absolute",
		left: `${(r.x / canvasSize.width) * 100}%`,
		top: `${(r.y / canvasSize.height) * 100}%`,
		width: `${(r.width / canvasSize.width) * 100}%`,
		height: `${(r.height / canvasSize.height) * 100}%`,
		overflow: "hidden",
		display: "flex",
		background: "transparent",
	};
	return clipPath ? { ...base, clipPath } : base;
}