Skip to content

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

feat(scene): the SceneDescription contract — app to native, with buildSceneDescription

Etienne Lescote1d6ca1c6129
diff --git a/poc-d3d/docs/d3d-migration.md b/poc-d3d/docs/d3d-migration.md
new file mode 100644
index 000000000..91b8f7c55
--- /dev/null
+++ b/poc-d3d/docs/d3d-migration.md
@@ -0,0 +1,114 @@
+# Migration propre : ai-edition → compositeur D3D
+
+But : **une seule preview (D3D), parité fonctionnelle complète, zéro fixture POC.**
+On garde les primitives GPU (elles sont prouvées, C0–C8), on supprime tout ce qui est
+spécifique à la fixture (animation layout codée en dur, boucle 6s, `cursor.json` fixture,
+`fixture_dir` + fallbacks), on branche les vrais effets/paramètres de l'app dessus, et on
+supprime l'ancienne preview web (DOM/Pixi).
+
+Statut colonne « Primitive D3D » :
+- **✅ a** = la primitive existe et rend déjà (il reste à la paramétrer depuis l'app).
+- **⚙️ param** = primitive présente mais valeur codée en dur (fixture) → à exposer.
+- **🆕 neuf** = à ajouter (nouvelle passe/logique GPU).
+
+---
+
+## 1. Barre latérale (inspector) — `EditorSettingsSnapshot` (`legacyEditor`)
+
+### Background (`BackgroundPane`)
+| Param | Type / valeurs | Sémantique app | Primitive D3D |
+|---|---|---|---|
+| `wallpaper` (couleur) | `#rrggbb` | fond plat derrière le screen | ✅ a (`bg_color`) |
+| `wallpaper` (gradient) | `linear-gradient(deg, c1, c2, …)` | fond dégradé | 🆕 neuf (shader lerp N stops + angle) |
+| `wallpaper` (image) | chemin `/wallpapers/…` ou `data:` | fond image | 🆕 neuf (upload texture + draw quad) |
+| `aspectRatio` | `16:9` \| `native` \| … | ratio du cadre de sortie | 🆕 neuf (OUT_W/H dérivés du ratio, aujourd'hui figé 1920×1080) |
+
+### Visual effects (`VideoEffectsPane`)
+| Param | Type | Sémantique | Primitive D3D |
+|---|---|---|---|
+| `showBlur` | bool | fond = screen flouté | ✅ a (dual-Kawase) |
+| `motionBlurAmount` | 0..1 | flou de mouvement | ✅ a (supersample temporel) — mais aujourd'hui *motion de layout* seulement ; à étendre au mouvement de contenu |
+| `shadowIntensity` | 0..1 | ombre portée écran/webcam | ✅ a (`shadow_scale`) |
+| `borderRadius` | px | coins arrondis écran | ⚙️ param (px absolu, pas ×base fixture) |
+| `padding` | 0..100 | marge autour du screen | ✅ a (`padding`) |
+| `cropRegion` | {x,y,w,h} 0..1 | recadrage source écran | 🆕 neuf (src rect du screen) |
+
+### Layout / webcam (`LayoutPane`)
+| Param | Type | Sémantique | Primitive D3D |
+|---|---|---|---|
+| `webcamLayoutPreset` | `picture-in-picture` \| `dual-frame` \| `vertical-stack` \| `no-webcam` | placement écran/webcam | ⚙️ param PiP (✅) + 🆕 side-by-side / top-bottom / no-webcam (la primitive de layout animé C6 existe) |
+| `webcamSizePreset` | 10..50 % | taille webcam | ✅ a |
+| `webcamMirrored` | bool | miroir horizontal | ✅ a |
+| `webcamMaskShape` | rect \| circle \| square \| rounded | forme webcam | ✅ a |
+| `webcamPosition` | {cx,cy} 0..1 | position webcam (drag) | 🆕 neuf (placement libre au lieu du coin fixe) |
+| `webcamReactiveZoom` | bool | webcam rétrécit pendant un zoom | 🆕 neuf (lie taille webcam au zoom actif) |
+
+### Cursor (`CursorPane`)
+| Param | Type | Sémantique | Primitive D3D |
+|---|---|---|---|
+| `cursorShow` | bool | afficher le curseur | ✅ a (`cfg.cursor`) |
+| `cursor.size` | échelle | taille | ✅ a (`cursor_size_scale`) |
+| `cursor.clickBounce` | échelle | rebond au clic | ✅ a (`cursor_bounce_scale`) |
+| `cursor.motionBlur` | 0..1 | traînée curseur | ⚙️ param (fantômes existent, liés à `mblur_n` ; à exposer) |
+| `cursor.smoothing` | 0..1 | lissage trajectoire | 🆕 neuf (filtrage de `CursorTrack.at`) |
+| `cursor.clipToBounds` | bool | clip au cadre écran | 🆕 neuf |
+| `cursorTheme` | id | jeu de sprites curseur | 🆕 neuf (atlas sprites + sélection ; aujourd'hui anneau générique) |
+| **télémétrie** | fichier/telem | positions réelles du curseur | 🆕 neuf (mapper la télémétrie app → `CursorTrack`, pas la fixture) |
+
+### Divers (pas de rendu compositeur)
+| Param | Rôle |
+|---|---|
+| `showTrimWaveform` | affichage waveform sur la piste trim (UI timeline) |
+| `autoFocusAll` | génération auto de zooms (édition, pas rendu) |
+
+---
+
+## 2. Timeline — effets & régions
+
+| Effet | Stockage | Champs | Sémantique | Primitive D3D |
+|---|---|---|---|---|
+| **Cut / trim** | `timeline.trimRanges[]` | assetId, startSec, endSec | retirer un segment | ✅ a (déjà reflété par les clips de l'export multiclip) |
+| **Clips** | `timeline.clips[]` | assetId, source[Start/End]Sec, timeline[Start/End]Sec, cropRegion | multiclip + trims + ordre | ✅ a (export multiclip) — à étendre au **preview** |
+| **Zoom** | `zoomRanges[]` | startMs, endMs, **depth 1..6**, **focus {cx,cy}**, focusMode auto/manual, **rotationPreset iso/left/right**, customScale | zoom animé sur un point | ⚙️ param (zoom+focus animés existent) + 🆕 rotation (iso/left/right) |
+| **Speed** | `timeline.speedRanges[]` | startMs, endMs, **speed** | accélère/ralentit un segment | 🆕 neuf (cadence de décodage/sortie + audio) |
+| **Annotation texte** | `annotations[]` type=text | content, position %, size, style, timing | overlay texte | 🆕 neuf (rendu texte) |
+| **Annotation image** | `annotations[]` type=image | imageContent, position, size, timing | overlay image | 🆕 neuf (texture) |
+| **Annotation figure** | `annotations[]` type=figure | figureData, … | flèche/forme | 🆕 neuf |
+| **Annotation blur** | `annotations[]` type=blur | blurData, position, size, timing | flou d'une zone | 🆕 neuf (blur localisé) |
+| **Caption** | `timeline.captionRanges[]` | startSec, endSec | sous-titres | 🆕 neuf (texte timé) |
+| **Camera fullscreen** | régions | startMs/endMs | webcam grandit pour remplir | 🆕 neuf (layout animé webcam) |
+| **Mute** | `timeline.muteRanges[]` | startSec, endSec | couper l'audio | audio (hors compositeur vidéo) |
+| **Gaps** | `timeline.gaps[]` | — | trous timeline | ⚙️ (tenue de frame / noir) |
+
+---
+
+## 3. Primitives D3D à GARDER (compose_frame / passes GPU)
+composite 2 sources · coins arrondis (SDF) · ombre portée · fond flouté (dual-Kawase) ·
+zoom animé + focus · **layout paramétrable** (aujourd'hui A↔B fixture — à généraliser aux
+presets) · curseur (dot+ring, bounce, fantômes motion-blur — à généraliser sprites+télémétrie) ·
+flou de mouvement (supersample temporel) · encode h264_amf · export mono/multiclip.
+
+## 4. Scaffolding fixture à SUPPRIMER (n'appartient qu'au POC)
+- `compositor.rs::timeline()` — planning A↔B + zoom **codés en dur** → remplacé par des params pilotés par l'app (layout preset, zoom regions).
+- `FIXTURE_FRAMES` (boucle 6s) et toute la logique de bouclage fixture.
+- `fixture_dir()` + fallbacks fixture dans `create_view`/`export` (napi).
+- fixture `poc-d3d/fixture/*` (screen.mp4, webcam.mp4, screen.cursor.json) — hors app.
+- Harnais `--live` / `--export` fixture (rester dev-only, hors chemin app).
+- Fallback « fixture » de l'overlay/hook côté TS.
+
+## 5. Ancienne preview web à SUPPRIMER (après parité)
+`PreviewCanvas` / `VirtualPreview` / `WebcamOverlay` / `CursorPreviewLayer` (Pixi) /
+`ZoomFocusOverlay` / `AnnotationOverlay` / `PreviewCompositor` — une fois la parité D3D atteinte,
+la preview DOM disparaît (le natif devient la seule surface).
+
+---
+
+## 6. Phases proposées
+- **P0 — Nettoyage fixture** : retirer `timeline()` fixture, `FIXTURE_FRAMES`, `fixture_dir`, fallbacks. Le compositeur ne rend plus QUE ce que l'app lui décrit (layout/zoom/curseur pilotés). Rien de visible tant que les params ne sont pas branchés → à faire avec P1.
+- **P1 — Contrat de scène** : un descripteur « scène » app → natif (clips + trims + layout preset + webcam pos/size/shape/mirror + bg + effets frame + zoom regions + curseur telemetry/theme), pour preview ET export, partagé.
+- **P2 — Parité rendu** (par ordre de valeur) : layout presets · bg gradient/image · zoom regions (focus/depth/rotation) · curseur télémétrie+thèmes · crop · webcam position/reactive-zoom · speed · annotations/captions · camera-fullscreen.
+- **P3 — Preview multiclip natif** (playhead pilote la scène) puis **suppression de la preview web**.
+- **P4 — Params d'export** (fps/taille/codec + downscale/upscale) sur le moteur multiclip.
+
+> Note perf (contrainte) : tout passe par décodage séquentiel + seek keyframe aux frontières,
+> primitives GPU inchangées → l'objectif ~120fps export tient.
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index 0a1414a4c..69dcdab2c 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -414,6 +414,12 @@ unsafe fn render_thread(
// config de base = C8 (tous effets) ; le fond flouté est piloté par le param live.
let mut cfg = config::all().pop().expect("au moins une config");
+ // Migration D3D : le layout et le zoom viennent de l'app (contrat de scène), pas du planning
+ // fixture. On désactive l'animation de layout A↔B et le zoom codés en dur de `timeline()` —
+ // sinon la preview d'un vrai enregistrement joue la « scène fixture » (le bug d'animation vu).
+ // Layout statique (PiP) par défaut ; les zoom regions / presets seront rebranchés via la scène.
+ cfg.zoom = false;
+ cfg.layout_anim = false;
let (mut w, mut h) = {
let r = *shared.rect.lock().unwrap();
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
new file mode 100644
index 000000000..6d24f7b3b
--- /dev/null
+++ b/src/native/sceneDescription.test.ts
@@ -0,0 +1,538 @@
+// Tests for `buildSceneDescription` — the pure serializer that maps an AxcutDocument +
+// editor settings to the frozen `SceneDescription` contract the native D3D compositor reads.
+//
+// Pure: no DOM, no React, no fs/network. We build minimal inline typed AxcutDocument fixtures
+// and verify every derivation branch listed in the spec (background / clips / zoomRegions /
+// crop / settings mapping / output dims).
+
+import { describe, expect, it } from "vitest";
+import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
+import type {
+ AxcutAsset,
+ AxcutClip,
+ AxcutDocument,
+ AxcutZoomRegion,
+} from "@/lib/ai-edition/schema";
+import { buildSceneDescription } from "./sceneDescription";
+
+// --- Fixture helpers --------------------------------------------------------
+// Keep fixtures minimal & deterministic — every field the serializer consults is filled in;
+// irrelevant fields are defaulted so schema-defaulting does not muddy the test.
+
+function makeAsset(
+ overrides: Partial<AxcutAsset> & Pick<AxcutAsset, "id" | "originalPath">,
+): AxcutAsset {
+ return {
+ kind: "video",
+ label: overrides.label ?? overrides.id,
+ cameraTrack: null,
+ ...overrides,
+ };
+}
+
+function makeClip(
+ overrides: Partial<AxcutClip> &
+ Pick<AxcutClip, "id" | "assetId" | "sourceStartSec" | "timelineStartSec" | "timelineEndSec">,
+): AxcutClip {
+ return {
+ wordRefs: [],
+ origin: "system",
+ reason: "",
+ ...overrides,
+ };
+}
+
+function makeZoom(
+ overrides: Partial<AxcutZoomRegion> &
+ Pick<AxcutZoomRegion, "id" | "startMs" | "endMs" | "depth" | "focus">,
+): AxcutZoomRegion {
+ return {
+ ...overrides,
+ };
+}
+
+function makeDoc(
+ overrides: Partial<AxcutDocument> & { assets?: AxcutAsset[]; clips?: AxcutClip[] } = {},
+): AxcutDocument {
+ const assets = overrides.assets ?? [];
+ const clips = overrides.clips ?? [];
+ const createdAt = "2024-01-01T00:00:00.000Z";
+ const baseProject = { id: "p1", title: "Test", createdAt, updatedAt: createdAt };
+ return {
+ schemaVersion: 4,
+ project: {
+ ...baseProject,
+ ...(overrides.project ?? {}),
+ primaryAssetId: overrides.project?.primaryAssetId ?? assets[0]?.id,
+ },
+ assets,
+ transcript: null,
+ transcripts: [],
+ timeline: {
+ clips,
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ ...(overrides.timeline ?? {}),
+ },
+ annotations: [],
+ zoomRanges: overrides.zoomRanges ?? [],
+ legacyEditor: overrides.legacyEditor ?? null,
+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },
+ preview: { strategy: "seek", revision: 0 },
+ export: { preset: "final-balanced", lastJobId: null },
+ history: { revisions: [] },
+ };
+}
+
+// --- background ------------------------------------------------------------
+
+describe("buildSceneDescription.background", () => {
+ it('"#123456" → color', () => {
+ const doc = makeDoc({ legacyEditor: { wallpaper: "#123456" } });
+ expect(buildSceneDescription(doc).background).toEqual({ kind: "color", color: "#123456" });
+ });
+
+ it('"linear-gradient(135deg, #eaebed, #bcc0c6)" → {angleDeg:135, stops:[…]}', () => {
+ const doc = makeDoc({
+ legacyEditor: { wallpaper: "linear-gradient(135deg, #eaebed, #bcc0c6)" },
+ });
+ expect(buildSceneDescription(doc).background).toEqual({
+ kind: "gradient",
+ angleDeg: 135,
+ stops: ["#eaebed", "#bcc0c6"],
+ });
+ });
+
+ it('"linear-gradient(#a1b2c3, #d4e5f6)" → {angleDeg:180, stops:[…]}', () => {
+ const doc = makeDoc({ legacyEditor: { wallpaper: "linear-gradient(#a1b2c3, #d4e5f6)" } });
+ expect(buildSceneDescription(doc).background).toEqual({
+ kind: "gradient",
+ angleDeg: 180,
+ stops: ["#a1b2c3", "#d4e5f6"],
+ });
+ });
+
+ it('"/wallpapers/x.jpg" → image', () => {
+ const doc = makeDoc({ legacyEditor: { wallpaper: "/wallpapers/x.jpg" } });
+ expect(buildSceneDescription(doc).background).toEqual({
+ kind: "image",
+ path: "/wallpapers/x.jpg",
+ });
+ });
+
+ it('"data:image/png;base64,AAAA" → image', () => {
+ const doc = makeDoc({ legacyEditor: { wallpaper: "data:image/png;base64,AAAA" } });
+ expect(buildSceneDescription(doc).background).toEqual({
+ kind: "image",
+ path: "data:image/png;base64,AAAA",
+ });
+ });
+});
+
+// --- clips -----------------------------------------------------------------
+
+describe("buildSceneDescription.clips", () => {
+ it("sorts clips ascending by timelineStartSec", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const clip2 = makeClip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 10,
+ timelineEndSec: 15,
+ });
+ const clip1 = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 2,
+ timelineEndSec: 7,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip2, clip1] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips.map((c) => c.sourceStartSec)).toEqual([0, 0]);
+ expect(clips.map((_, i) => buildSceneDescription(doc).clips[i].sourceStartSec)).toEqual([0, 0]);
+ // Re-derive the order independently so the assertion is on the explicit order property:
+ const ordered = buildSceneDescription(doc).clips;
+ // Mapping timelineStartSec onto the produced clips by index: c1 has timelineStartSec=2,
+ // c2 has 10. After sorting by timelineStartSec, the first clip's sourceStartSec belongs
+ // to c1 (because the clip we gave at timelineStartSec=2 was clip1, whose sourceStartSec
+ // is also 0 — same value — so verify the underlying ordering more directly).
+ // We can distinguish by reading the ids via the document pairing — here both clips share
+ // sourceStartSec=0 so check the paired timeline order by sourceEndSec instead (5 each).
+ // To make the sort visible we instead add unique sourceStartSec values and re-check.
+ expect(ordered).toHaveLength(2);
+ });
+
+ it("sorts clips ascending by timelineStartSec (with distinguishing values)", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const later = makeClip({
+ id: "c-late",
+ assetId: "a",
+ sourceStartSec: 100,
+ sourceEndSec: 105,
+ timelineStartSec: 50,
+ timelineEndSec: 55,
+ });
+ const earlier = makeClip({
+ id: "c-early",
+ assetId: "a",
+ sourceStartSec: 10,
+ sourceEndSec: 15,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [later, earlier] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips.map((c) => c.sourceStartSec)).toEqual([10, 100]);
+ expect(clips.map((c) => c.sourceEndSec)).toEqual([15, 105]);
+ });
+
+ it("infers sourceEndSec when undefined as start + (timelineEnd - timelineStart)", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 7,
+ // sourceEndSec omitted on purpose
+ timelineStartSec: 2,
+ timelineEndSec: 10,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips[0].sourceStartSec).toBe(7);
+ // 7 + (10 - 2) = 15
+ expect(clips[0].sourceEndSec).toBe(15);
+ });
+
+ it("uses the explicit sourceEndSec when set", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 7,
+ sourceEndSec: 11,
+ timelineStartSec: 2,
+ timelineEndSec: 10,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips[0].sourceEndSec).toBe(11);
+ });
+
+ it("routes screenPath/webcamPath/webcamOffsetSec through the cameraTrack when present", () => {
+ const asset = makeAsset({
+ id: "a",
+ originalPath: "/screen.mp4",
+ cameraTrack: {
+ sourcePath: "/cam.mp4",
+ startMs: 250,
+ offsetMs: 750,
+ visible: true,
+ },
+ });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips[0].screenPath).toBe("/screen.mp4");
+ expect(clips[0].webcamPath).toBe("/cam.mp4");
+ expect(clips[0].webcamOffsetSec).toBe((250 + 750) / 1000);
+ });
+
+ it("falls back to the screen path and 0 offset when no cameraTrack", () => {
+ const asset = makeAsset({ id: "a", originalPath: "/screen.mp4", cameraTrack: null });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip] });
+ const { clips } = buildSceneDescription(doc);
+ expect(clips[0].screenPath).toBe("/screen.mp4");
+ expect(clips[0].webcamPath).toBe("/screen.mp4");
+ expect(clips[0].webcamOffsetSec).toBe(0);
+ });
+
+ it("skips a clip whose asset is missing", () => {
+ const doc = makeDoc({
+ assets: [],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "ghost",
+ sourceStartSec: 0,
+ timelineStartSec: 0,
+ timelineEndSec: 1,
+ }),
+ ],
+ });
+ expect(buildSceneDescription(doc).clips).toEqual([]);
+ });
+
+ it("skips a clip whose asset lacks originalPath", () => {
+ // Force-typed fixture: originalPath is required by the schema, but the serializer is
+ // defensive and should skip on a falsy value. Cast through unknown to drop the constraint.
+ const asset = {
+ id: "a",
+ kind: "video",
+ label: "x",
+ originalPath: "",
+ cameraTrack: null,
+ } as unknown as AxcutAsset;
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 1,
+ timelineStartSec: 0,
+ timelineEndSec: 1,
+ });
+ const doc = makeDoc({ assets: [asset], clips: [clip] });
+ expect(buildSceneDescription(doc).clips).toEqual([]);
+ });
+});
+
+// --- zoomRegions -----------------------------------------------------------
+
+describe("buildSceneDescription.zoomRegions", () => {
+ it("depth 1 → scale 1.0", () => {
+ const z = makeZoom({ id: "z", startMs: 0, endMs: 1000, depth: 1, focus: { cx: 0.5, cy: 0.5 } });
+ const doc = makeDoc({ zoomRanges: [z] });
+ const { zoomRegions } = buildSceneDescription(doc);
+ expect(zoomRegions[0].scale).toBe(1.0);
+ });
+
+ it("depth 6 → scale 3.5", () => {
+ const z = makeZoom({ id: "z", startMs: 0, endMs: 1000, depth: 6, focus: { cx: 0.5, cy: 0.5 } });
+ const doc = makeDoc({ zoomRanges: [z] });
+ const { zoomRegions } = buildSceneDescription(doc);
+ expect(zoomRegions[0].scale).toBe(3.5);
+ });
+
+ it("customScale overrides the depth-derived value", () => {
+ const z = makeZoom({
+ id: "z",
+ startMs: 0,
+ endMs: 1000,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ customScale: 4.25,
+ });
+ const doc = makeDoc({ zoomRanges: [z] });
+ const { zoomRegions } = buildSceneDescription(doc);
+ expect(zoomRegions[0].scale).toBe(4.25);
+ });
+
+ it("passes focus + rotationPreset through verbatim", () => {
+ const z = makeZoom({
+ id: "z",
+ startMs: 2000,
+ endMs: 5000,
+ depth: 4,
+ focus: { cx: 0.25, cy: 0.75 },
+ rotationPreset: "iso",
+ });
+ const doc = makeDoc({ zoomRanges: [z] });
+ const { zoomRegions } = buildSceneDescription(doc);
+ expect(zoomRegions[0].focusX).toBe(0.25);
+ expect(zoomRegions[0].focusY).toBe(0.75);
+ expect(zoomRegions[0].rotation).toBe("iso");
+ });
+
+ it("converts ms→sec for start/end", () => {
+ const z = makeZoom({
+ id: "z",
+ startMs: 1500,
+ endMs: 4250,
+ depth: 2,
+ focus: { cx: 0.5, cy: 0.5 },
+ });
+ const doc = makeDoc({ zoomRanges: [z] });
+ const { zoomRegions } = buildSceneDescription(doc);
+ expect(zoomRegions[0].startSec).toBe(1.5);
+ expect(zoomRegions[0].endSec).toBe(4.25);
+ });
+
+ it("rotation defaults to null when no rotationPreset is set", () => {
+ const z = makeZoom({
+ id: "z",
+ startMs: 0,
+ endMs: 1000,
+ depth: 2,
+ focus: { cx: 0.5, cy: 0.5 },
+ });
+ const doc = makeDoc({ zoomRanges: [z] });
+ expect(buildSceneDescription(doc).zoomRegions[0].rotation).toBeNull();
+ });
+
+ it("yields [] when zoomRanges is missing", () => {
+ const doc = makeDoc({ zoomRanges: undefined });
+ expect(buildSceneDescription(doc).zoomRegions).toEqual([]);
+ });
+});
+
+// --- crop ------------------------------------------------------------------
+
+describe("buildSceneDescription.crop", () => {
+ it("returns null for the identity (DEFAULT_CROP_REGION)", () => {
+ const doc = makeDoc({ legacyEditor: { cropRegion: { ...DEFAULT_CROP_REGION } } });
+ expect(buildSceneDescription(doc).crop).toBeNull();
+ });
+
+ it("returns the region unchanged when non-identity", () => {
+ const region = { x: 0.1, y: 0.2, width: 0.5, height: 0.6 };
+ const doc = makeDoc({ legacyEditor: { cropRegion: region } });
+ expect(buildSceneDescription(doc).crop).toEqual(region);
+ });
+});
+
+// --- settings mapping ------------------------------------------------------
+
+describe("buildSceneDescription.settings mapping", () => {
+ it("divides padding by 100", () => {
+ const doc = makeDoc({ legacyEditor: { padding: 50 } });
+ expect(buildSceneDescription(doc).effects.padding).toBe(0.5);
+ });
+
+ it("roundnessPx equals borderRadius", () => {
+ const doc = makeDoc({ legacyEditor: { borderRadius: 12 } });
+ expect(buildSceneDescription(doc).effects.roundnessPx).toBe(12);
+ });
+
+ it("webcamSize is webcamSizePreset / 16.7", () => {
+ const doc = makeDoc({ legacyEditor: { webcamSizePreset: 33.4 } });
+ expect(buildSceneDescription(doc).layout.webcamSize).toBeCloseTo(2, 5);
+ });
+
+ it("maps the cursor sub-settings", () => {
+ const doc = makeDoc({
+ legacyEditor: {
+ cursorSize: 4,
+ cursorSmoothing: 0.9,
+ cursorMotionBlur: 0.5,
+ cursorClickBounce: 1.5,
+ cursorClipToBounds: true,
+ },
+ });
+ const cursor = buildSceneDescription(doc).cursor;
+ expect(cursor.size).toBe(4);
+ expect(cursor.smoothing).toBe(0.9);
+ expect(cursor.motionBlur).toBe(0.5);
+ expect(cursor.clickBounce).toBe(1.5);
+ expect(cursor.clipToBounds).toBe(true);
+ });
+
+ it("maps show / theme / shape / mirror through to layout+cursor", () => {
+ const doc = makeDoc({
+ legacyEditor: {
+ webcamMaskShape: "circle",
+ webcamMirrored: true,
+ cursorShow: false,
+ cursorTheme: "macos-dark",
+ },
+ });
+ const scene = buildSceneDescription(doc);
+ expect(scene.layout.webcamShape).toBe("circle");
+ expect(scene.layout.webcamMirror).toBe(true);
+ expect(scene.cursor.show).toBe(false);
+ expect(scene.cursor.theme).toBe("macos-dark");
+ });
+});
+
+// --- output dims -----------------------------------------------------------
+
+describe("buildSceneDescription.output", () => {
+ it("picks the larger of two used assets", () => {
+ const small = makeAsset({
+ id: "small",
+ originalPath: "/s.mp4",
+ video: { codec: "h264", width: 1280, height: 720, fps: 30 },
+ });
+ const big = makeAsset({
+ id: "big",
+ originalPath: "/b.mp4",
+ video: { codec: "h264", width: 3840, height: 2160, fps: 30 },
+ });
+ const doc = makeDoc({
+ assets: [small, big],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "small",
+ sourceStartSec: 0,
+ sourceEndSec: 1,
+ timelineStartSec: 0,
+ timelineEndSec: 1,
+ }),
+ makeClip({
+ id: "c2",
+ assetId: "big",
+ sourceStartSec: 0,
+ sourceEndSec: 1,
+ timelineStartSec: 1,
+ timelineEndSec: 2,
+ }),
+ ],
+ });
+ const { output } = buildSceneDescription(doc);
+ expect(output).toEqual({ width: 3840, height: 2160, fps: null });
+ });
+
+ it("falls back to {1920, 1080} when no asset has dims", () => {
+ const a = makeAsset({ id: "a", originalPath: "/a.mp4" }); // no video dims
+ const doc = makeDoc({
+ assets: [a],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 1,
+ timelineStartSec: 0,
+ timelineEndSec: 1,
+ }),
+ ],
+ });
+ const { output } = buildSceneDescription(doc);
+ expect(output).toEqual({ width: 1920, height: 1080, fps: null });
+ });
+
+ it("falls back to any asset with dims when no used asset has them", () => {
+ const used = makeAsset({ id: "used", originalPath: "/u.mp4" }); // no dims
+ const probe = makeAsset({
+ id: "probe",
+ originalPath: "/p.mp4",
+ video: { codec: "h264", width: 2560, height: 1440, fps: 30 },
+ });
+ const doc = makeDoc({
+ assets: [used, probe],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "used",
+ sourceStartSec: 0,
+ sourceEndSec: 1,
+ timelineStartSec: 0,
+ timelineEndSec: 1,
+ }),
+ ],
+ });
+ const { output } = buildSceneDescription(doc);
+ expect(output).toEqual({ width: 2560, height: 1440, fps: null });
+ });
+});
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
new file mode 100644
index 000000000..f27d96e50
--- /dev/null
+++ b/src/native/sceneDescription.ts
@@ -0,0 +1,235 @@
+/**
+ * Scene contract — the flat description the app hands the native D3D compositor so it can
+ * compute the composed frame itself (preview AND export) with **no POC-fixture logic**.
+ *
+ * Division of labour:
+ * - App (TS, this file): *serialize* the document + editor settings into this flat shape.
+ * Pure data mapping, no per-frame math.
+ * - Native (Rust, separate): owns the per-frame math (layout geometry, zoom easing, effect
+ * application) — it reads this description + the current time and composes.
+ *
+ * This replaces the hardcoded fixture `timeline()` (A↔B layout animation + 6s zoom schedule)
+ * that used to drive the compositor.
+ *
+ * NOTE (worker): implement `buildSceneDescription` below. Everything else here is the frozen
+ * contract — do not change the exported types.
+ */
+
+import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
+import type { AxcutDocument } from "@/lib/ai-edition/schema";
+import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
+import type { CompositorClipInput } from "./contracts";
+
+/** Background behind the screen. Parsed from `settings.wallpaper`. */
+export type SceneBackground =
+ | { kind: "color"; color: string } // "#rrggbb"
+ | { kind: "gradient"; angleDeg: number; stops: string[] } // linear-gradient(deg, c1, c2, …)
+ | { kind: "image"; path: string }; // "/wallpapers/…" or a data: URL
+
+/** A timeline zoom region (from `document.zoomRanges`). Times in seconds. */
+export interface SceneZoomRegion {
+ startSec: number;
+ endSec: number;
+ /** Target scale (>1 zooms in). Derived from `depth` (or `customScale` when present). */
+ scale: number;
+ /** Focus point, 0..1 of the frame. */
+ focusX: number;
+ focusY: number;
+ /** Optional rotation preset for the zoom. */
+ rotation: "iso" | "left" | "right" | null;
+}
+
+/** Webcam layout, from the editor settings. */
+export interface SceneLayout {
+ preset: "picture-in-picture" | "dual-frame" | "vertical-stack" | "no-webcam";
+ /** Native size scale (1 = the compositor's default PiP webcam). */
+ webcamSize: number;
+ webcamShape: "rectangle" | "circle" | "square" | "rounded";
+ webcamMirror: boolean;
+ /** Normalized position (0..1) for the webcam centre, or null to use the preset default. */
+ webcamPosition: { cx: number; cy: number } | null;
+ /** Webcam shrinks while a zoom region is active. */
+ webcamReactiveZoom: boolean;
+}
+
+/** Frame-styling effects, from the editor settings. */
+export interface SceneEffects {
+ /** 0..1 extra inset of the screen (padding). */
+ padding: number;
+ /** Blur the background (screen used as bg). */
+ blur: boolean;
+ /** 0..1 drop-shadow strength. */
+ shadow: number;
+ /** Corner radius in output px. */
+ roundnessPx: number;
+ /** 0..1 motion blur. */
+ motionBlur: number;
+}
+
+/** Cursor rendering, from the editor settings. */
+export interface SceneCursor {
+ show: boolean;
+ /** Direct scale (1 = default). */
+ size: number;
+ smoothing: number;
+ /** 0..1. */
+ motionBlur: number;
+ clickBounce: number;
+ clipToBounds: boolean;
+ /** Cursor theme id (sprite set). */
+ theme: string;
+}
+
+/** Everything native needs to compose the scene, serialized from one document. */
+export interface SceneDescription {
+ /** Ordered clips (multiclip) with source trims — same shape the export already uses. */
+ clips: CompositorClipInput[];
+ layout: SceneLayout;
+ effects: SceneEffects;
+ background: SceneBackground;
+ zoomRegions: SceneZoomRegion[];
+ cursor: SceneCursor;
+ /** Screen source crop (fractions of the frame), or null for the full frame. */
+ crop: { x: number; y: number; width: number; height: number } | null;
+ /** Output frame. `fps` null = use the first clip's source fps. */
+ output: { width: number; height: number; fps: number | null };
+}
+
+/** Mirror of `buildNativeClipList` in src/components/ai-edition/ExportDialog.tsx — keep these
+ * two derivation paths in lock-step so the native multiclip export and the in-process preview
+ * composer see the same clip stream. */
+function buildNativeClipList(document: AxcutDocument) {
+ const assetById = new Map(document.assets.map((a) => [a.id, a]));
+ return [...document.timeline.clips]
+ .sort((a, b) => a.timelineStartSec - b.timelineStartSec)
+ .flatMap((clip) => {
+ const asset = assetById.get(clip.assetId);
+ if (!asset?.originalPath) return [];
+ const cam = asset.cameraTrack;
+ const sourceEndSec =
+ clip.sourceEndSec ?? clip.sourceStartSec + (clip.timelineEndSec - clip.timelineStartSec);
+ return [
+ {
+ screenPath: asset.originalPath,
+ webcamPath: cam?.sourcePath ?? asset.originalPath,
+ sourceStartSec: clip.sourceStartSec,
+ sourceEndSec,
+ webcamOffsetSec: cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,
+ },
+ ];
+ });
+}
+
+/** Strip a trailing position percentage (or any whitespace tail) from a gradient stop token,
+ * returning the colour piece. The presets never nest parens so a whitespace split is fine. */
+function firstTokenOf(stop: string): string {
+ const trimmed = stop.trim();
+ if (trimmed.length === 0) return trimmed;
+ const spaceIdx = trimmed.indexOf(" ");
+ return spaceIdx === -1 ? trimmed : trimmed.slice(0, spaceIdx);
+}
+
+/** Parse the settings wallpaper string into the discriminated SceneBackground union. */
+function parseWallpaper(wallpaper: string) {
+ if (wallpaper.startsWith("#")) {
+ return { kind: "color", color: wallpaper } as const;
+ }
+ if (wallpaper.startsWith("linear-gradient(")) {
+ // Strip the outer wrapper once — assume well-formed `linear-gradient(...)`.
+ const openIdx = wallpaper.indexOf("(");
+ const closeIdx = wallpaper.lastIndexOf(")");
+ const inner = wallpaper.slice(openIdx + 1, closeIdx);
+ // Presets never contain nested parens; a flat comma split is sufficient.
+ const tokens = inner
+ .split(",")
+ .map((t) => t.trim())
+ .filter((t) => t.length > 0);
+ const angleMatch = /^-?\d+(\.\d+)?deg$/.exec(tokens[0] ?? "");
+ const angleDeg = angleMatch ? parseFloat(tokens[0]) : 180;
+ const stopsRaw = angleMatch ? tokens.slice(1) : tokens;
+ const stops = stopsRaw.map(firstTokenOf).filter((s) => s.length > 0);
+ return { kind: "gradient", angleDeg, stops } as const;
+ }
+ return { kind: "image", path: wallpaper } as const;
+}
+
+/** 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 } {
+ 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)) {
+ return { width: w, height: h };
+ }
+ return best;
+ };
+ let best: { width: number; height: number } | null = null;
+ for (const a of document.assets) {
+ if (usedAssetIds.has(a.id)) {
+ best = consider(a.video?.width ?? 0, a.video?.height ?? 0, best);
+ }
+ }
+ if (!best) {
+ for (const a of document.assets) {
+ best = consider(a.video?.width ?? 0, a.video?.height ?? 0, best);
+ }
+ }
+ return best ?? { width: 1920, height: 1080 };
+}
+
+/** Serialize a document into a {@link SceneDescription}. Pure — no per-frame math. */
+export function buildSceneDescription(document: AxcutDocument): SceneDescription {
+ const settings = getEditorSettings(document);
+
+ const crop =
+ settings.cropRegion.x === DEFAULT_CROP_REGION.x &&
+ settings.cropRegion.y === DEFAULT_CROP_REGION.y &&
+ settings.cropRegion.width === DEFAULT_CROP_REGION.width &&
+ settings.cropRegion.height === DEFAULT_CROP_REGION.height
+ ? null
+ : {
+ x: settings.cropRegion.x,
+ y: settings.cropRegion.y,
+ width: settings.cropRegion.width,
+ height: settings.cropRegion.height,
+ };
+
+ return {
+ clips: buildNativeClipList(document),
+ layout: {
+ preset: settings.webcamLayoutPreset,
+ webcamSize: settings.webcamSizePreset / 16.7,
+ webcamShape: settings.webcamMaskShape,
+ webcamMirror: settings.webcamMirrored,
+ webcamPosition: settings.webcamPosition,
+ webcamReactiveZoom: settings.webcamReactiveZoom,
+ },
+ effects: {
+ padding: settings.padding / 100,
+ blur: settings.showBlur,
+ shadow: settings.shadowIntensity,
+ roundnessPx: settings.borderRadius,
+ motionBlur: settings.motionBlurAmount,
+ },
+ cursor: {
+ show: settings.cursorShow,
+ size: settings.cursor.size,
+ smoothing: settings.cursor.smoothing,
+ motionBlur: settings.cursor.motionBlur,
+ clickBounce: settings.cursor.clickBounce,
+ clipToBounds: settings.cursor.clipToBounds,
+ theme: settings.cursorTheme,
+ },
+ background: parseWallpaper(settings.wallpaper),
+ zoomRegions: (document.zoomRanges ?? []).map((region) => ({
+ startSec: region.startMs / 1000,
+ endSec: region.endMs / 1000,
+ scale: region.customScale ?? region.depth / 2 + 0.5,
+ focusX: region.focus.cx,
+ focusY: region.focus.cy,
+ rotation: region.rotationPreset ?? null,
+ })),
+ crop,
+ output: { ...pickOutputDims(document), fps: null },
+ };
+}