Skip to content

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

feat(layout): weld screen and camera into one contain-fitted block, and give the camera the frame

Etienne Lescot9d4b30e9d3b7
diff --git a/docs/openscreen-ux-ui-spec.md b/docs/openscreen-ux-ui-spec.md
index 891d863b5..9d158fcbd 100644
--- a/docs/openscreen-ux-ui-spec.md
+++ b/docs/openscreen-ux-ui-spec.md
@@ -278,7 +278,7 @@ Two columns of rounded "control surfaces":
- **Motion Blur** — slider 0–1, step 0.01. Live numeric display.
- **Shadow** — slider 0–1, step 0.01. `Math.round(value*100)%` numeric.
- **Roundness** — slider 0–64 px, step 0.5. Numeric in px.
-- **Padding** — slider 0–100 %, step 1. Disabled when webcam layout is "vertical-stack".
+- **Padding** — slider 0–100 %, step 1. Applies to every webcam layout; in `dual-frame` / `vertical-stack` it insets the welded screen+camera block as one piece.
All sliders commit their value when the user releases the thumb (`onValueCommit`). Some update live (`onValueChange`) — e.g. padding uses `updateState` for the live preview and `commitState` on commit.
@@ -288,10 +288,18 @@ Only visible if a webcam video is present.
- **Preset** dropdown — `picture-in-picture` / `vertical-stack` / `dual-frame` / `no-webcam`. Some entries are filtered based on canvas aspect (e.g. vertical-stack only in portrait, dual-frame only in landscape). Switching presets also clears the saved PiP position unless the new preset is PiP.
- **Mirror Webcam** toggle — visible when preset ≠ no-webcam.
-- **Shrink on Zoom (Reactive Webcam)** toggle + info-tooltip — only when preset = PiP.
+- **Shrink on Zoom (Reactive Webcam)** toggle + info-tooltip — only when preset = PiP. `dual-frame` / `vertical-stack` force it off and hide the control: their camera box is sized off the screen capture, so shrinking it mid-zoom would tear a hole in the block (`supportsWebcamReactiveZoom`).
- **Camera Shape** — four small icon-buttons (rectangle / circle / square / rounded), each rendered as an SVG glyph.
- **Webcam Size** slider — 10–50 %.
+`dual-frame` ("Side by side") and `vertical-stack` ("Top / bottom") weld the screen and the camera into a single block, governed by three constraints (`computeCompositeLayout`, `block` branch):
+
+1. **Screen keeps its ratio** — the screen box is always the capture's own aspect ratio, untouched.
+2. **The block is contained in the scene** — screen + gap + camera contain-fit the (padded) scene whatever its ratio, so at padding 0 the block sits flush against the two edges its own ratio makes it reach.
+3. **The camera tends toward square** — the camera shares the screen's cross-edge (same height beside it, same width under it, so they read as one solid block); its one free dimension is chosen to make the *block* match the scene's aspect ratio (perfect fill, no bars), then held within **[0.8, 1.25]** of square (`BLOCK_CAMERA_ASPECT_TOLERANCE`). So the camera fills when it can and only goes *slightly* rectangular — never a thin slice — when the scene ratio pulls it there.
+
+There is no fixed split anymore: it falls out of those three constraints and adapts to both the capture ratio and the scene ratio. When the geometry allows a near-square camera that also fills the scene, both happen at once (e.g. a 4:3 capture top/bottom in a 9:16 scene → square camera, 100 % fill). Camera Shape and Webcam Size do not apply to either preset. The single tunable is the square tolerance.
+
The webcam bubble can also be dragged around the canvas (mouse-drag) — the position persists as `webcamPosition`.
##### Panel: Cursor
@@ -350,6 +358,14 @@ A single red destructive button "Delete Trim Region".
- Custom speed input — decimal text field; Enter or blur commits. Out-of-range (>16×) shows a toast "Speed can't go higher than 16×".
- **Delete Speed Region** button.
+##### Inspector: Selected Full Camera
+
+- Explanatory paragraph + **Delete region** button. The timing is edited by dragging the region's edges on the timeline; there is nothing else to tune.
+- Full Camera is **not** a zoom of the webcam bubble: it hands the camera the whole frame. At full strength the camera rect is exactly the output frame — no margin, no padding, no corner radius, no mask shape, no drop shadow, and nothing of the composition (wallpaper, screen capture, cursor) left showing behind it (`computeCameraFullscreenRect`).
+- Getting there is one lerp from the layout rect to `[0, 0, W, H]`, eased in at the region's start and out (over a longer window) at its end. The box changes aspect ratio along the way; every renderer cover-crops the camera into whatever box it is handed, so the image is never stretched by the animation.
+- The mask dissolves through its own radius rather than popping: a circle mask already *is* a rounded rect at radius = half its (square) box, so flattening the shape to a rectangle on frame one and easing the radius to 0 carries every shape out continuously, with no per-shape branch. The PiP drop shadow fades out on the same curve.
+- Reactive "shrink on zoom" is ignored for any frame where Full Camera is active — "shrink for the zoom" and "grow to full" in the same frame means nothing.
+
##### Inspector: Selected annotation (`<AnnotationSettingsPanel>`)
Top-level tabs: **Text** / **Image** / **Arrow**.
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index 26b355754..122cf1296 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -1248,12 +1248,23 @@ impl Compositor {
.as_ref()
.and_then(|s| s.layout.webcam_rect)
.map(|r| [r.x, r.y, r.width, r.height]);
+ // Idem pour l'écran. Les deux rects viennent du MÊME appel `computeCompositeLayout`, donc
+ // les consommer ensemble est la seule façon de garder le bloc écran+caméra cohérent :
+ // n'en prendre qu'un revenait à mélanger la géométrie de l'app et un placement fixture.
+ let app_screen_rect: Option<[f32; 4]> = scene_ref
+ .as_ref()
+ .and_then(|s| s.layout.screen_rect)
+ .map(|r| [r.x, r.y, r.width, r.height]);
let (mut p, mut pp) = match (&scene_preset, app_webcam_rect) {
(Some(_preset), Some(wr)) => {
- // webcam rect résolu côté app → on s'aligne strictement ; l'écran reste plein
- // cadre (le padding slider l'insètera ensuite dans `scale_frame`).
+ // webcam rect résolu côté app → on s'aligne strictement. Idem pour l'écran quand
+ // l'app le fournit ; sinon il reste plein cadre (le padding slider l'insètera
+ // ensuite dans `scale_frame`).
let mut fp = preset_placements(_preset);
fp.webcam.dst = wr;
+ if let Some(sr) = app_screen_rect {
+ fp.screen.dst = sr;
+ }
(fp, fp) // layout statique → vélocité nulle
}
(Some(preset), None) => {
@@ -1262,7 +1273,6 @@ impl Compositor {
}
(None, _) => (timeline(frame, cfg), timeline(frame - 1.0, cfg)),
};
- let is_vstack = scene_preset.as_deref() == Some("vertical-stack");
let lp = *self.live_params.borrow();
// Motion blur écran : quand la scène (contrat de l'app) est posée, c'est elle qui pilote
// (parité inspector : 1.0 + motion_blur*15 taps), sinon on retombe sur `cfg.mblur_n`
@@ -1325,8 +1335,11 @@ impl Compositor {
let webcam_size_scale_prev = base_size_scale * reactive_scale(pp.zoom, cam_progress_prev);
// padding : échelle globale du layout autour du centre du cadre (parité web frameRenderer :
- // paddingScale = 1 - padding*0.4 → padding 0 = plein cadre). Vertical-stack l'ignore.
- let padding_scale = if is_vstack { 1.0 } else { 1.0 - lp.padding * 0.4 };
+ // paddingScale = 1 - padding*0.4 → padding 0 = plein cadre). S'applique à TOUS les presets :
+ // côté web, side-by-side et top/bottom soudent écran+caméra en un bloc unique et c'est ce
+ // bloc que le padding rétrécit (cf. `compositeLayout.ts`, branche `block`). Vertical-stack
+ // en était exempté tant qu'il était full-bleed ; il ne l'est plus.
+ let padding_scale = 1.0 - lp.padding * 0.4;
let scale_frame = |dst: [f32; 4], s: f32| -> [f32; 4] {
[0.5 + (dst[0] - 0.5) * s, 0.5 + (dst[1] - 0.5) * s, dst[2] * s, dst[3] * s]
};
@@ -1409,8 +1422,20 @@ impl Compositor {
let (cx, cy) = (dst[0] + dst[2] * 0.5, dst[1] + dst[3] * 0.5);
[cx - nw * 0.5, cy - nh * 0.5, nw, nh]
};
- let s_dst = fit_dst_to_aspect(scale_frame(p.screen.dst, padding_scale), crop_aspect);
- let s_dst_prev = fit_dst_to_aspect(scale_frame(pp.screen.dst, padding_scale), crop_aspect);
+ // Quand l'app a résolu la boîte écran, elle a DÉJÀ appliqué le padding (le rect est
+ // calculé contre `maxContentSize`) et l'a DÉJÀ mise au ratio du crop
+ // (`computeCompositeLayout` reçoit la taille de la source recadrée) : rejouer
+ // `scale_frame` + `fit_dst_to_aspect` par-dessus appliquerait le padding deux fois et
+ // re-contiendrait une boîte déjà au bon ratio. Même raisonnement que pour la webcam.
+ let fit_screen = |dst: [f32; 4]| {
+ if app_screen_rect.is_some() {
+ dst
+ } else {
+ fit_dst_to_aspect(scale_frame(dst, padding_scale), crop_aspect)
+ }
+ };
+ let s_dst = fit_screen(p.screen.dst);
+ let s_dst_prev = fit_screen(pp.screen.dst);
// le padding n'affecte QUE l'écran (la quantité de fond révélée). La webcam reste ancrée
// en bas-droite à sa marge fixe, quelle que soit la valeur de padding (pas de scale_frame)
// — SAUF quand l'app a résolu un placement explicite (`app_webcam_rect`, drag-to-reposition
@@ -1437,35 +1462,17 @@ impl Compositor {
fit_cam_aspect(scale_corner_br(pp.webcam.dst, webcam_size_scale_prev))
};
- // Full Camera : la webcam grandit pour couvrir (presque) tout le cadre, en conservant
- // SON ratio actuel (pas celui du cadre) — parité `computeCameraFullscreenTargetRect` (TS) :
- // marge = 2.5% du plus petit côté du cadre, ajustée pour tenir dans les bornes.
+ // Full Camera : la caméra PREND le cadre — parité `computeCameraFullscreenRect` (TS).
+ // La cible est exactement [0,0,1,1] : pas de marge, pas de padding, pas d'arrondi, et
+ // plus rien de la composition (fond, écran, ombre) derrière. Le rect change de ratio en
+ // chemin, mais `cover_crop_uv` (plus bas) dérive la coupe source du ratio RÉEL de la
+ // boîte à chaque frame : la caméra n'est donc jamais étirée pendant l'animation.
let fullscreen_dst = |dst: [f32; 4], progress: f32| -> [f32; 4] {
if progress <= 0.0 {
return dst;
}
- let margin_px = self.rw().min(self.rh()) * 0.025;
- let bounds_w = (self.rw() - margin_px * 2.0).max(0.0);
- let bounds_h = (self.rh() - margin_px * 2.0).max(0.0);
- let cur_w_px = dst[2] * self.rw();
- let cur_h_px = dst[3] * self.rh();
- let aspect = if cur_h_px > 0.0 { cur_w_px / cur_h_px } else { 1.0 };
- let (mut full_w, mut full_h) = (bounds_w, bounds_w / aspect);
- if full_h > bounds_h {
- full_h = bounds_h;
- full_w = full_h * aspect;
- }
- let full_x = margin_px + (bounds_w - full_w) * 0.5;
- let full_y = margin_px + (bounds_h - full_h) * 0.5;
- let cur_x_px = dst[0] * self.rw();
- let cur_y_px = dst[1] * self.rh();
let lerp = |a: f32, b: f32| a + (b - a) * progress;
- [
- lerp(cur_x_px, full_x) / self.rw(),
- lerp(cur_y_px, full_y) / self.rh(),
- lerp(cur_w_px, full_w) / self.rw(),
- lerp(cur_h_px, full_h) / self.rh(),
- ]
+ [lerp(dst[0], 0.0), lerp(dst[1], 0.0), lerp(dst[2], 1.0), lerp(dst[3], 1.0)]
};
w_dst = fullscreen_dst(w_dst, cam_progress);
w_dst_prev = fullscreen_dst(w_dst_prev, cam_progress_prev);
@@ -1487,7 +1494,14 @@ impl Compositor {
// (une correction scalaire par `uniform_stretch` seul compenserait la MAGNITUDE mais pas
// l'ANISOTROPIE : elle laissait les coins elliptiques dès que stretch_x != stretch_y,
// càd dès que le ratio de sortie n'est pas 16:9 — cf. rapport utilisateur sur le 9:16).
- let s_radius = if cfg.rounded { p.screen.radius * lp.radius_scale } else { 0.0 };
+ // Rayon écran : celui que le preset impose quand l'app en envoie un (les layouts en bloc
+ // encadrent écran et caméra à l'identique), sinon le slider Roundness comme avant.
+ let app_screen_radius = scene_ref.as_ref().and_then(|s| s.layout.screen_radius);
+ let s_radius = match (cfg.rounded, app_screen_radius) {
+ (false, _) => 0.0,
+ (true, Some(r)) => r,
+ (true, None) => p.screen.radius * lp.radius_scale,
+ };
let w_px = [w_dst[2] * self.rw(), w_dst[3] * self.rh()];
// forme webcam : rayon SDF dérivé de la SEULE forme choisie. Le slider Roundness ne
// s'applique qu'à l'ÉCRAN, jamais à la caméra. Parité web (compositeLayout) : rectangle
@@ -1498,11 +1512,18 @@ impl Compositor {
// ratio de sortie.
let w_px_final = w_px;
let w_min_final = w_px_final[0].min(w_px_final[1]);
- let w_radius = match lp.webcam_shape {
- 1 => w_min_final * 0.5, // circle
- 3 => w_min_final * 0.3, // rounded (nettement plus arrondi)
- _ => w_min_final * 0.12, // rectangle / square → léger arrondi (identique)
- };
+ // Full Camera dissout la forme en même temps qu'elle prend le cadre : le rayon fond
+ // vers 0 avec `cam_progress`, donc le cercle devient un rect à coins de plus en plus
+ // francs puis un plein cadre net — aucun masque ne survit au plein écran (parité
+ // `computeCameraFullscreenRect`, qui ramène `maskShape` à "rectangle" et lerpe le
+ // rayon vers 0 pour exactement la même raison).
+ let shape_fade = (1.0 - cam_progress).clamp(0.0, 1.0);
+ let w_radius = shape_fade
+ * match lp.webcam_shape {
+ 1 => w_min_final * 0.5, // circle
+ 3 => w_min_final * 0.3, // rounded (nettement plus arrondi)
+ _ => w_min_final * 0.12, // rectangle / square → léger arrondi (identique)
+ };
self.begin([0.0, 0.0, 0.0, 1.0]);
@@ -1802,8 +1823,11 @@ impl Compositor {
// miroir = échanger les bornes u du rect source (flip horizontal).
let (u0, u1) = if lp.webcam_mirror { (su1, su0) } else { (su0, su1) };
if lp.has_webcam {
- if cfg.shadow {
- self.draw_shadow(w_dst, w_px, w_radius, 32.0, [0.0, 12.0], 0.5 * lp.shadow_scale);
+ // L'ombre portée appartient à la bulle flottante : elle se retire avec elle
+ // (`shape_fade`), pour qu'au plein écran plus rien n'encadre la caméra.
+ if cfg.shadow && shape_fade > 0.0 {
+ let strength = 0.5 * lp.shadow_scale * shape_fade;
+ self.draw_shadow(w_dst, w_px, w_radius, 32.0, [0.0, 12.0], strength);
}
self.draw_video(
&LayerCB {
diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rs
index ce54111eb..438b58ee7 100644
--- a/poc-d3d/src/scene.rs
+++ b/poc-d3d/src/scene.rs
@@ -53,6 +53,19 @@ pub struct SceneLayout {
/// ce champ, ce qui active le fallback `preset_placements` Rust historique (PiP codé en dur).
#[serde(default)]
pub webcam_rect: Option<SceneRect>,
+ /// Rect ÉCRAN résolu côté app (mêmes fractions 0..1 du cadre de sortie que `webcam_rect`).
+ /// Déjà paddé et déjà au ratio du crop — le natif le consomme TEL QUEL, sans `padding_scale`
+ /// ni `fit_dst_to_aspect`. Sans lui, le natif gardait sa boîte écran codée en dur
+ /// (`preset_placements`) tout en respectant la boîte caméra de l'app : les deux ne
+ /// s'accordaient plus et la caméra du preset side-by-side sortait du cadre.
+ ///
+ /// `#[serde(default)]` : ancien payload / tests → None → fallback `preset_placements`.
+ #[serde(default)]
+ pub screen_rect: Option<SceneRect>,
+ /// Rayon des coins de l'écran en px de la sortie, quand le preset en impose un (les layouts
+ /// en bloc encadrent écran et caméra à l'identique). None → slider Roundness, comme avant.
+ #[serde(default)]
+ pub screen_radius: Option<f32>,
}
/// Rect normalisé 0..1 du cadre de sortie : x, y en haut-gauche ; width, height.
@@ -130,9 +143,9 @@ pub struct SceneSpeedRegion {
pub speed: f64,
}
-/// Une zone "Full Camera" de la timeline (temps en secondes) : la webcam grandit pour couvrir
-/// (presque) tout le cadre pendant cette fenêtre. Pas de champs au-delà des bornes temporelles
-/// (miroir de `CameraFullscreenRegion`, TS).
+/// Une zone "Full Camera" de la timeline (temps en secondes) : la caméra PREND tout le cadre
+/// pendant cette fenêtre (plein écran net — ni marge, ni arrondi, ni masque, ni fond derrière).
+/// Pas de champs au-delà des bornes temporelles (miroir de `CameraFullscreenRegion`, TS).
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SceneCameraFullscreenRegion {
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 37dd8930d..e0a227441 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -44,9 +44,8 @@ import { createPlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock
import type { SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";
import {
- computeCameraFullscreenTargetRect,
+ computeCameraFullscreenRect,
computeCompositeLayout,
- lerpRect,
type WebcamCompositeLayout,
} from "@/lib/compositeLayout";
import { classifyWallpaper, resolveImageWallpaperUrl } from "@/lib/wallpaper";
@@ -250,10 +249,9 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
settings.padding,
]);
- // Full Camera: during a cameraFullscreen region the webcam overlay grows to
- // (almost) fill the canvas and eases back. Mirror the exporter's frameRenderer
- // exactly — lerp the PiP rect toward computeCameraFullscreenTargetRect (radius
- // 0 at full) — so preview and export animate to the identical rect.
+ // 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 cameraFullscreenProgress = useMemo(
() =>
computeCameraFullscreenProgress(
@@ -264,18 +262,13 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
);
const effectiveLayout = useMemo<WebcamCompositeLayout | null>(() => {
if (!layout?.webcamRect || cameraFullscreenProgress <= 0) return layout;
- const target = computeCameraFullscreenTargetRect(frameSize, layout.webcamRect);
- const fullRect = {
- x: target.x,
- y: target.y,
- width: target.width,
- height: target.height,
- borderRadius: 0,
- maskShape: layout.webcamRect.maskShape,
- };
return {
...layout,
- webcamRect: lerpRect(layout.webcamRect, fullRect, cameraFullscreenProgress),
+ webcamRect: computeCameraFullscreenRect(
+ layout.webcamRect,
+ frameSize,
+ cameraFullscreenProgress,
+ ),
};
}, [layout, cameraFullscreenProgress, frameSize]);
@@ -462,7 +455,7 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
borderRadius={
effectiveLayout?.webcamRect?.borderRadius ?? layout.webcamRect.borderRadius
}
- webcamMaskShape={settings.webcamMaskShape}
+ webcamMaskShape={effectiveLayout?.webcamRect?.maskShape ?? settings.webcamMaskShape}
layoutPreset={settings.webcamLayoutPreset}
/>
</div>
@@ -553,7 +546,11 @@ function buildWebcamStyle(
): React.CSSProperties {
if (!layout?.webcamRect) return { display: "none" };
const r = layout.webcamRect;
- const mask = settings.webcamMaskShape as WebcamMaskShape;
+ // 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",
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 6004ea30b..968d92167 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -52,6 +52,7 @@ import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";
import { formatMs } from "@/lib/ai-edition/timeline/format";
import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";
import { getAssetPath } from "@/lib/assetPath";
+import { supportsWebcamReactiveZoom } from "@/lib/compositeLayout";
import { CURSOR_THEMES, DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";
import { buildGradientFromEditor } from "@/lib/gradientBuilder";
import { resolveImageWallpaperUrl, WALLPAPER_PATHS, WALLPAPER_THUMB_PATHS } from "@/lib/wallpaper";
@@ -1371,10 +1372,15 @@ export function LayoutPane() {
return subscribeNativeCompositor(syncToNative);
}, [settings.webcamSizePreset, settings.webcamMirrored, settings.webcamMaskShape]);
// the mask shape picker only makes sense for Picture-in-Picture.
- // Dual-frame (side-by-side) and vertical-stack (top/bottom) hardcode a
- // rectangle in the legacy layout math, so we hide those controls when the
- // preset isn't PiP.
+ // Dual-frame (side-by-side) and vertical-stack (top/bottom) weld the camera
+ // to the screen as one block — the mask is rectangular and sized off the
+ // screen capture — so we hide those controls when the preset isn't PiP.
const isPip = settings.webcamLayoutPreset === "picture-in-picture";
+ // Same reason for "Shrink on zoom": shrinking the camera mid-zoom would tear a
+ // hole in the block, so the block layouts force it off (see
+ // `supportsWebcamReactiveZoom`) and the toggle is dropped rather than shown
+ // as a control that does nothing.
+ const supportsReactiveZoom = supportsWebcamReactiveZoom(settings.webcamLayoutPreset);
// P4 — a project can hold clips with no camera attached at all (plain
// imported videos, or a recording made without a webcam). The layout
// controls have nothing to act on in that case, so they're disabled
@@ -1419,14 +1425,16 @@ export function LayoutPane() {
}}
/>
</div>
- <div className={styles.paneRow}>
- <span className="label">Shrink on zoom</span>
- <Toggle
- checked={settings.webcamReactiveZoom}
- disabled={layoutControlsDisabled}
- onChange={(v) => void set({ webcamReactiveZoom: v })}
- />
- </div>
+ {supportsReactiveZoom ? (
+ <div className={styles.paneRow}>
+ <span className="label">Shrink on zoom</span>
+ <Toggle
+ checked={settings.webcamReactiveZoom}
+ disabled={layoutControlsDisabled}
+ onChange={(v) => void set({ webcamReactiveZoom: v })}
+ />
+ </div>
+ ) : null}
{isPip ? (
<>
<div className={styles.sectionLabel}>Camera shape</div>
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index de5cf856d..7fa773b22 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -460,9 +460,9 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
{paneHeader(<Maximize2 size={15} />, "Full Camera", onClose, tc("actions.close"))}
<div style={bodyStyle}>
<p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--muted)" }}>
- While this region plays, the webcam grows to (almost) fill the frame and eases back at
- the end. Drag the region's edges on the timeline to change when it starts and how long
- it lasts.
+ While this region plays, the camera takes the whole frame — no border, no rounding, no
+ background — and eases back at the end. Drag the region's edges on the timeline to
+ change when it starts and how long it lasts.
</p>
<button type="button" onClick={deleteAndClose} style={deleteBtnStyle}>
<Trash2 size={14} />
diff --git a/src/lib/compositeLayout.test.ts b/src/lib/compositeLayout.test.ts
index 26a640a52..12b78f7e7 100644
--- a/src/lib/compositeLayout.test.ts
+++ b/src/lib/compositeLayout.test.ts
@@ -1,10 +1,29 @@
import { describe, expect, it } from "vitest";
import {
- CAMERA_FULLSCREEN_MARGIN_FRACTION,
- computeCameraFullscreenTargetRect,
+ computeCameraFullscreenRect,
computeCompositeLayout,
+ isWebcamBlockLayout,
+ resolveWebcamReactiveZoom,
+ type StyledRenderRect,
} from "./compositeLayout";
+describe("resolveWebcamReactiveZoom", () => {
+ it("honours the stored setting for picture-in-picture", () => {
+ expect(resolveWebcamReactiveZoom("picture-in-picture", true)).toBe(true);
+ expect(resolveWebcamReactiveZoom("picture-in-picture", false)).toBe(false);
+ });
+
+ it("forces shrink-on-zoom off for the block layouts", () => {
+ // The camera box is welded to the screen there, so shrinking it mid-zoom
+ // would tear a hole in the block. The UI hides the toggle to match.
+ expect(resolveWebcamReactiveZoom("dual-frame", true)).toBe(false);
+ expect(resolveWebcamReactiveZoom("vertical-stack", true)).toBe(false);
+ expect(isWebcamBlockLayout("dual-frame")).toBe(true);
+ expect(isWebcamBlockLayout("vertical-stack")).toBe(true);
+ expect(isWebcamBlockLayout("picture-in-picture")).toBe(false);
+ });
+});
+
describe("computeCompositeLayout", () => {
it("anchors the overlay in the lower-right corner", () => {
const layout = computeCompositeLayout({
@@ -178,94 +197,208 @@ describe("computeCompositeLayout", () => {
});
});
- it("centers the combined screen and webcam stack in vertical stack mode", () => {
+ // ─── block layouts: geometry shared by both presets ────────────────────────
+
+ // The three constraints, asserted directly: screen keeps its ratio, the couple
+ // is contained in the scene, and the camera tends toward square.
+ const CAPTURES = [
+ { label: "21:9", size: { width: 2560, height: 1080 } },
+ { label: "16:9", size: { width: 1920, height: 1080 } },
+ { label: "4:3", size: { width: 1440, height: 1080 } },
+ { label: "1:1", size: { width: 1080, height: 1080 } },
+ { label: "4:5", size: { width: 1080, height: 1350 } },
+ { label: "9:16", size: { width: 1080, height: 1920 } },
+ ];
+ const SCENES = [
+ { label: "16:9", size: { width: 1920, height: 1080 } },
+ { label: "9:16", size: { width: 1080, height: 1920 } },
+ { label: "1:1", size: { width: 1080, height: 1080 } },
+ { label: "4:5", size: { width: 1080, height: 1350 } },
+ { label: "21:9", size: { width: 2560, height: 1080 } },
+ ];
+ // A 4:3 source camera, to prove the camera box is cut from the block, not the
+ // camera's own aspect ratio.
+ const CAM = { width: 960, height: 720 };
+
+ for (const preset of ["dual-frame", "vertical-stack"] as const) {
+ for (const capture of CAPTURES) {
+ for (const scene of SCENES) {
+ it(`${preset}: capture ${capture.label} in scene ${scene.label} — screen ratio kept, block contained, camera near square`, () => {
+ const layout = computeCompositeLayout({
+ canvasSize: scene.size,
+ maxContentSize: scene.size, // padding 0
+ screenSize: capture.size,
+ webcamSize: CAM,
+ layoutPreset: preset,
+ })!;
+ const screen = layout.screenRect;
+ const cam = layout.webcamRect!;
+
+ // 1. Screen keeps the capture's own aspect ratio.
+ expect(screen.width / screen.height).toBeCloseTo(
+ capture.size.width / capture.size.height,
+ 1,
+ );
+
+ // 2. The whole block is contained in the scene — nothing overflows.
+ for (const r of [screen, cam]) {
+ expect(r.x).toBeGreaterThanOrEqual(-1);
+ expect(r.y).toBeGreaterThanOrEqual(-1);
+ expect(r.x + r.width).toBeLessThanOrEqual(scene.size.width + 1);
+ expect(r.y + r.height).toBeLessThanOrEqual(scene.size.height + 1);
+ }
+
+ // 3. The camera tends toward square: its aspect stays within the
+ // tolerance band (4:5 … 5:4), never an extreme slice.
+ const camAspect = cam.width / cam.height;
+ expect(camAspect).toBeGreaterThanOrEqual(1 / 1.25 - 0.02);
+ expect(camAspect).toBeLessThanOrEqual(1.25 + 0.02);
+
+ // The camera keeps the block solid: aligned with the screen on the
+ // shared edge, sitting after it with a gap, no overlap.
+ if (preset === "dual-frame") {
+ expect(cam.height).toBeCloseTo(screen.height, 0);
+ expect(cam.x).toBeGreaterThanOrEqual(screen.x + screen.width);
+ } else {
+ expect(cam.width).toBeCloseTo(screen.width, 0);
+ expect(cam.y).toBeGreaterThanOrEqual(screen.y + screen.height);
+ }
+ });
+ }
+ }
+ }
+
+ it("fills the scene exactly (block aspect == scene aspect) when a near-square camera allows it", () => {
+ // A 16:9 screen stacked top/bottom in a portrait-ish scene: the square-ish
+ // camera that fills the scene is reachable inside the band, so the block
+ // touches all four edges and the camera lands close to square.
+ const scene = { width: 1000, height: 1587 };
const layout = computeCompositeLayout({
- canvasSize: { width: 1920, height: 1080 },
- maxContentSize: { width: 1536, height: 864 },
+ canvasSize: scene,
+ maxContentSize: scene,
screenSize: { width: 1920, height: 1080 },
- webcamSize: { width: 1280, height: 720 },
+ webcamSize: { width: 960, height: 720 },
layoutPreset: "vertical-stack",
- });
-
- expect(layout).not.toBeNull();
- // ponytail: padding insets the content vertically. `maxContentSize` is
- // 1536x864 (canvasSize × paddingFit=0.8), so the content area is
- // 1536×864 centered at y=(1080−864)/2=108. Everything inside the
- // stack is computed against this content area, not the canvas.
- expect(layout!.webcamRect).not.toBeNull();
- const contentHeight = 864;
- const webcamCapHeight = Math.min(1280 / (1280 / 720), Math.round(contentHeight * 0.4));
- const webcamHeight = Math.round(webcamCapHeight);
- const webcamWidth = Math.round(webcamHeight * (1280 / 720));
- const gap = Math.max(8, Math.round(1536 * 0.02));
- const contentY = Math.floor((1080 - contentHeight) / 2);
- // Camera is centered horizontally inside the content area, which is
- // itself centered in the canvas. Sits at contentY + (contentHeight
- // − webcamHeight − gap) — i.e. with the gap between it and the
- // screen, all inside the padded band.
- const screenHeight = contentHeight - webcamHeight - gap;
- const contentX = Math.floor((1920 - 1536) / 2);
- const camOffsetInContent = Math.floor((1536 - webcamWidth) / 2);
- expect(layout!.webcamRect!.x).toBe(contentX + camOffsetInContent);
- expect(layout!.webcamRect!.y).toBe(contentY + screenHeight + gap);
- expect(layout!.webcamRect!.width).toBe(webcamWidth);
- expect(layout!.webcamRect!.height).toBe(webcamHeight);
- // Border-radius follows the preset fraction (max:24, min:8, fraction:0.06)
- // on min(width, height) — gives soft rounded corners instead of 0.
- const expectedRadius = Math.min(
- 24,
- Math.max(8, Math.round(Math.min(webcamWidth, webcamHeight) * 0.06)),
- );
- expect(layout!.webcamRect!.borderRadius).toBe(expectedRadius);
- // Screen fills the padded band above the gap, centered horizontally
- // in the canvas. (cover mode.)
- expect(layout!.screenRect.x).toBe(contentX);
- expect(layout!.screenRect.y).toBe(contentY);
- expect(layout!.screenRect.width).toBe(1536);
- expect(layout!.screenRect.height).toBe(screenHeight);
- expect(layout!.screenCover).toBe(true);
+ })!;
+ const screen = layout.screenRect;
+ const cam = layout.webcamRect!;
+ const blockW = Math.max(screen.x + screen.width, cam.x + cam.width) - Math.min(screen.x, cam.x);
+ const blockH =
+ Math.max(screen.y + screen.height, cam.y + cam.height) - Math.min(screen.y, cam.y);
+ // Block matches the scene aspect → contains with (near) zero bars.
+ expect(blockW / blockH).toBeCloseTo(scene.width / scene.height, 1);
+ expect(cam.width / cam.height).toBeCloseTo(1, 1); // ~square
});
- it("keeps the screen full-canvas and omits the webcam when dimensions are unavailable in stack mode", () => {
+ it("makes the camera squarer for a landscape capture top/bottom than the old fixed 50/50 did", () => {
+ // Regression guard for the reported issue: a 16:9 capture used to give a
+ // 1.78:1 camera strip in Top / bottom. It must now be markedly squarer.
const layout = computeCompositeLayout({
canvasSize: { width: 1920, height: 1080 },
- maxContentSize: { width: 1536, height: 864 },
+ maxContentSize: { width: 1920, height: 1080 },
screenSize: { width: 1920, height: 1080 },
+ webcamSize: { width: 960, height: 720 },
layoutPreset: "vertical-stack",
- });
+ })!;
+ const cam = layout.webcamRect!;
+ expect(cam.width).toBeCloseTo(layout.screenRect.width, 0); // still full width
+ expect(cam.width / cam.height).toBeLessThan(1.3); // was 1.78
+ });
- expect(layout).not.toBeNull();
- expect(layout?.screenRect).toEqual({
- x: 0,
- y: 0,
- width: 1920,
- height: 1080,
- });
- expect(layout?.webcamRect).toBeNull();
- expect(layout?.screenCover).toBe(true);
+ it("keeps both block presets' frames sharing one corner radius", () => {
+ for (const layoutPreset of ["dual-frame", "vertical-stack"] as const) {
+ const layout = computeCompositeLayout({
+ canvasSize: { width: 1920, height: 1080 },
+ maxContentSize: { width: 1920, height: 1080 },
+ screenSize: { width: 1920, height: 1080 },
+ webcamSize: { width: 960, height: 720 },
+ layoutPreset,
+ })!;
+ expect(layout.screenBorderRadius).toBe(layout.webcamRect!.borderRadius);
+ expect(layout.screenBorderRadius).toBeGreaterThan(0);
+ }
+ });
+
+ // ─── block layouts: padding & fallback ─────────────────────────────────────
+
+ it.each([
+ "vertical-stack",
+ "dual-frame",
+ ] as const)("insets the whole %s block by the padding, keeping it centered", (layoutPreset) => {
+ const args = {
+ canvasSize: { width: 1920, height: 1080 },
+ screenSize: { width: 1920, height: 1080 },
+ webcamSize: { width: 960, height: 720 },
+ layoutPreset,
+ };
+ const flush = computeCompositeLayout({
+ ...args,
+ maxContentSize: { width: 1920, height: 1080 },
+ })!;
+ // maxContentSize = canvasSize × paddingFit(=0.8) — i.e. padding 50%.
+ const padded = computeCompositeLayout({
+ ...args,
+ maxContentSize: { width: 1536, height: 864 },
+ })!;
+
+ // Screen and camera shrink together by the same factor: the block moves
+ // as one piece, so their ratio to each other is untouched.
+ expect(padded.screenRect.width / flush.screenRect.width).toBeCloseTo(0.8, 2);
+ expect(padded.webcamRect!.width / flush.webcamRect!.width).toBeCloseTo(0.8, 2);
+ expect(padded.webcamRect!.height / flush.webcamRect!.height).toBeCloseTo(0.8, 2);
+
+ // Still centered in the canvas.
+ const blockLeft = Math.min(padded.screenRect.x, padded.webcamRect!.x);
+ const blockRight = Math.max(
+ padded.screenRect.x + padded.screenRect.width,
+ padded.webcamRect!.x + padded.webcamRect!.width,
+ );
+ const blockTop = Math.min(padded.screenRect.y, padded.webcamRect!.y);
+ const blockBottom = Math.max(
+ padded.screenRect.y + padded.screenRect.height,
+ padded.webcamRect!.y + padded.webcamRect!.height,
+ );
+ expect(blockLeft).toBeCloseTo(1920 - blockRight, 0);
+ expect(blockTop).toBeCloseTo(1080 - blockBottom, 0);
});
- it("uses a 2:1 split layout in dual frame mode", () => {
+ it.each([
+ "vertical-stack",
+ "dual-frame",
+ ] as const)("contain-fits the %s block into a portrait scene without overflowing", (layoutPreset) => {
+ const layout = computeCompositeLayout({
+ canvasSize: { width: 1080, height: 1920 },
+ maxContentSize: { width: 1080, height: 1920 },
+ screenSize: { width: 1920, height: 1080 },
+ webcamSize: { width: 960, height: 720 },
+ layoutPreset,
+ })!;
+
+ for (const rect of [layout.screenRect, layout.webcamRect!]) {
+ expect(rect.x).toBeGreaterThanOrEqual(0);
+ expect(rect.y).toBeGreaterThanOrEqual(0);
+ expect(rect.x + rect.width).toBeLessThanOrEqual(1080);
+ expect(rect.y + rect.height).toBeLessThanOrEqual(1920);
+ }
+ // The screen still carries the capture's own ratio in a scene whose
+ // ratio is nothing like it.
+ expect(layout.screenRect.width / layout.screenRect.height).toBeCloseTo(1920 / 1080, 2);
+ });
+
+ it.each([
+ "vertical-stack",
+ "dual-frame",
+ ] as const)("falls back to the screen alone in %s when the clip has no camera", (layoutPreset) => {
const layout = computeCompositeLayout({
canvasSize: { width: 1920, height: 1080 },
maxContentSize: { width: 1536, height: 864 },
screenSize: { width: 1920, height: 1080 },
- webcamSize: { width: 1280, height: 720 },
- layoutPreset: "dual-frame",
+ layoutPreset,
});
- expect(layout).not.toBeNull();
- expect(layout?.webcamRect).not.toBeNull();
- expect(layout?.screenRect.y).toBe(108);
- expect(layout?.screenRect.height).toBe(864);
- expect(layout?.screenBorderRadius).toBe(layout?.webcamRect?.borderRadius);
- expect(layout?.webcamRect?.y).toBe(108);
- expect(layout?.webcamRect?.height).toBe(864);
- expect(layout?.webcamRect?.x).toBeGreaterThan(layout?.screenRect.x ?? 0);
- expect(
- Math.abs((layout?.screenRect.width ?? 0) - 2 * (layout?.webcamRect?.width ?? 0)),
- ).toBeLessThanOrEqual(1);
- expect(layout?.screenCover).toBe(true);
+ expect(layout?.webcamRect).toBeNull();
+ // Contain-fit into the padded area, like every other preset.
+ expect(layout?.screenRect).toEqual({ x: 192, y: 108, width: 1536, height: 864 });
});
it("forces circular and square masks to use square dimensions", () => {
@@ -313,52 +446,84 @@ describe("computeCompositeLayout", () => {
});
});
-describe("computeCameraFullscreenTargetRect", () => {
- it("insets the target rect by the margin fraction of the canvas' shorter dimension", () => {
- const canvasSize = { width: 1920, height: 1080 };
- const margin = Math.round(
- Math.min(canvasSize.width, canvasSize.height) * CAMERA_FULLSCREEN_MARGIN_FRACTION,
- );
- // Square aspect source so height is the constrained dimension in a landscape canvas.
- const rect = computeCameraFullscreenTargetRect(canvasSize, { width: 1080, height: 1080 });
+describe("computeCameraFullscreenRect", () => {
+ const CANVAS = { width: 1920, height: 1080 };
+ const pip = (over: Partial<StyledRenderRect> = {}): StyledRenderRect => ({
+ x: 1520,
+ y: 740,
+ width: 360,
+ height: 270,
+ borderRadius: 24,
+ maskShape: "rectangle",
+ ...over,
+ });
- expect(rect.height).toBeCloseTo(canvasSize.height - margin * 2, 0);
- expect(rect.y).toBeCloseTo(margin, 0);
+ it("is the whole frame at full progress — no margin, no rounding, no mask", () => {
+ const rect = computeCameraFullscreenRect(pip(), CANVAS, 1);
+
+ expect(rect).toEqual({
+ x: 0,
+ y: 0,
+ width: CANVAS.width,
+ height: CANVAS.height,
+ borderRadius: 0,
+ maskShape: "rectangle",
+ });
});
- it("preserves the source aspect ratio (contain-fit) instead of stretching to the canvas", () => {
- const canvasSize = { width: 1920, height: 1080 };
- const source = { width: 1280, height: 720 }; // 16:9, same as canvas
- const rect = computeCameraFullscreenTargetRect(canvasSize, source);
+ it("leaves the layout rect untouched at zero progress", () => {
+ const base = pip();
+ const rect = computeCameraFullscreenRect(base, CANVAS, 0);
- expect(rect.width / rect.height).toBeCloseTo(source.width / source.height, 3);
+ expect(rect.x).toBe(base.x);
+ expect(rect.y).toBe(base.y);
+ expect(rect.width).toBe(base.width);
+ expect(rect.height).toBe(base.height);
+ expect(rect.borderRadius).toBe(base.borderRadius);
});
- it("fits a portrait source by constraining height, centering vertically and horizontally", () => {
- const canvasSize = { width: 1920, height: 1080 };
- const source = { width: 9, height: 16 }; // portrait webcam frame
- const rect = computeCameraFullscreenTargetRect(canvasSize, source);
-
- expect(rect.width / rect.height).toBeCloseTo(source.width / source.height, 3);
- expect(rect.height).toBeLessThanOrEqual(canvasSize.height);
- expect(rect.width).toBeLessThanOrEqual(canvasSize.width);
- // Centered: equal leftover space on both sides horizontally.
- expect(rect.x).toBeCloseTo(canvasSize.width - rect.x - rect.width, 0);
+ it("takes the frame whatever the canvas' own aspect ratio", () => {
+ const portrait = { width: 1080, height: 1920 };
+ const rect = computeCameraFullscreenRect(pip(), portrait, 1);
+
+ expect(rect.width).toBe(portrait.width);
+ expect(rect.height).toBe(portrait.height);
});
- it("fits a landscape source by constraining width when it would overflow", () => {
- const canvasSize = { width: 1080, height: 1920 }; // portrait canvas
- const source = { width: 16, height: 9 }; // landscape webcam frame
- const rect = computeCameraFullscreenTargetRect(canvasSize, source);
+ it("dissolves a circle mask through its radius instead of popping it to a rectangle", () => {
+ // computeCompositeLayout gives a circle a square box and a radius of half its
+ // side, so a rounded rect at that radius IS that circle — the mask can flatten
+ // to "rectangle" on frame one and the shape still eases out continuously.
+ const circle = pip({ width: 270, height: 270, borderRadius: 135, maskShape: "circle" });
- expect(rect.width / rect.height).toBeCloseTo(source.width / source.height, 3);
- expect(rect.y).toBeCloseTo(canvasSize.height - rect.y - rect.height, 0);
+ const start = computeCameraFullscreenRect(circle, CANVAS, 0);
+ expect(start.borderRadius).toBe(Math.min(circle.width, circle.height) / 2);
+ expect(start.maskShape).toBe("rectangle");
+
+ const mid = computeCameraFullscreenRect(circle, CANVAS, 0.5);
+ expect(mid.borderRadius).toBeCloseTo(circle.borderRadius / 2, 5);
+ expect(computeCameraFullscreenRect(circle, CANVAS, 1).borderRadius).toBe(0);
});
- it("falls back to a 1:1 aspect ratio for degenerate (zero-size) source rects", () => {
- const canvasSize = { width: 1920, height: 1080 };
- const rect = computeCameraFullscreenTargetRect(canvasSize, { width: 0, height: 0 });
+ it("moves monotonically toward the frame, so the growth never doubles back", () => {
+ const base = pip();
+ let prevArea = base.width * base.height;
+ for (const t of [0.25, 0.5, 0.75, 1]) {
+ const rect = computeCameraFullscreenRect(base, CANVAS, t);
+ const area = rect.width * rect.height;
+ expect(area).toBeGreaterThan(prevArea);
+ expect(rect.x).toBeGreaterThanOrEqual(0);
+ expect(rect.y).toBeGreaterThanOrEqual(0);
+ prevArea = area;
+ }
+ });
- expect(rect.width).toBeCloseTo(rect.height, 0);
+ it("clamps progress outside 0..1 instead of overshooting the frame", () => {
+ expect(computeCameraFullscreenRect(pip(), CANVAS, 2)).toEqual(
+ computeCameraFullscreenRect(pip(), CANVAS, 1),
+ );
+ expect(computeCameraFullscreenRect(pip(), CANVAS, -1)).toEqual(
+ computeCameraFullscreenRect(pip(), CANVAS, 0),
+ );
});
});
diff --git a/src/lib/compositeLayout.ts b/src/lib/compositeLayout.ts
index 3413911e0..eaf389e90 100644
--- a/src/lib/compositeLayout.ts
+++ b/src/lib/compositeLayout.ts
@@ -25,71 +25,42 @@ export interface StyledRenderRect extends RenderRect {
}
/**
- * Linearly interpolates position/size/borderRadius between two rects. Used to grow the
- * webcam overlay from its normal layout to a full-canvas rect during a "Full Camera"
- * timeline region, at progress `t` (0 = from, 1 = to). Pure and shape-agnostic so preview
- * (DOM transform) and export (canvas draw) can share the exact same math.
+ * The camera's rect during a "Full Camera" region: its layout rect at `progress` 0,
+ * the WHOLE frame at 1.
+ *
+ * Full Camera is not a zoom of the picture-in-picture bubble — it is the camera taking
+ * the frame. The endpoint is exactly `[0, 0, canvasWidth, canvasHeight]`: no margin, no
+ * padding, no corner rounding, and nothing of the composition (wallpaper, screen,
+ * shadow) left showing behind it. The box may change aspect ratio on its way there
+ * because every renderer cover-crops the camera into whatever box it is handed, so the
+ * image is never stretched by the animation.
+ *
+ * The mask shape degenerates to a plain rounded rectangle whose radius eases to 0, which
+ * is what makes the morph continuous instead of a pop: `computeCompositeLayout` already
+ * gives a circle mask a radius of half its (square) box, and a rounded rect at that
+ * radius IS that circle — so one lerp carries every shape out of existence with no
+ * per-shape branch.
+ *
+ * Pure, and shared by the preview, both exporters and the native compositor, so all four
+ * animate to the identical rect.
*/
-export function lerpRect(
- from: StyledRenderRect,
- to: StyledRenderRect,
- t: number,
+export function computeCameraFullscreenRect(
+ base: StyledRenderRect,
+ canvasSize: Size,
+ progress: number,
): StyledRenderRect {
- const clamped = Math.max(0, Math.min(1, t));
+ const t = Math.max(0, Math.min(1, progress));
+ const lerp = (from: number, to: number) => from + (to - from) * t;
return {
- x: from.x + (to.x - from.x) * clamped,
- y: from.y + (to.y - from.y) * clamped,
- width: from.width + (to.width - from.width) * clamped,
- height: from.height + (to.height - from.height) * clamped,
- borderRadius: from.borderRadius + (to.borderRadius - from.borderRadius) * clamped,
- maskShape: from.maskShape,
+ x: lerp(base.x, 0),
+ y: lerp(base.y, 0),
+ width: lerp(base.width, canvasSize.width),
+ height: lerp(base.height, canvasSize.height),
+ borderRadius: lerp(base.borderRadius, 0),
+ maskShape: "rectangle",
};
}
-/**
- * Inset fraction (of the canvas' shorter dimension) left as a visible border around the
- * webcam when Full Camera expands it, so rounded/circular webcam masks never touch the
- * canvas edge at full screen. Matches the same order of magnitude as `MARGIN_FRACTION`
- * used for the picture-in-picture layout above.
- */
-export const CAMERA_FULLSCREEN_MARGIN_FRACTION = 0.025;
-
-/**
- * Computes the Full Camera "grown" target rect: the largest rect matching `aspectRect`'s
- * aspect ratio that fits centered inside the canvas, inset by `CAMERA_FULLSCREEN_MARGIN_FRACTION`
- * of the canvas' shorter dimension. Preserving the base rect's aspect ratio (rather than
- * filling the canvas' own aspect ratio) keeps the webcam undistorted throughout the lerp,
- * since `lerpRect` only stays proportion-correct if both endpoints share the same ratio.
- * Pure function shared by preview (`VideoPlayback.tsx`) and export (`frameRenderer.ts`) so
- * both animate to the identical rect.
- */
-export function computeCameraFullscreenTargetRect(
- canvasSize: Size,
- aspectRect: { width: number; height: number },
-): RenderRect {
- const { width: canvasWidth, height: canvasHeight } = canvasSize;
- const margin = Math.round(
- Math.min(canvasWidth, canvasHeight) * CAMERA_FULLSCREEN_MARGIN_FRACTION,
- );
- const boundsWidth = Math.max(0, canvasWidth - margin * 2);
- const boundsHeight = Math.max(0, canvasHeight - margin * 2);
-
- const aspect =
- aspectRect.width > 0 && aspectRect.height > 0 ? aspectRect.width / aspectRect.height : 1;
-
- let width = boundsWidth;
- let height = width / aspect;
- if (height > boundsHeight) {
- height = boundsHeight;
- width = height * aspect;
- }
-
- const x = margin + (boundsWidth - width) / 2;
- const y = margin + (boundsHeight - height) / 2;
-
- return { x, y, width, height };
-}
-
export interface Size {
width: number;
height: number;
@@ -123,27 +94,56 @@ interface OverlayTransform {
minSize: number;
}
-interface StackTransform {
- type: "stack";
- gapFraction: number;
- minGap: number;
-}
-
-interface SplitTransform {
- type: "split";
+/**
+ * Screen + camera welded into one solid block that keeps the screen capture's own
+ * aspect ratio, then contain-fits into the (padded) scene — see the design notes in
+ * `computeCompositeLayout`. Used by both "Side by side" and "Top / bottom".
+ */
+interface BlockTransform {
+ type: "block";
+ /** Where the camera sits relative to the screen: beside it, or under it. */
+ direction: "row" | "column";
+ /** Gap between screen and camera, as a fraction of the screen's own width. */
gapFraction: number;
- minGap: number;
- screenUnits: number;
- webcamUnits: number;
}
export interface WebcamLayoutPresetDefinition {
label: string;
- transform: OverlayTransform | StackTransform | SplitTransform;
+ transform: OverlayTransform | BlockTransform;
borderRadius: BorderRadiusRule;
shadow: WebcamLayoutShadow | null;
}
+/**
+ * Presets whose camera box is welded to the screen. Their geometry is fully derived
+ * from the screen capture's aspect ratio, so the webcam-size slider, the mask-shape
+ * picker and the reactive "shrink on zoom" scaling have nothing to act on there.
+ */
+export function isWebcamBlockLayout(preset: WebcamLayoutPreset = "picture-in-picture"): boolean {
+ return preset === "dual-frame" || preset === "vertical-stack";
+}
+
+/**
+ * Whether "shrink on zoom" (the reactive webcam scaling) applies to a preset. Only the
+ * free-floating picture-in-picture bubble can shrink: the block layouts size their
+ * camera off the screen box, so shrinking it would break the "same width / same height
+ * as the screen capture" contract and tear a hole in the block. Single rule shared by
+ * the UI (which hides the toggle), the preview, both exporters and the native scene.
+ */
+export function supportsWebcamReactiveZoom(
+ preset: WebcamLayoutPreset = "picture-in-picture",
+): boolean {
+ return preset === "picture-in-picture";
+}
+
+/** Effective reactive-zoom flag: the stored setting, gated by the active preset. */
+export function resolveWebcamReactiveZoom(
+ preset: WebcamLayoutPreset | undefined,
+ enabled: boolean | undefined,
+): boolean {
+ return Boolean(enabled) && supportsWebcamReactiveZoom(preset);
+}
+
export interface WebcamCompositeLayout {
screenRect: RenderRect;
webcamRect: StyledRenderRect | null;
@@ -161,6 +161,23 @@ export function webcamSizeToFraction(percent: number): number {
const MARGIN_FRACTION = 0.02;
const MAX_BORDER_RADIUS = 24;
+/**
+ * Breathing room between the screen box and the camera box inside a block layout,
+ * as a fraction of the screen's own width. Expressed against the screen (not the
+ * canvas) so it scales with the block itself: the same value reads as the same
+ * visual gap whether the block is width- or height-constrained by the scene.
+ */
+const BLOCK_GAP_FRACTION = 0.02;
+/**
+ * How far the camera box may drift from square, as a maximum aspect ratio (its
+ * reciprocal is the minimum). The camera's free side is chosen to make the whole
+ * block match the SCENE's aspect ratio — perfect contain-fit, no bars — but the
+ * result is then held within `[1/T, T]` of square, so the camera never becomes an
+ * extreme slice. This single knob is the whole of "the camera tends toward square,
+ * going only slightly rectangular when filling the scene asks it to". `1.25` keeps
+ * it between 4:5 and 5:4.
+ */
+const BLOCK_CAMERA_ASPECT_TOLERANCE = 1.25;
const WEBCAM_LAYOUT_PRESET_MAP: Record<WebcamLayoutPreset, WebcamLayoutPresetDefinition> = {
"picture-in-picture": {
label: "Picture in Picture",
@@ -183,11 +200,11 @@ const WEBCAM_LAYOUT_PRESET_MAP: Record<WebcamLayoutPreset, WebcamLayoutPresetDef
},
},
"vertical-stack": {
- label: "Vertical Stack",
+ label: "Top / bottom",
transform: {
- type: "stack",
- gapFraction: 0.02,
- minGap: 8,
+ type: "block",
+ direction: "column",
+ gapFraction: BLOCK_GAP_FRACTION,
},
borderRadius: {
max: 24,
@@ -197,13 +214,11 @@ const WEBCAM_LAYOUT_PRESET_MAP: Record<WebcamLayoutPreset, WebcamLayoutPresetDef
shadow: null,
},
"dual-frame": {
- label: "Dual Frame",
+ label: "Side by side",
transform: {
- type: "split",
- gapFraction: 0.02,
- minGap: 12,
- screenUnits: 2,
- webcamUnits: 1,
+ type: "block",
+ direction: "row",
+ gapFraction: BLOCK_GAP_FRACTION,
},
borderRadius: {
max: MAX_BORDER_RADIUS,
@@ -294,156 +309,98 @@ export function computeCompositeLayout(params: {
return null;
}
- if (preset.transform.type === "stack") {
+ if (preset.transform.type === "block") {
+ const block = preset.transform;
+
if (!webcamWidth || !webcamHeight || webcamWidth <= 0 || webcamHeight <= 0) {
- // No webcam, so screen fills the whole canvas (cover mode).
+ // No camera on this clip: the block degenerates to the screen alone, which
+ // contain-fits the padded area like every other preset does.
return {
- screenRect: { x: 0, y: 0, width: canvasWidth, height: canvasHeight },
+ screenRect: centerRect({ canvasSize, size: screenSize, maxSize: maxContentSize }),
webcamRect: null,
- screenCover: true,
};
}
- // ponytail: padding insets the content vertically (like dual-frame
- // insets it horizontally). `maxContentSize` from `PreviewCanvas` is
- // already padded to `canvasSize × paddingFit`; we derive a content
- // area, vertically center the screen+gap+camera stack inside it, and
- // keep the wallpaper visible at the top and bottom of the canvas.
- const contentHeight = Math.min(
- canvasHeight,
- Math.max(1, Math.round(maxContentSize?.height ?? canvasHeight)),
- );
- const contentWidth = Math.min(
- canvasWidth,
- Math.max(1, Math.round(maxContentSize?.width ?? canvasWidth)),
+ // The block is laid out in UNIT space first, where the screen is exactly
+ // 1 wide and `h = 1 / screenAspect` tall. The gap and the camera are
+ // expressed against that same unit, so a single contain-fit at the end
+ // scales screen, gap and camera together.
+ //
+ // The camera's SOURCE aspect ratio plays no part: the box is a mask cut
+ // from the block's geometry, and the camera video is cover-cropped into it
+ // downstream (`screenCover` for the screen, the renderers' cover crop for
+ // the camera).
+ const screenAspect = screenWidth / screenHeight;
+ const unitScreenHeight = 1 / screenAspect; // h
+ const gap = block.gapFraction;
+ const isRow = block.direction === "row";
+
+ // The camera shares the screen's cross-edge (same height beside it, same
+ // width under it — the aligned edge that makes them one solid block), so its
+ // size ALONG the split axis is the one free dimension. Three constraints fix
+ // it, in order:
+ // 1. screen keeps its own aspect ratio → screen is 1 × h, untouched;
+ // 2. the block contain-fits the scene → pick `along` so the block's
+ // aspect equals the scene's (fills it, no bars) — see `alongForFill`;
+ // 3. the camera tends toward square → but clamp `along` so the
+ // camera stays within `[1/T, T]` of square, so filling the scene only
+ // nudges it slightly rectangular, never into a slice.
+ // Square is `along === cameraCross`; the clamp is symmetric in both layouts.
+ const cameraCross = isRow ? unitScreenHeight : 1;
+ const sceneAspect = canvasWidth / canvasHeight;
+ const alongForFill = isRow
+ ? sceneAspect * unitScreenHeight - 1 - gap // block width = 1 + gap + along
+ : 1 / sceneAspect - unitScreenHeight - gap; // block height = h + gap + along
+ const cameraAlong = Math.min(
+ cameraCross * BLOCK_CAMERA_ASPECT_TOLERANCE,
+ Math.max(cameraCross / BLOCK_CAMERA_ASPECT_TOLERANCE, alongForFill),
);
- const contentY = Math.max(0, Math.floor((canvasHeight - contentHeight) / 2));
- // ponytail: gap between screen and camera, scaled off the padded
- // content width so the proportional spacing stays consistent.
- const gap = Math.max(
- preset.transform.minGap,
- Math.round(contentWidth * preset.transform.gapFraction),
+ const unitCameraWidth = isRow ? cameraAlong : 1;
+ const unitCameraHeight = isRow ? unitScreenHeight : cameraAlong;
+ const blockWidth = isRow ? 1 + gap + cameraAlong : 1;
+ const blockHeight = isRow ? unitScreenHeight : unitScreenHeight + gap + cameraAlong;
+
+ // Contain-fit the whole block into the padded content area. `maxContentSize`
+ // is `canvasSize × paddingFit`, so padding shrinks the BLOCK (not just the
+ // screen) and padding 0 leaves it flush against the two scene edges its own
+ // ratio makes it touch — bottom/top for a column, left/right for a row.
+ const contentWidth = Math.min(canvasWidth, Math.max(1, maxContentSize.width));
+ const contentHeight = Math.min(canvasHeight, Math.max(1, maxContentSize.height));
+ const scale = Math.min(contentWidth / blockWidth, contentHeight / blockHeight);
+
+ const originX = (canvasWidth - blockWidth * scale) / 2;
+ const originY = (canvasHeight - blockHeight * scale) / 2;
+
+ const screenRect = snapRect(originX, originY, scale, unitScreenHeight * scale);
+ const cameraRect = snapRect(
+ isRow ? originX + (1 + gap) * scale : originX,
+ isRow ? originY : originY + (unitScreenHeight + gap) * scale,
+ unitCameraWidth * scale,
+ unitCameraHeight * scale,
);
- // Webcam: full content width at the bottom, capped at 40% of the
- // padded content area so the screen always has room (otherwise a
- // 16:9 webcam in a 16:9 canvas collapses the screen to 0px). Aspect
- // is preserved when the request overflows the cap. The 40% follows the
- // same 1-of-N ratio the dual-frame preset uses for screenUnits/webcamUnits.
- const webcamAspect = webcamWidth / webcamHeight;
- const requestedWebcamWidth = contentWidth;
- const requestedWebcamHeight = Math.round(requestedWebcamWidth / webcamAspect);
- const stackCapHeight = Math.max(1, Math.round(contentHeight * 0.4));
- const resolvedWebcamHeight = Math.min(requestedWebcamHeight, stackCapHeight);
- const resolvedWebcamWidth = Math.round(resolvedWebcamHeight * webcamAspect);
-
- // Screen: fills remaining space above the camera + gap, content width.
- const screenRectHeight = Math.max(0, contentHeight - resolvedWebcamHeight - gap);
-
- // Camera border-radius follows the same preset fraction rule as
- // dual-frame so the strip gets gentle rounded corners.
const webcamBorderRadius = Math.min(
preset.borderRadius.max,
Math.max(
preset.borderRadius.min,
- Math.round(
- Math.min(resolvedWebcamWidth, resolvedWebcamHeight) * preset.borderRadius.fraction,
- ),
+ Math.round(Math.min(cameraRect.width, cameraRect.height) * preset.borderRadius.fraction),
),
);
return {
- screenRect: {
- // ponytail: the content area (padded by `maxContentSize`) is
- // centered in the canvas — top/bottom from the canvas, and
- // left/right from the canvas when `maxContentSize` is narrower
- // than canvasWidth. This matches the dual-frame pattern where
- // padding = canvas-margin.
- x: Math.max(0, Math.floor((canvasWidth - contentWidth) / 2)),
- y: contentY,
- width: contentWidth,
- height: screenRectHeight,
- },
- webcamRect: {
- // ponytail: legacy hardcoded x:0 which left-aligned the camera
- // strip in the bottom-left when its aspect produced a narrower
- // width than the canvas. Center the strip horizontally within
- // the padded content area when there's room to spare, and
- // match the screen's horizontal inset.
- x:
- Math.max(0, Math.floor((canvasWidth - contentWidth) / 2)) +
- Math.floor((contentWidth - resolvedWebcamWidth) / 2),
- // ponytail: place camera BELOW the gap inside the padded area so
- // screen and camera don't touch.
- y: contentY + screenRectHeight + gap,
- width: resolvedWebcamWidth,
- height: resolvedWebcamHeight,
- borderRadius: webcamBorderRadius,
- },
- screenCover: true,
- };
- }
-
- if (preset.transform.type === "split") {
- const screenRect = centerRect({
- canvasSize,
- size: screenSize,
- maxSize: maxContentSize,
- });
-
- if (!webcamWidth || !webcamHeight || webcamWidth <= 0 || webcamHeight <= 0) {
- return { screenRect, webcamRect: null };
- }
-
- const contentWidth = Math.min(canvasWidth, Math.max(1, Math.round(maxContentSize.width)));
- const contentHeight = Math.min(canvasHeight, Math.max(1, Math.round(maxContentSize.height)));
- const contentX = Math.max(0, Math.floor((canvasWidth - contentWidth) / 2));
- const contentY = Math.max(0, Math.floor((canvasHeight - contentHeight) / 2));
- const gap = Math.max(
- preset.transform.minGap,
- Math.round(contentWidth * preset.transform.gapFraction),
- );
- const totalUnits = preset.transform.screenUnits + preset.transform.webcamUnits;
- const availableWidth = Math.max(1, contentWidth - gap);
- const screenSlotWidth = Math.max(
- 1,
- Math.round((availableWidth * preset.transform.screenUnits) / totalUnits),
- );
- const webcamSlotWidth = Math.max(1, availableWidth - screenSlotWidth);
-
- const screenSlot = {
- x: contentX,
- y: contentY,
- width: screenSlotWidth,
- height: contentHeight,
- };
- const webcamSlot = {
- x: contentX + screenSlotWidth + gap,
- y: contentY,
- width: webcamSlotWidth,
- height: contentHeight,
- };
-
- const webcamBorderRadius = Math.min(
- preset.borderRadius.max,
- Math.max(
- preset.borderRadius.min,
- Math.round(Math.min(webcamSlot.width, webcamSlot.height) * preset.borderRadius.fraction),
- ),
- );
-
- return {
- screenRect: screenSlot,
+ screenRect,
+ // Both halves of the block are framed alike, so the screen picks up the
+ // camera's corner rounding instead of the free-standing Roundness slider.
screenBorderRadius: webcamBorderRadius,
webcamRect: {
- x: webcamSlot.x,
- y: webcamSlot.y,
- width: webcamSlot.width,
- height: webcamSlot.height,
+ ...cameraRect,
borderRadius: webcamBorderRadius,
maskShape: "rectangle",
},
+ // The screen box already carries the capture's exact aspect ratio, so
+ // cover and contain agree here; cover just absorbs the ±1px rounding
+ // above instead of letterboxing a hairline of wallpaper into the frame.
screenCover: true,
};
}
@@ -531,6 +488,23 @@ export function computeCompositeLayout(params: {
};
}
+/**
+ * Rounds a float rect to whole pixels by rounding its EDGES rather than its origin
+ * and size independently. Adjacent boxes computed from the same float grid then keep
+ * a consistent gap, and the block's outer edges land exactly where the contain-fit
+ * put them, instead of drifting by a pixel per box.
+ */
+function snapRect(x: number, y: number, width: number, height: number): RenderRect {
+ const left = Math.round(x);
+ const top = Math.round(y);
+ return {
+ x: left,
+ y: top,
+ width: Math.max(1, Math.round(x + width) - left),
+ height: Math.max(1, Math.round(y + height) - top),
+ };
+}
+
function centerRect(params: { canvasSize: Size; size: Size; maxSize: Size }): RenderRect {
const { canvasSize, size, maxSize } = params;
return centerRectInBounds({
diff --git a/src/lib/exporter/frameRenderer.ts b/src/lib/exporter/frameRenderer.ts
index 222dc69ac..994a86b0b 100644
--- a/src/lib/exporter/frameRenderer.ts
+++ b/src/lib/exporter/frameRenderer.ts
@@ -45,11 +45,11 @@ import {
type MotionBlurState,
} from "@/components/video-editor/videoPlayback/zoomTransform";
import {
- computeCameraFullscreenTargetRect,
+ computeCameraFullscreenRect,
computeCompositeLayout,
getWebcamLayoutPresetDefinition,
- lerpRect,
reactiveWebcamScale,
+ resolveWebcamReactiveZoom,
type Size,
type StyledRenderRect,
} from "@/lib/compositeLayout";
@@ -890,10 +890,10 @@ export class FrameRenderer {
const croppedVideoWidth = videoWidth * (cropEndX - cropStartX);
const croppedVideoHeight = videoHeight * (cropEndY - cropStartY);
- // Padding is a percentage (0-100), where 50% ~ 0.8 scale.
- // Vertical stack is full-bleed, so it ignores padding.
- const effectivePadding = this.config.webcamLayoutPreset === "vertical-stack" ? 0 : padding;
- const paddingScale = 1.0 - (effectivePadding / 100) * 0.4;
+ // Padding is a percentage (0-100), where 50% ~ 0.8 scale. It applies to every
+ // preset — in the block layouts it insets the welded screen+camera block as
+ // one, which is the whole point of welding them (see `computeCompositeLayout`).
+ const paddingScale = 1.0 - (padding / 100) * 0.4;
const viewportWidth = width * paddingScale;
const viewportHeight = height * paddingScale;
const compositeLayout = computeCompositeLayout({
@@ -1385,36 +1385,29 @@ export class FrameRenderer {
const webcamRect = this.layoutCache?.webcamRect ?? null;
if (webcamFrame && webcamRect) {
const preset = getWebcamLayoutPresetDefinition(this.config.webcamLayoutPreset);
- const shape = webcamRect.maskShape ?? this.config.webcamMaskShape ?? "rectangle";
const cameraFullProgress = this.animationState.cameraFullscreenProgress;
let drawRect: StyledRenderRect;
if (cameraFullProgress > 0) {
- // Full Camera takes over the webcam's size/position entirely, growing it to cover
- // the whole stage (inset by a margin, aspect-preserving — see
- // computeCameraFullscreenTargetRect). Reactive zoom is ignored for this frame (see
+ // Full Camera takes over the webcam's size/position entirely, growing it to BE
+ // the frame — no margin, no rounding, no mask left (see
+ // computeCameraFullscreenRect). Reactive zoom is ignored for this frame (see
// design notes 6.4): mixing "shrink for zoom" and "grow to full" in the same frame
// doesn't make sense.
- const targetRect = computeCameraFullscreenTargetRect(
- { width: this.config.width, height: this.config.height },
+ drawRect = computeCameraFullscreenRect(
webcamRect,
+ { width: this.config.width, height: this.config.height },
+ cameraFullProgress,
);
- const fullRect: StyledRenderRect = {
- x: targetRect.x,
- y: targetRect.y,
- width: targetRect.width,
- height: targetRect.height,
- borderRadius: 0,
- maskShape: webcamRect.maskShape,
- };
- drawRect = lerpRect(webcamRect, fullRect, cameraFullProgress);
} else {
// Scale the PiP webcam inversely with the eased zoom, anchoring the shrink to the
// docked corner (bottom-right by default) like the preview, so it stays flush to the
// edges instead of drifting toward center.
- const reactiveFactor =
- this.config.webcamReactiveZoom && this.config.webcamLayoutPreset === "picture-in-picture"
- ? reactiveWebcamScale(this.animationState.appliedScale)
- : 1;
+ const reactiveFactor = resolveWebcamReactiveZoom(
+ this.config.webcamLayoutPreset,
+ this.config.webcamReactiveZoom,
+ )
+ ? reactiveWebcamScale(this.animationState.appliedScale)
+ : 1;
const camPos = this.config.webcamPosition;
const biasX = (camPos ? camPos.cx >= 0.5 : true) ? 1 : 0;
const biasY = (camPos ? camPos.cy >= 0.5 : true) ? 1 : 0;
@@ -1438,7 +1431,10 @@ export class FrameRenderer {
? webcamFrame.displayHeight
: webcamFrame.codedHeight) || webcamRect.height;
const sourceAspect = sourceWidth / sourceHeight;
- const targetAspect = webcamRect.width / webcamRect.height;
+ // The crop follows the box actually being DRAWN, not the layout box: Full
+ // Camera walks the box from the layout's aspect ratio to the frame's, and a
+ // crop pinned to the layout's aspect would stretch the face all the way there.
+ const targetAspect = drawRect.width / drawRect.height;
const sourceCropWidth =
sourceAspect > targetAspect ? Math.round(sourceHeight * targetAspect) : sourceWidth;
const sourceCropHeight =
@@ -1452,14 +1448,18 @@ export class FrameRenderer {
drawRect.y,
drawRect.width,
drawRect.height,
- shape,
+ drawRect.maskShape ?? this.config.webcamMaskShape ?? "rectangle",
drawRect.borderRadius,
);
- if (preset.shadow) {
+ // The drop shadow belongs to the floating bubble, so it recedes with it: at
+ // full screen the camera is the frame and nothing may frame it. Zero blur and
+ // zero offset leave the shadow exactly under the opaque camera, invisible.
+ const shadowFade = 1 - cameraFullProgress;
+ if (preset.shadow && shadowFade > 0) {
fgCtx.shadowColor = preset.shadow.color;
- fgCtx.shadowBlur = preset.shadow.blur;
- fgCtx.shadowOffsetX = preset.shadow.offsetX;
- fgCtx.shadowOffsetY = preset.shadow.offsetY;
+ fgCtx.shadowBlur = preset.shadow.blur * shadowFade;
+ fgCtx.shadowOffsetX = preset.shadow.offsetX * shadowFade;
+ fgCtx.shadowOffsetY = preset.shadow.offsetY * shadowFade;
}
fgCtx.fillStyle = "#000000";
fgCtx.fill();
diff --git a/src/lib/exporter/wgsl/composite.wgsl.ts b/src/lib/exporter/wgsl/composite.wgsl.ts
index bf1fcd036..d13f7693b 100644
--- a/src/lib/exporter/wgsl/composite.wgsl.ts
+++ b/src/lib/exporter/wgsl/composite.wgsl.ts
@@ -40,6 +40,8 @@ struct Uniforms {
b : vec4f,
// webcamShape | webcamMirrored | hasWebcam | hasShadow (0/1 as floats)
flags : vec4f,
+ // Webcam source sub-rect — the cover crop, normalised: x, y, w, h
+ webcamSrc : vec4f,
};
@group(0) @binding(0) var<uniform> u : Uniforms;
@@ -176,7 +178,11 @@ fn fs(in : VsOut) -> @location(0) vec4f {
if (u.flags.y > 0.5) {
wuv.x = 1.0 - wuv.x;
}
- let cam = textureSampleBaseClampToEdge(webcamTex, samp, clamp(wuv, vec2f(0.0), vec2f(1.0)));
+ // Through the cover crop: the box's aspect ratio is not the camera's (a block
+ // layout hands it a column slot, Full Camera walks it out to the whole frame),
+ // so the box selects a sub-rect of the source rather than stretching all of it.
+ let wsrc = u.webcamSrc.xy + clamp(wuv, vec2f(0.0), vec2f(1.0)) * u.webcamSrc.zw;
+ let cam = textureSampleBaseClampToEdge(webcamTex, samp, wsrc);
colour = overComposite(colour, vec4f(cam.rgb, wc));
}
}
diff --git a/src/lib/exporter/wgsl/evaluate.ts b/src/lib/exporter/wgsl/evaluate.ts
index 503a47d13..8c3e18a8c 100644
--- a/src/lib/exporter/wgsl/evaluate.ts
+++ b/src/lib/exporter/wgsl/evaluate.ts
@@ -43,10 +43,10 @@ import {
computeZoomTransform,
} from "@/components/video-editor/videoPlayback/zoomTransform";
import {
- computeCameraFullscreenTargetRect,
+ computeCameraFullscreenRect,
computeCompositeLayout,
- lerpRect,
reactiveWebcamScale,
+ resolveWebcamReactiveZoom,
type Size,
type StyledRenderRect,
type WebcamLayoutPreset,
@@ -140,10 +140,10 @@ export function evaluateLayout(scene: EvaluateScene, hasWebcam: boolean) {
height: scene.videoSize.height * crop.height,
};
- // Padding is a percentage (0-100) where 50% ~ 0.8 scale; vertical stack is
- // full-bleed and ignores it. Same constants as the Canvas2D path, on purpose.
- const effectivePadding = scene.webcamLayoutPreset === "vertical-stack" ? 0 : scene.padding;
- const paddingScale = 1.0 - (effectivePadding / 100) * 0.4;
+ // Padding is a percentage (0-100) where 50% ~ 0.8 scale, applied to every preset
+ // (in the block layouts it insets the welded screen+camera block as one). Same
+ // constants as the Canvas2D path, on purpose.
+ const paddingScale = 1.0 - (scene.padding / 100) * 0.4;
const layout = computeCompositeLayout({
canvasSize: { width, height },
@@ -344,25 +344,15 @@ function evaluateWebcamRect(
const shape = base.maskShape ?? scene.webcamMaskShape ?? "rectangle";
if (fullscreenProgress > 0) {
- // Full Camera owns size and position outright; reactive zoom is ignored for
- // the frame (mixing "shrink for zoom" and "grow to full" means nothing).
- const target = computeCameraFullscreenTargetRect(scene.outputSize, base);
- const full: StyledRenderRect = {
- x: target.x,
- y: target.y,
- width: target.width,
- height: target.height,
- borderRadius: 0,
- maskShape: base.maskShape,
- };
- const r = lerpRect(base, full, fullscreenProgress);
- return { ...r, shape };
+ // Full Camera owns size, position AND shape outright; reactive zoom is ignored
+ // for the frame (mixing "shrink for zoom" and "grow to full" means nothing).
+ const r = computeCameraFullscreenRect(base, scene.outputSize, fullscreenProgress);
+ return { ...r, shape: r.maskShape ?? "rectangle" };
}
- const reactive =
- scene.webcamReactiveZoom && scene.webcamLayoutPreset === "picture-in-picture"
- ? reactiveWebcamScale(appliedScale)
- : 1;
+ const reactive = resolveWebcamReactiveZoom(scene.webcamLayoutPreset, scene.webcamReactiveZoom)
+ ? reactiveWebcamScale(appliedScale)
+ : 1;
if (!(reactive < 1)) return { ...base, shape };
// Anchor the shrink to the docked corner (bottom-right by default), like the
diff --git a/src/lib/exporter/wgslFrameRenderer.ts b/src/lib/exporter/wgslFrameRenderer.ts
index 4e443bbf8..c8d4d5b87 100644
--- a/src/lib/exporter/wgslFrameRenderer.ts
+++ b/src/lib/exporter/wgslFrameRenderer.ts
@@ -78,8 +78,8 @@ const MASK_SHAPE_CODE: Record<string, number> = {
square: 3,
};
-/** Uniform block: 24 floats = 96 bytes. §8b budgets ~200; there is room. */
-const UNIFORM_FLOATS = 24;
+/** Uniform block: 28 floats = 112 bytes. §8b budgets ~200; there is room. */
+const UNIFORM_FLOATS = 28;
export class WgslFrameRenderer {
private config: WgslFrameRenderConfig;
@@ -422,6 +422,19 @@ export class WgslFrameRenderer {
u[21] = state.webcamMirrored ? 1 : 0;
u[22] = hasWebcam && w ? 1 : 0;
u[23] = state.shadowIntensity > 0 ? 1 : 0;
+ // webcamSrc: the largest centred sub-rect of the camera with the BOX's aspect
+ // ratio — `object-fit: cover`, computed here because the box's ratio is not the
+ // camera's (a block layout hands it a column slot; Full Camera walks it out to
+ // the whole frame) and the shader would otherwise stretch the face into it.
+ const src = this.config.webcamSize;
+ const boxAspect = w && w.height > 0 ? w.width / w.height : 1;
+ const srcAspect = src && src.width > 0 && src.height > 0 ? src.width / src.height : boxAspect;
+ const cropW = srcAspect > boxAspect ? boxAspect / srcAspect : 1;
+ const cropH = srcAspect > boxAspect ? 1 : srcAspect / boxAspect;
+ u[24] = (1 - cropW) / 2;
+ u[25] = (1 - cropH) / 2;
+ u[26] = cropW;
+ u[27] = cropH;
}
getCanvas(): HTMLCanvasElement {
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 5d9c763ce..703ff60ab 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -774,6 +774,52 @@ describe("buildSceneDescription.settings mapping", () => {
const scene = buildSceneDescription(doc);
expect(scene.layout.webcamRect).toBeNull();
});
+
+ it("ships the screen box next to the camera box for the block layouts", () => {
+ // Both rects come from the same computeCompositeLayout call; the native side must
+ // consume them together, otherwise it draws the app's camera against its own
+ // hardcoded screen box and the camera lands outside the scene.
+ const asset = makeAsset({
+ id: "a",
+ originalPath: "/a.mp4",
+ cameraTrack: { sourcePath: "/cam.mp4", startMs: 0, offsetMs: 0, visible: true },
+ });
+ const doc = makeDoc({
+ assets: [asset],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ }),
+ ],
+ legacyEditor: { webcamLayoutPreset: "dual-frame", padding: 0 },
+ });
+ const scene = buildSceneDescription(doc);
+ const screen = scene.layout.screenRect;
+ const cam = scene.layout.webcamRect;
+ expect(screen).not.toBeNull();
+ expect(cam).not.toBeNull();
+ // Side by side, padding 0: the block spans the full width of the frame.
+ expect(screen!.x).toBeCloseTo(0, 2);
+ expect(cam!.x + cam!.width).toBeCloseTo(1, 2);
+ // …and neither box escapes it.
+ expect(cam!.x + cam!.width).toBeLessThanOrEqual(1.001);
+ expect(cam!.y + cam!.height).toBeLessThanOrEqual(1.001);
+ // Camera sits after the screen, same height, no overlap.
+ expect(cam!.x).toBeGreaterThan(screen!.x + screen!.width);
+ expect(cam!.height).toBeCloseTo(screen!.height, 3);
+ // The block layouts impose their corner radius on the screen too.
+ expect(scene.layout.screenRadius).toBeGreaterThan(0);
+ });
+
+ it("leaves screenRadius null for picture-in-picture, so the Roundness slider still drives it", () => {
+ const doc = makeDoc({ legacyEditor: { webcamLayoutPreset: "picture-in-picture" } });
+ expect(buildSceneDescription(doc).layout.screenRadius).toBeNull();
+ });
});
// --- output dims -----------------------------------------------------------
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 621d8d70c..52ad8ac6a 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -23,7 +23,12 @@ import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
import { projectRegionsToSource } from "@/lib/ai-edition/timeline/timelineMap";
-import { computeCompositeLayout, webcamSizeToFraction } from "@/lib/compositeLayout";
+import {
+ computeCompositeLayout,
+ type RenderRect,
+ resolveWebcamReactiveZoom,
+ webcamSizeToFraction,
+} from "@/lib/compositeLayout";
import type { AspectRatio } from "@/utils/aspectRatioUtils";
import { getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
import type { CompositorClipInput } from "./contracts";
@@ -117,6 +122,21 @@ export interface SceneLayout {
* falls back to its legacy `preset_placements` for the affected preset.
*/
webcamRect?: SceneRect | null;
+ /**
+ * Screen rect resolved by the app (= `computeCompositeLayout(...).screenRect`, same
+ * fractions-of-the-output-frame convention as `webcamRect`). Already padded and
+ * already at the crop's aspect ratio, so the native compositor must consume it as-is
+ * — no `padding_scale`, no aspect fit. Without it the native side kept its hardcoded
+ * `preset_placements` screen box while honouring the app's camera box, which is what
+ * pushed the side-by-side camera past the edge of the scene.
+ */
+ screenRect?: SceneRect | null;
+ /**
+ * Corner radius of the screen box in pixels of the output frame, when the preset
+ * imposes one (the block layouts frame screen and camera alike). Null → the native
+ * side keeps deriving it from the user's Roundness slider.
+ */
+ screenRadius?: number | null;
}
/** Frame-styling effects, from the editor settings. */
@@ -414,8 +434,18 @@ export function buildSceneDescription(
// shipped to a 4:3 box). The probed size is keyed by sourcePath and survives across
// re-mounts of the same camera — `webcamSourceSize` is the dimension snapshot the
// caller (NativeCompositorOverlay) currently knows about.
+ // The block layouts (side-by-side / top-bottom) inset the welded screen+camera
+ // block by the padding, so the rect we ship must be resolved against the same
+ // padded content area the preview uses — `compositor.rs` consumes an app-provided
+ // `webcamRect` verbatim (it only scale_frame's the SCREEN by padding), so an
+ // unpadded rect here would leave the camera behind while the screen moved.
+ const paddingFit = 1 - (Math.min(100, Math.max(0, settings.padding)) / 100) * 0.4;
const computedLayout = computeCompositeLayout({
canvasSize: outputDims,
+ maxContentSize: {
+ width: Math.round(outputDims.width * paddingFit),
+ height: Math.round(outputDims.height * paddingFit),
+ },
screenSize: { width: 1920, height: 1080 },
webcamSize:
settings.webcamLayoutPreset === "no-webcam"
@@ -427,14 +457,16 @@ export function buildSceneDescription(
settings.webcamLayoutPreset === "picture-in-picture" ? settings.webcamPosition : null,
webcamMaskShape: settings.webcamMaskShape,
});
+ const toFrameFractions = (r: RenderRect) => ({
+ x: r.x / outputDims.width,
+ y: r.y / outputDims.height,
+ width: r.width / outputDims.width,
+ height: r.height / outputDims.height,
+ });
const webcamRect = computedLayout?.webcamRect
- ? {
- x: computedLayout.webcamRect.x / outputDims.width,
- y: computedLayout.webcamRect.y / outputDims.height,
- width: computedLayout.webcamRect.width / outputDims.width,
- height: computedLayout.webcamRect.height / outputDims.height,
- }
+ ? toFrameFractions(computedLayout.webcamRect)
: null;
+ const screenRect = computedLayout ? toFrameFractions(computedLayout.screenRect) : null;
return {
clips,
@@ -446,8 +478,15 @@ export function buildSceneDescription(
webcamShape: settings.webcamMaskShape,
webcamMirror: settings.webcamMirrored,
webcamPosition: settings.webcamPosition,
- webcamReactiveZoom: settings.webcamReactiveZoom,
+ // Gated by the preset: the block layouts size their camera off the screen
+ // box, so it must never shrink mid-zoom (the UI hides the toggle too).
+ webcamReactiveZoom: resolveWebcamReactiveZoom(
+ settings.webcamLayoutPreset,
+ settings.webcamReactiveZoom,
+ ),
webcamRect,
+ screenRect,
+ screenRadius: computedLayout?.screenBorderRadius ?? null,
},
effects: {
padding: settings.padding / 100,