Skip to content

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

docs(architecture): the native compositor, and the export pipeline as architecture

Etienne Lescotffad89384247
diff --git a/technical-documentation/architecture/export-pipeline.md b/technical-documentation/architecture/export-pipeline.md
index dd813821a..365542cea 100644
--- a/technical-documentation/architecture/export-pipeline.md
+++ b/technical-documentation/architecture/export-pipeline.md
@@ -1,39 +1,42 @@
-# Export pipeline — architecture and performance
-
-Status: **Current as of 2026‑07‑17.** Multi‑asset export is shipped. The performance work is measured.
-Scope: the `.axcut` (AI‑edition) export path. The legacy `components/video-editor` exporter is out of scope.
-Owners: ai-edition editor team
-
-> **This file replaces three.** `export-pipeline-v2-spec.md`, `native-core-tauri-spec.md` and
-> `export-native-encode-measurement.md` are deleted. They disagreed with each other and, on the
-> performance half, with reality — each was written on top of the previous one's wrong conclusion.
-> What was true in them is here; what was refuted is in §5, with the evidence, so nobody proposes it
-> again.
-
----
-
-## 1. The short version
-
-**The compositor is 79 % of an export's wall time.** Not the encoder, not the readback, not the IPC
-crossing. Everything else this pipeline has chased was a measurement artefact of one fact: the
-compositor *submits* GPU work and returns immediately, so whatever forces the first synchronisation
-gets billed for it.
-
-Fixing what the compositor rebuilt every frame — a drop shadow that depends only on a rectangle, a
-still wallpaper re‑blurred 1418 times, a GPU texture allocated and freed per frame, a mask
-retessellated per frame — made exports **~1.6–2.0× faster with byte‑identical output**.
-
-Three architectural rewrites were proposed, built or costed before that. All three lost (§5).
-
----
-
-## 2. Architecture as shipped
+# Export pipeline
+
+The MP4 export drives the same Rust + Direct3D 11 compositor that powers the
+live preview ([preview.md](preview.md) /
+[native-compositor.md](native-compositor.md)), one segment at a time. The
+Electron renderer turns the project document into a `RenderPlan`, the
+renderer hands the plan and the per-segment source files to the napi addon
+through the `compositor` IPC domain, and the addon drives `poc-d3d`'s
+`Player` + `Compositor::compose_frame` + AMF encoder + muxer to write one
+`.mp4`. The renderer only watches progress; the actual rendering does not
+leave the native process. Performance numbers, the bench, and the rejected
+alternatives that drove the design live in
+[engineering/rendering-performance.md](../engineering/rendering-performance.md).
+
+GIF and the legacy browser-side path are out of scope here: GIF has no native
+encoder yet (it has its own dedicated code path in
+`src/lib/exporter/gifExporter.ts`); the legacy path is the one the
+`RenderPlan` is being migrated away from.
+
+```mermaid
+flowchart LR
+ DOC["AxcutDocument"]
+ TSD["src/lib/ai-edition/exporter/renderPlan.ts<br/>buildRenderPlan / buildDocumentRenderPlan"]
+ RP["RenderPlan<br/>output + segments + virtual-time effects + appearance + cursor + webcam"]
+ ADDON["compositor_view.node addon<br/>exportMulti (Electron IPC)"]
+ NATIVE["poc-d3d::live::Player<br/>Compositor::compose_frame<br/>h264_amf encoder + mux"]
+ FILE["output.mp4"]
+ DOC --> TSD --> RP --> ADDON --> NATIVE --> FILE
+```
-### 2.1 The `RenderPlan`
+## The `RenderPlan`
-`src/lib/ai-edition/exporter/renderPlan.ts` turns an `AxcutDocument` into an ordered, per‑clip plan.
-`documentExporter.exportAxcutDocument()` is the single entry point — `ExportDialog` and the bench
-both go through it.
+`src/lib/ai-edition/exporter/renderPlan.ts` is the pure-logic data model that
+turns an `AxcutDocument` into an ordered, per-clip plan. `documentExporter`'s
+[`buildDocumentRenderPlan`](../../src/lib/ai-edition/exporter/documentExporter.ts)
+is the single boundary that builds it; `ExportDialog` and the bench both go
+through it. Every length that crosses the boundary is in seconds or
+fractions, every output is in fractions of the output frame, and the plan
+itself is JSON-serialisable.
```ts
interface RenderSegment {
@@ -42,263 +45,195 @@ interface RenderSegment {
videoUrl: string; // toFileUrl(asset.originalPath) — the doc is self-contained
sourceStartSec: number; // clip in-point in the asset's media time
sourceEndSec: number;
+ timelineStartSec: number; // position on the (1:1-with-source, pre-speed) virtual timeline
+ timelineEndSec: number;
intraTrims: Interval[]; // trimRanges of THIS asset inside [start,end)
- cropRegion: CropRegion;
+ cropRegion: CropRegion; // per-clip screen crop, fractions of the source
sourceWidth: number;
sourceHeight: number;
- camera?: { videoUrl: string; offsetMs: number } | null; // per-asset webcam
+ camera: { videoUrl: string; offsetMs: number } | null; // per-asset webcam
+ cursorSamples: CursorRecordingSample[]; // partitioned by assetId
}
-```
-
-### 2.2 Segment loop
-
-`VideoExporter.runSegmentLoop()` walks the segments with one `FrameRenderer`, one encoder and one
-muxer. Per segment: load metadata, `renderer.setSource(...)` for this asset's dims/crop/webcam,
-decode, render, encode; dispose the decoder before the next (one active decoder at a time).
-
-**Time projection.** The encoder timestamp is contiguous **output** time, so junctions are seamless.
-`renderFrame` receives **source** time, so zoom/annotation/cursor match the frame's content even when
-a speed region retimes the segment. An earlier draft proposed keying effects in virtual time
-throughout; that does not survive speed regions, and the two-clock split is why.
-
-### 2.3 Decisions in force
-
-- **Per-segment cursor.** `CursorRecordingSample.assetId` tags each sample, so the plan partitions
- the shared recording per segment.
-- **Clips are contiguous** — no gaps, no overlap.
-- **Audio and video junctions are seamless.** Audio is decoded per segment up front, retimed
- per speed sub-region (WSOLA, pitch preserved), then concatenated at offsets sized from the **real**
- per-segment frame counts — not the estimate — so A/V stays locked. An equal-power fade covers each
- join. The WSOLA stretch is kicked off before the video loop so it overlaps it.
-- **Output** is sized to the largest clip and honours the timeline's aspect ratio.
-
-### 2.4 Licensing
-
-The app is MIT and stays MIT. Any bundled ffmpeg must be built **without** `--enable-gpl` and
-without `--enable-nonfree` — those flags are what pull x264/x265 and fdk-aac, and licensing is
-all-or-nothing. `scripts/fetch-ffmpeg.mjs` vendors a **pinned, checksum-verified** BtbN LGPL build
-and gates it on three independent signals (`-L` says "Lesser General Public License"; no GPL flags
-or GPL libs in `-buildconf`/`-version`; no `libx264`/`libx265` in `-encoders`). It fails closed.
-
-Note `ffmpeg -version` has **no** `License:` line — only `configuration:`. The licence text is behind
-`-L`. An early gate looked for the former, found nothing, and refused to vendor anything; failing
-closed is why that was a bug and not an incident.
-
----
-
-## 3. Performance: what the wall actually is
-
-Measured with `npm run bench:export` (§4) on `proj_a7468696` (2 assets, 2 clips, webcam;
-MP4/1080p/60/H.264; 1418 frames), AMD Ryzen 5 7520U + integrated Radeon.
-
-### 3.1 The compositor, unmasked
-
-Three arms in one run, each adding one stage to the one above:
-
-| arm | ms/frame | what it does |
-|-----|---------:|--------------|
-| `composite-ceiling` | **24.6** | decode + composite, **nothing downstream** |
-| `readback-ceiling` | **24.6** | the same **+ a full `copyTo()`** |
-| `webcodecs` | 31.1 | the same + encode + mux + file |
-
-**Adding the entire GPU→CPU descent moves the wall by 0.03 ms/frame.** The compositor is 79 % of the
-export. The encoder is 4.5.
-
-### 3.2 Why every earlier measurement lied
-
-`renderFrame` **submits** GPU work and returns; `new VideoFrame(canvas)` is **lazy**; nothing has
-executed yet. The first stage to force a synchronisation is billed for everything queued before it.
-
-So `render` reported **2.06 ms/frame** for work costing **24.6** — under by **13×** (with a shadow
-on: 1.55 vs 63.7, under by **41×**). The cost surfaced downstream, under whatever name that stage
-had: `encodeWait` at "90 % of wall", a "readback" of 32 seconds, a "descent" of 38.9 ms/frame. One
-wall, three disguises — and each disguise launched an architecture programme against the wrong thing.
-
-**This retires "≈13 ms/frame of Chromium overhead on a path we do not control."** It is our
-compositor, and we control all of it.
-
-**Any stage timer in this pipeline measures submission, not execution, unless something forces a
-sync.** Trust the ceiling arms, not `StageTimings`.
-
-### 3.3 What the compositor was rebuilding every frame
-
-| what | why it was free to fix | measured |
-|------|------------------------|---------:|
-| **drop shadow** | three chained `drop-shadow` over the full frame. `drop-shadow` reads **SourceAlpha only**, and `videoCanvas`'s alpha is just the sprite masked by a roundRect — so it blurred 2M pixels of *video* to compute a function of `(rect, radius, intensity)`. The video never reached the result. | **~30 ms/frame** |
-| **wallpaper blur** | a still image, rasterised once at load, then re-blurred 1418 times | ~5 ms/frame |
-| **video texture** | `Texture.from(videoFrame)` + `oldTexture.destroy(true)`: allocate, upload and free a 1080p GPU texture per frame (every `VideoFrame` is a new object, so nothing caches) | — |
-| **rounded mask** | `clear()/roundRect()/fill()` retessellates a shape identical from frame to frame | — |
-
-Per-effect cost on the real compositor, isolated (spread 3–4 %): **shadow 43.5 ms/frame**, blur 17.9,
-radius 13.3. Radius is ~free — it draws inside a pass that already exists.
-### 3.4 The fix, and its shape
-
-**Classify by what invalidates it, not by layer:**
-
-| never | on geometry | every frame |
-|-------|-------------|-------------|
-| wallpaper blur | drop shadow, rounded mask, video texture | video, cursor, webcam, annotations |
-
-The shadow now runs against a **silhouette** — taken from `videoCanvas`'s own alpha
-(`drawImage` + `source-in` over black), not re-derived from the layout, so nothing has to stay in
-sync as layout code evolves. Its output *is* `silhouette OVER shadow`, so drawing `videoCanvas` on
-top covers the silhouette exactly, **including the anti-aliased corners**. Cached on the geometry:
-**1417 hits / 1 miss** over 1418 frames.
-
-Also: `clearRect(w,h)` before a `drawImage(w,h)` that covers the canvas is two full-frame passes
-where `globalCompositeOperation = "copy"` is one.
-
-### 3.5 What it bought
-
-Within-run ratios only (§4.2 explains why):
-
-| run | before | after | ratio |
-|-----|-------:|------:|------:|
-| `composite-ceiling`, shadow+radius | 39.45 ms/frame | 20.22 | **1.95×** |
-| `webcodecs`, blur+shadow+radius | 67 717 ms | 33 707 | **2.01×** |
-| `webcodecs`, shadow+radius | 63 825 ms | 39 839 | **1.60×** |
-
-**Output is byte-identical.** Same timeline, same encoder, old compositor vs new → the files are
-identical byte for byte, SSIM 1.000000 across all 1418 frames. Not a pixel moved.
-
-### 3.6 What is left
-
-- **Zoom defeats the shadow cache.** A zoom region changes the geometry every frame, so the shadow
- pays full price for its whole duration. This is the strongest remaining case for a single-pass
- shader — and it must be argued on what remains *after* §3.4, not on the 30 ms already gone.
-- **The 3D path is not cached** and stays at full price on purpose: it blurs `foregroundCanvas`,
- whose alpha carries the webcam, cursor and annotations, so it has no stable geometry to key on.
-- **The webcam mask** is unaudited: the shape does not change, only the pixels inside it.
-
----
-
-## 4. The bench
-
-```bash
-npm run bench:export -- --project=<id|title> --arms=webcodecs,native --runs=2 --effects=shadow,blur
+interface RenderPlan {
+ output: { width, height, frameRate, bitrate, codec };
+ aspectRatioValue: number;
+ segments: RenderSegment[]; // sorted by timelineStartSec
+ zoomRegions: ZoomRegion[]; // VIRTUAL (output) time, no projection
+ annotationRegions: AnnotationRegion[]; // same — captions are derived + joined here
+ speedRegions: SpeedRegion[]; // same
+ appearance: RenderPlanAppearance; // wallpaper, padding, radius, shadow, blur, motion
+ cursor: RenderPlanCursor | null; // shared atlas + style; per-segment samples above
+ webcam: RenderPlanWebcam; // shared layout/style; per-segment source above
+}
```
-`scripts/bench-export.mjs` + `src/bench/runBench.ts`. It **simulates nothing**: it opens the real
-editor window (same `webPreferences`, preload and sandbox), loads a real saved project through the
-same bridge the editor uses, and calls `exportAxcutDocument` — `ExportDialog`'s own entry point. Only
-React is skipped, so nothing renders alongside the export.
-
-It exists because driving this through the UI cost ~5 minutes a run and kept injecting confounds: one
-A/B ran with DevTools open on **one arm only**; another ran on a laptop at 5 % battery whose SoC
-budget drifted 26 % *between the two arms* — enough to invert the conclusion.
-
-**Arms** set `localStorage` flags read at runtime, so one app session measures every arm against one
-document: `webcodecs`, `native`, `*-legacy` (the pre-2026‑07‑17 compositor, for attribution),
-`composite-ceiling` (render only), `readback-ceiling` (render + `copyTo`, discard).
-
-**`--effects=shadow,blur,radius,zoom`** patches an in-memory **copy** of the document; nothing
-reaches disk. Saved projects carry no appearance at all (`shadowIntensity` defaults to **0**), so
-whole effects never execute — "fixing" the shadow on a default project measures exactly zero. `zoom`
-matters beyond its own cost: it is the only effect that changes geometry per frame, so it is what
-invalidates a geometry-keyed cache. **A parity test without it passes with a broken cache key**,
-because nothing ever asks the cache to invalidate.
-
-### 4.1 Parity is gated, not argued
-
-Unit tests never look at a pixel. The `native*` arms write real files: export the same timeline
-through the same encoder with each compositor, then `cmp` and `ffmpeg -lavfi ssim`. Every compositor
-change above cleared it byte-for-byte. **"Obviously equivalent" is what this pipeline keeps
-punishing** — gate it.
-
-### 4.2 This machine is not reproducible. Only ratios are.
-
-The same arm, same project, same settings has measured **44.0, 36.8, 32.3, 31.8, 22.2 and 11.9 fps**
-across sessions. The 11.9 run reported **0 % spread** over its two samples — it looked airtight and
-did not survive a re-run 40 minutes later (22.2).
-
-So: **arms interleave (A,B,A,B), and the bench reports same-arm spread and declares itself VOID above
-10 %.** Never quote an absolute fps as "what the export does"; quote a within-run ratio. A stable
-measurement is not a true one.
-
----
-
-## 5. Refuted: do not re-propose these
-
-Every row was built or costed against the wrong wall (§3.2). Kept so the argument is not re-run.
-
-| proposal | verdict |
-|----------|---------|
-| **Native ffmpeg fed from the renderer** (bundled LGPL, hardware encoder) | **2.1× SLOWER** (38.5 s → 80.8 s, spread 3–4 %). ffmpeg consumes frames *faster* (`encodeWait` −29 %, `flush` −94 %) — but WebCodecs encodes straight off the GPU texture and never brings a frame to the CPU. Adding a descent to a wall that was already there. |
-| **A′ — `sandbox: false`**, renderer spawns ffmpeg and writes its stdin | **Excluded without building it.** With the crossing at *exactly zero* (frames descended then discarded: no IPC, no ffmpeg, no muxer) the pipeline still lost, **while WebCodecs was also writing the file**. A′ does not even remove the crossing — it swaps a structured clone (~390 MB/s) for a pipe write (~500 MB/s), ~1.2× on one leg, bought by giving up the sandbox that guards demux/decode of untrusted media. |
-| **Phase 4 — GPU BGRA→NV12 packing** | Cannot rescue the above. The descent measured **6.7 ms fixed + 3.9 ms/MB** (257 MB/s marginal — a sync, not a copy), so NV12 halves it and still lands at parity at best. |
-| **Native CPU compositor** | Reached parity at best — and that comparison was anchored on the 44 fps figure §4.2 retired, so it is not even that solid. Compositing is what CPUs are bad at and GPUs are good at; avoiding the descent pays it back in compositing. |
-| **Worker + OffscreenCanvas** | Buys UI responsiveness, not speed. The main thread was never the throughput limit. |
-| **GPU-resident compositing** (`a31cf49` → reverted `e6cbb45`) | Implemented, measured, reverted: moved the work, left the synchronisation where it was. |
-
-### 5.1 Native core / Tauri
-
-**It is not *Node vs Rust*, and not *Electron vs Tauri*.** Neither the language nor the shell forces
-the descent — **the browser engine does**. The compositor is Pixi/WebGL/Canvas2D inside Chromium's
-renderer, and Chromium exposes its GPU textures to nobody. Tauri's webview on Windows *is* Chromium
-(WebView2): composite in the webview under Tauri and you pay the identical descent.
-
-Zero descent requires one thing: **the compositor stops being a web canvas** and becomes our own GPU
-code, owning the same device as the encoder. That is reachable **from Electron too** — an N-API
-addon, or a native sidecar. **The shell is a consequence, not a cause**; it earns its place on bundle
-size and memory, never on this measurement. What would actually force the shell question is the
-**preview**: once the compositor is native, the preview must come from it too, or the product ships
-two compositors and loses the parity that is its entire value.
-
-**Hardware findings, if anyone revisits this** (measured 2026‑07‑17, bundled ffmpeg, this laptop):
-
-- **GPU decode → GPU encode, no descent, no compositing: 234 fps.** The physics has room; the floor
- is not the problem.
-- **Vulkan is a dead end for the encoder here**: the driver exposes `video_decode_queue` only (no
- encode queue), and AMF refuses to initialise from a Vulkan device — *"not supported"*, explicitly.
-- **`scale_d3d11` fails** to create its texture (`80070057`) on every format tried.
-- **d3d11 → OpenCL `hwmap` fails** on NV12's UV plane.
-- So **the ffmpeg CLI cannot express GPU-composite → GPU-encode on this hardware** — a limit of its
- filter plumbing, not of the GPU, which composites the whole scene natively today. A real native
- core would decode with libavcodec into a **D3D11** texture (not Vulkan, not OpenCL), composite on
- that device, and hand the texture to AMF.
-
----
-
-## 6. Traps this pipeline has actually fallen into
+Effects (`zoomRegions`, `annotationRegions`, `speedRegions`) live on the
+plan in **virtual** (output) time. The segment loop already tracks the
+virtual-time cursor that an earlier design tried to compute up-front by
+projecting every region onto source time — that projection is what the TS
+exporter still does for the legacy single-source renderer; the segment
+loop does not need it.
+
+The plan also carries the `codec` as a WebCodecs encoder string per
+user-facing choice (`avc1.640033` for H.264, `hvc1.1.6.L120.90` for H.265,
+`vp09.00.10.08` for VP9). The native side's AMF encoder takes those
+strings and produces the matching mp4 track family.
+
+`isIdentityFastPathEligible(plan)` is a single boolean: one segment, no
+intra-trims, identity crop, no zoom/annotation, no cursor overlay, no
+speed, and `output.size === segment.source.size` → the renderer can take a
+stream-copy / remux-only fast path. Everything else goes through the full
+decode → composite → encode round trip.
+
+## Segment loop
+
+The renderer hands the addon `exportMulti(clips, outPath, sceneJson, params)`
+through `compositorViewService.exportMulti`
+([`compositorViewService.ts:425`](../../electron/native-bridge/services/compositorViewService.ts)).
+The service resolves the same asset paths the renderer used (wallpaper
+images, cursor theme sprite) and forwards the call to the addon
+([`compositorViewService.ts:437`](../../electron/native-bridge/services/compositorViewService.ts)).
+The addon loads `poc-d3d`'s `Player` with the clip list and the shared
+`SceneDescription` JSON, then walks the segments with **one** compositor
+and **one** encoder + muxer pair:
+
+- Per segment: load metadata, hand the asset to the `Player` (so screen
+ and webcam decode land on `poc-d3d`'s shared `ID3D11Device`), drive
+ `compose_frame` at the segment's source time, and let the AMF encoder
+ consume the rendered RT. The compositor is paused on the live preview
+ for the duration of the export (`set_playing(false)` on every active
+ preview view), which the addon does automatically — the only cost of
+ running export against a live preview is GPU contention from the preview
+ still composing; the bench measures that overhead at ~10 % of wall time
+ in the measurement scenario, recovered by the auto-pause.
+
+- **Time projection.** The encoder timestamp is contiguous **output**
+ time, so junctions between segments are seamless. `compose_frame`
+ receives **source** time (`source_t = frame / FPS`), so
+ zoom / annotation / cursor match the frame's content even when a speed
+ region retimes the segment. An earlier draft proposed keying effects in
+ virtual time throughout; that does not survive speed regions, and the
+ two-clock split is why.
+
+- **Clips are contiguous** — no gaps, no overlap. The renderer sums
+ per-segment rounded frame counts into a single output frame counter;
+ audio follows the same integer accumulation (`AudioConcatPlan`).
+
+- **Audio and video junctions are seamless.** Audio is decoded per
+ segment up front (`audio.rs::decode_clip_audio`), WSOLA stretches each
+ speed sub-segment to its output sample count, and
+ `assemble_concatenated_pcm` concatenates the per-segment PCM at the
+ integer sample offsets the video loop just produced — never
+ `round(cumulativeSec * sampleRate)`, because that compounds per-segment
+ rounding error into audible A/V drift across a long multi-segment
+ timeline. A short equal-power fade (`cos` on the tail, `sin` on the
+ head, `cos² + sin² = 1`) covers each internal boundary to suppress the
+ click where two recordings meet butt-joined, without shifting timing.
+ The WSOLA stretch is kicked off before the video loop so it overlaps
+ the encode and does not add to the wall.
+
+- **Output** is sized to the largest clip and honours the timeline's
+ selected aspect ratio. `pickReferenceDimensions` (in `renderPlan.ts`)
+ picks the largest source area, then `calculateMp4ExportSettings` maps
+ quality + source dims + aspect ratio to the encoder width / height /
+ bitrate.
+
+## Per-segment cursor
+
+`CursorRecordingSample.assetId` tags each sample, so the plan partitions
+the shared recording per segment (`cursorSamplesForAsset`,
+[`renderPlan.ts:178`](../../src/lib/ai-edition/exporter/renderPlan.ts)).
+Samples with no `assetId` belong to the primary asset — the convention that
+keeps single-asset projects rendering their cursor exactly as before.
+Untagged samples were the format before multi-asset cursor tagging
+landed; the fallback is the documented behaviour, not a heuristic.
+
+The shared parts of the cursor render — the sprite atlas and the style
+knobs (`scale`, `smoothing`, `motionBlur`, `clickBounce`, `clipToBounds`,
+`theme`) — live on `plan.cursor` once. The time-varying samples live per
+segment on `segment.cursorSamples`. A segment with no cursor samples
+renders with no cursor overlay, which is correct (the asset had no
+recording), not a gap.
+
+## Output formats and codecs
+
+The native MP4 export takes `width`, `height`, `frameRate`, and `codec` as
+parameters on `exportMulti` and writes H.264 (AMF) by default. The user-
+facing codec choice (H.264 / H.265 / VP9) is mapped by `renderPlan.ts` to
+the WebCodecs encoder string the addon's AMF encoder consumes; VP9
+falls back to the same H.264 path on machines without a hardware VP9
+encoder (software VP9 was measured too slow and removed — see
+[native-compositor.md](native-compositor.md#known-gaps)). GIF is a
+separate path through `GifExporter` and does not use the native addon.
+
+## Licensing
+
+The app is MIT and stays MIT. Any bundled ffmpeg must be built **without**
+`--enable-gpl` and without `--enable-nonfree` — those flags pull
+x264/x265/xvid and fdk-aac, and licensing is all-or-nothing. The same
+rule applies to the BtbN build the addon links against (see
+[native-compositor.md](native-compositor.md#build)): LGPL-shared
+`*lgpl-shared`, not GPL. `scripts/fetch-ffmpeg.mjs` vendors a pinned,
+checksum-verified BtbN LGPL build and gates it on three independent
+signals (`-L` says "Lesser General Public License"; no GPL flags or GPL
+libs in `-buildconf`/`-version`; no `libx264` / `libx265` in
+`-encoders`). It fails closed.
+
+Note `ffmpeg -version` has **no** `License:` line — only `configuration:`.
+The licence text is behind `-L`. An early gate looked for the former,
+found nothing, and refused to vendor anything; failing closed is why that
+was a bug and not an incident.
+
+## Traps this pipeline has actually fallen into
Each cost hours and each produced a confident, wrong conclusion.
-1. **`app.getGPUFeatureStatus()` from a windowless script** reports everything `disabled_software`.
- Always probe with a real window.
-2. **Piping via `cat` under Git Bash** caps at ~70 MB/s — MSYS emulation, not Windows.
-3. **`new VideoFrame(canvas)` is lazy.** Timing the constructor measures nothing.
-4. **Isolated component benchmarks cannot price the cost of connecting the component.** The
- `node → ffmpeg` probe measured 489–589 MB/s by materialising frames **once**, outside the timed
- loop — a true statement about the pipe that said nothing about the pipeline.
-5. **`-encoders` lists what was compiled in, not what the machine can run.** A portable build lists
- nvenc/qsv/amf everywhere; on this AMD laptop nvenc dies with "Cannot load nvcuda.dll". Only a
- one-frame smoke encode settles it — and the unit tests passed *because the fixtures encoded the
- same wrong assumption as the code*.
-6. **Electron cannot transfer an ArrayBuffer renderer→main.** The transfer list takes
- `MessagePort[]`; transferring a buffer silently drops the whole message
- ([electron#34905](https://github.com/electron/electron/issues/34905)) — it works renderer→renderer.
-7. **`Buffer.from(typedArray)` copies.** Wrapping (`Buffer.from(buf.buffer, byteOffset, byteLength)`)
- measured +31 %.
-8. **A stale `dist-electron` bundle** runs the *previous* main process against the new renderer. It
- read as "export IPC not registered" once and as "the bench flag does nothing" once. The bench now
- refuses to run against one.
-9. **The installed app (`openscreen.exe`) holds the same single-instance lock as the dev build.** A
- launch exits 0 and reports nothing — silently.
-
----
-
-## 7. Unrelated but recorded: project files can corrupt
-
-`proj_de6ffaaa` (`os_parity`) is **4006 bytes: 3485 of valid JSON followed by the tail of a longer
-version of the same document.** That is two concurrent `fs.writeFile` calls of two different
-versions — both open with `O_TRUNC`, then write at their own offsets. `listProjects` skips it, so the
-project is unopenable.
-
-`writeProject` (`document-service.ts`) truncates correctly on its own; what is missing is
-**serialisation of saves and an atomic write** (temp file + rename).
-
-**Not repaired.** The recoverable prefix has `speedRegions: 0, zoomRegions: 0` while the real
-timeline had two 3× regions and a 1.80× zoom — truncating would have returned a project silently
-stripped of its effects, and the zoom is not recoverable from the file at all. A byte-exact backup
-sits beside it (`*.corrupt-backup-20260716`).
+1. **`app.getGPUFeatureStatus()` from a windowless script** reports
+ everything `disabled_software`. Always probe with a real window.
+2. **Piping via `cat` under Git Bash** caps at ~70 MB/s — MSYS emulation,
+ not Windows.
+3. **`new VideoFrame(canvas)` is lazy.** Timing the constructor measures
+ nothing.
+4. **Isolated component benchmarks cannot price the cost of connecting
+ the component.** A `node → ffmpeg` probe measured 489–589 MB/s by
+ materialising frames **once**, outside the timed loop — a true
+ statement about the pipe that said nothing about the pipeline.
+5. **`-encoders` lists what was compiled in, not what the machine can
+ run.** A portable build lists nvenc/qsv/amf everywhere; on this AMD
+ laptop nvenc dies with "Cannot load nvcuda.dll". Only a one-frame
+ smoke encode settles it — and the unit tests passed *because the
+ fixtures encoded the same wrong assumption as the code*.
+6. **Electron cannot transfer an `ArrayBuffer` renderer→main.** The
+ transfer list takes `MessagePort[]`; transferring a buffer silently
+ drops the whole message
+ ([electron#34905](https://github.com/electron/electron/issues/34905)) —
+ it works renderer→renderer.
+7. **`Buffer.from(typedArray)` copies.** Wrapping
+ (`Buffer.from(buf.buffer, byteOffset, byteLength)`) measured +31 %.
+8. **A stale `dist-electron` bundle** runs the *previous* main process
+ against the new renderer. It read as "export IPC not registered" once
+ and as "the bench flag does nothing" once. The bench now refuses to
+ run against one.
+9. **The installed app (`openscreen.exe`) holds the same single-instance
+ lock as the dev build.** A launch exits 0 and reports nothing —
+ silently.
+
+## A truncated project file is unopenable, not partially readable
+
+`listProjects` skips a project whose JSON does not parse, so a truncated file
+presents as a project that has vanished rather than as an error. Worth knowing
+when a bench fixture disappears.
+
+Two concurrent saves used to be able to produce exactly that. They no longer can:
+`DocumentService` serialises saves through a per-project write queue and writes
+atomically (unique temp file → `fsync` → rename, `electron/ai-edition/document-service.ts:354`).
+One fixture from before the fix is still corrupt — see the Known gaps in
+[../engineering/rendering-performance.md](../engineering/rendering-performance.md).
+
+The reason that one was never repaired is the useful part: its recoverable prefix
+had `speedRegions: 0, zoomRegions: 0` while the real timeline held two 3× speed
+regions and a 1.80× zoom. Truncating to the valid prefix would have returned a
+project that opened cleanly and was silently stripped of its effects. **A partial
+document that parses is more dangerous than one that does not** — which is why the
+loader rejects rather than salvages.
\ No newline at end of file
diff --git a/technical-documentation/architecture/native-compositor.md b/technical-documentation/architecture/native-compositor.md
new file mode 100644
index 000000000..5c1bc05e8
--- /dev/null
+++ b/technical-documentation/architecture/native-compositor.md
@@ -0,0 +1,255 @@
+# Native compositor
+
+`poc-d3d/` is the Rust + Direct3D 11 crate behind both the live preview and the MP4
+export. It exposes its compositor and pipeline to Electron through a small
+napi-rs addon (`compositor-view-napi/`) loaded by
+[`compositorViewService`](../../electron/native-bridge/services/compositorViewService.ts).
+The whole GPU-resident path lives here — `demux → decode → composite → encode → mux`,
+zero CPU readback between stages — and is shared, with the same scene contract, by
+[preview.md](preview.md) (frame-by-frame RGBA8 pull) and
+[export-pipeline.md](export-pipeline.md) (multiclip MP4 write). The performance
+numbers and the rejected alternatives that drove the design live in
+[engineering/rendering-performance.md](../engineering/rendering-performance.md).
+
+A single `ID3D11Device` ([`poc-d3d/src/d3d.rs`](../../poc-d3d/src/d3d.rs))
+is shared by every consumer on the path: the ffmpeg `D3D11VA` decoder, the HLSL
+compositor, the `h264_amf` encoder, and the live swapchain. It is created with
+feature level **11_1**, the flags `VIDEO_SUPPORT | BGRA_SUPPORT` (`VIDEO_SUPPORT`
+is required for `D3D11VA`; `BGRA_SUPPORT` enables the DirectWrite/Direct2D path
+used by text annotations), and `ID3D10Multithread::SetMultithreadProtected(TRUE)`
+— ffmpeg's decoder thread and the render loop touch the device concurrently,
+and without that flag the runtime corruption is silent.
+
+## Module map
+
+| source | responsibility |
+|---|---|
+| [`poc-d3d/src/lib.rs`](../../poc-d3d/src/lib.rs) | crate root: exposes `run()` (CLI / bench / GUI dispatcher), re-exports every module |
+| [`poc-d3d/src/d3d.rs`](../../poc-d3d/src/d3d.rs) | the single `ID3D11Device` (feature level 11_1, `VIDEO_SUPPORT`, multithread-protected) |
+| [`poc-d3d/src/ffi.rs`](../../poc-d3d/src/ffi.rs) | bindgen-generated `libav*` bindings (ffmpeg 8.x headers) |
+| [`poc-d3d/src/compositor.rs`](../../poc-d3d/src/compositor.rs) | HLSL compositor — every per-frame pass (`compose_frame`, background, screen, webcam, cursor, annotations, shadows, blur) |
+| [`poc-d3d/src/scene.rs`](../../poc-d3d/src/scene.rs) | the `Scene` struct parsed from the app's `SceneDescription` JSON |
+| [`poc-d3d/src/regions.rs`](../../poc-d3d/src/regions.rs) | zoom / speed / Full Camera regions — envelope shapes and per-frame state sampling |
+| [`poc-d3d/src/pipeline.rs`](../../poc-d3d/src/pipeline.rs) | demux + `D3D11VA` decode + composite + AMF encode + mux (`run_c0` for decode/encode only, `run_composited` for the full path) |
+| [`poc-d3d/src/audio.rs`](../../poc-d3d/src/audio.rs) | per-clip audio decode, swresample → f32 planar 48 kHz stereo, WSOLA speed stretch, multi-track mix, AAC encoder |
+| [`poc-d3d/src/cursor.rs`](../../poc-d3d/src/cursor.rs) | `.cursor.json` parser + interpolated cursor track (position, click bounces, adaptive follow samples) |
+| [`poc-d3d/src/text.rs`](../../poc-d3d/src/text.rs) | DirectWrite + Direct2D text rasterisation for annotation labels, cached per (content, style, box) |
+| [`poc-d3d/src/text_anim.rs`](../../poc-d3d/src/text_anim.rs) | text-annotation appearance animations (port of the TS animation curves, in fractions of the output short side) |
+| [`poc-d3d/src/config.rs`](../../poc-d3d/src/config.rs) | cumulative bench configs C0..C8 (each adds one layer: composite, rounded corners, shadow, background blur, zoom, layout animation, cursor, motion blur) |
+| [`poc-d3d/src/live.rs`](../../poc-d3d/src/live.rs) | off-screen view: `Player` + `Compositor::compose_frame` → RGBA8 staging texture, pulled by the napi addon |
+| [`poc-d3d/src/app.rs`](../../poc-d3d/src/app.rs) | standalone Win32 GUI (combo preset, Play/Pause, Export, progress bar) — wraps the measured pipeline for interactive demo |
+| [`poc-d3d/src/main.rs`](../../poc-d3d/src/main.rs) | thin `main` that calls `lib::run()` |
+| [`poc-d3d/src/shaders.hlsl`](../../poc-d3d/src/shaders.hlsl) | all GPU effects (modes 0/1/5/8/9/10/12 — see pipeline below), compiled at runtime via Fxc |
+
+## The compositing pipeline
+
+Every visible frame is rasterised into one RGBA render target
+(`OUT_W × OUT_H = 1920×1080`, then optionally bilinearly resized to the real
+output aspect). `Compositor::compose_frame`
+([`poc-d3d/src/compositor.rs:1421`](../../poc-d3d/src/compositor.rs))
+runs one fixed draw order — derived from the per-frame math it performs, not
+from any list the caller can reorder — and `shaders.hlsl` keys each effect off
+the `mode` field of the same `LayerCB` struct, so the modes below are exactly
+what `shaders.hlsl` actually implements:
+
+1. **Background** (the wallpaper). `mode = 1` for a solid colour
+ ([`compositor.rs:1761`](../../poc-d3d/src/compositor.rs)),
+ `mode = 5` for a CSS gradient
+ ([`compositor.rs:1765`](../../poc-d3d/src/compositor.rs)), or a cover-fitted
+ image loaded through `draw_image_bg`
+ ([`compositor.rs:1156`](../../poc-d3d/src/compositor.rs)). When the
+ scene's `effects.blur` is on, `blur_bg` (dual-Kawase, ~18 px) blurs whatever
+ was just drawn — that is what "Blur BG" does, mirroring the web
+ `frameRenderer.blurredBackgroundLayer`
+ ([`compositor.rs:1807`](../../poc-d3d/src/compositor.rs)).
+2. **Screen shadow.** Drop-shadow SDF; opacity scales with the `shadow`
+ slider. The shadow tracks the rendered silhouette — a tilted plane gets a
+ tilted shadow, not a rect shadow
+ ([`compositor.rs:1885`](../../poc-d3d/src/compositor.rs) /
+ [`compositor.rs:1882`](../../poc-d3d/src/compositor.rs), `mode = 12`).
+3. **Screen video.** Cropped from the active clip's source, with the zoom region
+ applied to its UVs and rounded corners via SDF. `mode = 0` for the standard
+ quad ([`compositor.rs:1898`](../../poc-d3d/src/compositor.rs));
+ `mode = 8` for the 3D tilt path (zoom `rotation: iso | left | right`,
+ [`compositor.rs:1950`](../../poc-d3d/src/compositor.rs)). Motion blur
+ uses the previous frame's UV delta as a per-pixel velocity vector and samples
+ along it (the "blur by velocity" optimisation — early-outs on still frames).
+4. **Cursor.** Math dot+ring by default; sprite (loaded from
+ `cursor.cursorSpritePath`) when the app hands the native side a theme
+ path. Motion blur is its own accumulation buffer (additive blend into an
+ isolated RT, then "over"-composited onto the scene), independent of the
+ scene's `effects.motionBlur`
+ ([`compositor.rs:2038`](../../poc-d3d/src/compositor.rs) /
+ [`compositor.rs:2060`](../../poc-d3d/src/compositor.rs)). Click
+ bounce amplitude comes from the `.cursor.json` track
+ ([`poc-d3d/src/cursor.rs`](../../poc-d3d/src/cursor.rs)).
+5. **Webcam shadow.** Drawn only when `cfg.shadow` is on AND the layout is PiP
+ (not the block layouts, which weld the camera flush to the screen — no
+ floating bubble, no shadow). The strength fades to zero as the camera
+ enters Full Camera mode
+ ([`compositor.rs:2118`](../../poc-d3d/src/compositor.rs), `mode = 12`).
+6. **Webcam video.** UV rectangle derived from the destination aspect, with
+ mirror, mask shape (rectangle / circle / square / rounded), and reactive
+ scale applied
+ ([`compositor.rs:2127`](../../poc-d3d/src/compositor.rs), `mode = 0`).
+ Full Camera lerps the destination to `[0, 0, 1, 1]` and dissolves the mask
+ shape — same rule as `computeCameraFullscreenRect` on the TS side.
+7. **Annotations.** Highest layer. One full-frame `CopySubresourceRegion` of
+ the composed scene is taken at the top of `draw_annotations` so that
+ multiple blur annotations on the same frame read from a consistent snapshot
+ of the underlying pixels
+ ([`compositor.rs:2162`](../../poc-d3d/src/compositor.rs)).
+ Per-annotation: figure (arrow, `mode = 9`), blur/mosaic (`mode = 10`),
+ text (DirectWrite → D3D11 SRV, then `mode = 0`), image (cached per
+ annotation id).
+
+```mermaid
+flowchart TB
+ subgraph frame["compose_frame - one frame"]
+ BG["background<br/>mode 1 / 5 / image<br/>+ optional blur_bg dual-Kawase"]
+ SS["screen shadow<br/>mode 12<br/>tilt-aware quad"]
+ SV["screen video<br/>mode 0 or 8 (tilt)<br/>velocity motion blur"]
+ CU["cursor<br/>math dot+ring or sprite<br/>own accumulation buffer"]
+ WS["webcam shadow<br/>mode 12, PiP only"]
+ WV["webcam video<br/>mode 0<br/>shape + reactive scale"]
+ ANN["annotations<br/>mode 9 figure<br/>mode 10 blur<br/>text/image quad"]
+ end
+ BG --> SS --> SV --> CU --> WS --> WV --> ANN
+```
+
+## Scene contract
+
+The app hands the native compositor a flat JSON description once per document
+or settings change. The TypeScript producer is
+[`buildSceneDescription`](../../src/native/sceneDescription.ts); the Rust
+mirror is the `Scene` struct in
+[`poc-d3d/src/scene.rs`](../../poc-d3d/src/scene.rs). Field renames are
+camelCase on both sides (`#[serde(rename_all = "camelCase")]`), so the wire
+format is the same names a TS caller already writes. Three fields the
+contract insists on carrying as **fractions** of their reference box, not
+pixels, because the native side rasterises the preview into a small
+contain-fitted frame and the export at full output size:
+
+- `effects.roundnessFrac` — of the output frame's short side.
+- `layout.screenRadiusFrac`, `layout.webcamRadiusFrac` — of their own box's
+ short side (the only way two halves of a block layout can agree on a
+ radius; see `compositor.rs` §1's comment on
+ [`compositor.rs:1702`](../../poc-d3d/src/compositor.rs)).
+- `annotation.x|y|w|h` and `annotation.text.fontSizeRel` — of the screen
+ rect (annotations anchor to the screen box, not the output frame, and
+ intentionally bypass the zoom transform).
+
+The consumer is `Compositor::compose_frame`
+([`compositor.rs:1421`](../../poc-d3d/src/compositor.rs)). It reads
+the scene per frame, derives per-clip and per-frame values through
+`Scene::for_clip_window`
+([`scene.rs:436`](../../poc-d3d/src/scene.rs)) — which retains only the
+regions whose `clipIndex` matches the clip being composed and which overlap
+its source window — and only then issues GPU draws. Region visibility is
+expressed as `[startSec, endSec)` intervals matched against `t = source_time`,
+so a region straddling a clip boundary already arrives split per clip from
+the TS `projectRegionsToSource` call. The struct's `#[serde(default)]`
+fields (`webcamRect`, `screenRect`, `annotations`, `speedRegions`,
+`cameraFullscreenRegions`, `layoutByClip`, `cropByClip`) keep older
+payloads parseable so the addon's `require()` never breaks a saved project
+mid-load.
+
+## Audio
+
+`audio.rs` ([`poc-d3d/src/audio.rs`](../../poc-d3d/src/audio.rs)) is the
+single audio path for the export. Per clip, it opens the source container,
+enumerates **every** audio stream (not just the first `av_find_best_stream`
+returns), opens a `SwrContext` to convert each one to **planar f32, 48 kHz,
+stereo** (the `AUDIO_OUTPUT_*` constants at the top of the file), and mixes
+all streams into a single per-clip buffer by sample-aligned summation. The
+alignment is the load-bearing detail: each track's first decoded frame
+anchors its `origin_sec`, the seek is sized to the requested window, and
+each track is recut to the same `[source_start_sec, source_end_sec)` —
+pads in front for late-starting tracks, trims the pre-roll for early-decoded
+ones — so a summing mixer is enough and a real mix matrix is not needed.
+
+Speed regions apply after decode: WSOLA stretches each speed sub-segment to
+its output frame count, sharing search positions across channels from a
+mono down-mix (so the stereo image does not wander between channels).
+Across segments, `build_audio_concat_plan` sizes each segment's PCM by
+**integer accumulation of the per-segment rounded sample count**, never
+`round(cumulativeSec * sampleRate)` — that single change is what keeps A/V
+locked across a long multi-clip timeline. `assemble_concatenated_pcm`
+copies each segment into its planned slot, truncating a too-long buffer and
+zero-padding a too-short one so a small decode over/under-run cannot shift
+the timeline, and applies a short equal-power fade (`cos` on the tail,
+`sin` on the head, `cos² + sin² = 1`) at every internal boundary to suppress
+the click where two recordings meet butt-joined — without shifting timing,
+so A/V stays locked to the independently retimed video.
+
+The live preview does not use this path. `live.rs`
+([`poc-d3d/src/live.rs`](../../poc-d3d/src/live.rs)) only handles video;
+audio is decoded and mixed by `audio.rs` for the export run and not for the
+on-screen view, so editing playback is silent against the exported file.
+
+## Build
+
+The crate links `libav*` (ffmpeg) via bindgen
+([`build.rs`](../../poc-d3d/build.rs) /
+[`wrapper.h`](../../poc-d3d/wrapper.h)). ffmpeg is not vendored — the
+path is pinned in `poc-d3d/.cargo/config.toml`:
+
+```
+[env]
+FFMPEG_DIR = { value = "thirdparty/ffmpeg-n8.1.2-win64-lgpl-shared", relative = true }
+LIBCLANG_PATH = "C:\\Program Files\\LLVM\\bin"
+```
+
+So the thirdparty ffmpeg is **`poc-d3d/thirdparty/ffmpeg-n8.1.2-win64-lgpl-shared`**
+(the BtbN LGPL-shared build of ffmpeg-n8.1.2-22-g94138f6973, tag
+`autobuild-2026-07-15-14-01`). It must be the **same build** that
+`scripts/fetch-ffmpeg.mjs` vendorises into
+`electron/native/bin/<tag>/` for packaging. The addon's `require()` loads
+`avcodec-NN.dll` / `avformat-NN.dll` / etc. against the vendorised tree at
+runtime; if those import names do not match the build the crate linked
+against, the require fails on first use
+(`compositorViewService` prepends the ffmpeg `bin` directory to `PATH`
+before loading, so a system ffmpeg on `PATH` does not satisfy it either —
+see [`compositorViewService.ts:206`](../../electron/native-bridge/services/compositorViewService.ts)).
+The reason for the hard pin (no floating snapshot): the patch-level suffix
+in `avcodec-NN.dll` is a build-id, not a soname, and changes between
+autobuilds. A floated snapshot would compile fine and crash at runtime on
+the first `require()`.
+
+`x.bat` ([`poc-d3d/x.bat`](../../poc-d3d/x.bat)) sets up the toolchain
+end-to-end: vcvars64 (MSVC + Windows SDK headers/libs for both the linker
+and libclang), the ffmpeg `bin` directory on `PATH` (so the linker can
+find `avcodec-NN.dll`'s import lib AND any DLL the crate emits resolves its
+transitive imports at runtime), and `LIBCLANG_PATH` so bindgen can find
+libclang. Then it calls `cargo`. Three modes:
+`x.bat run --release` (GUI demo with preview + Export button),
+`x.bat run --release -- --cfg C0..C8 --fixture fixture --repeat 3 --out out/`
+(headless bench — the only numbers worth quoting per §10 of the bench
+protocol), `x.bat run --release -- --live` (the off-screen embed path used
+by the napi addon).
+
+The ffmpeg build must be **LGPL-shared** (`*-lgpl-shared`), not the Gyan
+GPL system build: GPL pulls x264/x265/xvid and would taint the app's MIT
+licence. D3D11VA + AMF survive the LGPL-shared build (verified:
+`avutil gpl=false amf=true`).
+
+## Known gaps
+
+- **No software/CPU fallback.** `d3d::Gpu::create`
+ ([`poc-d3d/src/d3d.rs`](../../poc-d3d/src/d3d.rs)) requests
+ `D3D_DRIVER_TYPE_HARDWARE` (no `WARP` / no `REFERENCE`) and pins
+ `D3D_FEATURE_LEVEL_11_1` — any other feature level fails with `bail!`,
+ and `VIDEO_SUPPORT` is mandatory for `D3D11VA`. A machine without a
+ GPU that exposes FL 11_1 with video support will hard-fail at startup;
+ there is no path that decodes on CPU or falls back to a reference
+ rasteriser. The compositor is therefore unusable on virtualised
+ environments that do not pass through a compatible adapter, and there
+ is no second renderer behind it.
+- **Software VP9 encoding is not supported.** A software VP9 encoder was
+ implemented, measured too slow without a hardware VP9 path on the
+ target GPU, and removed. The export pipeline now offers H.264 (AMF) and
+ H.265; VP9 is not a runtime option.
+- **Live preview is video-only** — `live.rs` does not decode or play audio.
+ Editing playback is silent against the exported file; users hear sound
+ only when the export runs. Documented in
+ [preview.md](preview.md#known-gaps).
\ No newline at end of file