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): PiP duplication, doubled CSS shadows, the real camera aspect, crop and a frozen webcam

Etienne Lescotbf046b8f2fbe
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 36f61b6e8..aa4ee121d 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -391,6 +391,8 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
request.payload.screenPath,
request.payload.webcamPath,
request.payload.webcamOffsetSec,
+ request.payload.clipIndex,
+ request.payload.sourceTimeSec,
);
return createSuccessResponse(requestId, { ok: true });
case "destroyView":
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
index 009f28f2e..78916472e 100644
--- a/electron/native-bridge/services/compositorViewService.ts
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -288,12 +288,19 @@ export class CompositorViewService {
addon.setScene(id, resolveSceneAssetPaths(sceneJson));
}
- setActiveClip(id: number, screenPath: string, webcamPath: string, webcamOffsetSec: number): void {
+ setActiveClip(
+ id: number,
+ screenPath: string,
+ webcamPath: string,
+ webcamOffsetSec: number,
+ clipIndex: number,
+ sourceTimeSec: number,
+ ): void {
const addon = this.ensureAddon();
if (!addon) {
return;
}
- addon.setActiveClip(id, screenPath, webcamPath, webcamOffsetSec);
+ addon.setActiveClip(id, screenPath, webcamPath, webcamOffsetSec, clipIndex, sourceTimeSec);
}
destroyView(id: number): void {
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
index 52a5d23cd..93eed62c2 100644
--- a/electron/native/compositor-view/addon.d.ts
+++ b/electron/native/compositor-view/addon.d.ts
@@ -80,12 +80,19 @@ export interface CompositorViewAddon {
readFrame(id: number): Buffer | null;
setParam(id: number, key: string, value: CompositorParamValue): void;
setPlaying(id: number, playing: boolean): void;
- /** Seeks the view to `seconds` (app playhead-driven). */
+ /** Seeks the view to source-media `seconds` for the active clip. */
presentTime(id: number, seconds: number): void;
/** Installs the app scene (JSON `SceneDescription`) — layout preset etc. drive the render
* instead of the fixture. Invalid JSON is ignored native-side. */
setScene(id: number, sceneJson: string): void;
- setActiveClip(id: number, screenPath: string, webcamPath: string, webcamOffsetSec: number): void;
+ setActiveClip(
+ id: number,
+ screenPath: string,
+ webcamPath: string,
+ webcamOffsetSec: number,
+ clipIndex: number,
+ sourceTimeSec: number,
+ ): void;
destroyView(id: number): void;
/** Renders the fixture to `outPath` (C8), auto-pausing live previews. */
export(outPath: string): Promise<ExportStats>;
diff --git a/poc-d3d/compositor-view-napi/src/lib.rs b/poc-d3d/compositor-view-napi/src/lib.rs
index 0de73a54a..5676223d8 100644
--- a/poc-d3d/compositor-view-napi/src/lib.rs
+++ b/poc-d3d/compositor-view-napi/src/lib.rs
@@ -167,7 +167,7 @@ pub fn set_playing(id: i32, playing: bool) {
}
}
-/// Positionne la vue au temps `seconds` (seek piloté par la playhead de l'app).
+/// Positionne la vue au temps SOURCE du clip actif (conversion timeline faite côté renderer).
#[napi]
pub fn present_time(id: i32, seconds: f64) {
if let Some(v) = registry().lock().unwrap().get(&id) {
@@ -175,16 +175,26 @@ pub fn present_time(id: i32, seconds: f64) {
}
}
-/// Remplace les sources du clip actif sans recréer la vue ni son thread de rendu.
+/// Remplace les sources du clip actif sans recréer la vue ni son thread de rendu. L'identité
+/// timeline et le playhead source sont atomiques avec le switch : deux clips partageant les
+/// mêmes fichiers restent distincts, et les deux décodeurs ouvrent directement la bonne frame.
#[napi]
pub fn set_active_clip(
id: i32,
screen_path: String,
webcam_path: String,
webcam_offset_sec: f64,
+ clip_index: u32,
+ source_time_sec: f64,
) {
if let Some(v) = registry().lock().unwrap().get(&id) {
- v.set_active_clip(&screen_path, &webcam_path, webcam_offset_sec);
+ v.set_active_clip(
+ &screen_path,
+ &webcam_path,
+ webcam_offset_sec,
+ clip_index as usize,
+ source_time_sec,
+ );
}
}
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index 5d19ffec7..38cedb3ea 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -3,7 +3,7 @@
use crate::config::Cfg;
use crate::cursor::CursorTrack;
-use crate::scene::{Scene, SceneBackground};
+use crate::scene::{Scene, SceneBackground, SceneCrop};
use crate::d3d::Gpu;
use crate::ffi::AVFrame;
use anyhow::{bail, Result};
@@ -40,6 +40,41 @@ fn parse_hex(s: &str) -> Option<[f32; 4]> {
Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0])
}
+/// Rect source après crop puis zoom, dans les UV de la texture D3D. `u_max`/`v_max`
+/// excluent le padding NV12 ; le crop reste donc exprimé dans le frame visible (0..1),
+/// comme `VirtualPreview.cropVideoStyle`, puis le focus du zoom est remappé dans ce crop.
+fn screen_source_rect(
+ u_max: f32,
+ v_max: f32,
+ crop: Option<SceneCrop>,
+ zoom: f32,
+ focus: [f32; 2],
+) -> [f32; 4] {
+ let normalized_crop = crop.and_then(|crop| {
+ if !crop.x.is_finite() || !crop.y.is_finite()
+ || !crop.width.is_finite() || !crop.height.is_finite()
+ {
+ return None;
+ }
+ let x0 = crop.x.clamp(0.0, 1.0);
+ let y0 = crop.y.clamp(0.0, 1.0);
+ let x1 = (crop.x + crop.width).clamp(x0, 1.0);
+ let y1 = (crop.y + crop.height).clamp(y0, 1.0);
+ (x1 > x0 && y1 > y0).then_some([x0, y0, x1, y1])
+ });
+ let [x0, y0, x1, y1] = normalized_crop.unwrap_or([0.0, 0.0, 1.0, 1.0]);
+ let (cu0, cv0, cu1, cv1) = (x0 * u_max, y0 * v_max, x1 * u_max, y1 * v_max);
+ let (cw, ch) = (cu1 - cu0, cv1 - cv0);
+ let zoom = if zoom.is_finite() && zoom >= 1.0 { zoom } else { 1.0 };
+ let fx = if focus[0].is_finite() { focus[0].clamp(0.0, 1.0) } else { 0.5 };
+ let fy = if focus[1].is_finite() { focus[1].clamp(0.0, 1.0) } else { 0.5 };
+ let (hu, hv) = (cw / (2.0 * zoom), ch / (2.0 * zoom));
+ // `.max(cu0/cv0)` absorbs the tiny float inversion possible at zoom=1.
+ let su0 = (cu0 + fx * cw - hu).clamp(cu0, (cu1 - 2.0 * hu).max(cu0));
+ let sv0 = (cv0 + fy * ch - hv).clamp(cv0, (cv1 - 2.0 * hv).max(cv0));
+ [su0, sv0, su0 + 2.0 * hu, sv0 + 2.0 * hv]
+}
+
/// Constant buffer d'un calque (doit matcher `cbuffer Layer` du HLSL, 64 octets).
#[repr(C)]
#[derive(Clone, Copy, Default)]
@@ -76,6 +111,13 @@ pub struct LiveParams {
/// vélocité), pas par un flou gaussien variable comme le canvas web — plus simple à
/// réutiliser côté GPU, effet de streak équivalent.
pub cursor_motion_blur: f32,
+ /// False when the "webcam" decoder is actually just the screen video again (the TS side
+ /// falls `webcamPath` back to the screen asset's own path when a clip has no real camera,
+ /// purely so the decoder pipeline has something valid to open) — drawing the PiP box in
+ /// that case duplicates the screen video into its own corner. Live-only: derived in
+ /// `live.rs` by comparing the active clip's screen/webcam paths; defaults `true` (draw)
+ /// so fixture/bench renders and any caller that never sets it keep their old behavior.
+ pub has_webcam: bool,
}
impl Default for LiveParams {
@@ -91,6 +133,7 @@ impl Default for LiveParams {
cursor_size_scale: 1.0,
cursor_bounce_scale: 1.0,
cursor_motion_blur: 0.0,
+ has_webcam: true,
}
}
}
@@ -1299,18 +1342,17 @@ impl Compositor {
});
}
- // --- screen : zoom appliqué au rect source (§8) ---
- let cx = p.focus[0] * u_max;
- let cy = p.focus[1] * v_max;
- let hu = u_max / (2.0 * p.zoom);
- let hv = v_max / (2.0 * p.zoom);
- let su0 = (cx - hu).clamp(0.0, u_max - 2.0 * hu);
- let sv0 = (cy - hv).clamp(0.0, v_max - 2.0 * hv);
- // rect source à la frame précédente (zoom différent) pour la vélocité
- let hu_p = u_max / (2.0 * pp.zoom);
- let hv_p = v_max / (2.0 * pp.zoom);
- let su0_p = (cx - hu_p).clamp(0.0, u_max - 2.0 * hu_p);
- let sv0_p = (cy - hv_p).clamp(0.0, v_max - 2.0 * hv_p);
+ // --- screen : crop du clip actif, puis zoom appliqué dans ce rect source (§8) ---
+ // `for_clip_window` conserve l'index pour distinguer plusieurs clips du même asset.
+ let active_crop = scene_ref.as_ref().and_then(|scene| {
+ scene.crop_by_clip.get(scene.active_clip_index).copied().flatten()
+ });
+ let [su0, sv0, su1, sv1] = screen_source_rect(u_max, v_max, active_crop, p.zoom, p.focus);
+ let (hu, hv) = ((su1 - su0) * 0.5, (sv1 - sv0) * 0.5);
+ // Le focus courant reste volontairement utilisé pour la frame précédente, comme avant.
+ let [su0_p, sv0_p, su1_p, sv1_p] =
+ screen_source_rect(u_max, v_max, active_crop, pp.zoom, p.focus);
+ let (hu_p, hv_p) = ((su1_p - su0_p) * 0.5, (sv1_p - sv0_p) * 0.5);
let s_px = [s_dst[2] * OUT_W as f32, s_dst[3] * OUT_H as f32];
if cfg.shadow {
self.draw_shadow(s_dst, s_px, s_radius, 40.0, [0.0, 16.0], 0.45 * lp.shadow_scale);
@@ -1500,25 +1542,27 @@ impl Compositor {
// miroir = échanger les bornes u du rect source (flip horizontal).
let (u0, u1) = if lp.webcam_mirror { (su1, su0) } else { (su0, su1) };
let wv = wch / wth as f32;
- if cfg.shadow {
- self.draw_shadow(w_dst, w_px, w_radius, 32.0, [0.0, 12.0], 0.5 * lp.shadow_scale);
+ 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);
+ }
+ self.draw_video(
+ &LayerCB {
+ dst: w_dst,
+ src: [u0, 0.0, u1, wv],
+ quad_px: w_px,
+ radius_px: w_radius,
+ mode: 0.0,
+ color: [0.0, 0.0, 0.0, 1.0],
+ src_prev: [u0, 0.0, u1, wv], // src fixe (pas de zoom webcam)
+ dst_prev: w_dst_prev,
+ mb: [mb_taps, 0.0, 0.0, 0.0],
+ ..Default::default()
+ },
+ &wy,
+ &wuv,
+ );
}
- self.draw_video(
- &LayerCB {
- dst: w_dst,
- src: [u0, 0.0, u1, wv],
- quad_px: w_px,
- radius_px: w_radius,
- mode: 0.0,
- color: [0.0, 0.0, 0.0, 1.0],
- src_prev: [u0, 0.0, u1, wv], // src fixe (pas de zoom webcam)
- dst_prev: w_dst_prev,
- mb: [mb_taps, 0.0, 0.0, 0.0],
- ..Default::default()
- },
- &wy,
- &wuv,
- );
Ok(())
}
@@ -1936,3 +1980,28 @@ impl Compositor {
self.srv_cache.borrow_mut().clear();
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn assert_rect(actual: [f32; 4], expected: [f32; 4]) {
+ for (actual, expected) in actual.into_iter().zip(expected) {
+ assert!((actual - expected).abs() < 1e-6, "actual={actual}, expected={expected}");
+ }
+ }
+
+ #[test]
+ fn crop_maps_visible_frame_fractions_to_texture_uvs() {
+ let crop = SceneCrop { x: 0.25, y: 0.1, width: 0.5, height: 0.6 };
+ assert_rect(screen_source_rect(0.8, 0.9, None, 1.0, [0.2, 0.7]), [0.0, 0.0, 0.8, 0.9]);
+ assert_rect(screen_source_rect(0.8, 0.9, Some(crop), 1.0, [0.5, 0.5]), [0.2, 0.09, 0.6, 0.63]);
+ }
+
+ #[test]
+ fn zoom_focus_is_applied_inside_the_crop() {
+ let crop = SceneCrop { x: 0.25, y: 0.1, width: 0.5, height: 0.6 };
+ assert_rect(screen_source_rect(0.8, 0.9, Some(crop), 2.0, [0.5, 0.5]), [0.3, 0.225, 0.5, 0.495]);
+ assert_rect(screen_source_rect(0.8, 0.9, Some(crop), 2.0, [1.0, 1.0]), [0.4, 0.36, 0.6, 0.63]);
+ }
+}
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index 68402bf47..fdb850d64 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -44,6 +44,10 @@ fn parse_hex_color(s: &str) -> Option<[f32; 4]> {
Some([r, g, b, 1.0])
}
+fn webcam_seek_time(screen_source_time_sec: f64, webcam_offset_sec: f64) -> f64 {
+ (screen_source_time_sec - webcam_offset_sec).max(0.0)
+}
+
/// Lit deux sources en lockstep et compose la frame courante dans le RT du compositeur.
/// Partagé avec la GUI standalone (`app.rs`).
pub struct Player {
@@ -74,27 +78,28 @@ impl Player {
}
/// Remplace atomiquement la paire de décodeurs du clip actif. Les nouvelles sources sont
- /// ouvertes et positionnées avant de libérer l'ancienne paire, qui reste donc utilisable si
- /// l'ouverture échoue.
+ /// ouvertes et positionnées au playhead source courant avant de libérer l'ancienne paire.
pub unsafe fn set_active_clip(
&mut self,
screen_path: &str,
webcam_path: &str,
webcam_offset_sec: f64,
+ source_time_sec: f64,
) -> Result<()> {
+ let source_time_sec = source_time_sec.max(0.0);
let mut sdec = Decoder::open(screen_path, &self.gpu)?;
let mut wdec = Decoder::open(webcam_path, &self.gpu)?;
- let sf = sdec.seek_to(0.0)?;
- let wf = wdec.seek_to((0.0 - webcam_offset_sec).max(0.0))?;
+ let sf = sdec.seek_to(source_time_sec)?;
+ let wf = wdec.seek_to(webcam_seek_time(source_time_sec, webcam_offset_sec))?;
if sf.is_null() || wf.is_null() {
- anyhow::bail!("clip actif vide (screen=\"{screen_path}\", webcam=\"{webcam_path}\")");
+ anyhow::bail!("clip actif vide au temps source {source_time_sec:.3}s (screen=\"{screen_path}\", webcam=\"{webcam_path}\")");
}
self.sdec = sdec;
self.wdec = wdec;
self.webcam_offset_sec = webcam_offset_sec;
self.has_current_frame = true;
self.use_current_on_next_step = true;
- self.idx = 0;
+ self.idx = (source_time_sec * self.sdec.fps()).round().max(0.0) as u32;
Ok(())
}
@@ -160,7 +165,7 @@ impl Player {
let sf = self.sdec.seek_to(target_sec)?;
let wf = self
.wdec
- .seek_to((target_sec - self.webcam_offset_sec).max(0.0))?;
+ .seek_to(webcam_seek_time(target_sec, self.webcam_offset_sec))?;
if sf.is_null() || wf.is_null() {
self.has_current_frame = false;
return Ok(false);
@@ -226,32 +231,57 @@ struct ActiveClipRequest {
screen_path: String,
webcam_path: String,
webcam_offset_sec: f64,
+ /// Identité dans le flux `Scene.clips` trié (les chemins ne suffisent pas pour un asset partagé).
+ clip_index: usize,
+ /// Playhead exprimé sur l'horloge source écran du nouveau clip.
+ source_time_sec: f64,
}
fn same_source_path(a: &str, b: &str) -> bool {
a.eq_ignore_ascii_case(b)
}
+fn scene_clip_matches(
+ clip: &crate::scene::SceneClip,
+ screen_path: &str,
+ webcam_path: &str,
+ webcam_offset_sec: f64,
+) -> bool {
+ same_source_path(&clip.screen_path, screen_path)
+ && same_source_path(&clip.webcam_path, webcam_path)
+ && (clip.webcam_offset_sec - webcam_offset_sec).abs() <= 1e-6
+}
+
fn find_scene_clip_index(
scene: &Scene,
screen_path: &str,
webcam_path: &str,
webcam_offset_sec: f64,
) -> Option<usize> {
- scene
- .clips
- .iter()
- .position(|clip| {
+ scene.clips.iter()
+ .position(|clip| scene_clip_matches(clip, screen_path, webcam_path, webcam_offset_sec))
+ .or_else(|| scene.clips.iter().position(|clip| {
same_source_path(&clip.screen_path, screen_path)
&& same_source_path(&clip.webcam_path, webcam_path)
- && (clip.webcam_offset_sec - webcam_offset_sec).abs() <= 1e-6
- })
- .or_else(|| {
- scene.clips.iter().position(|clip| {
- same_source_path(&clip.screen_path, screen_path)
- && same_source_path(&clip.webcam_path, webcam_path)
- })
- })
+ }))
+}
+
+/// Paths and the asset-level webcam offset are identical for multiple cuts of one recording,
+/// so path lookup alone always returns clip 0. Prefer the explicit timeline identity.
+fn resolve_scene_clip_index(
+ scene: &Scene,
+ requested_clip_index: usize,
+ screen_path: &str,
+ webcam_path: &str,
+ webcam_offset_sec: f64,
+) -> Option<usize> {
+ if scene.clips.get(requested_clip_index)
+ .is_some_and(|clip| scene_clip_matches(clip, screen_path, webcam_path, webcam_offset_sec))
+ {
+ Some(requested_clip_index)
+ } else {
+ find_scene_clip_index(scene, screen_path, webcam_path, webcam_offset_sec)
+ }
}
fn scene_for_clip(scene: &Scene, clip_index: usize) -> Scene {
@@ -460,18 +490,23 @@ impl LiveView {
}
}
- /// Programme le remplacement de la paire screen/webcam sur le thread de rendu.
+ /// Programme le remplacement de la paire screen/webcam sur le thread de rendu. L'identité
+ /// du clip et son playhead source voyagent avec les chemins pour rendre le switch atomique.
pub fn set_active_clip(
&self,
screen_path: &str,
webcam_path: &str,
webcam_offset_sec: f64,
+ clip_index: usize,
+ source_time_sec: f64,
) {
if let Ok(mut request) = self.shared.active_clip_request.lock() {
*request = Some(ActiveClipRequest {
screen_path: screen_path.to_string(),
webcam_path: webcam_path.to_string(),
webcam_offset_sec,
+ clip_index,
+ source_time_sec: source_time_sec.max(0.0),
});
}
}
@@ -545,6 +580,7 @@ unsafe fn render_thread(
&request.screen_path,
&request.webcam_path,
request.webcam_offset_sec,
+ request.source_time_sec,
) {
Ok(()) => {
active_screen_path = request.screen_path;
@@ -552,8 +588,9 @@ unsafe fn render_thread(
active_webcam_offset_sec = request.webcam_offset_sec;
let scene = shared.scene.lock().unwrap().clone();
if let Some(base_scene) = scene {
- if let Some(index) = find_scene_clip_index(
+ if let Some(index) = resolve_scene_clip_index(
&base_scene,
+ request.clip_index,
&active_screen_path,
&active_webcam_path,
active_webcam_offset_sec,
@@ -596,6 +633,11 @@ unsafe fn render_thread(
cfg.bg_blur = ip.bg_blur;
cfg.mblur_n = ip.mblur_taps;
cfg.cursor = ip.cursor_show;
+ // TS falls `webcamPath` back to the screen asset's own path when a clip has no real
+ // camera (so the decoder pipeline always has something valid to open) — if we drew the
+ // PiP box in that case it would just duplicate the screen video into its own corner.
+ // `same_source_path` already exists for exactly this comparison (scene/clip matching).
+ let has_real_webcam = !same_source_path(&active_webcam_path, &active_screen_path);
comp.set_live_params(LiveParams {
bg_color: ip.bg_color,
shadow_scale: ip.shadow_scale,
@@ -607,6 +649,7 @@ unsafe fn render_thread(
cursor_size_scale: ip.cursor_size_scale,
cursor_bounce_scale: ip.cursor_bounce_scale,
cursor_motion_blur: ip.cursor_motion_blur,
+ has_webcam: has_real_webcam,
});
// Lissage ressort-amortisseur : re-génère la piste (240 Hz) uniquement quand la valeur
// change (pas à chaque frame — le resample+ressort parcourt tout l'enregistrement).
@@ -627,8 +670,9 @@ unsafe fn render_thread(
let scene = shared.scene.lock().unwrap().clone();
let scene = scene.map(|base_scene| {
scene_applied = true;
- if let Some(index) = find_scene_clip_index(
+ if let Some(index) = resolve_scene_clip_index(
&base_scene,
+ active_clip_index,
&active_screen_path,
&active_webcam_path,
active_webcam_offset_sec,
@@ -855,3 +899,44 @@ unsafe fn client_size(hwnd: HWND) -> (u32, u32) {
let _ = GetClientRect(hwnd, &mut rc);
((rc.right - rc.left).max(0) as u32, (rc.bottom - rc.top).max(0) as u32)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn multiclip_scene() -> Scene {
+ Scene::from_json(r##"{
+ "clips": [
+ {"screenPath":"/shared-screen.mp4","webcamPath":"/shared-webcam.mp4","sourceStartSec":0,"sourceEndSec":4,"webcamOffsetSec":1.25,"hasAudio":true},
+ {"screenPath":"/shared-screen.mp4","webcamPath":"/shared-webcam.mp4","sourceStartSec":20,"sourceEndSec":24,"webcamOffsetSec":1.25,"hasAudio":true},
+ {"screenPath":"/distinct-screen.mp4","webcamPath":"/distinct-webcam.mp4","sourceStartSec":100,"sourceEndSec":104,"webcamOffsetSec":0.5,"hasAudio":true}
+ ],
+ "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":[null,null,null],
+ "output":{"width":1920,"height":1080,"fps":30}
+ }"##).expect("multiclip scene")
+ }
+
+ #[test]
+ fn explicit_index_disambiguates_clips_sharing_sources() {
+ let scene = multiclip_scene();
+ assert_eq!(find_scene_clip_index(&scene, "/shared-screen.mp4", "/shared-webcam.mp4", 1.25), Some(0));
+ assert_eq!(resolve_scene_clip_index(&scene, 1, "/shared-screen.mp4", "/shared-webcam.mp4", 1.25), Some(1));
+ }
+
+ #[test]
+ fn explicit_index_tracks_a_distinct_asset() {
+ let scene = multiclip_scene();
+ assert_eq!(resolve_scene_clip_index(&scene, 2, "/distinct-screen.mp4", "/distinct-webcam.mp4", 0.5), Some(2));
+ }
+
+ #[test]
+ fn webcam_seek_uses_screen_source_time_and_offset() {
+ assert_eq!(webcam_seek_time(22.5, 1.25), 21.25);
+ assert_eq!(webcam_seek_time(0.5, 1.25), 0.0);
+ }
+}
diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rs
index fd9681062..ce54111eb 100644
--- a/poc-d3d/src/scene.rs
+++ b/poc-d3d/src/scene.rs
@@ -200,6 +200,9 @@ pub struct Scene {
/// Crop écran par clip, dans le même ordre que `clips` (`cropByClip` côté TS).
#[serde(default)]
pub crop_by_clip: Vec<Option<SceneCrop>>,
+ /// État de rendu interne, positionné par `for_clip_window` (jamais envoyé par l'app).
+ #[serde(skip)]
+ pub(crate) active_clip_index: usize,
pub output: SceneOutput,
}
@@ -232,6 +235,7 @@ impl Scene {
scene.camera_fullscreen_regions.retain(|region| {
belongs(region.clip_index, region.start_sec, region.end_sec)
});
+ scene.active_clip_index = clip_index;
scene
}
}
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index e12f9e37a..ba48ad546 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import {
setActiveClip,
@@ -6,7 +6,13 @@ import {
setNativeScene,
useNativeCompositorView,
} from "@/native";
+import { resolveNativePlaybackPosition } from "@/native/nativePlaybackPosition";
import { buildSceneDescription } from "@/native/sceneDescription";
+import {
+ getWebcamNativeSize,
+ getWebcamNativeSizeRevision,
+ subscribeWebcamNativeSize,
+} from "@/native/webcamSizeCache";
/**
* POC Option A — preview rendue par le compositeur D3D11 natif (`compositor_view.node`),
@@ -36,26 +42,30 @@ export function NativeCompositorOverlay() {
const previousActiveClipIdRef = useRef<string | null>(null);
const document = useProjectStore((s) => s.document);
const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
+ // ponytail: re-render whenever the webcam dim cache changes (the WebcamOverlay
+ // mounts AFTER the first scene push and only knows the real dims once the <video>
+ // fires loadedmetadata; subscribing here re-triggers the scene push so the native
+ // compositor stops sizing its box for a hardcoded 4:3 once the real aspect arrives).
+ const _webcamSizeRevision = useSyncExternalStore(
+ subscribeWebcamNativeSize,
+ getWebcamNativeSizeRevision,
+ () => 0,
+ );
- const orderedClips = useMemo(
- () =>
- document
- ? [...document.timeline.clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec)
- : [],
- [document],
+ // Match buildSceneDescription's sorted+visible clip stream exactly. The resulting index is
+ // sent to Rust because paths/offsets cannot distinguish multiple cuts of one source asset.
+ const nativeClips = useMemo(() => {
+ if (!document) return [];
+ const assetById = new Map(document.assets.map((asset) => [asset.id, asset]));
+ return [...document.timeline.clips]
+ .sort((a, b) => a.timelineStartSec - b.timelineStartSec)
+ .filter((clip) => assetById.get(clip.assetId)?.originalPath);
+ }, [document]);
+ const activePosition = useMemo(
+ () => resolveNativePlaybackPosition(nativeClips, currentTimeSec),
+ [nativeClips, currentTimeSec],
);
- const activeClip = useMemo(() => {
- return (
- orderedClips.find((clip, index) => {
- const isLast = index === orderedClips.length - 1;
- return (
- currentTimeSec >= clip.timelineStartSec &&
- (currentTimeSec < clip.timelineEndSec ||
- (isLast && currentTimeSec <= clip.timelineEndSec))
- );
- }) ?? null
- );
- }, [orderedClips, currentTimeSec]);
+ const activeClip = activePosition?.clip ?? null;
// `null` = document pas encore chargé (on attend) ; `{}` = chargé sans asset (→ fixture) ;
// `{screenPath,…}` = vraies sources de l'asset primaire.
@@ -92,19 +102,28 @@ export function NativeCompositorOverlay() {
return () => setCurrentNativeViewId(null);
}, [viewId]);
- // Pousse la scène (document → SceneDescription → JSON) au natif quand le document change ou
- // la vue s'active : le layout preset et cie pilotent le rendu (remplace le layout fixture).
- // Effet APRÈS celui du viewId ci-dessus → currentViewId est déjà publié quand on pousse.
+ // Pousse la scène (document → SceneDescription → JSON) au natif quand le document change,
+ // la vue s'active, OU que la taille réelle de la webcam active vient d'être sondée (voir
+ // `_webcamSizeRevision` ci-dessus) : le layout preset et cie pilotent le rendu (remplace le
+ // layout fixture). Effet APRÈS celui du viewId ci-dessus → currentViewId est déjà publié
+ // quand on pousse.
useEffect(() => {
if (viewId === null || !document) {
return;
}
try {
- setNativeScene(JSON.stringify(buildSceneDescription(document)));
+ const activeWebcamPath = sources && "webcamPath" in sources ? sources.webcamPath : undefined;
+ const webcamSourceSize = activeWebcamPath ? getWebcamNativeSize(activeWebcamPath) : null;
+ setNativeScene(JSON.stringify(buildSceneDescription(document, webcamSourceSize)));
} catch (error) {
console.warn("[compositor-view] build/push scene failed:", error);
}
- }, [viewId, document]);
+ // _webcamSizeRevision itself isn't read in the body — it's a dependency purely to
+ // re-trigger this effect when the probed-size cache mutates; the actual value is
+ // re-read fresh via getWebcamNativeSize() above on every run (biome flags this as
+ // an "unnecessary" dependency, but removing it would mean a probed webcam size
+ // arriving after mount never gets pushed to native).
+ }, [viewId, document, sources, _webcamSizeRevision]);
// Change les décodeurs screen/webcam uniquement quand le playhead entre dans un autre clip.
// `currentTimeSec` est déjà rafraîchi par la boucle de lecture existante ; aucun timer dédié.
@@ -112,7 +131,7 @@ export function NativeCompositorOverlay() {
if (viewId === null || !document) {
return;
}
- if (!activeClip) {
+ if (!activeClip || !activePosition) {
previousActiveClipIdRef.current = null;
return;
}
@@ -129,11 +148,13 @@ export function NativeCompositorOverlay() {
asset.originalPath,
cam?.sourcePath ?? asset.originalPath,
cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
+ activePosition.clipIndex,
+ activePosition.sourceTimeSec,
).catch((error: unknown) => {
console.warn("[compositor-view] setActiveClip failed:", error);
});
previousActiveClipIdRef.current = activeClip.id;
- }, [viewId, document, activeClip]);
+ }, [viewId, document, activeClip, activePosition]);
if (!ready) {
return null;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 40fccbd76..a6517f45d 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -59,8 +59,6 @@ export function NewEditorShell() {
const [videoElement, setVideoElement] = useState<HTMLVideoElement | null>(null);
const [playing, setPlaying] = useState(false);
const [loop, setLoop] = useState(false);
- // Mirror transport/playhead onto the native compositor view (no-op if inactive).
- useNativePlaybackSync(playing, currentTimeSec);
// v4 shell: three modes (Media / Edit / Rec), a collapsible agent (chat)
// column, and a floating facet inspector over the stage.
const [mode, setMode] = useState<EditorMode>("edit");
@@ -125,6 +123,9 @@ export function NewEditorShell() {
document?.assets.find((a) => a.id === document.project.primaryAssetId)?.originalPath ?? null;
void primaryAssetPath;
const clips: AxcutClip[] = document?.timeline.clips ?? [];
+ // Mirror transport/playhead onto the native compositor view (no-op if inactive). The hook
+ // maps absolute timeline time into the active clip's trimmed source-media clock.
+ useNativePlaybackSync(playing, currentTimeSec, clips);
const hasProject = Boolean(document);
const hasAsset = projectId !== null && (document?.assets.length ?? 0) > 0;
const project = document?.project
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 8943944bc..d270dcfce 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -46,7 +46,6 @@ import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview
import {
computeCameraFullscreenTargetRect,
computeCompositeLayout,
- getWebcamLayoutCssBoxShadow,
lerpRect,
type WebcamCompositeLayout,
} from "@/lib/compositeLayout";
@@ -512,24 +511,21 @@ function buildFrameStyle(
}
// Screen stage: rectangle from the composite layout, converted to percentages
-// of the canvas. The container carries the SAME borderRadius as the <video>
-// inside it (still clipped via the video's own radius, this is belt-and-
-// braces) — a box-shadow only follows the shape of the element it's applied
-// to, so a square container behind a rounded video drew a squared-off shadow
-// poking out past the video's rounded corners. Box-shadow follows the user's
-// `shadowIntensity` setting only — at intensity 0 the stage is flat so it
-// bleeds into the canvas cleanly.
+// of the canvas. Positions/sizes the interactive overlays (ZoomFocusOverlay,
+// AnnotationLayer) hosted inside it and the CSS-hidden <video> (decode/clock
+// only) — no borderRadius/boxShadow here: the native canvas already draws its
+// own rounded corners + shadow for this exact rect, and this container sits
+// on TOP of it (z-index for the interactive layers). Duplicating the same
+// decoration in CSS produced a visible "double rounded corner" — two
+// slightly-offset rounded edges (native's + this container's own) instead of
+// one.
function buildScreenStyle(
layout: WebcamCompositeLayout | null,
- settings: ReturnType<typeof useEditorSettings>["settings"],
+ _settings: ReturnType<typeof useEditorSettings>["settings"],
canvasSize: { width: number; height: number },
): React.CSSProperties {
if (!layout?.screenRect) return { display: "none" };
const r = layout.screenRect;
- const shadow = settings.shadowIntensity
- ? `0 ${4 + settings.shadowIntensity * 20}px ${16 + settings.shadowIntensity * 36}px rgba(0,0,0,${0.18 + settings.shadowIntensity * 0.45})`
- : undefined;
- const borderRadius = layout.screenBorderRadius ?? settings.borderRadius;
return {
position: "absolute",
left: `${(r.x / canvasSize.width) * 100}%`,
@@ -538,8 +534,6 @@ function buildScreenStyle(
height: `${(r.height / canvasSize.height) * 100}%`,
overflow: "hidden",
display: "flex",
- borderRadius: `${borderRadius}px`,
- boxShadow: shadow,
};
}
@@ -551,12 +545,14 @@ function videoBorderRadiusStyle(
return { borderRadius: `${borderRadius}px` };
}
-// Webcam slot: full composite-layout rect with mask shape + shadow. The
-// container's own borderRadius matches r.borderRadius (same radius the inner
-// <video> clips to, and for "circle" that's already a half-dimension radius)
-// so the box-shadow — which only ever follows border-radius, never
-// clip-path — traces the same rounded/circular shape instead of a square
-// poking out behind the masked content.
+// Webcam slot: full composite-layout rect — sizes/positions the drag hitbox
+// (handleWebcamPointerDown) and the CSS-hidden webcam <video> (decode/clock
+// only). No borderRadius/boxShadow: the native canvas already draws its own
+// rounded/circular shape + shadow for this exact rect (duplicating it here
+// produced a visible "double rounded corner"). `clipPath` is kept — unlike
+// borderRadius/boxShadow it's not just decoration, it also shapes the
+// hitbox's actual pointer-event area (e.g. "circle" mask), which should still
+// match the native-drawn shape.
function buildWebcamStyle(
layout: WebcamCompositeLayout | null,
settings: ReturnType<typeof useEditorSettings>["settings"],
@@ -575,8 +571,6 @@ function buildWebcamStyle(
overflow: "hidden",
display: "flex",
background: "transparent",
- borderRadius: `${r.borderRadius}px`,
- boxShadow: getWebcamLayoutCssBoxShadow(settings.webcamLayoutPreset as WebcamLayoutPreset),
};
return clipPath ? { ...base, clipPath } : base;
}
diff --git a/src/components/ai-edition/WebcamOverlay.tsx b/src/components/ai-edition/WebcamOverlay.tsx
index 5d7246d40..d194421af 100644
--- a/src/components/ai-edition/WebcamOverlay.tsx
+++ b/src/components/ai-edition/WebcamOverlay.tsx
@@ -28,6 +28,7 @@ import {
} from "@/lib/ai-edition/timeline/playback-clock";
import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";
import { getCssClipPath } from "@/lib/webcamMaskShapes";
+import { setWebcamNativeSize } from "@/native/webcamSizeCache";
import styles from "./NewEditorShell.module.css";
interface WebcamOverlayProps {
@@ -184,7 +185,18 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
playsInline
preload="metadata"
onError={() => setHasError(true)}
- onLoadedMetadata={() => {
+ onLoadedMetadata={(event) => {
+ // ponytail: cache the REAL webcam dimensions so the composite layout
+ // shapes its box to match the actual camera aspect (otherwise we'd ship
+ // a 4:3 box for a 16:9 webcam and the Rust `fit_cam_aspect` closure
+ // would shrink the 16:9 content inside a 4:3 box — visible empty margin
+ // inside the PiP container).
+ const target = event.currentTarget;
+ const w = target.videoWidth;
+ const h = target.videoHeight;
+ if (w > 0 && h > 0) {
+ setWebcamNativeSize(cameraTrack.sourcePath, { width: w, height: h });
+ }
if (
cameraTime !== null &&
videoEl &&
diff --git a/src/native/compositorViewClient.ts b/src/native/compositorViewClient.ts
index 9589a1487..6ff80a699 100644
--- a/src/native/compositorViewClient.ts
+++ b/src/native/compositorViewClient.ts
@@ -90,11 +90,13 @@ export function setActiveClip(
screenPath: string,
webcamPath: string,
webcamOffsetSec: number,
+ clipIndex: number,
+ sourceTimeSec: number,
): Promise<{ ok: true }> {
return requireNativeBridgeData<{ ok: true }>({
domain: "compositor",
action: "setActiveClip",
- payload: { id, screenPath, webcamPath, webcamOffsetSec },
+ payload: { id, screenPath, webcamPath, webcamOffsetSec, clipIndex, sourceTimeSec },
});
}
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index a5338ba24..8820aabda 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -735,6 +735,10 @@ export type NativeBridgeRequest =
screenPath: string;
webcamPath: string;
webcamOffsetSec: number;
+ /** Index in the sorted SceneDescription.clips stream (disambiguates shared assets). */
+ clipIndex: number;
+ /** Current screen-source time within the active clip's source window. */
+ sourceTimeSec: number;
};
requestId?: string;
};
diff --git a/src/native/nativeCompositorStore.ts b/src/native/nativeCompositorStore.ts
index 7dd651b8c..87954939b 100644
--- a/src/native/nativeCompositorStore.ts
+++ b/src/native/nativeCompositorStore.ts
@@ -60,8 +60,8 @@ export function setNativeParam(key: string, value: CompositorParamValue): void {
});
}
-/** Seek la vue native active au temps `seconds` (playhead de l'app). No-op si aucune vue.
- * Transitoire (position de lecture) → non mémorisé/rejoué, contrairement à setNativeParam. */
+/** Seek la vue native au temps SOURCE du clip actif. La conversion depuis la playhead timeline
+ * est faite par `useNativePlaybackSync`. Transitoire → non mémorisé/rejoué. */
export function setNativeTime(seconds: number): void {
if (currentViewId === null) {
return;
diff --git a/src/native/nativePlaybackPosition.test.ts b/src/native/nativePlaybackPosition.test.ts
new file mode 100644
index 000000000..e0aabc135
--- /dev/null
+++ b/src/native/nativePlaybackPosition.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutClip } from "@/lib/ai-edition/schema";
+import { resolveNativePlaybackPosition } from "./nativePlaybackPosition";
+
+function clip(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id" | "assetId">): AxcutClip {
+ return {
+ id: overrides.id,
+ assetId: overrides.assetId,
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ wordRefs: [],
+ origin: "user",
+ reason: "test",
+ ...overrides,
+ };
+}
+
+describe("resolveNativePlaybackPosition", () => {
+ it("tracks later source windows when three timeline clips share one asset", () => {
+ const clips = [
+ clip({ id: "c1", assetId: "shared", sourceStartSec: 0, sourceEndSec: 4 }),
+ clip({
+ id: "c2",
+ assetId: "shared",
+ sourceStartSec: 20,
+ sourceEndSec: 24,
+ timelineStartSec: 4,
+ timelineEndSec: 8,
+ }),
+ clip({
+ id: "c3",
+ assetId: "shared",
+ sourceStartSec: 40,
+ sourceEndSec: 44,
+ timelineStartSec: 8,
+ timelineEndSec: 12,
+ }),
+ ];
+
+ expect(resolveNativePlaybackPosition(clips, 6.5)).toMatchObject({
+ clip: { id: "c2" },
+ clipIndex: 1,
+ sourceTimeSec: 22.5,
+ });
+ expect(resolveNativePlaybackPosition(clips, 10)).toMatchObject({
+ clip: { id: "c3" },
+ clipIndex: 2,
+ sourceTimeSec: 42,
+ });
+ });
+
+ it("tracks the active source clock when each clip references a distinct asset", () => {
+ const clips = [
+ clip({ id: "a-clip", assetId: "asset-a", sourceStartSec: 5, sourceEndSec: 9 }),
+ clip({
+ id: "b-clip",
+ assetId: "asset-b",
+ sourceStartSec: 100,
+ sourceEndSec: 105,
+ timelineStartSec: 4,
+ timelineEndSec: 9,
+ }),
+ clip({
+ id: "c-clip",
+ assetId: "asset-c",
+ sourceStartSec: 12,
+ sourceEndSec: 15,
+ timelineStartSec: 9,
+ timelineEndSec: 12,
+ }),
+ ];
+
+ expect(resolveNativePlaybackPosition(clips, 7.25)).toMatchObject({
+ clip: { id: "b-clip", assetId: "asset-b" },
+ clipIndex: 1,
+ sourceTimeSec: 103.25,
+ });
+ expect(resolveNativePlaybackPosition(clips, 11)).toMatchObject({
+ clip: { id: "c-clip", assetId: "asset-c" },
+ clipIndex: 2,
+ sourceTimeSec: 14,
+ });
+ });
+
+ it("selects the new clip exactly at a boundary and returns null in a gap", () => {
+ const clips = [
+ clip({ id: "first", assetId: "a", sourceStartSec: 10, sourceEndSec: 14 }),
+ clip({
+ id: "second",
+ assetId: "b",
+ sourceStartSec: 30,
+ sourceEndSec: 34,
+ timelineStartSec: 5,
+ timelineEndSec: 9,
+ }),
+ ];
+
+ expect(resolveNativePlaybackPosition(clips, 4.5)).toBeNull();
+ expect(resolveNativePlaybackPosition(clips, 5)).toMatchObject({
+ clip: { id: "second" },
+ clipIndex: 1,
+ sourceTimeSec: 30,
+ });
+ });
+});
diff --git a/src/native/nativePlaybackPosition.ts b/src/native/nativePlaybackPosition.ts
new file mode 100644
index 000000000..610c36596
--- /dev/null
+++ b/src/native/nativePlaybackPosition.ts
@@ -0,0 +1,43 @@
+import type { AxcutClip } from "@/lib/ai-edition/schema";
+
+export interface NativePlaybackPosition {
+ clip: AxcutClip;
+ /** Index in timeline order, matching SceneDescription.clips when the caller passes visible clips. */
+ clipIndex: number;
+ /** Screen-source seconds expected by the native decoder for this clip. */
+ sourceTimeSec: number;
+}
+
+/**
+ * Resolve an app timeline playhead to the active clip's screen-source clock.
+ *
+ * Native `presentTime` and `setActiveClip` do not consume absolute timeline
+ * seconds: both decoders seek in the active asset, with webcam time derived as
+ * `screenSourceTime - webcamOffset`. Keeping this conversion pure and shared
+ * prevents paused scrubs and clip-boundary switches from using different clocks.
+ */
+export function resolveNativePlaybackPosition(
+ clips: readonly AxcutClip[],
+ timelineTimeSec: number,
+): NativePlaybackPosition | null {
+ if (!Number.isFinite(timelineTimeSec) || clips.length === 0) return null;
+
+ const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
+ const clipIndex = ordered.findIndex((clip, index) => {
+ const isLast = index === ordered.length - 1;
+ return (
+ timelineTimeSec >= clip.timelineStartSec &&
+ (timelineTimeSec < clip.timelineEndSec || (isLast && timelineTimeSec <= clip.timelineEndSec))
+ );
+ });
+ if (clipIndex < 0) return null;
+
+ const clip = ordered[clipIndex];
+ const unclampedSourceTime = clip.sourceStartSec + (timelineTimeSec - clip.timelineStartSec);
+ const sourceEndSec = clip.sourceEndSec ?? unclampedSourceTime;
+ return {
+ clip,
+ clipIndex,
+ sourceTimeSec: Math.max(clip.sourceStartSec, Math.min(sourceEndSec, unclampedSourceTime)),
+ };
+}
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 742e1f5c0..ecac94251 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -235,7 +235,10 @@ function pickOutputDims(document: AxcutDocument): { width: number; height: numbe
}
/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */
-export function buildSceneDescription(document: AxcutDocument): SceneDescription {
+export function buildSceneDescription(
+ document: AxcutDocument,
+ webcamSourceSize: { width: number; height: number } | null = null,
+): SceneDescription {
const settings = getEditorSettings(document);
// Sort+filter the clips once, in the order they will appear in the scene's
@@ -333,10 +336,21 @@ export function buildSceneDescription(document: AxcutDocument): SceneDescription
// 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);
+ // ponytail: when the active camera has been probed (real webcam dims cached by
+ // WebcamOverlay's loadedmetadata handler), use them so the box matches the actual
+ // camera aspect. Without this the box defaults to a hardcoded 4:3 (960x720) and the
+ // Rust `fit_cam_aspect` closure shrinks the real content inside the wrong-aspect box,
+ // leaving visible empty margin inside the PiP container (typical case: a 16:9 webcam
+ // 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.
const computedLayout = computeCompositeLayout({
canvasSize: outputDims,
screenSize: { width: 1920, height: 1080 },
- webcamSize: settings.webcamLayoutPreset === "no-webcam" ? null : { width: 960, height: 720 },
+ webcamSize:
+ settings.webcamLayoutPreset === "no-webcam"
+ ? null
+ : (webcamSourceSize ?? { width: 960, height: 720 }),
layoutPreset: settings.webcamLayoutPreset,
webcamSizePreset: settings.webcamSizePreset,
webcamPosition:
diff --git a/src/native/useNativePlaybackSync.ts b/src/native/useNativePlaybackSync.ts
index adafcffa8..4c6ba5c9f 100644
--- a/src/native/useNativePlaybackSync.ts
+++ b/src/native/useNativePlaybackSync.ts
@@ -17,15 +17,27 @@
* drift (independent tickers); acceptable for the fixture (~6 s loop). A pause
* re-aligns them.
*/
-import { useEffect, useSyncExternalStore } from "react";
+import { useEffect, useMemo, useSyncExternalStore } from "react";
+import type { AxcutClip } from "@/lib/ai-edition/schema";
import {
getCurrentNativeViewId,
setNativePlaying,
setNativeTime,
subscribeNativeCompositor,
} from "./nativeCompositorStore";
+import { resolveNativePlaybackPosition } from "./nativePlaybackPosition";
-export function useNativePlaybackSync(playing: boolean, currentTimeSec: number): void {
+export function useNativePlaybackSync(
+ playing: boolean,
+ currentTimeSec: number,
+ clips: readonly AxcutClip[],
+): void {
+ // `currentTimeSec` is the app's absolute timeline clock. Rust's live player expects the
+ // active clip's source-media clock, including its source trim offset.
+ const sourceTimeSec = useMemo(
+ () => resolveNativePlaybackPosition(clips, currentTimeSec)?.sourceTimeSec ?? null,
+ [clips, currentTimeSec],
+ );
// Reactive "is a native view active?" so activation mid-session re-pushes the
// current transport/playhead (time & playing aren't memoised in the store).
const active = useSyncExternalStore(
@@ -43,9 +55,9 @@ export function useNativePlaybackSync(playing: boolean, currentTimeSec: number):
// Scrub/step while paused → discrete seek (see header for why not during play).
useEffect(() => {
- if (!active || playing) {
+ if (!active || playing || sourceTimeSec === null) {
return;
}
- setNativeTime(currentTimeSec);
- }, [active, playing, currentTimeSec]);
+ setNativeTime(sourceTimeSec);
+ }, [active, playing, sourceTimeSec]);
}
diff --git a/src/native/webcamSizeCache.ts b/src/native/webcamSizeCache.ts
new file mode 100644
index 000000000..6daa48bba
--- /dev/null
+++ b/src/native/webcamSizeCache.ts
@@ -0,0 +1,71 @@
+/**
+ * Cache of real webcam dimensions per `sourcePath`, populated by the live webcam <video>'s
+ * loadedmetadata event and consumed by `PreviewCanvas` (to shape its overlay box) and by
+ * `NativeCompositorOverlay` (to shape the rect it ships to the native compositor in the scene
+ * description).
+ *
+ * Why this exists: the composite layout's webcam rect is sized for the ASSUMED webcam aspect.
+ * If we ship a 4:3 box and the real camera is 16:9, the Rust side's `fit_cam_aspect` closure
+ * shrinks the 16:9 content to fit the 4:3 box, leaving visible empty margin inside the PiP
+ * container. Probing the real webcam dims once at mountedmetadata time and threading them into
+ * the layout call lets TS shape the box for the REAL aspect from the start, so the container
+ * and the camera content agree.
+ *
+ * Tiny pub/sub (consistent with `nativeCompositorStore`) so callers can re-render when the
+ * probe result arrives (the first push to native happens before loadedmetadata fires; the probe
+ * triggers a re-push with the correct dimensions).
+ */
+type Size = { width: number; height: number };
+
+const sizes = new Map<string, Size>();
+const listeners = new Set<() => void>();
+/** Monotonic counter — bumped on every cache mutation. Lets `useSyncExternalStore`
+ * produce a fresh snapshot on each push without diffing the whole map (which would
+ * re-fire the React effect regardless). */
+let revision = 0;
+
+function notify(): void {
+ revision += 1;
+ for (const l of listeners) l();
+}
+
+/** Record the webcam dimensions observed for `sourcePath`. `null` removes any prior entry. */
+export function setWebcamNativeSize(sourcePath: string, size: Size | null): void {
+ if (size && size.width > 0 && size.height > 0) {
+ const prev = sizes.get(sourcePath);
+ if (prev && prev.width === size.width && prev.height === size.height) {
+ return;
+ }
+ sizes.set(sourcePath, size);
+ notify();
+ return;
+ }
+ if (sizes.delete(sourcePath)) {
+ notify();
+ }
+}
+
+/** Real webcam dimensions for `sourcePath`, or null if not yet probed / unsupported file. */
+export function getWebcamNativeSize(sourcePath: string): Size | null {
+ return sizes.get(sourcePath) ?? null;
+}
+
+/** Monotonic revision counter — useful for `useSyncExternalStore` snapshots. */
+export function getWebcamNativeSizeRevision(): number {
+ return revision;
+}
+
+/** Clear the entire cache (used by tests, or when the document is unloaded). */
+export function clearWebcamNativeSizeCache(): void {
+ if (sizes.size === 0) return;
+ sizes.clear();
+ notify();
+}
+
+/** Subscribe to any cache mutation. Returns an unsubscribe function. */
+export function subscribeWebcamNativeSize(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}