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(scene): tag regions with their clip, follow the chosen aspect, and fit only the video rects

Etienne Lescot7c0b4db322e9
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index e2a9a8ebc..67088ab6e 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -1239,6 +1239,34 @@ impl Compositor {
w_dst = fullscreen_dst(w_dst, cam_progress);
w_dst_prev = fullscreen_dst(w_dst_prev, cam_progress_prev);
+ // Contre-étirement "fit" : le canvas interne compose TOUJOURS en OUT_W×OUT_H (16:9),
+ // puis `blit_resized` étire tout, de façon non uniforme si besoin, vers la résolution
+ // de sortie demandée — voulu pour que le FOND (dessiné plus bas en dst=[0,0,1,1])
+ // remplisse tout le cadre quel que soit le ratio choisi. Mais l'écran et la webcam ne
+ // doivent PAS être déformés par cet étirement : on rétrécit ici leur rect de
+ // destination (centré, dans cet espace 16:9 PRÉ-étirement) par l'inverse du plus fort
+ // des deux facteurs d'étirement, pour qu'après l'étirement final leur ratio d'origine
+ // reste préservé (letterboxé/pillarboxé sur le fond, qui lui reste plein cadre) — mode
+ // "fit"/contain. Si l'utilisateur veut un rendu "fill" (remplir sans bandes), il ajuste
+ // le crop lui-même ; le natif ne fait plus ce choix à sa place en étirant l'image.
+ let (final_out_w, final_out_h) = scene_ref
+ .as_ref()
+ .map(|s| (s.output.width.max(1) as f32, s.output.height.max(1) as f32))
+ .unwrap_or((OUT_W as f32, OUT_H as f32));
+ let stretch_x = final_out_w / OUT_W as f32;
+ let stretch_y = final_out_h / OUT_H as f32;
+ let uniform_stretch = stretch_x.min(stretch_y);
+ let (undistort_x, undistort_y) = (uniform_stretch / stretch_x, uniform_stretch / stretch_y);
+ let undistort = |dst: [f32; 4]| -> [f32; 4] {
+ let (cx, cy) = (dst[0] + dst[2] * 0.5, dst[1] + dst[3] * 0.5);
+ let (nw, nh) = (dst[2] * undistort_x, dst[3] * undistort_y);
+ [cx - nw * 0.5, cy - nh * 0.5, nw, nh]
+ };
+ let s_dst = undistort(s_dst);
+ let s_dst_prev = undistort(s_dst_prev);
+ w_dst = undistort(w_dst);
+ w_dst_prev = undistort(w_dst_prev);
+
let s_radius = if cfg.rounded { p.screen.radius * lp.radius_scale } else { 0.0 };
let w_px = [w_dst[2] * OUT_W as f32, w_dst[3] * OUT_H as f32];
// forme webcam : rayon SDF dérivé de la SEULE forme choisie. Le slider Roundness ne
@@ -1691,31 +1719,27 @@ impl Compositor {
/// Redimensionne (bilinéaire) le RT composé (OUT_W×OUT_H) vers `resize_target.rgba`, avant
/// la conversion NV12 dans `rgb_to_nv12_scaled`.
///
- /// Mode "fit"/contain : quand `target_w`×`target_h` n'a pas le même ratio que OUT_W×OUT_H
- /// (ex. l'utilisateur choisit un format portrait/carré alors que la scène est composée en
- /// 16:9 interne), on NE remplit PAS tout le viewport — ça étirerait l'image de façon non
- /// uniforme (écran + webcam déformés). On calcule une échelle uniforme (`min` des deux
- /// ratios), on centre le rectangle résultant dans la cible, et on clear le reste en noir
- /// (letterbox/pillarbox) — l'image composée garde son ratio d'origine quel que soit le
- /// conteneur demandé.
+ /// Étirement PLEIN CADRE volontaire, y compris non uniforme quand `target_w`×`target_h`
+ /// n'a pas le ratio de OUT_W×OUT_H : le fond (wallpaper) doit remplir tout le cadre de
+ /// sortie quel que soit le ratio choisi — ce n'est PAS lui qu'il faut préserver en "fit".
+ /// L'écran et la webcam, eux, sont protégés de cet étirement en amont, dans
+ /// `compose_frame` (rétrécissement inverse de leur rect de destination AVANT ce blit —
+ /// voir le commentaire sur `undistort` juste avant leur dessin) : ils gardent leur ratio
+ /// d'origine (letterboxé/pillarboxé sur le fond, qui lui reste plein cadre) sans qu'il
+ /// faille toucher au viewport ici.
unsafe fn blit_resized(&self, target_w: u32, target_h: u32) -> Result<()> {
self.ensure_resize_target(target_w, target_h)?;
let cache = self.resize_target.borrow();
let t = cache.as_ref().unwrap();
- self.ctx.ClearRenderTargetView(&t.rgba_rtv, &[0.0, 0.0, 0.0, 1.0]);
self.ctx.OMSetBlendState(&self.blend_none, None, 0xffffffff);
self.ctx.OMSetRenderTargets(Some(&[Some(t.rgba_rtv.clone())]), None);
self.ctx.PSSetShaderResources(0, Some(&[Some(self.rt_srv.clone())]));
self.ctx.VSSetShader(&self.vs_fs, None);
self.ctx.PSSetShader(&self.ps_tex, None);
self.ctx.PSSetSamplers(0, Some(&[Some(self.sampler.clone())]));
- let scale = (target_w as f32 / OUT_W as f32).min(target_h as f32 / OUT_H as f32);
- let fit_w = OUT_W as f32 * scale;
- let fit_h = OUT_H as f32 * scale;
let vp = D3D11_VIEWPORT {
- TopLeftX: (target_w as f32 - fit_w) * 0.5,
- TopLeftY: (target_h as f32 - fit_h) * 0.5,
- Width: fit_w, Height: fit_h, MinDepth: 0.0, MaxDepth: 1.0,
+ TopLeftX: 0.0, TopLeftY: 0.0,
+ Width: target_w as f32, Height: target_h as f32, MinDepth: 0.0, MaxDepth: 1.0,
};
self.ctx.RSSetViewports(Some(&[vp]));
self.ctx.Draw(3, 0);
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index b35171366..04ca7a7e7 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -580,6 +580,62 @@ impl Drop for LiveView {
}
}
+/// Bascule le `Player` + le compositeur sur le clip suivant de `scene` (reboucle sur le
+/// premier après le dernier). No-op pour une scène à 1 clip (le bouclage léger existant de
+/// `Player::step` suffit et coûte moins cher qu'un `set_active_clip` — reopen des décodeurs).
+///
+/// Partagée entre le déclenchement PROACTIF (seuil `source_end_sec` franchi) et le filet de
+/// sécurité RÉACTIF de `render_thread` (le temps du décodeur a reculé — `Player::step` a
+/// bouclé sur l'EOF RÉEL du fichier avant que le seuil ne soit jamais atteint : cas d'un clip
+/// NON trimmé dont la dernière frame réelle a un PTS strictement inférieur au
+/// `source_end_sec` déclaré, qui égale alors la durée totale du fichier — le seuil `>=` ne se
+/// déclenche jamais dans ce cas, d'où le "ça boucle sur le 1er clip" observé malgré le
+/// déclenchement proactif).
+#[allow(clippy::too_many_arguments)]
+unsafe fn advance_to_next_scene_clip(
+ player: &mut Player,
+ comp: &Compositor,
+ scene: &Scene,
+ active_screen_path: &mut String,
+ active_webcam_path: &mut String,
+ active_webcam_offset_sec: &mut f64,
+ active_clip_index: &mut usize,
+ raw_cursor: &mut Option<CursorTrack>,
+ last_smoothing: &mut f32,
+) {
+ if scene.clips.len() <= 1 {
+ return;
+ }
+ let next_index = if *active_clip_index + 1 < scene.clips.len() {
+ *active_clip_index + 1
+ } else {
+ 0
+ };
+ let next_clip = &scene.clips[next_index];
+ match player.set_active_clip(
+ &next_clip.screen_path,
+ &next_clip.webcam_path,
+ next_clip.webcam_offset_sec,
+ next_clip.source_start_sec,
+ ) {
+ Ok(()) => {
+ *active_screen_path = next_clip.screen_path.clone();
+ *active_webcam_path = next_clip.webcam_path.clone();
+ *active_webcam_offset_sec = next_clip.webcam_offset_sec;
+ *active_clip_index = next_index;
+ comp.set_scene(Some(scene_for_clip(scene, *active_clip_index)));
+ let cursor_path = format!("{}.cursor.json", active_screen_path);
+ *raw_cursor = CursorTrack::load(&cursor_path, 0.0, 24.0 * 3600.0).ok();
+ match raw_cursor {
+ Some(track) => comp.set_cursor(track.smoothed(0.0)),
+ None => comp.clear_cursor(),
+ }
+ *last_smoothing = -1.0;
+ }
+ Err(e) => eprintln!("[live] auto-advance clip: {e:#}"),
+ }
+}
+
/// Boucle de rendu (thread dédié) : décode → compose → resize → readback → publie
/// dans `Shared::latest_frame`.
unsafe fn render_thread(
@@ -790,45 +846,47 @@ unsafe fn render_thread(
// avait déjà dépassé la fin de la fenêtre, voire atteint l'EOF brut du
// fichier et rebouclé sur lui-même — d'où le "retour au 1er clip" observé.
if let Some(scene) = &full_scene {
- if scene.clips.len() > 1 {
- if let Some(clip) = scene.clips.get(active_clip_index) {
- if player.screen_time_sec() >= clip.source_end_sec {
- let next_index = if active_clip_index + 1 < scene.clips.len() {
- active_clip_index + 1
- } else {
- 0
- };
- let next_clip = &scene.clips[next_index];
- match player.set_active_clip(
- &next_clip.screen_path,
- &next_clip.webcam_path,
- next_clip.webcam_offset_sec,
- next_clip.source_start_sec,
- ) {
- Ok(()) => {
- active_screen_path = next_clip.screen_path.clone();
- active_webcam_path = next_clip.webcam_path.clone();
- active_webcam_offset_sec = next_clip.webcam_offset_sec;
- active_clip_index = next_index;
- comp.set_scene(Some(scene_for_clip(scene, active_clip_index)));
- let cursor_path = format!("{}.cursor.json", active_screen_path);
- raw_cursor =
- CursorTrack::load(&cursor_path, 0.0, 24.0 * 3600.0).ok();
- match &raw_cursor {
- Some(track) => comp.set_cursor(track.smoothed(0.0)),
- None => comp.clear_cursor(),
- }
- last_smoothing = -1.0;
- }
- Err(e) => eprintln!("[live] auto-advance clip: {e:#}"),
- }
- }
+ if let Some(clip) = scene.clips.get(active_clip_index) {
+ if player.screen_time_sec() >= clip.source_end_sec {
+ advance_to_next_scene_clip(
+ &mut player,
+ &comp,
+ scene,
+ &mut active_screen_path,
+ &mut active_webcam_path,
+ &mut active_webcam_offset_sec,
+ &mut active_clip_index,
+ &mut raw_cursor,
+ &mut last_smoothing,
+ );
}
}
}
+ let screen_time_before_step = full_scene.as_ref().map(|_| player.screen_time_sec());
if player.step(&comp, &cfg)? {
stepped = true;
}
+ // Filet de sécurité : un clip NON trimmé (source_end_sec == durée totale du
+ // fichier) peut ne jamais franchir le seuil ci-dessus si la dernière frame
+ // réelle a un PTS strictement inférieur à `source_end_sec` déclaré — `step()`
+ // finit alors par boucler tout seul sur l'EOF réel (temps qui recule
+ // brutalement). On détecte ce recul et on corrige immédiatement en enchaînant
+ // sur le clip suivant, plutôt que de rester bloqué sur le 1er clip.
+ if let (Some(scene), Some(t_before)) = (&full_scene, screen_time_before_step) {
+ if player.screen_time_sec() < t_before {
+ advance_to_next_scene_clip(
+ &mut player,
+ &comp,
+ scene,
+ &mut active_screen_path,
+ &mut active_webcam_path,
+ &mut active_webcam_offset_sec,
+ &mut active_clip_index,
+ &mut raw_cursor,
+ &mut last_smoothing,
+ );
+ }
+ }
acc -= step;
n += 1;
}
diff --git a/src/lib/ai-edition/timeline/region-ventilation.test.ts b/src/lib/ai-edition/timeline/region-ventilation.test.ts
index e5afc3907..b8e0d95d6 100644
--- a/src/lib/ai-edition/timeline/region-ventilation.test.ts
+++ b/src/lib/ai-edition/timeline/region-ventilation.test.ts
@@ -34,28 +34,28 @@ const threeClips = [c1, c2, c3];
describe("ventilateSpanAcrossClips", () => {
it("keeps a span inside one clip as a single clip-local fragment", () => {
expect(ventilateSpanAcrossClips(2, 6, threeClips)).toEqual([
- { clipId: "c1", localStartSec: 2, localEndSec: 6 },
+ { clipId: "c1", clipIndex: 0, localStartSec: 2, localEndSec: 6 },
]);
});
it("splits a span straddling two clips into per-clip fragments", () => {
expect(ventilateSpanAcrossClips(8, 13, threeClips)).toEqual([
- { clipId: "c1", localStartSec: 8, localEndSec: 10 },
- { clipId: "c2", localStartSec: 0, localEndSec: 3 },
+ { clipId: "c1", clipIndex: 0, localStartSec: 8, localEndSec: 10 },
+ { clipId: "c2", clipIndex: 1, localStartSec: 0, localEndSec: 3 },
]);
});
it("splits across three clips", () => {
expect(ventilateSpanAcrossClips(5, 25, threeClips)).toEqual([
- { clipId: "c1", localStartSec: 5, localEndSec: 10 },
- { clipId: "c2", localStartSec: 0, localEndSec: 10 },
- { clipId: "c3", localStartSec: 0, localEndSec: 5 },
+ { clipId: "c1", clipIndex: 0, localStartSec: 5, localEndSec: 10 },
+ { clipId: "c2", clipIndex: 1, localStartSec: 0, localEndSec: 10 },
+ { clipId: "c3", clipIndex: 2, localStartSec: 0, localEndSec: 5 },
]);
});
it("omits clips the span doesn't touch", () => {
expect(ventilateSpanAcrossClips(22, 28, threeClips)).toEqual([
- { clipId: "c3", localStartSec: 2, localEndSec: 8 },
+ { clipId: "c3", clipIndex: 2, localStartSec: 2, localEndSec: 8 },
]);
});
});
@@ -121,7 +121,9 @@ describe("reprojectRegionsForReorder", () => {
describe("virtualSpanToSourceSpans (export coherence)", () => {
it("is a no-op for an identity single clip (source == virtual)", () => {
const clips = [clip("c1", 0, 10, 0)];
- expect(virtualSpanToSourceSpans(2000, 4000, clips)).toEqual([{ startMs: 2000, endMs: 4000 }]);
+ expect(virtualSpanToSourceSpans(2000, 4000, clips)).toEqual([
+ { clipIndex: 0, startMs: 2000, endMs: 4000 },
+ ]);
});
it("shifts by clip in/out (a virtual span maps to its source range)", () => {
@@ -129,7 +131,9 @@ describe("virtualSpanToSourceSpans (export coherence)", () => {
const clips = [clip("c1", 0, 10, 5)];
// Zoom at virtual 2..4 → source 7..9 (so the export matches the right frames
// instead of source 2..4, which are trimmed off the clip's head).
- expect(virtualSpanToSourceSpans(2000, 4000, clips)).toEqual([{ startMs: 7000, endMs: 9000 }]);
+ expect(virtualSpanToSourceSpans(2000, 4000, clips)).toEqual([
+ { clipIndex: 0, startMs: 7000, endMs: 9000 },
+ ]);
});
it("splits a span across a clip boundary into two source spans", () => {
@@ -137,8 +141,8 @@ describe("virtualSpanToSourceSpans (export coherence)", () => {
const clips = [clip("c1", 0, 10, 0), clip("c2", 10, 10, 20)];
// Zoom at virtual 8..12 straddles the boundary → source 8..10 and 20..22.
expect(virtualSpanToSourceSpans(8000, 12000, clips)).toEqual([
- { startMs: 8000, endMs: 10000 },
- { startMs: 20000, endMs: 22000 },
+ { clipIndex: 0, startMs: 8000, endMs: 10000 },
+ { clipIndex: 1, startMs: 20000, endMs: 22000 },
]);
});
@@ -152,8 +156,8 @@ describe("projectRegionsToSourceTime (export coherence)", () => {
const clips = [clip("c1", 0, 10, 0), clip("c2", 10, 10, 20)];
const zooms = [{ id: "z1", startMs: 8000, endMs: 12000, depth: 4 }];
expect(projectRegionsToSourceTime(zooms, clips, () => "z2")).toEqual([
- { id: "z1", startMs: 8000, endMs: 10000, depth: 4 },
- { id: "z2", startMs: 20000, endMs: 22000, depth: 4 },
+ { id: "z1", startMs: 8000, endMs: 10000, depth: 4, clipIndex: 0 },
+ { id: "z2", startMs: 20000, endMs: 22000, depth: 4, clipIndex: 1 },
]);
});
diff --git a/src/lib/ai-edition/timeline/region-ventilation.ts b/src/lib/ai-edition/timeline/region-ventilation.ts
index 344cdb0ff..fdda60121 100644
--- a/src/lib/ai-edition/timeline/region-ventilation.ts
+++ b/src/lib/ai-edition/timeline/region-ventilation.ts
@@ -11,6 +11,11 @@ import type { AxcutClip } from "../schema";
export interface ClipFragment {
clipId: string;
+ /** Index of the covering clip within the `clips` array passed in — MUST be the same
+ * array (same order) as the one serialized to `Scene.clips` (native side), so this
+ * lines up with the native `clip_index` used to disambiguate clips that share a
+ * source asset / overlapping source-time windows. */
+ clipIndex: number;
/** Offset (seconds) from the covering clip's timelineStartSec. */
localStartSec: number;
localEndSec: number;
@@ -28,17 +33,18 @@ export function ventilateSpanAcrossClips(
const lo = Math.min(startSec, endSec);
const hi = Math.max(startSec, endSec);
const out: ClipFragment[] = [];
- for (const c of clips) {
+ clips.forEach((c, clipIndex) => {
const s = Math.max(lo, c.timelineStartSec);
const e = Math.min(hi, c.timelineEndSec);
if (e > s) {
out.push({
clipId: c.id,
+ clipIndex,
localStartSec: s - c.timelineStartSec,
localEndSec: e - c.timelineStartSec,
});
}
- }
+ });
return out;
}
@@ -117,17 +123,26 @@ export function reprojectRegionsForReorder<
* yields two source spans (which land at the right output frames on each side
* of the clip boundary). Returns [] when the span sits on no clip.
*/
+export interface SourceSpan extends Span {
+ /** Index of the covering clip within the `clips` array passed in (see `ClipFragment`) —
+ * travels through to `clipIndex` on the projected region so the native side can
+ * disambiguate clips whose source-time windows numerically overlap (same or different
+ * underlying asset) instead of matching by time-overlap alone. */
+ clipIndex: number;
+}
+
export function virtualSpanToSourceSpans(
startMs: number,
endMs: number,
clips: AxcutClip[],
-): Span[] {
+): SourceSpan[] {
const byId = new Map(clips.map((c) => [c.id, c]));
return ventilateSpanAcrossClips(startMs / 1000, endMs / 1000, clips).flatMap((f) => {
const c = byId.get(f.clipId);
if (!c) return [];
return [
{
+ clipIndex: f.clipIndex,
startMs: Math.round((c.sourceStartSec + f.localStartSec) * 1000),
endMs: Math.round((c.sourceStartSec + f.localEndSec) * 1000),
},
@@ -139,12 +154,16 @@ export function virtualSpanToSourceSpans(
* Project a list of virtual-ms regions to source-ms for the export matcher
* (see `virtualSpanToSourceSpans`). Regions straddling clips split into one per
* covered clip (extra copies get a fresh id from `makeId`; the first keeps the
- * original id). A region over no clip is passed through unchanged (best effort).
+ * original id). A region over no clip is passed through unchanged (best effort,
+ * `clipIndex` left unset — matches the native "belongs to any clip" fallback).
+ *
+ * `clips` MUST be the same array (same order) serialized to `Scene.clips` on the native
+ * side, so the emitted `clipIndex` lines up — see `ClipFragment`.
*/
export function projectRegionsToSourceTime<
T extends { id: string; startMs: number; endMs: number },
->(regions: T[], clips: AxcutClip[], makeId: () => string): T[] {
- const out: T[] = [];
+>(regions: T[], clips: AxcutClip[], makeId: () => string): (T & { clipIndex?: number })[] {
+ const out: (T & { clipIndex?: number })[] = [];
for (const region of regions) {
const spans = virtualSpanToSourceSpans(region.startMs, region.endMs, clips);
if (spans.length === 0) {
@@ -157,6 +176,7 @@ export function projectRegionsToSourceTime<
id: i === 0 ? region.id : makeId(),
startMs: span.startMs,
endMs: span.endMs,
+ clipIndex: span.clipIndex,
});
});
}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 3fe96cf8f..c1e6e1ecf 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -474,8 +474,8 @@ describe("buildSceneDescription.cameraFullscreenRegions", () => {
});
const { cameraFullscreenRegions } = buildSceneDescription(doc);
expect(cameraFullscreenRegions).toEqual([
- { startSec: 103, endSec: 105 },
- { startSec: 200, endSec: 202 },
+ { startSec: 103, endSec: 105, clipIndex: 0 },
+ { startSec: 200, endSec: 202, clipIndex: 1 },
]);
});
});
@@ -506,7 +506,7 @@ describe("buildSceneDescription.speedRegions", () => {
},
});
const { speedRegions } = buildSceneDescription(doc);
- expect(speedRegions).toEqual([{ startSec: 2, endSec: 5.5, speed: 2.5 }]);
+ expect(speedRegions).toEqual([{ startSec: 2, endSec: 5.5, speed: 2.5, clipIndex: 0 }]);
});
it("yields [] when legacyEditor.speedRegions is missing", () => {
@@ -544,8 +544,8 @@ describe("buildSceneDescription.speedRegions", () => {
});
const { speedRegions } = buildSceneDescription(doc);
expect(speedRegions).toEqual([
- { startSec: 103, endSec: 105, speed: 3.0 },
- { startSec: 200, endSec: 202, speed: 3.0 },
+ { startSec: 103, endSec: 105, speed: 3.0, clipIndex: 0 },
+ { startSec: 200, endSec: 202, speed: 3.0, clipIndex: 1 },
]);
});
});
@@ -802,4 +802,36 @@ describe("buildSceneDescription.output", () => {
const { output } = buildSceneDescription(doc);
expect(output).toEqual({ width: 2560, height: 1440, fps: null });
});
+
+ it("honors legacyEditor.aspectRatio instead of always following the source asset's own ratio", () => {
+ // BUG corrigé : output ignorait complètement le sélecteur de ratio et retournait
+ // toujours les dims brutes de l'asset (16:9 ici) — la correction "fit" côté natif
+ // (compose_frame, compositor.rs) compare `output` à sa résolution interne 16:9 pour
+ // savoir combien corriger l'écran/la webcam, donc un `output` toujours ~16:9 rendait
+ // cette correction systématiquement un no-op quel que soit le ratio choisi.
+ 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: { aspectRatio: "9:16" },
+ });
+ const { output } = buildSceneDescription(doc);
+ // Longest side (1920, the source asset's own width) stays pinned; the other side is
+ // derived from the 9:16 ratio — portrait, not the source's native 16:9.
+ expect(output.width).toBe(1080);
+ expect(output.height).toBe(1920);
+ });
});
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index ecac94251..e53054b3c 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -23,6 +23,8 @@ 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 { computeCompositeLayout, webcamSizeToFraction } from "@/lib/compositeLayout";
+import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import { getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
import type { CompositorClipInput } from "./contracts";
/** Background behind the screen. Parsed from `settings.wallpaper`. */
@@ -46,12 +48,19 @@ export interface SceneZoomRegion {
focusMode: "manual" | "auto" | null;
/** Optional rotation preset for the zoom. */
rotation: "iso" | "left" | "right" | null;
+ /** Index of the clip (within `SceneDescription.clips`) whose source time this region's
+ * `startSec`/`endSec` are expressed in — disambiguates clips whose source windows
+ * numerically overlap (same or different asset). Unset only for a region that
+ * `projectRegionsToSourceTime` couldn't place on any clip. */
+ clipIndex?: number;
}
/** A "Full Camera" timeline region (from `legacyEditor.cameraFullscreenRegions`). Times in seconds. */
export interface SceneCameraFullscreenRegion {
startSec: number;
endSec: number;
+ /** See `SceneZoomRegion.clipIndex`. */
+ clipIndex?: number;
}
/** A speed region projected onto each clip's source time. The native compositor matches
@@ -65,6 +74,8 @@ export interface SceneSpeedRegion {
endSec: number;
/** Playback rate multiplier (1 = unchanged). */
speed: number;
+ /** See `SceneZoomRegion.clipIndex`. */
+ clipIndex?: number;
}
/** Normalized rect in 0..1 of the output frame (x, y top-left; width, height). */
@@ -212,7 +223,7 @@ function parseWallpaper(wallpaper: string) {
/** Largest asset pixel area among the timeline's used assets; falls back to any asset with
* dims, then 1920x1080. Mirrors `referenceSource` in ExportDialog.tsx. */
-function pickOutputDims(document: AxcutDocument): { width: number; height: number } {
+function referenceAssetDims(document: AxcutDocument): { width: number; height: number } {
const usedAssetIds = new Set(document.timeline.clips.map((c) => c.assetId));
const consider = (w: number, h: number, best: { width: number; height: number } | null) => {
if (w > 0 && h > 0 && (!best || w * h > best.width * best.height)) {
@@ -234,6 +245,35 @@ function pickOutputDims(document: AxcutDocument): { width: number; height: numbe
return best ?? { width: 1920, height: 1080 };
}
+/** The output frame's dimensions, honoring the timeline's chosen aspect ratio.
+ *
+ * BUG corrigé : cette fonction ne retournait QUE les dimensions brutes du plus gros asset
+ * source (typiquement 16:9), sans jamais tenir compte du sélecteur de ratio de l'utilisateur
+ * (`document.legacyEditor.aspectRatio`, même source que `EXPORT_ASPECT` dans
+ * ExportDialog.tsx). `output.width`/`height` alimente le calcul "fit" côté natif
+ * (`compose_frame`, compositor.rs) qui compare `output` à la résolution interne 16:9 pour
+ * savoir de combien corriger l'écran/la webcam avant l'étirement final — avec la valeur
+ * précédente (toujours ~16:9), cette correction était systématiquement un no-op, quel que
+ * soit le ratio réellement choisi (9:16, 1:1…), d'où la déformation qui persistait.
+ *
+ * Convention alignée sur `calculateSourceDimensions` (mp4ExportSettings.ts) : le plus grand
+ * côté de l'asset de référence reste la base, l'autre côté est dérivé du ratio choisi.
+ */
+function pickOutputDims(document: AxcutDocument): { width: number; height: number } {
+ const reference = referenceAssetDims(document);
+ const aspectRatio =
+ (document.legacyEditor as { aspectRatio?: AspectRatio } | null)?.aspectRatio ?? "16:9";
+ const ratio =
+ aspectRatio === "native"
+ ? getNativeAspectRatioValue(reference.width, reference.height)
+ : getAspectRatioValue(aspectRatio);
+ const longSide = Math.max(reference.width, reference.height);
+ if (ratio >= 1) {
+ return { width: longSide, height: Math.round(longSide / ratio) };
+ }
+ return { width: Math.round(longSide * ratio), height: longSide };
+}
+
/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */
export function buildSceneDescription(
document: AxcutDocument,
@@ -303,15 +343,26 @@ export function buildSceneDescription(
// covered clips' source ranges (splitting any region that straddles a clip
// boundary) so the native side gets the same shape the export pipeline
// already proves correct.
- const docClips = document.timeline.clips;
- const projectedZoomRegions = projectRegionsToSourceTime(document.zoomRanges ?? [], docClips, () =>
- createId("zoom"),
+ //
+ // BUG corrigé : ces trois projections utilisaient `document.timeline.clips` BRUT
+ // (ordre non trié, non filtré) au lieu de `visibleClips` (trié par timelineStartSec
+ // + filtré, = l'ordre EXACT de `clips[]` envoyé au natif). Le `clipIndex` projeté sur
+ // chaque région ne correspondait donc jamais à l'index réel dans `Scene.clips`, ET
+ // `clipIndex` n'était de toute façon jamais émis avant ce fix (voir `region-ventilation.ts`)
+ // — le natif retombait alors sur un simple recouvrement temporel (`belongs` dans
+ // `for_clip_window`, compositor.rs), qui laissait fuir un zoom d'un clip vers un autre
+ // dès que leurs fenêtres source se chevauchaient numériquement (typiquement deux clips
+ // qui démarrent tous les deux près du temps source 0 de leur propre fichier).
+ const projectedZoomRegions = projectRegionsToSourceTime(
+ document.zoomRanges ?? [],
+ visibleClips,
+ () => createId("zoom"),
);
const projectedCameraFullscreenRegions = projectRegionsToSourceTime(
((document.legacyEditor as Record<string, unknown> | null)?.cameraFullscreenRegions as
| CameraFullscreenRegion[]
| undefined) ?? [],
- docClips,
+ visibleClips,
() => createId("camfull"),
);
// Speed regions carry an extra `speed` field the standard `rangeSchema` does not, so we
@@ -324,7 +375,7 @@ export function buildSceneDescription(
((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as
| SpeedRegion[]
| undefined) ?? [],
- docClips,
+ visibleClips,
() => createId("speed"),
);
@@ -405,15 +456,18 @@ export function buildSceneDescription(
focusY: region.focus.cy,
focusMode: region.focusMode ?? null,
rotation: region.rotationPreset ?? null,
+ clipIndex: region.clipIndex,
})),
cameraFullscreenRegions: projectedCameraFullscreenRegions.map((region) => ({
startSec: region.startMs / 1000,
endSec: region.endMs / 1000,
+ clipIndex: region.clipIndex,
})),
speedRegions: projectedSpeedRegions.map((region) => ({
startSec: region.startMs / 1000,
endSec: region.endMs / 1000,
speed: region.speed,
+ clipIndex: region.clipIndex,
})),
cropByClip,
output: { ...pickOutputDims(document), fps: null },