Skip to content

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

fix(preview): cursor overflow, the readback's COM interface, and odd canvas dimensions

Etienne Lescot628514ff570f
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index 6ac091bdd..5d19ffec7 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -1052,23 +1052,45 @@ impl Compositor {
let u_max = scw / stw as f32;
let v_max = sch / sth as f32;
- // Scène de l'app présente → placements du layout preset ; sinon planning fixture (bench).
+ // Scène de l'app présente → placements du layout preset (ou, mieux, le rect résolu par
+ // l'app dans `layout.webcam_rect`) ; sinon planning fixture (bench).
+ let scene_ref = self.scene.borrow();
let scene_preset: Option<String> =
- self.scene.borrow().as_ref().map(|s| s.layout.preset.clone());
- let (mut p, mut pp) = match &scene_preset {
- Some(preset) => {
- let fp = preset_placements(preset);
+ scene_ref.as_ref().map(|s| s.layout.preset.clone());
+ // Webcam rect résolu par l'app (= `computeCompositeLayout`, source de vérité unique
+ // entre preview et natif) : quand il est présent ET que la scène est posée, on l'utilise
+ // COMME placement de base. Sinon, fallback sur `preset_placements` historique (PiP
+ // codé en dur à 320 px + 40 px de marge — l'arrangement qui dérivait de la preview).
+ let app_webcam_rect: Option<[f32; 4]> = scene_ref
+ .as_ref()
+ .and_then(|s| s.layout.webcam_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`).
+ let mut fp = preset_placements(_preset);
+ fp.webcam.dst = wr;
(fp, fp) // layout statique → vélocité nulle
}
- None => (timeline(frame, cfg), timeline(frame - 1.0, cfg)),
+ (Some(preset), None) => {
+ let fp = preset_placements(preset);
+ (fp, fp)
+ }
+ (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();
- let mb_taps = cfg.mblur_n as f32;
+ // 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`
+ // (le bench fixture continue d'utiliser ses taps explicites).
+ let mb_taps = scene_ref
+ .as_ref()
+ .map(|s| 1.0 + s.effects.motion_blur.clamp(0.0, 1.0) * 15.0)
+ .unwrap_or(cfg.mblur_n as f32);
// Zoom regions + Full Camera : filtrées en amont pour le clip actif et échantillonnées
// dans le même référentiel source que le PTS du décodeur écran.
- let scene_ref = self.scene.borrow();
let empty_zoom: Vec<crate::scene::SceneZoomRegion> = Vec::new();
let empty_cam: Vec<crate::scene::SceneCameraFullscreenRegion> = Vec::new();
let zoom_regions = scene_ref.as_ref().map(|s| &s.zoom_regions).unwrap_or(&empty_zoom);
@@ -1365,7 +1387,13 @@ impl Compositor {
Some(s) if s.cursor.clip_to_bounds => s_dst,
_ => [-1.0, -1.0, 3.0, 3.0],
};
- if cfg.cursor {
+ // « Show cursor » : piloté par la scène (contrat de l'app) quand elle est posée ; sinon
+ // par `cfg.cursor` (inspector / bench fixture).
+ let cursor_show = scene_ref
+ .as_ref()
+ .map(|s| s.cursor.show)
+ .unwrap_or(cfg.cursor);
+ if cursor_show {
let cursor_ref = self.cursor.borrow();
if let Some(track) = cursor_ref.as_ref() {
let t = self.cursor_t_override.borrow().unwrap_or(frame / FPS);
@@ -1381,7 +1409,11 @@ impl Compositor {
}
})
};
- if let Some(cur) = map(track.at(t), [su0, sv0], [hu, hv], s_dst) {
+ let raw_xy = track.at(t);
+ // Hors de [0,1] = pointeur hors du rect source actuel (zoom serré / hors écran) —
+ // état normal en cours de lecture, pas une erreur : rien à dessiner cette frame.
+ let mapped = map(raw_xy, [su0, sv0], [hu, hv], s_dst);
+ if let Some(cur) = mapped {
// taille + amplitude du bounce pilotées par l'inspector (défauts = fixture).
// `padding_scale` : le curseur est un recouvrement synthétique, pas cuit dans
// la vidéo — quand le padding rétrécit l'écran, le curseur doit rétrécir
@@ -1655,19 +1687,38 @@ impl Compositor {
target_w: u32,
target_h: u32,
) -> Result<Vec<u8>> {
- let w = target_w.max(1);
- let h = target_h.max(1);
+ // `ensure_resize_target` (partagé avec l'export) crée INCONDITIONNELLEMENT une
+ // texture NV12 en plus de la RGBA, même si ce chemin RGBA-only ne s'en sert jamais —
+ // et NV12 (4:2:0, chroma sous-échantillonnée 2×2) exige des dimensions PAIRES.
+ // Le canvas Electron (taille device-pixel arbitraire, ex. 910×513) atterrit souvent
+ // sur une dimension impaire → `CreateTexture2D` de la texture NV12 échouait avec
+ // E_INVALIDARG (0x80070057), et donc TOUT le readback live (jamais une seule frame
+ // publiée). On arrondit au pair supérieur ici uniquement — l'export appelle
+ // `rgb_to_nv12_scaled`/`blit_resized` directement avec ses propres dimensions et
+ // n'est pas concerné par cet arrondi.
+ let w = (target_w.max(1) + 1) & !1;
+ let h = (target_h.max(1) + 1) & !1;
+ // Dims RÉELLEMENT demandées par l'appelant — le buffer retourné doit rester à cette
+ // taille exacte (le canvas JS attend `target_w*target_h*4` octets pile), même si le GPU
+ // travaille en interne à `w`×`h` (arrondi pair) pour satisfaire la contrainte NV12.
+ let out_w = target_w.max(1);
+ let out_h = target_h.max(1);
// 1) Resize GPU exactement comme `rgb_to_nv12_scaled` : remplit le `resize_target`
// RGBA à `w`×`h`. On s'arrête avant la conversion NV12 — on copie le RGBA.
self.blit_resized(w, h)?;
- // On a besoin de l'`ID3D11Texture2D` réel sous le SRV du resize_target pour
- // `CopyResource` (qui prend un `ID3D11Resource`). Le SRV partage la même
- // ressource, donc `cast::<ID3D11Texture2D>()` est valide.
- let rgba_tex: ID3D11Texture2D = {
+ // BUG corrigé : un SRV n'est PAS la ressource (`ID3D11ShaderResourceView` et
+ // `ID3D11Texture2D` sont des interfaces COM sans rapport de parenté) — un
+ // `.cast::<ID3D11Texture2D>()` direct sur le SRV échoue avec E_NOINTERFACE
+ // (0x80004002, confirmé à l'exécution). Il faut passer par `GetResource()`
+ // (méthode de `ID3D11View`, implémentée par tout SRV/RTV) pour récupérer la
+ // ressource sous-jacente, ici directement en `ID3D11Resource` — le type que
+ // `CopyResource` attend de toute façon, donc pas besoin d'aller jusqu'à
+ // `ID3D11Texture2D`.
+ let rgba_resource: ID3D11Resource = {
let cache = self.resize_target.borrow();
let t = cache.as_ref().unwrap();
- t.rgba_srv.cast()?
+ t.rgba_srv.GetResource()?
};
// 2) Staging texture CPU-readable à la taille cible, recréée paresseusement
@@ -1703,14 +1754,17 @@ impl Compositor {
// 3) GPU → CPU : `CopyResource` resize_target → staging, puis `Map` + copie
// ligne par ligne qui respecte `RowPitch` (cf. `dump_nv12`/`dump_raw`).
- let src: ID3D11Resource = rgba_tex.cast()?;
+ // `ID3D11Texture2D` hérite réellement de `ID3D11Resource` (contrairement au
+ // SRV plus haut) donc ce `.cast()` est valide.
let dst: ID3D11Resource = staging.cast()?;
- self.ctx.CopyResource(&dst, &src);
+ self.ctx.CopyResource(&dst, &rgba_resource);
let mut m = D3D11_MAPPED_SUBRESOURCE::default();
self.ctx.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut m))?;
- let mut out: Vec<u8> = vec![0u8; (w * h * 4) as usize];
- let row_bytes = (w * 4) as usize;
- for y in 0..h as usize {
+ // Crop implicite : on ne lit que les `out_w`×`out_h` premiers pixels de la texture
+ // (arrondie pair) — le reliquat éventuel (au plus 1px en largeur/hauteur) est ignoré.
+ let mut out: Vec<u8> = vec![0u8; (out_w * out_h * 4) as usize];
+ let row_bytes = (out_w * 4) as usize;
+ for y in 0..out_h as usize {
let src_row = (m.pData as *const u8).add(y * m.RowPitch as usize);
let dst_row = out.as_mut_ptr().add(y * row_bytes);
std::ptr::copy_nonoverlapping(src_row, dst_row, row_bytes);
diff --git a/poc-d3d/src/cursor.rs b/poc-d3d/src/cursor.rs
index 414784cae..826d9f524 100644
--- a/poc-d3d/src/cursor.rs
+++ b/poc-d3d/src/cursor.rs
@@ -13,6 +13,11 @@ pub struct CursorTrack {
}
impl CursorTrack {
+ /// Nombre d'échantillons de la piste (utile au diag de chargement).
+ pub fn sample_count(&self) -> usize {
+ self.samples.len()
+ }
+
/// Charge la fenêtre [offset_ms, offset_ms + dur_s*1000] et la ramène à t=0.
pub fn load(path: &str, offset_ms: f64, dur_s: f64) -> Result<CursorTrack> {
let txt = std::fs::read_to_string(path).with_context(|| format!("lecture {path}"))?;
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index d8d257415..68402bf47 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -570,8 +570,22 @@ unsafe fn render_thread(
}
let cursor_path = format!("{}.cursor.json", active_screen_path);
raw_cursor = CursorTrack::load(&cursor_path, 0.0, 24.0 * 3600.0).ok();
- if raw_cursor.is_none() {
- comp.clear_cursor();
+ match &raw_cursor {
+ Some(track) => {
+ eprintln!(
+ "[live] cursor: path={} loaded=ok samples={}",
+ cursor_path,
+ track.sample_count(),
+ );
+ comp.set_cursor(track.smoothed(0.0));
+ }
+ None => {
+ eprintln!(
+ "[live] cursor: path={} loaded=FAIL — clear_cursor()",
+ cursor_path,
+ );
+ comp.clear_cursor();
+ }
}
last_smoothing = -1.0;
clip_changed = true;
diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rs
index 1024aa611..fd9681062 100644
--- a/poc-d3d/src/scene.rs
+++ b/poc-d3d/src/scene.rs
@@ -43,6 +43,26 @@ pub struct SceneLayout {
pub webcam_position: Option<WebcamPosition>,
/// la webcam rétrécit pendant un zoom actif.
pub webcam_reactive_zoom: bool,
+ /// Rect webcam résolu côté app (0..1 fractions du cadre de sortie), en PARITÉ EXACTE avec
+ /// `computeCompositeLayout` (TS). Permet à TS et Rust de partager la même source de vérité :
+ /// le natif ne dérive PLUS ses propres placements pour PiP/dual-frame/vertical-stack — il
+ /// consomme ce rect directement et applique par-dessus les ajustements purement par-frame
+ /// (`webcam_size_scale`, `reactive_scale`, Full Camera).
+ ///
+ /// `#[serde(default)]` : champ ajouté après coup ; les anciens JSON (et les tests) omettent
+ /// ce champ, ce qui active le fallback `preset_placements` Rust historique (PiP codé en dur).
+ #[serde(default)]
+ pub webcam_rect: Option<SceneRect>,
+}
+
+/// Rect normalisé 0..1 du cadre de sortie : x, y en haut-gauche ; width, height.
+#[derive(Debug, Clone, Copy, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneRect {
+ pub x: f32,
+ pub y: f32,
+ pub width: f32,
+ pub height: f32,
}
/// Effets de cadre (padding, blur, ombre, coins, motion blur).
@@ -264,4 +284,47 @@ mod tests {
}
assert_eq!(s.output.fps, Some(30.0));
}
+
+ #[test]
+ fn parses_webcam_rect_payload() {
+ // webcamRect est une fraction 0..1 du cadre de sortie ; sa présence doit désactiver
+ // le fallback `preset_placements` Rust côté `compose_frame` (voir `compositor.rs`).
+ let json = r##"{
+ "clips": [],
+ "layout": {
+ "preset": "picture-in-picture",
+ "webcamSize": 0.25,
+ "webcamShape": "rounded",
+ "webcamMirror": false,
+ "webcamPosition": null,
+ "webcamReactiveZoom": false,
+ "webcamRect": { "x": 0.8125, "y": 0.8125, "width": 0.1666667, "height": 0.1666667 }
+ },
+ "effects": {"padding": 0, "blur": false, "shadow": 0, "roundnessPx": 24, "motionBlur": 0},
+ "background": {"kind":"color","color":"#000000"},
+ "zoomRegions": [],
+ "cursor": {"show": true, "size": 1, "smoothing": 0, "motionBlur": 0, "clickBounce": 1, "clipToBounds": false, "theme": "default"},
+ "cropByClip": [],
+ "output": {"width": 1920, "height": 1080, "fps": null}
+ }"##;
+ let s = Scene::from_json(json).expect("parse w/ webcamRect");
+ let r = s
+ .layout
+ .webcam_rect
+ .expect("webcam_rect doit être présent pour ce payload");
+ // bornes + ratio cohérent avec `computeCompositeLayout` (TS) pour le preset PiP @25%.
+ assert!((0.0..=1.0).contains(&r.x) && (0.0..=1.0).contains(&r.y));
+ assert!(r.width > 0.0 && r.width <= 1.0);
+ assert!((r.width - r.height).abs() < 1e-5);
+ }
+
+ #[test]
+ fn webcam_rect_field_optional_in_payload() {
+ // L'ancien payload sans `webcamRect` doit toujours parser sans erreur (le champ est
+ // `#[serde(default)]`) ; `webcam_rect` est alors None → fallback `preset_placements`.
+ let json = r##"{"clips":[],"layout":{"preset":"picture-in-picture","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},"effects":{"padding":0,"blur":false,"shadow":0,"roundnessPx":0,"motionBlur":0},"background":{"kind":"color","color":"#000000"},"zoomRegions":[],"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},"cropByClip":[],"output":{"width":1920,"height":1080,"fps":null}}"##;
+ let s = Scene::from_json(json).expect("parse sans webcam_rect");
+ assert!(s.layout.webcam_rect.is_none());
+ assert_eq!(s.layout.preset, "picture-in-picture");
+ }
}
diff --git a/src/components/ai-edition/VirtualPreview.module.css b/src/components/ai-edition/VirtualPreview.module.css
index f17574b64..41eb59b5d 100644
--- a/src/components/ai-edition/VirtualPreview.module.css
+++ b/src/components/ai-edition/VirtualPreview.module.css
@@ -1,4 +1,5 @@
.container {
+ position: relative;
display: flex;
flex-direction: column;
gap: 0.5rem;
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 7102b9252..9efdfa687 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -393,89 +393,102 @@ export function VirtualPreview({
return (
<div className={styles.container}>
{activeSource ? (
- <div ref={videoFrameRef} className={styles.videoFrame}>
- <video
- // Key on the asset id, not the URL: distinct assets that resolve
- // to the same file URL must still remount the <video> on switch so
- // onLoadedMetadata refires and the pending cross-asset seek/resume
- // runs (otherwise playback stalls at the clip boundary).
- key={activeSource.id}
- ref={videoRef}
- src={activeSource.src}
- className={`${styles.video}${isIdentityCrop ? "" : ` ${styles.videoCropped}`}`}
- // When a synthetic cursor is being drawn on top (CursorPreviewLayer),
- // hide the real OS pointer here so it doesn't compete with it.
- style={{
- ...cropVideoStyle,
- ...videoStyle,
- cursor: settings.cursorShow ? "none" : undefined,
- }}
- preload="metadata"
- playsInline
- onLoadedMetadata={(e) => {
- setLoadState("ready");
- // ponytail: forward the raw duration (possibly NaN for
- // MediaRecorder WebMs) to the parent. handleLoadedMetadata
- // falls back to a 60s seed when it isn't finite so the
- // timeline gets a populated clip even before the EBML fix
- // lands. Previously this gate skipped the callback for
- // non-finite durations and stranded the editor on
- // "No clips yet" until manual intervention. The assetId is
- // forwarded so the parent only ever corrects clips that
- // belong to the asset which actually fired this event —
- // without it, switching between clips of different assets
- // during multi-clip playback clobbered clip[0]'s duration
- // with whichever asset's video happened to load last.
- onLoadedMetadata?.(
- e.currentTarget.duration,
- activeSource.id,
- e.currentTarget.videoWidth,
- e.currentTarget.videoHeight,
- );
- if (pendingSeekRef.current) {
- const { sourceTimeSec, play } = pendingSeekRef.current;
- pendingSeekRef.current = null;
- e.currentTarget.currentTime = sourceTimeSec;
- if (play) {
- void e.currentTarget.play().catch(() => setIsPlaying(false));
+ <>
+ <div ref={videoFrameRef} className={styles.videoFrame}>
+ <video
+ // Key on the asset id, not the URL: distinct assets that resolve
+ // to the same file URL must still remount the <video> on switch so
+ // onLoadedMetadata refires and the pending cross-asset seek/resume
+ // runs (otherwise playback stalls at the clip boundary).
+ key={activeSource.id}
+ ref={videoRef}
+ src={activeSource.src}
+ className={`${styles.video}${isIdentityCrop ? "" : ` ${styles.videoCropped}`}`}
+ // When a synthetic cursor is being drawn on top (CursorPreviewLayer),
+ // hide the real OS pointer here so it doesn't compete with it.
+ style={{
+ ...cropVideoStyle,
+ ...videoStyle,
+ cursor: settings.cursorShow ? "none" : undefined,
+ }}
+ preload="metadata"
+ playsInline
+ onLoadedMetadata={(e) => {
+ setLoadState("ready");
+ // ponytail: forward the raw duration (possibly NaN for
+ // MediaRecorder WebMs) to the parent. handleLoadedMetadata
+ // falls back to a 60s seed when it isn't finite so the
+ // timeline gets a populated clip even before the EBML fix
+ // lands. Previously this gate skipped the callback for
+ // non-finite durations and stranded the editor on
+ // "No clips yet" until manual intervention. The assetId is
+ // forwarded so the parent only ever corrects clips that
+ // belong to the asset which actually fired this event —
+ // without it, switching between clips of different assets
+ // during multi-clip playback clobbered clip[0]'s duration
+ // with whichever asset's video happened to load last.
+ onLoadedMetadata?.(
+ e.currentTarget.duration,
+ activeSource.id,
+ e.currentTarget.videoWidth,
+ e.currentTarget.videoHeight,
+ );
+ if (pendingSeekRef.current) {
+ const { sourceTimeSec, play } = pendingSeekRef.current;
+ pendingSeekRef.current = null;
+ e.currentTarget.currentTime = sourceTimeSec;
+ if (play) {
+ void e.currentTarget.play().catch(() => setIsPlaying(false));
+ }
+ } else if (clips.length > 0) {
+ seekToVirtualTime(virtualTimeSec);
}
- } else if (clips.length > 0) {
- seekToVirtualTime(virtualTimeSec);
- }
- }}
- onWaiting={() => setLoadState("loading")}
- onCanPlay={() => setLoadState("ready")}
- onError={() => {
- // ponytail: don't blindly advance to the next source — if
- // the failed source owns the current virtual clip, the
- // next sourceIndex will seekToVirtualTime right back into
- // the same failed asset, looping. Fail the preview.
- pendingSeekRef.current = null;
- setLoadState("error");
- setIsPlaying(false);
- onVideoError?.();
- }}
- onPause={() => setIsPlaying(false)}
- onPlay={() => setIsPlaying(true)}
- onEnded={() => setIsPlaying(false)}
- // ponytail: handleTimeUpdate is now driven by the rAF loop
- // above (60 Hz) instead of the <video> onTimeUpdate event
- // (~4 Hz) — the 4 Hz sync was too slow to keep the webcam
- // <video> and any audio in sync. The rAF tick also
- // handles clip-end advancement, so dropping the event
- // handler here is safe.
- />
- {loadState !== "ready" && (
- <div className={styles.overlay}>
- {loadState === "error" ? "Video preview could not be loaded." : "Loading preview…"}
- </div>
- )}
+ }}
+ onWaiting={() => setLoadState("loading")}
+ onCanPlay={() => setLoadState("ready")}
+ onError={() => {
+ // ponytail: don't blindly advance to the next source — if
+ // the failed source owns the current virtual clip, the
+ // next sourceIndex will seekToVirtualTime right back into
+ // the same failed asset, looping. Fail the preview.
+ pendingSeekRef.current = null;
+ setLoadState("error");
+ setIsPlaying(false);
+ onVideoError?.();
+ }}
+ onPause={() => setIsPlaying(false)}
+ onPlay={() => setIsPlaying(true)}
+ onEnded={() => setIsPlaying(false)}
+ // ponytail: handleTimeUpdate is now driven by the rAF loop
+ // above (60 Hz) instead of the <video> onTimeUpdate event
+ // (~4 Hz) — the 4 Hz sync was too slow to keep the webcam
+ // <video> and any audio in sync. The rAF tick also
+ // handles clip-end advancement, so dropping the event
+ // handler here is safe.
+ />
+ {loadState !== "ready" && (
+ <div className={styles.overlay}>
+ {loadState === "error" ? "Video preview could not be loaded." : "Loading preview…"}
+ </div>
+ )}
+ </div>
+ {/* ponytail: CursorPreviewLayer must NOT nest inside .videoFrame — that
+ container has a hardcoded `overflow: hidden` (needed for the oversized/
+ offset video crop trick, see .videoFrame in the CSS module) which clips
+ ANY child regardless of that child's own overflow/clip-path. A child's
+ `overflow: visible` can never escape an ancestor's `overflow: hidden`, so
+ the "Clip to canvas" toggle's internal CSS override was silently powerless
+ whenever it lived inside .videoFrame — the cursor was always cut at the
+ video frame edge no matter the setting. Rendered here as a sibling instead,
+ positioned absolutely over the same box (.container has no overflow
+ clipping of its own), so the toggle's own clip-path/overflow logic is the
+ only thing constraining it. */}
<CursorPreviewLayer
videoPath={activeSource ? fromFileUrl(activeSource.src) : null}
currentTimeSec={sourceTimeSec}
isPlaying={isPlaying}
/>
- </div>
+ </>
) : (
<div className={styles.placeholder}>Attach a video to start previewing.</div>
)}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index ef60d33c2..3fe96cf8f 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -665,6 +665,60 @@ describe("buildSceneDescription.settings mapping", () => {
expect(scene.cursor.show).toBe(false);
expect(scene.cursor.theme).toBe("macos-dark");
});
+
+ it("populates layout.webcamRect with computeCompositeLayout's webcamRect, in fractions", () => {
+ // PiP @ 25% doit produire un rect (fractions) aligné avec `computeCompositeLayout`.
+ // Parité preview ↔ natif : la valeur que `PreviewCanvas` pose dans `.webcamSlot` est
+ // exactement celle que reçoit le natif dans `layout.webcamRect`. Ce test couvre
+ // principalement la conversion pixels → fractions (width/height du canvas = output dims).
+ const asset = makeAsset({
+ id: "a",
+ originalPath: "/a.mp4",
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ });
+ const doc = makeDoc({
+ assets: [asset],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 1,
+ timelineStartSec: 0,
+ timelineEndSec: 1,
+ }),
+ ],
+ legacyEditor: { webcamSizePreset: 25 },
+ });
+ const scene = buildSceneDescription(doc);
+ const rect = scene.layout.webcamRect;
+ expect(rect).not.toBeNull();
+ // Le preset picture-in-picture à size=25% (default) place la webcam en bas-droite avec
+ // une marge ~2% du canvas (cf. `compositeLayout.ts:162`). Pour un canvas 1920×1080 :
+ // - côté ≈ sqrt(1920*1080) * 0.25 ≈ 360px ; avec aspect 4:3 → ~360x270
+ // - x ≈ (1920 - margin - 360) / 1920 ≈ 0.795 ; y similaire pour h
+ // Les valeurs exactes sont issues de computeCompositeLayout ; on vérifie surtout :
+ // • bornes 0..1 strictes ; • ratio PIXELS ≈ webcamSize (4:3 conservé) ; • x/y > 0.5 (bas-droite).
+ expect(rect!.x).toBeGreaterThan(0.5);
+ expect(rect!.y).toBeGreaterThan(0.5);
+ expect(rect!.x + rect!.width).toBeLessThanOrEqual(1.0);
+ expect(rect!.y + rect!.height).toBeLessThanOrEqual(1.0);
+ // ratio cohérent en PIXELS (largeur*canvasW / hauteur*canvasH ~ 960/720 = 4/3 ≈ 1.333) —
+ // PAS le ratio des fractions brutes, qui diffère du ratio pixel dès que le canvas n'est
+ // pas carré (ici 1920x1080 : une fraction-ratio de 0.75 correspond bien à un pixel-ratio
+ // de 4/3, puisque 1920/1080 = 16/9 redistribue les deux axes différemment).
+ const pixelWidth = rect!.width * scene.output.width;
+ const pixelHeight = rect!.height * scene.output.height;
+ expect(pixelWidth / pixelHeight).toBeCloseTo(4 / 3, 1);
+ });
+
+ it("layout.webcamRect is null when no-webcam preset is selected", () => {
+ const doc = makeDoc({
+ legacyEditor: { webcamLayoutPreset: "no-webcam" },
+ });
+ const scene = buildSceneDescription(doc);
+ expect(scene.layout.webcamRect).toBeNull();
+ });
});
// --- output dims -----------------------------------------------------------
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 8b8811573..742e1f5c0 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -22,7 +22,7 @@ import type { AxcutDocument } from "@/lib/ai-edition/schema";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
import { projectRegionsToSourceTime } from "@/lib/ai-edition/timeline/region-ventilation";
-import { webcamSizeToFraction } from "@/lib/compositeLayout";
+import { computeCompositeLayout, webcamSizeToFraction } from "@/lib/compositeLayout";
import type { CompositorClipInput } from "./contracts";
/** Background behind the screen. Parsed from `settings.wallpaper`. */
@@ -67,6 +67,14 @@ export interface SceneSpeedRegion {
speed: number;
}
+/** Normalized rect in 0..1 of the output frame (x, y top-left; width, height). */
+export interface SceneRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
/** Webcam layout, from the editor settings. */
export interface SceneLayout {
preset: "picture-in-picture" | "dual-frame" | "vertical-stack" | "no-webcam";
@@ -88,6 +96,15 @@ export interface SceneLayout {
webcamPosition: { cx: number; cy: number } | null;
/** Webcam shrinks while a zoom region is active. */
webcamReactiveZoom: boolean;
+ /**
+ * Webcam rect resolved by the app (= `computeCompositeLayout(...).webcamRect`, pixels
+ * → fractions of the output frame, parity EXACTE entre preview et natif). When set, the
+ * native compositor consumes it directly for the base webcam placement instead of its
+ * own hardcoded PiP math; it still applies `webcamSize` (slider) + reactive-zoom scaling
+ * + Full Camera lerp on top. Absent (older payloads / passthrough) → the native side
+ * falls back to its legacy `preset_placements` for the affected preset.
+ */
+ webcamRect?: SceneRect | null;
}
/** Frame-styling effects, from the editor settings. */
@@ -308,6 +325,33 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
() => createId("speed"),
);
+ // Webcam rect, single source of truth between preview & native :
+ // on résout le rect AVEC LA MÊME maths que `PreviewCanvas.computeCompositeLayout` et on
+ // l'envoie au natif dans `layout.webcamRect` (fractions du cadre de sortie). Le natif le
+ // consomme tel quel (voir `compositor.rs::preset_placements` bypass). La résolution ici se
+ // fait sur la résolution de sortie (= taille du canvas rendu) avec les unités sources du
+ // premier asset visible — la même convention que `pickOutputDims` + SCREEN_SOURCE_SIZE /
+ // WEBCAM_SOURCE_SIZE dans PreviewCanvas — ce qui garde preview/export/natif alignés.
+ const outputDims = pickOutputDims(document);
+ const computedLayout = computeCompositeLayout({
+ canvasSize: outputDims,
+ screenSize: { width: 1920, height: 1080 },
+ webcamSize: settings.webcamLayoutPreset === "no-webcam" ? null : { width: 960, height: 720 },
+ layoutPreset: settings.webcamLayoutPreset,
+ webcamSizePreset: settings.webcamSizePreset,
+ webcamPosition:
+ settings.webcamLayoutPreset === "picture-in-picture" ? settings.webcamPosition : null,
+ webcamMaskShape: settings.webcamMaskShape,
+ });
+ 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,
+ }
+ : null;
+
return {
clips,
layout: {
@@ -319,6 +363,7 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
webcamMirror: settings.webcamMirrored,
webcamPosition: settings.webcamPosition,
webcamReactiveZoom: settings.webcamReactiveZoom,
+ webcamRect,
},
effects: {
padding: settings.padding / 100,