Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
docs(architecture): one export document, and the target rendering architecture
Etienne Lescot9907a85d1566
diff --git a/docs/architecture/export-native-encode-measurement.md b/docs/architecture/export-native-encode-measurement.mddeleted file mode 100644index 4d3d3bb76..000000000--- a/docs/architecture/export-native-encode-measurement.md+++ /dev/null@@ -1,264 +0,0 @@-# Native encode, measured end‑to‑end — why option A cannot win--**Date:** 2026‑07‑16-**Companion to:** [`export-pipeline-v2-spec.md`](./export-pipeline-v2-spec.md) (§3.1, §4.4, §7, Phase 3, Phase 4) and [`native-core-tauri-spec.md`](./native-core-tauri-spec.md)-**Code:** `6d521c53` — bench + instrumentation-**Machine:** AMD Ryzen 5 7520U (integrated Radeon), Windows 11, `h264_amf`, on AC-------## 1. Verdict--Feeding the bundled native ffmpeg from the renderer — **option A**, the path the v2 spec calls "the actual win" (Phase 3) — is **2.1× slower** than the WebCodecs path it was meant to replace.--| arm | wall (median) | fps | readback |-|-----|--------------:|----:|---------:|-| `webcodecs` | **38.5 s** | **36.9** | 158 ms |-| `native` | 80.8 s | 17.5 | **55 207 ms** |-| `native-cpu` | 83.6 s | 17.0 | 57 989 ms |-| `webcodecs-cpu` | 38.0 s | 37.3 | 166 ms |--*proj_a7468696 — 2 assets, 2 clips, webcam; MP4/1080p/60/H.264; 1418 output frames; 2 runs per arm, interleaved; same‑arm spread 3–4 %.*--**ffmpeg is not the problem.** It consumes frames *faster* than WebCodecs does — exactly as §3.1 predicted:--| stage | webcodecs | native | delta |-|-------|----------:|-------:|------:|-| `encodeWait` | 26 731 ms | 18 990 ms | **−29 %** |-| `flush` | 1 444 ms | 80 ms | **−94 %** |-| `readback` | 158 ms | 55 207 ms | **×349** |--The encoder win is real and it is dwarfed by the **price of admission**: getting the pixels to the CPU at all.--And that price is disqualifying on its own. With the crossing set to **exactly zero** — frames descended to RAM and then discarded, no IPC, no ffmpeg, no muxer, no audio — the pipeline still runs at **40.5 fps against WebCodecs' 44.0**, and WebCodecs is *also writing the file* (§5). So no amount of engineering on the crossing can save this shape: not option A′ (`sandbox: false`), not shared memory, not zero‑copy transfer. **The descent itself is the disqualification.**-------## 2. Why--WebCodecs never brings a frame to the CPU. `encoder.encode(new VideoFrame(canvas))` hands the hardware encoder a **GPU texture**; the pixels are composited, encoded and emitted without ever crossing to system RAM. The `readback` stage reads ~0.1 ms/frame in that arm because **nothing is read back** — `new VideoFrame(canvas)` is lazy and the encoder consumes the texture in place.--ffmpeg cannot do that over a pipe. Raw video on stdin means the pixels must exist **in system RAM**, so the export must force the descent that WebCodecs never performs:--```-webcodecs: canvas ──(GPU texture)──────────────▶ HW encoder ──▶ mp4-native: canvas ──▶ copyTo() ──▶ RAM ──IPC──▶ main ──stdin──▶ ffmpeg ──▶ mp4- ▲ 38.9 ms/frame-```--This inverts §3.1's conclusion a second time. That section established, correctly, that *readback is 0.1 % of wall* and that *the encoder is the wall, and the wall is the API*. Both hold. What the Phase‑0 probe could not see is that **the 0.1 % was conditional**: readback cost nothing precisely because nothing forced it, and forcing it is exactly what feeding a native encoder requires. §3.1's own probe measured `node -> ffmpeg stdin pipe: 489–589 MB/s, costs ~3%` — a true statement about the *pipe*, obtained by materialising frames once, outside the timed loop. The measurement never included the descent, because in that harness the descent happened once for 546 frames instead of once per frame.--The trap is the same one §3.1 already names ("`new VideoFrame(canvas)` is lazy"), applied one level up: **an isolated component benchmark cannot price the cost of connecting it.**-------## 3. Was the canvas the problem? No — hypothesis tested and dead--`frameRenderer.ts` requests GPU‑backed 2D canvases outside Linux (`willReadFrequently: this.isLinux`). Plausible hypothesis: a GPU‑backed canvas makes compositing cheap and readback expensive, which is the wrong trade for a path that reads back **every** frame. Flipping it should collapse the 38.9 ms.--It does not. `native-cpu` (57 989 ms) is no better than `native` (55 207 ms), and the control `webcodecs-cpu` is indistinguishable from `webcodecs`.--The arm is real, not a silent no‑op: `willReadFrequently` is a *hint*, so the renderer now logs what Chromium **granted**, not what we asked for —--```-· canvas requested willReadFrequently=false granted=false ← native-· canvas requested willReadFrequently=true granted=true ← native-cpu-```--— and the readback did not move. The cost is not the canvas backing.-------## 4. Would NV12 save it? No — and we did not have to build it to know--Phase 4 proposes packing BGRA (8.294 MB/frame) → NV12 (3.110 MB/frame) on the GPU. If the readback were bandwidth‑bound, that is a 2.7× cut.--Two resolutions give the descent a shape:--| output | bytes/frame | readback total | **ms/frame** |-|--------|------------:|---------------:|-------------:|-| 1080p | 8.294 MB | 55 207 ms | **38.93** |-| 720p | 3.686 MB | 29 795 ms | **21.01** |--*720p: 2 runs, spread 1 %.*--Fitting `t = a + b·MB` over the two points:--```-b = (38.93 − 21.01) / (8.294 − 3.686) = 3.889 ms/MB (≈ 257 MB/s marginal)-a = 38.93 − 3.889 × 8.294 = 6.68 ms (fixed per frame)-```--So the descent is **~6.7 ms of fixed stall plus ~3.9 ms/MB**. It scales with size, but at 257 MB/s — two orders below memory bandwidth — which is why it reads as a pipeline sync, not a copy.--Extrapolating NV12 (3.110 MB): **6.68 + 12.10 = 18.77 ms/frame**, roughly halving the readback. Projecting the native loop at 1080p:--| | render | readback | encodeWait | total | fps |-|---|---:|---:|---:|---:|---:|-| native, measured | 1.70 | 38.93 | 13.39 | 54.0 ms | 18.5 |-| native + NV12, projected | 1.70 | 18.77 | 13.39 | 33.9 ms | **29.5** |-| native + NV12, optimistic¹ | 1.70 | 18.77 | 5.02 | 25.5 ms | **39.2** |-| **webcodecs, measured** | 1.70 | 0.11 | 18.85 | **20.7 ms** | **48.4** |--¹ assumes `encodeWait` also falls in proportion to bytes, i.e. the IPC crossing is pure bandwidth.--Even the optimistic projection only reaches **parity**, after building GPU shader packing. Phase 4 cannot rescue this path.-------## 5. What about option A′ — dropping the sandbox to remove the crossing?--The obvious rescue: if the crossing is what costs, remove it. **A′** (`sandbox: false`, renderer spawns ffmpeg and writes its stdin directly) skips the IPC structured clone; other variants propose shared memory or a zero‑copy transfer.--None of them can be rescued, and none had to be built to find out. They all keep `copyTo()` — ffmpeg needs the pixels in RAM whoever spawns it — so a single arm bounds every one of them at once: **descend every frame, then discard it.** The crossing costs exactly zero, there is no encoder, no muxer, no audio.--| arm | wall | fps | readback | encodeWait | writes a file? |-|-----|-----:|----:|---------:|-----------:|:--------------:|-| `webcodecs` | 32.2 s | **44.0** | 170 ms | 20 997 ms | **yes** |-| `readback-ceiling` | 35.0 s | **40.5** | 29 210 ms | **2 ms** | no |-| `native` | 69.1 s | 20.5 | 34 389 ms | 26 787 ms | yes |--*Same project and settings as §1; 2 runs per arm, spread 1–2 %. Absolute numbers differ from §1 — a later session, a warmer/steadier machine — which is exactly why arms are only ever compared within a run.*--`encodeWait: 2 ms` across 1418 frames confirms the arm does what it claims: the crossing really is zero.--**And it still loses: 40.5 fps against WebCodecs' 44.0 — while WebCodecs also muxes and writes the file** (its `flush` 1222 ms + `audioEncode` 397 ms are included in that 44.0). The descent *alone*, with nothing behind it, is slower than WebCodecs doing the entire job.--So the ceiling for every "remove the crossing" design sits **below** the path we already ship. A′ is in fact strictly worse than this ceiling: it does not eliminate the crossing, it swaps a structured clone (~390 MB/s) for a pipe write (~500 MB/s, §3.1 of the v2 spec) — a ~1.2× improvement on one leg, bought by giving up the renderer sandbox that [`native-core-tauri-spec.md`](./native-core-tauri-spec.md) §3.2 identifies as protecting the demux/decode of untrusted user media.--Combining A′ with Phase 4 does not save it either: NV12 projects the ceiling to ~20.4 ms/frame (≈49 fps), but A′'s pipe write of 3.110 MB at ~500 MB/s adds ~6.2 ms/frame back, landing ≈37.6 fps — still under 44.0, now having paid both the sandbox *and* GPU shader packing.--**Conclusion: descending the frame is disqualifying, independently of what happens afterwards.** The only remaining move is not to descend — §6.-------## 6. What this means--### For the spec--| section | status |-|---------|--------|-| §3.1 — "the encoder is the wall, and the wall is the API" | **holds**, but incomplete: it prices the encoder, not the connection to it |-| §3.1 — "readback is 0.1 % of wall" | **holds only for WebCodecs.** Conditional on nothing forcing the descent |-| §4.4 / §7 / Phase 3 — native ffmpeg as primary encoder, fed from the renderer | **refuted on this machine.** 2.1× regression |-| Phase 4 — GPU BGRA→NV12 packing | **cannot save Phase 3.** Best case is parity |-| §7 — "WebCodecs demoted then removed" | **must not proceed.** WebCodecs is currently the fastest path we have |-| A′ (`sandbox: false`) and other "remove the crossing" variants | **excluded by the ceiling** (§5), without being built |--### For the roadmap--The agreed plan was **A** (ship ai‑edition at ~×10 via bundled ffmpeg) then **C** (Tauri/Rust for the last ×2). The measurement inverts it:--- **A is not ×10. It is ×0.48.** The bundled LGPL ffmpeg, the encoder probe, the IPC and the credit window all work correctly — and the architecture still loses, because a sandboxed renderer cannot hand a GPU texture to a native process.-- **A′ is not a rescue.** It buys ~1.2× on one leg (structured clone → pipe write) at the cost of the sandbox, and the ceiling with that leg at *zero* already loses (§5).-- **C is where the win is, and for a new reason.** Not "the last ×2", but the *only* way to make native encode pay: if compositing and encoding live on one device in one process, the composited surface feeds the encoder (D3D11VA / VideoToolbox) **without ever descending**. The descent does not get cheaper — it stops existing.--The ×10 was never in front of us. And the wall is not the crossing — the ceiling arm set the crossing to zero and the shape still lost. **The wall is the descent**: any design in which a composited frame reaches system RAM has already paid more than WebCodecs pays for the whole export.--### What survives from the native work--Nothing here invalidates the parts, only their arrangement. `ffmpegCapabilities` (smoke‑tested encoder election), `ffmpegEncodeSession` (stdin + backpressure + progress), the pinned licence‑gated LGPL binary and `scripts/fetch-ffmpeg.mjs` are all reusable by option C, which still needs a native H.264 encoder. What does not survive is *feeding it from the renderer*.-------## 7. Method--```bash-npm run bench:export -- --project=proj_a7468696 --arms=webcodecs,native,native-cpu,webcodecs-cpu --runs=2-```--The bench (`scripts/bench-export.mjs` + `src/bench/runBench.ts`) simulates nothing: it opens the **real editor window** (same `webPreferences`, preload and sandbox), loads a **real saved project** through the bridge the editor uses, and calls **`exportAxcutDocument`** — `ExportDialog`'s own entry point. Only React is skipped, so nothing renders alongside the export. Arms are set via `localStorage` and read at runtime, so one app session measures every arm against one document.--Four arms, because two would not have been decidable:--| arm | encoder | canvas |-|-----|---------|--------|-| `webcodecs` | WebCodecs | GPU |-| `native` | ffmpeg | GPU |-| `native-cpu` | ffmpeg | **CPU** |-| `webcodecs-cpu` | WebCodecs | **CPU** |--Without `webcodecs-cpu`, a `native-cpu` result could be attributed to the canvas, the encoder, or neither.--**Arms interleave (A,B,A,B) and same‑arm spread is reported.** Above 10 % the run declares itself VOID. This is not decoration — see §7.-------## 8. Two runs discarded, and why they are in this report--**Run 1 (UI, ~5 % battery, unplugged).** Baseline 84.6 s → native 54.1 s, "1.56× faster". Discarded: the SoC (15 W class, shared CPU/iGPU budget) was power‑squeezed and the budget **drifted upward while charging, between the arms**. Also self‑inflicted: DevTools were open for the native arm only, streaming hundreds of console lines — a handicap applied to one arm.--**Run 2 (UI, on AC, DevTools closed, A/B/A/B).**--| | A1 | B1 | A2 | B2 |-|---|---:|---:|---:|---:|-| | webcodecs | native | webcodecs | native |-| wall | 77.6 s | 79.9 s | **61.7 s** | **49.4 s** |--Discarded by its own gate: **A1 vs A2 disagree by 26 %; B1 vs B2 by 62 %** — with the battery climbing 34 % → 43 % throughout. The drift exceeded the effect and *inverted the conclusion*: A1↔B1 says "native 3 % slower", A2↔B2 says "native 20 % faster". Either would have been reported as a finding.--The valid run's 3–4 % spread is what makes §1 trustworthy. **A single A/B on this machine was never capable of answering the question**, and no amount of care in reading the numbers would have revealed that — only the repeat did.--Everything the bench guards against is something that already produced a confident wrong answer:--- a **stale `dist-electron` bundle** (twice — once the export IPC read "no handler registered", once the bench flag silently did nothing and the app opened its normal HUD)-- a **leftover instance** holding the single‑instance lock, making the launch exit 0 in silence-- a **dead dev server** yielding a blank window-- a **runner that swallowed the app's own stderr** while it was explaining the failure-------## 9. Caveats--- **One machine.** Ryzen 5 7520U, integrated Radeon, `h264_amf`. The descent is a Chromium GPU→CPU transfer and is likely universal, but a discrete GPU (PCIe) or Intel QSV could produce different constants. `npm run bench:export` makes that a one‑command check — this should be re‑run before the conclusion is generalised beyond iGPU laptops.-- **The linear fit is two points**, not a proof. It is directionally clear (readback scales with bytes, ~257 MB/s marginal, ~6.7 ms fixed), but the NV12 projection is an extrapolation, not a measurement.-- **The workload is not os_parity.** The v2 spec's reference project (2 assets, 2×3× speed, 1.80× zoom, webcam, 546 frames) is **corrupt on disk** — see §9. `proj_a7468696` (2 assets, 2 clips, webcam, 1418 frames) has no speed or zoom regions, so it composites *less* per frame than os_parity. That biases nothing here: zoom and speed affect `render` (1.7 ms/frame, ~4 % of the loop), not the descent under test, and every arm ran the same document.-- **The native arm does not mux audio yet** (the A/V‑lock ordering needs the real per‑segment frame counts, which only exist after the loop). Audio decode and the WSOLA stretch run on **both** arms deliberately, so the CPU contention on the video loop is identical; only `audioEncode` (373 ms, ~1 %) is missing from the native arm. Crediting it fully to native does not change a 2.1× gap.-------## 10. Unrelated finding: `os_parity` is corrupt (data‑loss bug)--While resolving the bench's target project, `listProjects` was silently skipping `proj_de6ffaaa` (`os_parity`). The file is 4006 bytes: **3485 bytes of valid, complete JSON followed by the tail of a longer version of the same document.**--That is the signature of **two concurrent `fs.writeFile` calls of two different document versions**: both open with `O_TRUNC`, then write at their own offsets. The shorter version won bytes 0–3485; the longer one's bytes past 3485 survive. `writeProject` (`document-service.ts`) truncates correctly on its own — what is missing is **serialisation of saves and an atomic write** (temp file + rename).--Consequence: the project is unopenable in the editor today.--**Not repaired.** The recoverable prefix has `speedRegions: 0, zoomRegions: 0`, while the real timeline has two 3× regions and a 1.80× zoom. Truncating to the valid prefix would have returned a project silently stripped of its effects. The zoom is not present anywhere in the file and is not recoverable from it. A byte‑exact backup sits beside it (`*.corrupt-backup-20260716`); the original is untouched.-------## 11. PoC findings: the hardware is willing, the ffmpeg CLI is not--Probing option C on this machine with the bundled ffmpeg (2026‑07‑17), before writing any Rust:--| measured | fps |-|----------|----:|-| **GPU decode (d3d11va) → GPU encode (h264_amf), no compositing, no descent** | **234** |-| WebCodecs export today, full effect set | 44 |--234 fps is the **floor of the native‑GPU path** on this laptop: 5.3× today's export before a single effect is composited. The physics has room.--What does *not* work here is the plumbing between ffmpeg's filter graph and the encoder:--| API | decode | filters | encode | bridge to AMF |-|-----|:------:|:-------:|:------:|---------------|-| **Vulkan** | ✅ | ✅ (`scale_vulkan`, `overlay_vulkan`, `gblur_vulkan`, `color_vulkan`) | ❌ driver exposes `video_decode_queue` only — **no encode queue** | ❌ *"AMF initialisation from a vulkan device is not supported"* |-| **D3D11** | ✅ | ❌ `scale_d3d11` fails to create its texture (`80070057`) on every format | ✅ AMF | — |-| **OpenCL** | — | ✅ but **no scaler** | — | ❌ `hwmap` from d3d11 fails on NV12's UV plane |--So **the ffmpeg CLI cannot express GPU‑composite → GPU‑encode on this hardware.** That is a limit of the CLI's plumbing, not of the GPU: the same GPU decodes at 234 fps, encodes at 234 fps, and already composites the entire scene at **1.7 ms/frame** (the `render` stage, measured on every bench run above).--**This does not test option C** — it tests ffmpeg's filter graph, which no native core would use. A real one decodes with libavcodec into a D3D11 texture, composites with wgpu/D3D11 **on that same device**, and hands the texture to AMF. The CLI is built for linear transcode, not multi‑layer compositing; running out of road here says nothing about the architecture, only that the PoC needs code.--**What this does settle for the PoC's design, on AMD/Windows:** Vulkan is a dead end for the encoder (no encode queue, no AMF interop), so the compositor must own a **D3D11** device and hand D3D11 textures to AMF — not Vulkan, not OpenCL, whatever wgpu's default backend would pick.-------## 12. Open questions--1. **Does the descent behave differently on a discrete GPU, or on Intel QSV?** One bench run per machine.-2. **Can option C actually keep the frame on‑device end to end?** Still the load‑bearing assumption of the whole native‑core case, and still unmeasured — §11 raised the floor (234 fps) and mapped the constraint (D3D11, not Vulkan), but the compositing‑to‑encoder handoff needs real code. Prototype and bench it *before* committing to a migration; this report exists because the last "obvious" architectural win was 2.1× backwards.-3. **Is WebCodecs' 18.85 ms/frame `encodeWait` improvable at all?** It is now the largest single cost in the fastest path we have. §3.1's isolated probe says the same silicon does 165 fps (6 ms/frame) under ffmpeg, so ~13 ms/frame is Chromium overhead on a path we do not control.-4. **Is `render` = 1.7 ms/frame the true GPU compositing cost, or an artefact of async?** `renderFrame` returns before the GPU finishes, so part of that work may be billed to whatever forces the sync next. It matters: 1.7 ms is what makes the native‑GPU projection (~167 fps) attractive.diff --git a/docs/architecture/export-pipeline-v2-spec.md b/docs/architecture/export-pipeline-v2-spec.mddeleted file mode 100644index 7ac2e6b6c..000000000--- a/docs/architecture/export-pipeline-v2-spec.md+++ /dev/null@@ -1,500 +0,0 @@-# Export Pipeline v2 — Multi‑Asset Rendering + Performance--Status: **Revised 2026‑07‑16** — multi‑asset shipped; the **perf half was rewritten after measurement disproved its central premise**. Read §3.1 first: the bottleneck is the WebCodecs API (~90 % of wall), not the readback (0.1 %). The plan is now native ffmpeg encode (§7), not GPU‑resident compositing (§4.4, cancelled).--> ⛔ **The perf half is refuted again — do not implement Phase 3 or Phase 4 as written.**-> Native ffmpeg fed from the renderer was built and measured end‑to‑end: it is **2.1× SLOWER** than-> WebCodecs (38.5 s → 80.8 s on 1418 frames, 1080p60, spread 3–4 %). ffmpeg consumes frames *faster*-> (`encodeWait` −29 %, `flush` −94 %) — but it needs the pixels in RAM, and that descent costs-> 38.9 ms/frame that WebCodecs never pays because it encodes straight off the GPU texture. §3.1's-> "readback is 0.1 %" holds **only while nothing forces the descent**, and feeding a native encoder-> is exactly what forces it. Phase 4 (NV12) cannot rescue it either — best case is parity.->-> **The wall is the descent, not the crossing.** With the crossing at *exactly zero* (frames-> descended then discarded: no IPC, no ffmpeg, no muxer) the pipeline still runs 40.5 fps vs-> WebCodecs' 44.0 — and WebCodecs is also writing the file. That ceiling excludes option A′-> (`sandbox: false`), shared memory and zero‑copy transfer **without building any of them**.-> **Full evidence, method and consequences: [`export-native-encode-measurement.md`](./export-native-encode-measurement.md) (2026‑07‑16).**-Owners: ai-edition editor team-Scope: the `.axcut` (AI‑edition) export path only. The legacy `components/video-editor` exporter is out of scope.-------## 1. Goals & non‑goals--### Goals-1. **Multi‑asset export.** Render every clip on the timeline from *its own* source asset, in timeline order — matching what the preview already plays. Today only the primary asset is rendered; clips pointing at other assets are silently dropped.-2. **Performance.** ~~Cut export time by removing the per‑frame GPU→CPU→GPU round‑trips, moving the pipeline off the renderer main thread, and properly pipelining decode/render/encode. Target: ≥2× faster.~~ **Rewritten 2026‑07‑16 after measurement (§3.1):** those targets are ≤2.3 % of wall. Cut export time by **replacing the WebCodecs encoder — ~90 % of wall — with a bundled native LGPL ffmpeg** using the platform's hardware encoder. Target: **≥4×** on the frame pipeline at 1080p (measured end‑to‑end: 8 → **34 fps** BGRA, → **81 fps** with NV12 packing). The encoder alone does 165 fps, but the renderer→main crossing — not the encoder — is what we end up bound by (§4.4.1).-3. **Correct framing.** Output honors the timeline’s selected aspect ratio and is sized to the largest clip. *(Already shipped — see §9.)*--### Constraints-- **The app is MIT and must stay MIT.** No GPL component may end up in what we ship (§7.2).-- **Windows + macOS + Linux**, x64 and arm64 (Apple Silicon). **No platform gets a degraded export.** Native encode ships on all three. *(Etienne, 2026‑07‑16 — see the rejected option below.)*-- Must degrade gracefully where no hardware encoder exists (→ WebCodecs fallback).-- **Bundle size is not a constraint** *(Etienne, 2026‑07‑16)*: ~200 MB per platform is acceptable. Do not trade features, codec coverage or simplicity for bytes. Precedent: the app already ships native binaries (`wgc-capture.exe`, `cursor-sampler.exe`, `whisper.dll`, `ggml-*.dll`).--### Non‑goals (this spec)-- Overlapping/mixed audio tracks (we assume **sequential** per‑clip audio).-- Compositing multiple assets **simultaneously** (picture‑in‑picture of two screen recordings). The webcam overlay is the only simultaneous second source and stays as‑is.-- ~~Replacing WebCodecs with a native ffmpeg binary as the primary encoder (WebCodecs already *is* the hardware path; native ffmpeg is only a fallback).~~ **Inverted — this is now Goal 2.** WebCodecs reaches the same silicon but at **8 fps vs 165 fps** for native ffmpeg (§3.1). It becomes the *fallback*; native ffmpeg is the primary encoder (§7).-- Shipping a **GPL** ffmpeg build (x264/x265). We build LGPL only, so the app stays MIT (§7.2).-- **Keeping WebCodecs as the primary encoder on macOS** because the gap is smaller there. **Rejected — do not reintroduce this.** It is a tempting argument and it will come back, so here it is with its rebuttal: WebCodecs *is* closer to native on VideoToolbox (~3.5× off, per [w3c/webcodecs#492](https://github.com/w3c/webcodecs/issues/492)) than on our Windows/AMD reference (~20×), and skipping the macOS ffmpeg build would dodge real work — BtbN publishes prebuilt LGPL binaries for Windows and Linux but **not macOS**, so macOS is the one platform we must build (and notarise) ourselves. We are still not doing it: "3.5× slower, but only on Macs" is a degraded export on a platform where our users edit, sold as an engineering convenience. Native encode ships on all three, or the plan is wrong.-- Rewriting the compositor. The Canvas2D composite stays; only the encoder changes (§4.4).-- GIF export changes beyond what falls out of the shared render plan.-------## 2. Current architecture (as‑is)--### 2.1 Data flow--```-ExportDialog.handleStart() (renderer MAIN thread)- └─ exportAxcutDocument(document, options) src/lib/ai-edition/exporter/documentExporter.ts- ├─ pick primaryAsset; videoUrl = toFileUrl(primaryAsset.originalPath)- ├─ trimRegions = complement of primary-asset clips + trimRanges (single asset!)- ├─ cropSchedule = per-clip crop (primary asset only)- ├─ zoom/annotation/speed → projected to SOURCE time of the primary asset- └─ new VideoExporter(config).export() src/lib/exporter/videoExporter.ts- ├─ StreamingVideoDecoder.loadMetadata(videoUrl) (WebCodecs VideoDecoder)- ├─ (optional) source-copy fast path (identity export → remux, no re-encode)- ├─ FrameRenderer(width,height, …) (PixiJS/WebGL + Canvas2D)- ├─ VideoMuxer + AudioProcessor (WebCodecs audio + mp4 mux)- └─ streamingDecoder.decodeAll(fps, trimRegions, speedRegions, perFrame)- perFrame(videoFrame, …):- renderer.setCropRegion(resolveCropAt(cropSchedule, t))- renderer.renderFrame(videoFrame) ← WebGL render- canvas = renderer.getCanvas() ← Canvas2D composite- exportFrame = new VideoFrame(canvas) ← re-upload to GPU- encoder.encode(exportFrame) ← WebCodecs VideoEncoder (HW)-```--### 2.2 Key types & files-- `DocumentExportOptions` — `src/lib/ai-edition/exporter/documentExporter.ts`-- `VideoExporterConfig extends ExportConfig` — `src/lib/exporter/videoExporter.ts` (`videoUrl`, `trimRegions`, `speedRegions`, `cropSchedule`, `zoomRegions`, `annotationRegions`, webcam*, cursor*, `width`/`height`/`frameRate`/`bitrate`/`codec`).-- `FrameRenderer` — `src/lib/exporter/frameRenderer.ts`. PixiJS/WebGL for the video layer + filters (`pixi-filters/motion-blur`, `threeDPass.ts`); **Canvas2D** for background/shadow/foreground compositing.-- `StreamingVideoDecoder` — `src/lib/exporter/streamingDecoder.ts`. `loadMetadata()`, `decodeAll(fps, trims, speeds, cb)`, `getDemuxer()`.-- `AudioProcessor` / `VideoMuxer` — `src/lib/exporter/audioEncoder.ts`, `src/lib/exporter/muxer.ts`.-- Preview (the behavioral reference) — `src/components/ai-edition/preview-compositor/PreviewCompositor.tsx` (`videoSources[]`, `sourceIndex`, `locateSourcePosition`, switches active `<video>` per clip’s `assetId`).--### 2.3 Confirmed characteristics-- **Single stream.** `config.videoUrl` is one asset. Multi‑asset timelines lose every non‑primary clip.-- **Runs on the renderer main thread.** `exportAxcutDocument` is `await`‑ed directly from the dialog; it yields between frames but competes with the UI for the thread and the GPU.-- **Per‑frame readback.** WebGL render → `getCanvas()` (Canvas2D) → `new VideoFrame(canvas)`. On Linux there is an *explicit* `getImageData()` CPU readback (EGL/Ozone workaround). A 4K RGBA frame is ~33 MB; at 60 fps this is ~2 GB/s of avoidable copying.-- **Serial pipeline.** Only encoder‑queue backpressure (`waitForEncoderQueueSpace`, `encodeQueueSize`) exists; decode/render/encode are not otherwise decoupled.-- **Encoder is WebCodecs, and that is the bottleneck.** `VideoEncoder` with `hardwareAcceleration: "prefer-hardware"`. ~~This is the OS hardware codec — the same path native ffmpeg uses.~~ **Wrong:** it reaches the same silicon but through Chromium's wrapper, and measures **~8 fps @1080p vs 165 fps** for native ffmpeg on the same GPU (§3.1). Hardware encode *is* enabled (`video_encode=enabled`, no blocklist) — the loss is Chromium's per‑frame overhead.-------## 3. Problem statement--| # | Problem | Impact | Status |-|---|---------|--------|--------|-| P1 | Only the primary asset is rendered | Multi‑recording timelines export wrong/partial video (**correctness bug**) | **fixed** (segment loop) |-| P2 | ~~Per‑frame GPU↔CPU readback + re‑upload — dominant time sink~~ | **DISPROVEN.** Measured 0.2 ms/frame = **0.1 %** of wall. | closed, see §3.1 |-| P3 | Whole export on the renderer main thread | UI stutters. Real, but a **responsiveness** issue, not throughput | deferred |-| P4 | Serial decode→render→encode | Real but small: the audio half is fixed; the rest is masked by P6 | partly fixed |-| P5 | Aspect ratio hardcoded 16:9 | Wrong framing for non‑16:9 timelines | **fixed, see §9** |-| **P6** | **WebCodecs caps the encoder at ~8 fps @1080p** | **~90 % of export wall time.** The actual bottleneck. | **open — §7** |--### 3.1 What Phase‑0 measurement actually found (2026‑07‑16)--The original perf direction here ("WebCodecs already ≈ native; the wins are readback + threading; ~2–3× reported by Descript from removing the copies") **did not survive measurement.** Instrumenting `runSegmentLoop` (`StageTimings`) on **os_parity** (2 assets, 2×3× speed, 1.80× zoom, webcam; MP4/1080p/60/H.264; 546 output frames):--| stage | software | hardware | GPU‑resident composite |-|-------|---------:|---------:|-----------------------:|-| **encodeWait** | **75.5 s (89 %)** | **52.8 s (92 %)** | **55.1 s (90.6 %)** |-| audioEncode | 6.9 s | 3.2 s | 4.1 s |-| render | 1.9 s (2.2 %) | 1.2 s | 1.3 s |-| **readback** | **0.12 s (0.1 %)** | 0.07 s | **0.10 s** |-| **wall** | **94.6 s** | **72.7 s** | **97.9 s** |--Then an **isolated encoder probe** (120 synthetic frames — no decode, no render, no composite) settled the cause:--```-gl: ANGLE (AMD, AMD Radeon(TM) Graphics, Direct3D11) ← real GPU, not SwiftShader-video_encode = enabled ← no blocklist, HW encode available-hw/canvas-frame 22.8 fps hw/cpu-rgba-frame 35.6 fps-sw/canvas-frame 31.4 fps hw/canvas@720p 48.4 fps-```--versus **native ffmpeg on the same machine, same 546 real frames**:--```-h264_amf (AMD hardware) 165 fps ← 20× WebCodecs-libx264 -preset ultrafast 198 fps ← 25× WebCodecs-node -> ffmpeg stdin pipe: 489-589 MB/s, costs ~3%-```--Conclusions that redirect this spec:--- **The encoder is the wall, and the wall is the API.** Hardware encode is enabled and reachable; Chromium's WebCodecs pipeline still yields 8–36 fps where the same silicon does 165. The loss is Chromium's per‑frame overhead (renderer↔GPU‑process IPC, format conversion), not our feeding of it.-- **GPU‑backed frames are *slower* into the encoder than CPU ones** (22.8 vs 35.6 fps). The premise behind §4.4 was false. The GPU‑resident composite was implemented, measured (no gain), and **reverted** (`e6cbb45`).-- **The "CPU bridge" is a non‑issue** — 3 %. (An earlier 8× penalty was an artefact of MSYS's emulated pipe, not a real Windows pipe.)-- Everything except the encoder — readback, `latencyMode`, Worker/OffscreenCanvas, compositing — is **≤2.3 % combined**. Optimising any of it is noise.--**Beware two measurement traps** we fell into: `app.getGPUFeatureStatus()` from a **windowless** Electron script reports everything `disabled_software` (meaningless — always probe with a real window), and piping via `cat` under Git Bash caps at ~70 MB/s (MSYS emulation, not Windows).-------## 4. Target architecture (to‑be)--Both the multi‑asset feature and the perf rework converge on one idea: **a `RenderPlan` of ordered segments, consumed by a worker‑hosted pipeline that keeps frames on the GPU.**--```-documentExporter builds a RenderPlan (ordered segments, virtual-time effects)- │ postMessage(plan) ─────────────────────────────────────────────► Export Worker- │ (OffscreenCanvas + WebGL/WebGPU)- │ ┌─ for each segment in plan.segments:- │ │ decoder = StreamingVideoDecoder(segment.videoUrl)- │ │ decode [sourceStart,sourceEnd) − intraTrims- │ │ render into ONE output surface (virtual time)- │ │ VideoFrame(gpuSurface) → encoder (no readback)- │ └─ audio: decode each segment, concat → muxer- ◄─ progress / result (transferred ArrayBuffer) ◄──────────────────────-```--### 4.1 The `RenderPlan` (new shared data model)--```ts-// src/lib/ai-edition/exporter/renderPlan.ts (new)-interface RenderSegment {- clipId: string;- assetId: string;- videoUrl: string; // toFileUrl(asset.originalPath)- sourceStartSec: number; // clip in-point in the asset's media time- sourceEndSec: number; // clip out-point- intraTrims: Interval[]; // trimRanges of THIS asset inside [start,end)- cropRegion: CropRegion; // per-clip crop (identity when absent)- sourceWidth: number; // asset.video.width (for the renderer)- sourceHeight: number; // asset.video.height- camera?: { videoUrl: string; offsetMs: number } | null; // per-asset webcam-}--interface RenderPlan {- output: { width: number; height: number; frameRate: number; bitrate: number; codec: string };- aspectRatioValue: number; // timeline ratio (see §9)- segments: RenderSegment[]; // timeline order == output order- // Effects keyed in VIRTUAL (output) time — NOT per-asset source time:- zoomRegions: ZoomRegion[];- annotationRegions: AnnotationRegion[];- speedRegions: SpeedRegion[];- cursor: CursorPlan; // see §6.4- appearance: { wallpaper: string; padding: number; borderRadius: number;- shadowIntensity: number; showBlur: boolean; motionBlurAmount: number; };-}-```--**Why virtual time.** Today `documentExporter` projects timeline‑authored effects onto each asset’s *source* time (`projectRegionsToSourceTime`) because there is a single source stream. With a segment loop that already tracks a running **output/virtual‑time cursor**, effects can be keyed directly in virtual time — this is *simpler*, removes the projection round‑trip, and is exactly how the editor authors them.--### 4.2 Segment loop (replaces the single `decodeAll`)--`VideoExporter.export()` becomes:--1. Compute `output` + create **one** `FrameRenderer`, **one** `VideoEncoder`, **one** `VideoMuxer`.-2. `outputCursorSec = 0`.-3. For each `segment`:- a. `decoder = new StreamingVideoDecoder(); await decoder.loadMetadata(segment.videoUrl)`.- b. `renderer.setSource(segment.sourceWidth, segment.sourceHeight, segment.camera)` — reconfigure the renderer’s input dims/crop/webcam for this asset.- c. `decoder.decodeAll(fps, complementOf(segment.intraTrims within [start,end)), speedForSegment, perFrame)`, where `perFrame` renders at `timestamp = outputCursorSec + localOffset` and looks up zoom/annotation/cursor by **virtual time**.- d. Advance `outputCursorSec` by the segment’s rendered virtual duration.- e. Dispose the decoder before the next segment (bounded memory: one active decoder at a time in Phase 2; see §6.6 for prefetch).-4. Audio (§6.3), finalize muxer, return buffer.--### 4.3 Worker + OffscreenCanvas — *deferred to Phase 5 (2026‑07‑16)*--> Kept for reference. Measurement (§3.1) showed the main thread is **not** the throughput limit — it sits idle in `encodeWait` ~90 % of the time. This buys **UI responsiveness**, not speed, so it is no longer part of the perf programme and waits behind Phase 3.--- New `src/lib/ai-edition/exporter/exportWorker.ts` (module worker). It owns the `FrameRenderer` (constructed on an `OffscreenCanvas`), the decoders, the encoder, and the muxer.-- The dialog posts `{ plan }` and a `MessagePort`; the worker streams `{ type: "progress", … }` and finally `{ type: "done", buffer }` (transferred).-- `FrameRenderer` must accept an `OffscreenCanvas`; PixiJS supports WebGL on `OffscreenCanvas` in a worker. The Canvas2D composite canvases become `OffscreenCanvas` too. (This is the main portability task — see Risk R2.)--### 4.4 ~~Keep frames on the GPU (kill the readback)~~ → **Native encode** *(rewritten 2026‑07‑16)*--> **Abandoned.** This section proposed moving the whole composite onto the GPU so `new VideoFrame(gpuCanvas)` would reach the hardware encoder zero‑copy. It was **implemented, measured, and reverted** (`a31cf49` → `e6cbb45`): the readback it removed was 0.1 % of wall, and GPU‑backed frames turned out to be **slower** into the encoder than CPU ones (22.8 vs 35.6 fps). Keep the proven Canvas2D composite. See §3.1.--The frame path stays as it is (Pixi/WebGL for the video, Canvas2D composite, `getCanvas()`). Only the **encoder** changes:--```-FrameRenderer.getCanvas() → read pixels (~0.2 ms, measured, negligible)- │- ▼ NV12/RGBA frame (renderer → main; 489–589 MB/s over a real pipe, ~3 % cost)-native ffmpeg subprocess -c:v h264_nvenc | h264_qsv | h264_amf | h264_videotoolbox | h264_vaapi- │- ▼ writes the .mp4 directly to disk-```--This also deletes three things we currently pay for: the WebCodecs encoder, the JS muxer (`mediabunny`), and the whole in‑memory `Blob` + final save IPC — ffmpeg muxes and writes the file itself.--### 4.4.1 The upstream chain, measured (2026‑07‑16)--The 165 fps figure is `node → ffmpeg` **in one process**. The real path adds a renderer→main process crossing per frame, so the whole chain was measured end‑to‑end. **The encoder is no longer the bottleneck — the IPC crossing is.**--**Stage 1 — canvas → bytes (mandatory: the renderer is sandboxed, so bytes must cross a process boundary):**--| method | ms/frame | ceiling |-|--------|---------:|--------:|-| **`new VideoFrame(canvas2D).copyTo(buf)`** | **1.43** | **698 fps** ← use this |-| `getImageData` → RGBA | 7.00 | 143 fps |-| `gl.readPixels` → RGBA | 8.18 | 122 fps |-| `new VideoFrame(**GL** canvas).copyTo(buf)` | 11.23 | 89 fps |--Two consequences. First, `copyTo` on a **2D** canvas is 5× cheaper than `getImageData` — it is the extraction method, and it takes extraction off the critical path. Second, reading back a **WebGL** canvas is **8× slower than a 2D one** — which is the retroactive explanation for why the GPU‑resident composite (§4.4) never paid off. That revert was right for a reason we only learned here.--**Format constraint:** `VideoFrame(canvas).format` is **BGRA**, and `copyTo({format:"NV12"})` / `{format:"I420"}` throw `NotSupportedError` — Chromium will not convert. Only RGBA/BGRA come out. So we ship **BGRA at 7.9 MB/frame** and let ffmpeg's swscale convert. We cannot get the 3.0 MB NV12 frame from the renderer.--**Stage 2 — renderer → main (the new bottleneck):**--| transport | fps | throughput |-|-----------|----:|-----------:|-| `ipcRenderer.send`, window=1 (stop‑and‑wait) | 84 | 249 MB/s |-| **`ipcRenderer.send`, credit window=8** | **130** | **387 MB/s** |-| `ipcRenderer.send`, credit window=32 | 131 | 389 MB/s |-| MessagePort zero‑copy transfer | ❌ **impossible** | — |--A **credit window** (N frames in flight) is worth **+56 %** over stop‑and‑wait; window=8 already saturates it, 32 adds nothing. Use 8.--**Zero‑copy to main does not exist in Electron.** `MessagePortMain.postMessage(message, [transfer])` accepts `MessagePortMain[]` **only**; transferring an ArrayBuffer from renderer to main silently loses the entire message (measured: `ev.data === null`; known bug [electron#34905](https://github.com/electron/electron/issues/34905) — it works renderer→renderer, not renderer→main). Every frame is structured‑cloned, i.e. copied. That caps the crossing at ~390–420 MB/s, which at 7.9 MB/frame is **53 fps** for the crossing alone (measured).--**Stage 3 — end‑to‑end, measured (not extrapolated):**--| pipeline | fps | throughput |-|----------|----:|-----------:|-| IPC alone · NV12 3.0 MB | 130 | 387 MB/s |-| IPC alone · BGRA 7.9 MB | 53 | 418 MB/s |-| **IPC + ffmpeg · NV12 3.0 MB** | **81** | 240 MB/s |-| **IPC + ffmpeg · BGRA 7.9 MB** | **34** | 268 MB/s |--Two facts fall out, and both matter:--1. **The crossing is bandwidth‑bound, not per‑message‑bound** (387 vs 418 MB/s at wildly different frame sizes). So halving the bytes really does double the fps — Phase 4 is worth it, and this is what justifies it.-2. **Main is a serialisation point.** Attaching ffmpeg costs ~40 % of the crossing throughput (418 → 268 MB/s) because the same process both receives the IPC message and writes stdin. Moving ffmpeg to a `utilityProcess` does **not** fix this — the receiving process still does both halves; it only moves which process pays.--Also: `Buffer.from(typedArray)` **copies**. In the main‑process sink, wrap instead — `Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)`. Measured worth **+31 %** (26 → 34 fps BGRA); at 7.9 MB × 546 frames a stray copy is 4.3 GB of pure waste.--**The chain, and what to expect:**--| stage | ceiling |-|-------|--------:|-| composite (Pixi) | 377 fps |-| extract (`VideoFrame(2D).copyTo`) | 698 fps |-| **renderer → main → ffmpeg stdin (BGRA)** | **34 fps** ← bottleneck |-| ffmpeg `h264_amf` | 165 fps (3× headroom) |--**Phase 3 target: 8 → 34 fps (≈4.3× on the frame pipeline).** Ship it first: most of the win, low risk.-**Phase 4 (GPU NV12 packing): 34 → 81 fps (≈10× vs today).** Now clearly justified by fact 1 above — but still gated on the packing not reintroducing the slow GL readback (11.23 ms).-------## 5. Phasing--Each phase is independently shippable and independently verifiable.--### Phase 0 — Measure & de‑risk (S) — ✅ **DONE**-- `StageTimings` harness + isolated encoder probe in `videoExporter.ts`.-- **Outcome:** it did its job — it *invalidated* the plan it was meant to validate. Readback is 0.1 %, not dominant; the encoder API is 90 %. See §3.1. This is why Phase 0 exists.--### Phase 1 — Multi‑asset correctness (L) — ✅ **DONE**-- `RenderPlan`, segment loop, per‑segment audio/cursor/webcam/speed, seamless junctions. Shipped and verified in the dev app.--### Phase 2 — ~~Worker + GPU‑resident compositing~~ — ❌ **CANCELLED**-- GPU‑resident composite: built, measured, **reverted** (§4.4) — target was 2.3 % of wall.-- Worker + OffscreenCanvas: **demoted to Phase 5**. It buys UI responsiveness, not throughput, and is not worth its portability risk (R2) until the encoder is fixed.--### Phase 3 — ~~Native ffmpeg encode (L) — the actual win~~ — ❌ **REFUTED (2026‑07‑16)**-> Built and measured end‑to‑end: **2.1× slower** than WebCodecs. The encoder half worked exactly as-> designed (`encodeWait` −29 %, `flush` −94 %); the frame's descent to RAM — which WebCodecs never-> performs — costs 38.9 ms/frame and swamps it. See-> [`export-native-encode-measurement.md`](./export-native-encode-measurement.md).-> A native encoder only pays if the frame never descends, i.e. compositing and encoding on one-> device: [`native-core-tauri-spec.md`](./native-core-tauri-spec.md) (option C), not this.-> The reusable parts (`ffmpegCapabilities` smoke‑tested election, `ffmpegEncodeSession`, the pinned-> LGPL binary + `fetch-ffmpeg.mjs`) all survive — option C still needs a native H.264 encoder.--Replace the WebCodecs encoder + JS muxer with a bundled LGPL ffmpeg subprocess (§7).--1. **Build & bundle.** ffmpeg per platform, built **without** `--enable-gpl` and without `--enable-nonfree` — that is what makes it LGPL, and it is the *only* control that matters (those flags are what pull x264/x265; absent them ffmpeg simply won't build a GPL component, whatever else is enabled). **Binary size is not a constraint** (~200 MB/platform is fine), so do **not** strip for size — enable the codecs we may want next (HEVC, AV1, VP9, ProRes) so a future format doesn't need a rebuild + re‑qualification. Ship next to the existing native binaries in `electron/native/bin/<platform>-<arch>/`. Add the LGPL notice + source offer.-- **Where each platform's binary comes from:**-- | platform | source | effort |- |---|---|---|- | Windows x64 + arm64 | **[BtbN prebuilt LGPL](https://github.com/BtbN/FFmpeg-Builds)** — daily builds, `h264_amf`/`h264_nvenc`/`h264_qsv` compiled in | just verify + vendor |- | Linux x64 + arm64 | **BtbN prebuilt LGPL** | just verify + vendor |- | **macOS x64 + arm64** | **we build it** — BtbN has no macOS target | **real work: build + sign + notarise** |-- macOS is the one we own end‑to‑end, and skipping it is not on the table (§1 non‑goals). A VideoToolbox‑only macOS build is inherently x264‑free, which makes the LGPL gate easy there — the cost is the build/notarisation pipeline, not the licence.-- **Verify every binary before vendoring it**, whatever the source: `ffmpeg -version` must print `License: LGPL version 2.1 or later`, its `configuration:` line must contain neither `--enable-gpl` nor `--enable-nonfree`, and `ffmpeg -encoders` must not list `libx264`/`libx265`. `isLgplBuild()` in `electron/media/ffmpegCapabilities.ts` encodes exactly this check — wire it into CI so a "just add x264" patch cannot silently relicense the app.-2. **Capability probe** (§7.1), cached per machine.-3. **Encode service** (main process): spawn ffmpeg, stream **BGRA** frames to stdin **honouring `drain`** (the measured 489–589 MB/s depends on it), parse progress from stderr, handle cancel (kill the tree) and non‑zero exit.-4. **Renderer side:** after `renderFrame`, extract with `new VideoFrame(canvas).copyTo(buf)` (**not** `getImageData` — 1.43 ms vs 7.00, §4.4.1) and ship the frame to the service over a **credit window of 8**. Keep the WebCodecs path behind the capability probe as the fallback.-5. **Delete on success:** the `mediabunny` video muxing path and the in‑memory `Blob` → ffmpeg writes the file.--- **Exit criteria:** the frame pipeline reaches **≥30 fps** (measured ceiling 34, §4.4.1) vs 8 today with frame‑diff parity vs the current output and A/V still locked; WebCodecs fallback still produces a correct file when no hardware encoder is present; cancel leaves no orphan process.--### Phase 4 — ~~Halve the crossing: GPU BGRA→NV12 packing (M, measure‑gated)~~ — ❌ **CANNOT RESCUE PHASE 3 (2026‑07‑16)**-> The 34→81 fps figures below came from a **bench harness, not the app**: it materialised frames once-> and then timed the pipe, so it never priced the per‑frame descent. Measured in the real pipeline,-> that descent is **6.7 ms fixed + 3.9 ms/MB** (257 MB/s marginal — a sync, not a copy). NV12-> therefore halves the readback to ~18.8 ms/frame and lands at **29.5 fps** projected, vs **36.9 fps-> measured for WebCodecs today**; even assuming the IPC scales perfectly it only reaches parity.-> Halving the bytes is real and still not enough. See-> [`export-native-encode-measurement.md`](./export-native-encode-measurement.md) §4.--- The renderer→main crossing is the bottleneck at **34 fps**, purely because Chromium only hands us **7.9 MB BGRA** (it refuses NV12, §4.4.1) and Electron cannot transfer buffers zero‑copy. The crossing is **bandwidth‑bound** — measured 387 MB/s at 3.0 MB/frame vs 418 MB/s at 7.9 MB/frame — so halving the bytes really does double the rate: NV12 measures **81 fps** end‑to‑end (≈10× vs today).-- **Gate:** GL‑canvas readback measured 8× slower than 2D (11.23 vs 1.43 ms) — the packing must not reintroduce that. Prototype and measure the packing + readback together before committing.--### Phase 5 — Parallel segments (M, measure‑gated)-- Only if the above leaves us *encoder*‑bound (it currently does not — the encoder has 3× headroom over the crossing). Consumer NVENC/AMF expose 3–8 sessions; needs DTS‑ordered stitching.--### Phase 5 — Worker + OffscreenCanvas (M, optional)-- UI responsiveness during export. Independent of throughput; do it when it's worth it, not before.-------## 6. Detailed design notes--### 6.1 Building segments (documentExporter)-- `segments = timeline.clips` sorted by `timelineStartSec`. For each clip: resolve its asset, `videoUrl`, `[sourceStartSec, sourceEndSec]`, `cropRegion ?? IDENTITY`, and the clip’s asset dims.-- `intraTrims`: the subset of `timeline.trimRanges` whose `assetId === clip.assetId` intersected with `[sourceStart, sourceEnd)` — these are cuts *inside* a clip (existing `computeExportTrimRegions` logic, but scoped per segment instead of one global complement).-- Gaps between clips are simply absent segments (no black frames unless we choose to insert them — **decision D3**).--### 6.2 Renderer reconfiguration per segment-- `FrameRenderer` currently takes `videoWidth/videoHeight` once. Add `setSource({ videoWidth, videoHeight, webcam })` to rebuild the source‑dependent sprites/filter sizes between segments. Output size stays fixed for the whole export.--### 6.3 Audio-- Per segment, decode `[sourceStart, sourceEnd)` of that asset’s audio (reuse `AudioProcessor`), append PCM to a running timeline, resampling to a **common** sample rate/channel layout chosen up‑front (from the first segment with audio, or 48 kHz stereo default). Encode once at the end and mux.-- Segments with no audio track contribute silence of their virtual duration (keeps A/V aligned).-- `selectSupportedExportCodecForSource` is chosen from the **first** segment’s demuxer; heterogeneous source codecs are fine because we re‑encode to one output codec.--### 6.4 Cursor (per‑segment) — **decision D1**-- Cursor telemetry (`CursorRecordingData`) is recorded per recording and currently taken from the primary asset. Proposal: carry cursor data **per segment** on the asset (`asset.cursor…`) and have the renderer switch cursor source at segment boundaries, offset into the segment’s source time.-- If a segment’s asset has no cursor data, that segment renders with no cursor overlay. This is the smallest correct behavior and avoids inventing cursor motion.--### 6.5 Speed regions-- `speedRegions` remain virtual‑time. Within a segment, the local decode→output time map applies the covering speed factor (existing `decodeAll` speed handling, but the *timestamp* handed to the renderer/encoder is the virtual cursor, so cross‑segment continuity holds).--### 6.6 Memory & backpressure-- One active decoder per segment in Phase 2. Optionally **prefetch** the next segment’s `loadMetadata` while the current one drains (bounded to 2 in flight) to hide seek/demux latency — add only if Phase 0 shows boundary stalls.-- Keep the three WebCodecs bottleneck signals bounded: `decoder.decodeQueueSize`, count of open `VideoFrame`s, `encoder.encodeQueueSize`. Close every `VideoFrame` in a `finally`.--### 6.7 Fast path-- The source‑copy fast path (`trySourceCopyFastPath`) stays, but only qualifies when `segments.length === 1` **and** identity (no effects/crop/speed, output size == source, matching fps/codec). Multi‑segment always re‑encodes.-------## 7. Encoder strategy — native ffmpeg primary, WebCodecs fallback--> **This section was inverted on 2026‑07‑16.** It used to read *"a native ffmpeg swap would not beat it"*. Measured on the same machine, same GPU, same 546 frames: **WebCodecs ≈ 8 fps, native ffmpeg `h264_amf` = 165 fps.** The claim was wrong by ~20×. See §3.--- **Primary: native ffmpeg subprocess** (main process), hardware encoder selected per platform. This is what After Effects / CapCut / Resolve do, and it is the only lever that touches the 90 %.-- **Fallback: WebCodecs** (`prefer-hardware`, software fallback) — today's path, kept verbatim for machines with no usable hardware encoder. No regression, no extra work.--### 7.1 Encoder selection (runtime probe, first that works wins)--| OS | Order | ffmpeg encoder |-|----|-------|----------------|-| Windows | NVIDIA › Intel › AMD | `h264_nvenc` › `h264_qsv` › `h264_amf` |-| macOS | Apple Media Engine (every Apple Silicon) | `h264_videotoolbox` |-| Linux | NVIDIA › Intel/AMD | `h264_nvenc` › `h264_vaapi` |-| any | *(none of the above)* | fall back to WebCodecs |--Probe once per machine (`ffmpeg -encoders` + a 1‑frame smoke encode), cache the result, re‑probe on driver/version change.--### 7.2 Licensing — LGPL build, no compromise (why this is safe for an MIT app)--Three layers people conflate:--1. **ffmpeg's own licence.** LGPL 2.1+ **by default**. It only becomes GPL if built with `--enable-gpl` (which pulls x264/x265) — and it is all‑or‑nothing: one GPL component makes the whole binary GPL.-2. **What binds us.** We build ffmpeg **ourselves, LGPL** (no `--enable-gpl`, no `--enable-nonfree`). Obligations: dynamic linking **or a separate executable** (a subprocess trivially satisfies this), ship ffmpeg's source for the exact version (or a written offer), include the LGPL text + attribution, don't forbid reverse‑engineering for debugging. **Our code stays MIT. Zero contamination.**-3. **Patents ≠ copyright.** An LGPL/GPL licence grants **no** patent rights; H.264 sits in a patent pool (Via LA). Hardware encoders inherit the vendor/OS licence. Not a *new* exposure: the app already ships H.264 export via WebCodecs today. *(Not legal advice — worth a real review before commercialising.)*--**What we give up: x264 only.** Measured cost of that: `libx264 -preset ultrafast` 201 fps vs `h264_amf` 165 fps — and x264's number is misleading, because it saturates every CPU core and would then contend with the renderer, while a hardware encoder runs on dedicated silicon and leaves the CPU free. In the real pipeline hardware is likely *ahead*. Giving up x264 costs us ~nothing.--**Rejected alternatives** (all evaluated 2026‑07‑16):--| Option | Why not |-|--------|---------|-| `@napi-rs/webcodecs` | MIT wrapper, zero‑copy, same API (near‑zero migration) — but **no AMF**: AMD‑on‑Windows falls back to software. Its docs also reference `libx265` ⇒ likely a GPL build. The wrapper's MIT does **not** cover the bundled binary. |-| `node-av` | MIT wrapper but exposes `FF_ENCODER_LIBX264` ⇒ ships a GPL ffmpeg build. |-| `beamcoder` | GPL v3. |-| GStreamer | No official Node binding; no perf edge over ffmpeg. *(We also called it "heavier" — that no longer counts against it, since size is not a constraint. It still loses on the binding.)* |-| Own N‑API addon on OS APIs (Media Foundation / VideoToolbox / VAAPI) | Theoretical max — buys **+3 %** (the measured pipe cost) for three native codebases and three toolchains. *(Its "ships nothing extra" upside is moot: size is not a constraint, so it has no advantage left.)* |-| Chromium GPU flags / blocklist | Dead end: `video_encode=enabled` already, with a real window. No blocklist to lift. |--Building ffmpeg ourselves is the **only** path that simultaneously guarantees LGPL, covers AMD/AMF, and stays one integration for three OSes.-------## 8. Testing & verification--**Unit / vitest** (no GPU needed):-- `renderPlan` builder: N clips across M assets → correct ordered segments, intraTrims scoping, gaps, identity fast‑path eligibility. Table‑driven, mirrors `documentExporter` test style.-- Audio concat timing: segment durations → sample offsets; silence padding for audio‑less segments.-- Aspect/size math (already covered by `mp4ExportSettings.test.ts`).--**Integration (Electron dev app, manual + scripted):**-- 1 asset identity export == byte/visual parity with pre‑refactor (Phase 1 gate).-- 2‑asset A→B timeline: both clips present, in order, A/V synced, cursor switches correctly.-- Non‑16:9 timeline framing matches preview.-- Cancel mid‑export releases decoders/encoder/frames (no leak; watch `VideoFrame` count).--**Perf harness (Phase 0, kept):**-- `StageTimings` in `runSegmentLoop` logs `[export perf]` per‑stage ms + fps (via `console.warn`, so the app's `rendererConsoleForwarder` forwards it to the Electron stdout — **`console.log` is not forwarded**). `ENCODER_PROBE` in `videoExporter.ts` benchmarks the encoder in isolation.-- Record before/after each phase in the PR. Reference fixture: **os_parity**, MP4/1080p/60/H.264, 546 output frames.-- **Baselines to beat (same machine, 2026‑07‑16):** WebCodecs software 94.6 s · WebCodecs hardware **72.7 s** · native `h264_amf` ceiling **~10 s**.--**Benchmarking natives without the app** (how §3.1's numbers were produced — reuse this before implementing):-```bash-# encode-only: materialise real frames once, then time the encoder alone-ffmpeg -i export.mp4 -an -f rawvideo -pix_fmt nv12 raw.nv12-ffmpeg -f rawvideo -pix_fmt nv12 -s 1920x1080 -r 60 -i raw.nv12 -c:v h264_amf -b:v 8000k out.mp4-# the real architecture: Node streams NV12 into ffmpeg's stdin (respect `drain`)-node pipebench.cjs # measured 165 fps @ 489 MB/s-```-**Measurement traps this spec was burned by — all three produced false conclusions:**-1. `cat | ffmpeg` under **Git Bash** caps at ~70 MB/s (MSYS emulated pipe) and fabricates an 8× penalty. Use Node → stdin (489–589 MB/s).-2. `app.getGPUFeatureStatus()` from a **windowless** Electron script reports everything `disabled_software`. Meaningless — always probe with a real `BrowserWindow` (then: all `enabled`).-3. **`new VideoFrame(canvas)` is lazy.** Timing it measures ~0.2 ms and tells you nothing; the GPU→CPU descent only happens at `copyTo()`/`getImageData()` (1.43–11.23 ms, §4.4.1). The old "readback is 0.1 % of wall" line came from exactly this mistake.--**General rule this spec keeps re‑learning: benchmark the stage you are about to optimise, in the process topology it will really run in.** Every wrong turn here came from measuring a stage in isolation and assuming the surrounding chain was free.-------## 9. Already shipped (aspect ratio)--`documentExporter` reads `document.legacyEditor.aspectRatio` and converts via `getAspectRatioValue` (`"native"` → `getNativeAspectRatioValue(sourceW, sourceH)`), replacing the hardcoded `16/9`. `ExportDialog` computes the same value so the per‑tier size labels (`W × H`, `· Upscale` when a tier exceeds the largest clip) match the actual output. Output is sized to the **largest** clip on the timeline (`referenceSource`, by pixel count). Covered by existing tests; `tsc`/Biome clean.-------## 10. Risks & mitigations--| ID | Risk | Mitigation |-|----|------|-----------|-| ~~R1~~ | ~~GPU‑resident composite is a large rewrite~~ | **Moot** — cancelled and reverted (§4.4) |-| R2 | PixiJS on OffscreenCanvas in a worker has platform quirks (esp. Linux EGL/Ozone) | Deferred with Phase 5; not on the critical path |-| R3 | Per‑segment cursor data may not exist for imported (non‑OpenScreen) media | Render no cursor for such segments (§6.4); acceptable and correct |-| R4 | Parallel HW encode doesn’t scale | Phase 4 is measure‑gated; ship serial if numbers are flat |-| R5 | Audio resample drift across many segments | Single common rate chosen up‑front; accumulate sample counts as integers |-| **R6** | **Bundling ffmpeg: 3 build matrices + macOS signing/notarisation of a shipped binary** | Precedent exists: the app already ships `wgc-capture.exe`, `cursor-sampler.exe`, `whisper.dll`, `ggml-*.dll` — the packaging/signing path is solved. **Size is explicitly not a risk** (~200 MB/platform accepted), so no stripping and no size/feature trade‑off |-| **R7** | **LGPL compliance slips** (someone rebuilds with `--enable-gpl` for "just x264")| Pin the configure flags in the build script + CI assertion that `ffmpeg -L` reports no GPL component. One GPL component relicenses the whole binary (§7.2) |-| **R8** | **Hardware encoder quality/compat varies by vendor** (AMF historically the weakest; driver bugs) | Frame‑diff parity gate per encoder in Phase 3; WebCodecs fallback always available; allow forcing the fallback via a setting |-| **R9** | **ffmpeg subprocess lifecycle** (orphans on crash/cancel, stdin backpressure deadlock) | Kill the process tree on cancel/quit; respect `stdin.write()` backpressure (the measured 489–589 MB/s assumes honouring `drain`) |-------## 11. Open decisions (need product/eng sign‑off)--- ~~**D1 — Cursor across recordings**~~ — **signed off 2026‑07‑15:** per‑segment cursor, from each clip's own recording. Shipped.-- ~~**D2 — Audio model**~~ — **signed off:** sequential concat only.-- ~~**D3 — Gaps between clips**~~ — **signed off:** clips are always contiguous (the timeline reposes them); cuts are trims laid on top. No gaps to fill.-- ~~**D4 — Phase 3 parallelism / perf programme**~~ — **RESOLVED 2026‑07‑16, and not as written.**-- D4 originally read *"do everything: kill the readback, Worker + OffscreenCanvas, pipeline, parallel encode"*. Phase‑0 measurement killed that framing: those targets are **≤2.3 %** of wall combined, while **WebCodecs alone is ~90 %** (§3.1). The GPU‑resident composite was built, measured at ~0 gain, and reverted.-- **D4 is now: replace the WebCodecs encoder with a bundled LGPL native ffmpeg (§7), Phase 3.** The encoder alone goes 8 → 165 fps (20×), but end‑to‑end we land at **34 fps (≈4.3×)** because the renderer→main crossing becomes the new bottleneck; **81 fps (≈10×)** once Phase 4 halves the bytes (§4.4.1 — all measured). **No licensing compromise** (LGPL build, we control the flags; we give up only x264, worth ~0 in‑pipeline).-- Parallel encode survives as **Phase 4, still measure‑gated** — but now it is gated on whether *native* encode leaves us encoder‑bound, which is a very different question.-- **Shipped from the old D4** (kept, they're real): hardware‑first encoder selection (`a31cf49`, ~23 % on the fallback path) and overlapping the WSOLA audio stretch with the video loop (`09db50f`, ~4 s, free — the loop is idle in `encodeWait`).diff --git a/docs/architecture/export-pipeline.md b/docs/architecture/export-pipeline.mdnew file mode 100644index 000000000..dd813821a--- /dev/null+++ b/docs/architecture/export-pipeline.md@@ -0,0 +1,304 @@+# 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++### 2.1 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.++```ts+interface RenderSegment {+ clipId: string;+ assetId: string;+ videoUrl: string; // toFileUrl(asset.originalPath) — the doc is self-contained+ sourceStartSec: number; // clip in-point in the asset's media time+ sourceEndSec: number;+ intraTrims: Interval[]; // trimRanges of THIS asset inside [start,end)+ cropRegion: CropRegion;+ sourceWidth: number;+ sourceHeight: number;+ camera?: { videoUrl: string; offsetMs: number } | null; // per-asset webcam+}+```++### 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+```++`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++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`).diff --git a/docs/architecture/native-core-tauri-spec.md b/docs/architecture/native-core-tauri-spec.mddeleted file mode 100644index e1d252fe7..000000000--- a/docs/architecture/native-core-tauri-spec.md+++ /dev/null@@ -1,185 +0,0 @@-# Native Core — moving the compositor out of the browser renderer--Status: **Exploratory / for decision.** This is a product-architecture proposal, not a perf patch.-Scope: the render/composite/encode core of the `.axcut` editor — preview *and* export.-Prerequisite reading: [`export-pipeline-v2-spec.md`](./export-pipeline-v2-spec.md) §3.1 and §4.4.1 — every number below comes from there.--> **Re‑framed 2026‑07‑16 by measurement.** The plan was A (bundled ffmpeg, ~×10) *then* C (this doc,-> the last ×2). A was built and measured: it is **×0.48** — 2.1× slower than WebCodecs, because a-> sandboxed renderer cannot hand a GPU texture to a native process, so every frame must descend to-> RAM (38.9 ms/frame) where WebCodecs never descends at all. See-> [`export-native-encode-measurement.md`](./export-native-encode-measurement.md).->-> **Option A′ (`sandbox: false`) is excluded — measured, not argued.** With the crossing set to-> *exactly zero* (frames descended to RAM then discarded: no IPC, no ffmpeg, no muxer) the pipeline-> still runs 40.5 fps against WebCodecs' 44.0, and WebCodecs is also writing the file. That ceiling-> bounds every "remove the crossing" variant at once — A′, shared memory, zero‑copy transfer — since-> none of them can skip `copyTo()`. A′ is strictly worse than that ceiling anyway: it swaps a-> structured clone (~390 MB/s) for a pipe write (~500 MB/s), i.e. ~1.2× on one leg, bought by giving-> up the sandbox that §3.2 identifies as protecting demux/decode of untrusted media.->-> This does not make C a bigger win by default — it makes C the **only** arrangement in which native-> encode can pay, and for a different reason than this doc argues: not "fewer copies", but *the frame-> never descends*. That is now the load‑bearing assumption of this entire proposal, and it is-> **unmeasured**. Prototype and bench "composite and encode on one device, frame never descends"-> **before** committing to a migration. The last architectural certainty was 2.1× backwards.-------## 1. Why this exists--The export pipeline was measured end‑to‑end (2026‑07‑16). After replacing the WebCodecs encoder with native ffmpeg, the bottleneck is **not** the encoder any more — it is the **renderer→main process crossing**:--| architecture | fps @1080p | vs today |-|---|---:|---:|-| today (WebCodecs) | 8 | — |-| Phase 3 — native ffmpeg, BGRA over IPC | 34 | 4.3× |-| Phase 4 — + GPU NV12 packing (halves the bytes) | 81 | 10× |-| **native compositor (no crossing)** | **~165** (encoder‑bound) | **20×** |-| native compositor + parallel encode sessions | >165 | >20× |--The crossing exists for one reason: **the compositor runs inside a sandboxed Chromium renderer**, so every finished frame must be copied across a process boundary to reach a native encoder. Electron offers no zero‑copy path out ([electron#34905](https://github.com/electron/electron/issues/34905): the transfer list accepts `MessagePortMain[]` only — an ArrayBuffer transfer silently drops the message). Every frame is structured‑cloned: ~390–420 MB/s, and attaching ffmpeg to the receiving process costs another ~40 % because one thread both receives IPC and writes stdin.--**Phase 4 works around the wall (10×). This document is about removing it (20×+).**--## 2. The trap this must avoid--> Moving compositing to Rust **for export only** would give us two implementations of the entire visual identity — zoom spring, auto‑focus follow, motion blur, three‑layer drop shadow, webcam masks, cursor smoothing/click‑bounce/motion‑blur, annotations, 3D rotation, gradients, border‑radius, padding, crop — that must agree **pixel‑for‑pixel, forever**, because the preview would stay in the browser.--We spent a full session validating parity for *one* path. Two paths means paying that validation on every visual change, indefinitely. **A native compositor is only worth building if it serves the preview too.** That is the whole argument of this document, and the reason it is an architecture decision rather than an optimisation.--## 3. Correcting the framing: "Electron for UI + Tauri for backend"--That combination does not exist. **Electron and Tauri are both application shells** — each provides the window, the webview and the native backend. Electron = web UI + Node backend; Tauri = web UI + Rust backend. You pick one.--The real question is not *Electron vs Tauri*. It is:--> **Where does the compositor live, and how does the preview display its output?**--It is not *Node vs Rust* either. Neither the language nor the shell is what forces the descent — **the browser engine is**. The compositor is Pixi/WebGL/Canvas2D inside Chromium's renderer, and Chromium exposes its GPU textures to nobody: there is no API to obtain the D3D11 texture behind a canvas. So any encoder outside Chromium must have the pixels come down. 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 only: **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 native addon in the main process, or a native sidecar. Rust is the sane choice for new GPU code, not a requirement.--**So the shell is a consequence, not a cause.** Tauri earns its place *after* that decision, on bundle size, memory and not shipping a second Chromium — never on this measurement. What actually forces the shell question is the **preview** (§4): once the compositor is native, the preview must come from it too, or the product ships two compositors (option B) and loses the parity that is its entire value.--| option | compositor | preview display | crossing? | parity | other cost |-|---|---|---|---|---|---|-| **A. status quo + Phase 4** | Pixi/WebGL in renderer | canvas in the webview | yes (3.0 MB/frame) | ✅ one compositor | — |-| **A′. Electron, export window with `sandbox:false`** | Pixi/WebGL in renderer | canvas in the webview | **no** | ✅ one compositor | **the sandbox** |-| **B. Rust compositor, export only** | Rust/wgpu | Pixi (unchanged) | export: no | ❌ **two compositors** | months |-| **C. Rust compositor + native preview surface** | Rust/wgpu | native surface in the window | no | ⚠️ *promised*, not given (see below) | months + shell migration |-| **D. Rust compositor, preview via webview** | Rust/wgpu | frames pushed to the webview | **yes, reversed** | ✅ one compositor | months, for nothing |--> ❌ **A′ is dead — measured 2026‑07‑16, see [`export-native-encode-measurement.md`](./export-native-encode-measurement.md) §5.**-> The paragraph below is preserved because its *reasoning* is the trap worth remembering, not because-> its conclusion holds. It is wrong in one specific way: `pipebench.cjs` measured the **pipe**, having-> materialised frames once, outside the timed loop. It never priced getting a *composited* frame out-> of the GPU — which is per‑frame, ~20–39 ms, and which A′ does **not** remove. A′ deletes the-> structured clone; it keeps the descent. The `crossing? no` in the table above should read-> **"IPC no, descent yes"**.-> Measured ceiling with the crossing at *exactly zero*: **40.5 fps vs WebCodecs' 44.0**. A′ cannot-> reach 165 fps, and it cannot beat what we already ship.--**A′ is the option this document originally missed, and it matters.** The crossing is not purely architectural — it is partly *configuration*. With `sandbox:false` + `nodeIntegration:true`, the renderer **is** a Node process: it can `spawn('ffmpeg')` and write frames straight to `stdin`. V8 heap → pipe, no Mojo, no structured clone. (That is literally what our 165 fps `pipebench.cjs` measured.) **A′ reaches the same ~165 fps as C, for a boolean.**--We are **not** taking it. The app deliberately runs `nodeIntegration:false` + `contextIsolation:true` with the sandbox on by default, and the editor already spends its security budget on `webSecurity:false`. Turning the sandbox off on the window that handles user-supplied media trades a layer of defence-in-depth for 2×. (The threat model is narrower than it first looks — demuxing is WASM, decoding runs in the GPU process, and ffmpeg only ever sees rawvideo we produced — but an exploit in the WASM demuxer or the WebGL path would land on full Node instead of having to escape a sandbox first. That is a real loss.)--**What A′ does to the case for C:** they buy the *same thing* — removing the crossing, ~165 fps. A′ costs the sandbox; C costs months plus a wgpu compositor. So C is not "the only way to 20×" — it is "the way to 20× that lets us *design* the isolation instead of deleting it" (§3.2 — and only if we actually budget for that design).--**On C's parity column — read it honestly.** It is marked ⚠️, not ✅, on purpose. One compositor gives parity *by construction* only **after** the shadow, webcam mask, cursor and zoom easing are re‑implemented identically in wgpu — which is precisely where parity breaks in practice. Until then the ✅ is a promise, not a state. B is worse still: two compositors permanently, on a product whose entire value is that the export looks like the preview.--D is a trap: pushing preview frames back to the webview reintroduces the exact bottleneck, reversed.--### 3.1 A′′ — sandboxed demux, unsandboxed composite (unverified)--[electron#34905](https://github.com/electron/electron/issues/34905) notes the zero‑copy transfer that fails renderer→main **works renderer→renderer**. That suggests a narrower A′: keep demux/decode in the sandboxed editor renderer, transfer the *decoded* frames zero‑copy to a second, `sandbox:false` window that only ever sees **our own pixels**, and let that window spawn ffmpeg. The lock stays where the hostile input actually arrives.--**This is speculation.** Not measured, not validated. Two things would have to hold: that renderer→renderer transfer really is zero‑copy in our Electron version, and that a renderer holding no untrusted input is meaningfully safer — which is arguable, since it still runs Blink/V8. Worth an hour before anyone spends a month on C; not worth more than that until someone measures it.--### 3.2 Security: "going native" relocates the problem, it does not solve it--An earlier draft justified C partly as *"the way to 20× that keeps the sandbox"*. **That is wrong, and it is the most important correction in this document.**--| | who parses hostile input | is one bug enough? |-|---|---|---|-| **A + Phase 4** | `web-demuxer` in **WASM** (confined linear memory) + decode in the **GPU process** (separately sandboxed) | no — needs a parser bug *chained with* a sandbox escape |-| **A′** | unchanged — still WASM + GPU process | **yes** — *any* renderer bug reaches `require('child_process')` |-| **C** | **native ffmpeg (C), in‑process, no sandbox at all** | **yes** — any ffmpeg demuxer CVE lands on the machine |--Read the media column again: today the riskiest parser runs in **WASM**. A native core would replace it with **unsandboxed C parsing untrusted containers** — on the media path specifically, **C is a regression against both A and A′**. Media demuxers are among the most CVE‑dense code in existence, which is exactly why browsers confine them.--So the security objection to A′ does **not** convert into an argument for C. The honest distinction is narrower:--- **A′ removes a layer wholesale, with no recourse.** `nodeIntegration` is all‑or‑nothing for that renderer.-- **C hands us the isolation design.** We *can* run demux/decode in a sandboxed child process (what Chromium does), keep our own logic in memory‑safe Rust, and ship a webview with **no Node** at all (Tauri's IPC is a command allowlist, far narrower than `nodeIntegration`).--That is a **capability, not a property**. If C is built without that isolation, we will have spent months to end up **less safe than today**. Therefore:--> **Requirement (blocking) for C:** demux and decode of user‑supplied media MUST run in a sandboxed child process, not in the core. Any C proposal that does not budget for this is not a C proposal — it is a regression with better fps.--**For the record — this app is a screen recorder.** It legitimately holds screen contents, microphone, camera and the filesystem. An RCE here is worth more to an attacker than in almost any other desktop app. That asymmetry, not the raw CVE odds, is why the 2× does not buy the sandbox.--C is achievable in **either** shell — Electron with a napi‑rs addon plus a native child window, or Tauri natively. Tauri is the natural home (the backend already *is* Rust, and `wry` + a wgpu surface is a known pattern); Electron would be swimming against the process model. **This is what Cap (cap.so) does** — and why its native encoder crates make sense for it: Tauri/Rust, capture + composite + preview all native, no sandboxed renderer in the frame path.--## 4. Target architecture (option C)--```-┌─ Web UI (React) ─ unchanged ────────────────────────────────┐-│ timeline, inspector, dialogs, state (Zustand), i18n │-│ │ commands (seek, set zoom, play…) ▲ events │-└─────────┼────────────────────────────────────┼──────────────┘- ▼ │-┌─ Rust core ─────────────────────────────────────────────────┐-│ compositor (wgpu) ← ONE implementation, used by both │-│ ├── preview → native surface layered in the window │-│ └── export → frame → encoder, in‑process, no crossing │-│ decode (ffmpeg/VideoToolbox/MF) │-│ encode (h264_nvenc / h264_qsv / h264_amf / videotoolbox / │-│ vaapi — via ff-encode or vendor crates) │-│ muxing, audio (WSOLA + AAC) │-└─────────────────────────────────────────────────────────────┘-```--**Key property:** the compositor is a pure function of `(RenderPlan, time) → frame`. The preview draws it to a surface; the export hands it to an encoder. Same code, same pixels, by construction — parity stops being a thing we validate and becomes a thing we get for free.--### 4.1 What ports, and what does not--| layer | today | native core | effort |-|---|---|---|---|-| Web UI, timeline, state | React | **unchanged** | none |-| `RenderPlan` model | TS (`renderPlan.ts`) | port to Rust (pure data + logic, already unit‑tested) | S |-| geometry/timing SSOT (`compositeLayout`, `zoomTransform`, zoom spring, auto‑focus, cursor smoothing) | TS, pure | port to Rust — these are pure maths with tests, the cheapest part to move | M |-| compositor (Pixi/WebGL + Canvas2D layers) | TS | **rewrite in wgpu** — video sprite, wallpaper, 3‑layer shadow, webcam mask, cursor, annotations, 3D rotation, blur/motion‑blur | **L — the real cost** |-| preview display | `<canvas>` in webview | native wgpu surface in the window | M |-| decode | WebCodecs + web‑demuxer (WASM) | ffmpeg/native | M |-| encode | WebCodecs | native (this is the 20×) | S — mostly done in Phase 3 |-| audio (WSOLA, AAC, concat) | TS, pure + tested | port to Rust | M |-| capture (WGC, cursor sampler) | already native `.exe` | reuse as‑is or fold into the core | S |-| STT (whisper) | already native | unchanged | none |-| shell (IPC, updater, packaging, single‑instance, global shortcuts) | Electron | **rewrite for Tauri** | **L — the hidden cost** |--**The two big items are the wgpu compositor and the shell migration.** Everything the app already ships natively (`wgc-capture.exe`, `cursor-sampler.exe`, whisper) survives.--### 4.2 Why wgpu--One Rust codebase targeting Vulkan/Metal/D3D12 natively — and WebGPU in a browser, which keeps a web build possible. Effects map to shaders; the current 2D‑canvas layers (shadow, masks, cursor) become quads + fragment shaders. Alternative: per‑platform native APIs (Cap's `enc-avfoundation` / `enc-mediafoundation` model) — more code, no portability upside for compositing.--## 5. Honest cost / risk--- **This touches the product's entire visual identity.** Every effect must be re‑implemented and must look *right*, not merely *similar*. The frame‑diff harness from the export work is the gate, but the surface is large.-- **Shell migration is not free**: Electron APIs in use (`desktopCapturer`, `globalShortcut`, single‑instance lock, auto‑update, notarisation/packaging for 3 OSes, the whole `electron/ipc` surface) all need Tauri equivalents. Some are better in Tauri, some worse.-- **The team's language mix changes.** Today: TS + a little C++/native. After: a substantial Rust core that the whole team must be able to touch.-- **It is a months‑scale project**, and it competes with product work for the same 2× that Phase 4 does not deliver (10× → 20×).-- **Risk of a half‑migration**: option B (export‑only Rust compositor) is the tempting shortcut and it is the worst outcome — two compositors, permanent parity tax. If we start, we must reach C.--## 6. Recommendation & sequencing--1. **Do Phase 4 first, now** (§4.4.1 of the export spec): NV12 packing + move the ffmpeg stdin write off the IPC‑receiving thread. Target ~81–100 fps (**10×**), no architecture change, one compositor, no security trade. It is *not* wasted if we later go native — the encoder selection, the LGPL ffmpeg bundling and the capability probe all survive into the Rust core.-2. **Exhaust the free levers before paying for anything.** They can close the question outright: **N parallel MessagePorts** (untested — if the crossing goes 387 → ~600 MB/s, Phase 4 becomes encoder‑bound and C loses its entire reason to exist), and moving the stdin write to a `worker_thread` so the IPC‑receiving thread stops serialising with it (that serialisation costs a measured 40 %). A bigger credit window is **already ruled out** — measured 131 fps at window=32 vs 130 at window=8, saturated.-3. **Then decide C on evidence**, judged against A′ rather than against A: C's actual offer is *"the 2× that A′ gives for free, but without giving up the sandbox"*. That is worth something — it is not worth what this document originally implied.-4. **Spend an hour on A′′ (§3.1) before spending a month on C.** If renderer→renderer zero‑copy holds up, the crossing may be removable without touching the lock that guards the hostile input.-5. If we go C: **spike first** — a wgpu compositor rendering *one* clip with zoom + shadow + webcam, frame‑diffed against the current export. That subset is where the ⚠️ in §3's parity column lives. If parity is achievable there at reasonable cost, the rest is grind. If not, we learn cheaply. **Budget the sandboxed demux/decode child process from day one** (§3.2) — it is blocking, not a nice‑to‑have.--**Bottom line:** Phase 4 buys **10×** for weeks, safely. C buys the last **2×** (81 → 165 fps: 6.7 s → 3.3 s on os_parity, ~7.4 → ~3.6 min on a 10‑minute recording) for months, a Rust compositor, a shell migration, and a parity risk that is real. A′ buys that same 2× for a boolean — and we are refusing it on security. Consistency does not *force* refusing C, but not for the reason first written here: C does **not** "keep the sandbox" (§3.2). It relocates the exposure into native code and hands us the isolation design — which is a capability we then have to pay for. Same 2× prize either way; price it as such.--**Retracted:** an earlier draft argued *"measure 4K, the crossing scales with pixels while the encoder degrades more gently, so 4K makes this case much stronger."* That was itself an unmeasured extrapolation — the encoder slows at 4K too (h264_amf drops to roughly 40–50 fps), so the gap narrows rather than widens. 4K does not rescue this case.diff --git a/docs/architecture/rendering-architecture.md b/docs/architecture/rendering-architecture.mdnew file mode 100644index 000000000..2f6bbf6de--- /dev/null+++ b/docs/architecture/rendering-architecture.md@@ -0,0 +1,376 @@+# OpenScreen — Target rendering architecture++**Self-contained edition.** This document assumes **no prior knowledge** of the codebase, the previous specs, or the conversation that produced them. Everything an implementing agent needs is inlined: what the product does, how the current pipeline works, what was measured, what to build, and in what order.++**Date:** 2026-07-17+**Source tree referenced:** `getopenscreen/openscreen@a159121` (branch `feat/ai-edition`)+**Priorities, in order:** (1) preview fluidity, (2) export speed+**Supersedes:** `export-pipeline-v2-spec.md` Phase 3/Phase 4 conclusions; incorporates `native-encode-measured-e2e.md` (2026-07-16) and the layer bench.++---++## Part I — Context++### 1. What OpenScreen is++OpenScreen is an open-source (MIT) desktop app for turning raw screen recordings into polished demo videos — an alternative to Screen Studio. Electron app (Chromium renderer + Node main process), shipped on Windows, macOS and Linux, x64 and arm64.++A user records their screen (plus webcam, microphone, and a cursor trace), then edits on a timeline: they cut, speed up boring parts, add zooms that follow the cursor, captions from an auto-transcript, and annotations. The app styles the result — wallpaper background, padding, rounded corners, drop shadow, webcam bubble — and exports an MP4 (or GIF).++**The product promise: what you see in the preview is exactly what the export produces.** The entire value of the tool is that styling and motion design require zero skill — you scrub, you tweak, you export, and it looks right.++### 2. The feature inventory (functional spec)++This is the complete set of behaviours the rendering architecture must support. If a feature is not in this list, it does not constrain the architecture.++**Sources (inputs):**++| source | nature | notes |+|---|---|---|+| screen recording | H.264/VP8/VP9 video file | high resolution, low motion (screen content), long GOPs |+| webcam | second video stream | composited as a PiP bubble or fullscreen |+| cursor trace | recorded positions + click events | rendered **synthetically** (drawn each frame from data, not baked into pixels) |+| audio | mic / system | waveform peaks shown in the timeline UI |+| transcript | whisper-generated timed text | becomes captions |++**Timeline edits (the document):**++- **cuts** — remove time ranges+- **speed regions** — e.g. 3× (audio is time-stretched with WSOLA so pitch is preserved)+- **zoom regions** — animated zoom-in, eased and spring-smoothed, optional auto-focus that pans with the cursor+- **camera-fullscreen regions** — the webcam grows to cover the stage+- **captions** — timed text with progressive reveal (words appear as spoken)+- **annotations** — `text | image | blur` regions, with arrows++**Per-frame appearance (all deterministic given the document and a time `t`):**++- layout presets (picture-in-picture, vertical-stack), padding that reveals the background+- background: solid colour, gradient, or image; optional blur+- rounded corners + mask on the screen video; webcam mask in several shapes+- drop shadow under the video (intensity-scaled, soft cascaded falloff)+- motion blur on fast camera moves, and on the cursor+- cursor click-bounce and shadow+- optional 3D rotation of the foreground+- webcam shrinks reactively during zooms++**Sinks (outputs):**++- **preview** — the editor viewport: scrubbing, playback, live tweaking+- **MP4 export** — H.264 + AAC, reference target 1080p 60 fps+- **GIF export** — exists today (`src/lib/exporter/gifExporter.ts`)+- plausible future: HEVC/AV1 export++### 3. Primer — the vocabulary of this document++Skip if you know real-time graphics. Everything later depends on these five ideas.++**Frame budget.** A 60 fps video has one frame every 16.7 ms. Export doesn't need to hit 60 fps in real time — it can run as fast as the machine allows — so the metric is *milliseconds per frame*, and fps = 1000 / ms:++```+ms/frame : 4.7 9.0 16.7 20.7 54.0 125+fps : 213 111 60 48 18.5 8+ ▲ ▲ ▲ ▲+ encoder realtime today's where this+ alone playback pipeline project started+```++**GPU vs CPU, and "the descent".** Video frames are big: one 1080p RGBA frame is 8.3 MB; at 60 fps that's ~500 MB/s of pixels. GPUs handle this easily *as long as the pixels stay in GPU-managed memory*. Copying a frame from GPU to CPU memory ("readback", or in this doc **the descent**) is slow — not because of raw bandwidth, but because reading pixels back forces the GPU to **finish all queued work first** (a pipeline stall). The single most important measured fact in this project: *forcing every frame to descend to CPU RAM costs more than the entire rest of the export combined* (§7).++**Asynchronous GPU APIs — the trap this project fell into three times.** When code calls a draw function, the GPU hasn't drawn anything yet — the call just *queues* work and returns immediately. The work actually executes later, and its cost lands on **whichever operation first needs the result** (the "sync point"). Consequence: a timer around a draw call measures ~0 ms even if the draw costs 15 ms, and the 15 ms shows up in some *other* stage's timer. Three confident wrong conclusions in this project came from exactly this (§7.4).++**Compositing.** Assembling the final frame from its parts: draw the background, the shadow, the masked screen video, the webcam bubble, the cursor, the captions — in order, into one image. This can be done with the 2D canvas API (CPU-flavoured, easy, slow) or with GPU shaders (one program that computes every output pixel in parallel).++**Encoding.** Compressing raw frames into H.264 (~8.3 MB/frame → ~17 KB/frame at 8 Mbps). Modern chips have a dedicated hardware block for this. In Chromium it's reached through the **WebCodecs** API (`VideoEncoder`); natively through ffmpeg or the OS APIs (Media Foundation, VideoToolbox, VAAPI).++### 4. Hard constraints++- App stays MIT-licensed (no GPL contamination; an LGPL ffmpeg binary pinned by `scripts/fetch-ffmpeg.mjs` exists and is licence-clean, but see §7 — it is currently shelved).+- Windows + macOS + Linux, x64 + arm64.+- The Chromium **sandbox stays on** for anything that demuxes/decodes user media (untrusted input; this is the renderer's attack surface).+- Export output must remain pixel-faithful to the preview.+- App size is not a constraint (≤ ~200 MB per platform is fine).++---++## Part II — The system today, and what was measured++### 5. The current export pipeline++Everything runs in the Chromium renderer process:++```+ ┌─────────┐ ┌──────────────┐ ┌──────────────┐ ┌───────────┐ ┌──────┐+ │ demux │──▶│ decode │──▶│ COMPOSITE │──▶│ encode │──▶│ mux │+ │ (WASM │ │ WebCodecs │ │ Pixi/WebGL │ │ WebCodecs │ │ mp4 │+ │ ffmpeg) │ │ VideoDecoder │ │ + 4× Canvas2D │ │ VideoEnc. │ │(JS) │+ └─────────┘ │ (hardware) │ │ + 2nd WebGL │ │ (hardware) │ └──────┘+ └──────────────┘ └──────────────┘ └───────────┘+ ▲ this box is the problem+```++Audio is decoded, WSOLA-stretched per speed region, AAC-encoded, and muxed by timestamp. It never touches the pixel path — keep it that way.++**The composite box in detail** (`src/lib/exporter/frameRenderer.ts`). The frame walks across **six surfaces and two independent GL contexts** per frame:++```+ Pixi/WebGL (GL#1) Canvas2D surfaces+ ┌────────────────┐+ VideoFrame ───▶│ video sprite │+ │ + zoom + mask │──drawImage──▶ shadowCanvas ──▶ foregroundCanvas+ │ + motion blur │ (3× gaussian │ + webcam+ └────────────────┘ drop-shadow!) │ + cursor+ │ + annotations+ threeDPass (GL#2, own context) ◀──texImage2D──────────────────────┤ (if 3D)+ │ rotate quad │+ └──drawImage back─────────────────────────────────────────▶ ▼+ compositeCanvas+ wallpaper ──▶ (final; wallpaper+ re-blurred re-drawn every+ every frame frame)+ │+ new VideoFrame(canvas)+ ▼+ encoder+```++**The preview is a *different* compositor** (`src/components/ai-edition/preview-compositor/PreviewCompositor.tsx`): Pixi composites *only* the screen recording; the **webcam stays a plain `<video>` DOM element** with its own sync logic; the cursor is a separate DOM layer that measures the sibling `<video>`. Preview/export parity is maintained **by hand across two divergent implementations** — it is a discipline today, not a property.++### 6. The measurement record++All on the reference machine: Ryzen 5 7520U laptop, integrated AMD Radeon GPU, Windows 11. This is deliberately the *weak* case. (Caveat: it is also the *only* fully-measured machine.)++**Bench methodology** (`npm run bench:export`): opens the real editor window, loads a real saved project, calls the real export entry point. Arms interleave A/B/A/B; same-arm spread is reported; a run above 10 % spread declares itself VOID. Two earlier runs were discarded because battery/thermal drift (up to 62 % spread) *inverted the conclusion* — treat any un-gated benchmark on this hardware as noise.++**M1 — the starting point.** Export ran at **~8 fps** (94.6 s for a 9.1 s clip). 90 % of wall time sat in `encodeWait` (blocked on the encoder queue). Conclusion drawn at the time: *"the encoder is the wall."* (Wrong — see §7.4.)++**M2 — native ffmpeg, fed from the renderer.** A bundled LGPL ffmpeg with the AMD hardware encoder (`h264_amf`) measured **165 fps** encoding pre-materialised frames. So it was wired in: composite in the renderer → copy pixels to CPU → IPC to the main process → pipe into ffmpeg. Result, end-to-end, same project:++| arm | wall | fps | readback time |+|---|---:|---:|---:|+| WebCodecs (status quo) | 38.5 s | **36.9** | 0.16 s |+| native ffmpeg | 80.8 s | 17.5 | **55.2 s** |++**2.1× slower.** ffmpeg itself consumed frames *faster* than WebCodecs (`encodeWait` −29 %) — the loss is entirely the **descent**: `copyTo()` measured 1.43 ms in an isolated probe, but **38.9 ms** inside the real loop (the probe hit an idle GPU; the loop forces a pipeline stall — see "the trap", §3).++**M3 — the ceiling arm.** To bound *every* "make the crossing cheaper" idea at once (removing the sandbox, shared memory, zero-copy IPC): descend every frame and **throw it away** — no IPC, no encoder, no muxer, no audio. Result: **40.5 fps**, vs **44.0 fps** for WebCodecs *doing the whole export including writing the file*. The descent alone, with nothing behind it, loses to the complete shipping pipeline. Every architecture that routes frames through renderer CPU RAM is dead on this machine, and none of them had to be built.++**M4 — the layer bench.** Rebuild the pipeline layer by layer and measure each addition:++| layer | fps | ms/frame | Δ ms |+|---|---:|---:|---:|+| L0 — decode + encode only | **213** | 4.7 | — |+| L1 — + flat background, scale, webcam | 111 | 9.0 | **+4.3** |+| L2 — + wallpaper image | 75 | 13.3 | **+4.3** |+| L4 — + rounded corners | 68 | 14.7 | +1.4 |+| L5 — + drop shadow | 53 | 18.9 | **+4.2** |+| L6 — + circular webcam mask | 52 | 19.2 | +0.3 |+| L7 — + animated zoom | *not yet measured* | | |++Read the first row again. **The full WebCodecs decode→encode loop runs at 213 fps** on this machine. The encoder was never slow.++### 7. What the measurements mean++#### 7.1 The wall was the compositor all along++```+compositing (L1→L6): 14.5 ms+encoder (h264_amf, alone): 6.1 ms+ ───────+ 20.6 ms → 48.5 fps+observed WebCodecs export: 20.7 ms → 48.4 fps ← the numbers close+```++Why it hid: `new VideoFrame(canvas)` is lazy and `encoder.encode()` is the first operation that forces the GPU/canvas work to finish (`src/lib/exporter/videoExporter.ts:477–519`). So the compositor's 14.5 ms was **billed to the encoder's timer**. The `render` timer (1.7 ms) measured *submission*, not execution.++> **Gate G0 — run this before implementing anything else in this document.**+> Insert a fence (`gl.finish()` or equivalent) after compositing, *before* the `encodeWait` timer starts. If `encodeWait` collapses from ~18.9 ms to ~6 ms, §7.1 is confirmed. If it does not, this document's premise is wrong — stop and re-derive. (~10 lines.)++#### 7.2 Where the 14.5 ms goes — and why it's recoverable++The three +4 ms layers are not paying for content; each opens a **full-frame Canvas2D operation on static or geometry-only data**:++| cost | what actually happens | why it's waste | site |+|---|---|---|---|+| +4.2 ms | **three chained gaussian `drop-shadow` filters over 2.07 Mpx of video, every frame** | `drop-shadow` reads only the alpha channel. The video is opaque and masked by a rounded rect — its alpha *is* the rounded-rect silhouette. The result depends only on `(x, y, w, h, radius, intensity)`, not on a single video pixel. | `frameRenderer.ts:1045` (dup at `:533`) |+| +4.3 ms | **the wallpaper — a static image — is cleared, re-blurred (`blur(6px)`) and re-blitted every frame** | it never changes; blur it once at init | `frameRenderer.ts:1007–1017` |+| +4.3 ms (L1) | a `BlurFilter` that is **always zero** (all four writes to `.blur` in the export path set 0) sits permanently in `videoContainer.filters`, forcing Pixi into render-to-texture + a full-screen pass per filter, per frame; plus a GL texture is created and destroyed per frame | dead filter; texture churn | `frameRenderer.ts:235/238/240`, `:409–415` |++Also rebuilt per frame for no reason: the mask tessellation (`:769–771`). The correct patterns already exist elsewhere in the same tree: conditional filter attachment in `pixiCursorRenderer.ts:568`; texture reuse in `threeDPass.ts`.++#### 7.3 Verdicts on the previously-considered options++| option | verdict | why |+|---|---|---|+| WebCodecs pipeline | **stays — fastest path measured** | M2/M3 |+| native ffmpeg fed from the renderer | **dead** | M2: ×0.48 |+| `sandbox: false` + direct pipe to ffmpeg | **dead** | M3 bounds it; also sacrifices the sandbox for ~1.2× on one leg |+| GPU→NV12 packing to shrink the descent | **withdrawn** | best case parity, against a compositor about to get 3× faster |+| full Tauri/Rust rewrite ("option C") | **deferred, gated** | its premise (composited texture → encoder with zero descent, via wgpu↔D3D11/VideoToolbox interop) is *unmeasured*; spike required before any migration (§12) |++#### 7.4 The trap, named once for the whole document++**An isolated component benchmark cannot price the cost of connecting the component.** Three confident wrong answers came from probes that didn't force the work the real loop forces: the pipe probe (489 MB/s "≈3 %" — frames materialised outside the loop), the `copyTo` probe (1.43 ms idle vs 38.9 ms in-loop), and the `render` timer (1.7 ms submission vs 14.5 ms execution). Any new benchmark an agent writes for this project must answer: *what sync point am I including, and does the real loop include the same one?*++---++## Part III — The target architecture++### 8. Three structural conclusions++**(a) The frame is a pure function.** Every §2 appearance feature is deterministic given `(document, t)`. So extract:++```+evaluate : (Document, t) → FrameState+FrameState = { sourceTimes, rects, transforms, velocity, maskParams,+ shadowGeom, activeCaptions, annotations }+```++CPU, microseconds, testable without a GPU. **Parity lives here**: preview and export call the *same* `evaluate`, so they cannot drift on layout, easing, timing, or reveal logic. (The geometry code already exists, smeared across `compositeLayout.ts`, `zoomTransform.ts`, `updateAnimationState` — this is an extraction, not a rewrite.)++**(b) The compositor is tiny.** The entire feature set compiles to:++```+4 textures screen · webcam · background · glyph/annotation atlas+1 uniform block ~200 bytes: rects, matrices, velocity, radii, shadow+ params, mask selector, reveal progress+2 passes P1: directional motion blur (only when |velocity| > 0)+ P2: composite — one draw call+ (P3: 3D rotation — folds into P2's vertex stage)+caches wallpaper 1× · shadow per-geometry · masks per-shape ·+ caption rasters per-segment · cursor sprites 1×+```++Any 2015-class GPU runs this in **< 2 ms** at 1080p. Compositing cost therefore justifies **no** stack choice. Text is the one thing that stays CPU-rasterised (glyphs → offscreen → texture, cached per segment, raster only the caption's ~1920×200 rect).++**(c) Only two seams matter.** With (a) at ~0 ms and (b) at ≤2 ms, the architecture is decided by two data handoffs:++```+S1 : decoded frame ──▶ compositor texture (decode → GPU)+S2 : composited target ──▶ encoder (GPU → encode)+```++Every measured disaster in §6 happened at a seam. **Design rule: both seams stay on the GPU device and are crossed exactly once per frame.** The web platform's S1 (`VideoFrame` → texture import) and S2 (`VideoFrame(canvas)` → `VideoEncoder`) are the designed fast paths and are what L0's 213 fps already includes.++### 9. The reference diagram++```+┌──────────────────────────────────────────────────────────────────┐+│ UI shell — timeline, panels, inspector (React/DOM) │+│ never touches pixels │+└──────────────┬───────────────────────────────────────────────────┘+ │ edits (pure data operations)+┌──────────────▼───────────────┐+│ Document store │ atomic writes: temp + rename,+│ undo/redo = data │ serialised saves (§13 — bug)+└──────────────┬───────────────┘+ │ (Document, t)+┌──────────────▼───────────────┐ ┌───────────────────────────┐+│ EVALUATOR — pure CPU fn │ │ AUDIO ENGINE │+│ (Document, t) → FrameState │ │ decode · WSOLA · mix │+└──────────────┬───────────────┘ │ playback: MASTER CLOCK │+ │ uniforms │ export: AAC → mux │+┌──────────────▼───────────────┐ └─────────────┬─────────────┘+│ MEDIA I/O │ │+│ demux · HW decode · seek │ │+│ decode-ahead ring S1 │ │+└──────────────┬───────────────┘ │+ │ GPU-resident textures │+┌──────────────▼───────────────┐ │+│ COMPOSITOR — one WGSL prog │ │+│ P1? · P2 · (P3) + caches │ │+└──────┬───────────────┬───────┘ │+ │ swapchain │ offscreen S2 │+┌──────▼──────┐ ┌─────▼───────────┐ │+│ PREVIEW │ │ ENCODER │◀── mux by ─────┘+│ vsync/rAF │ │ HW, pipelined, │ timestamp+│ viewport │ │ queue depth ≥ 2 │+└─────────────┘ └─────────────────┘+```++Sinks differ by **three parameters only** — target, clock, resolution:++| sink | target | clock | resolution |+|---|---|---|---|+| preview | swapchain | display (rAF/vsync) | viewport |+| MP4 | offscreen texture | frame index | output |+| GIF | offscreen texture | frame index (low fps) | output (+ palette pass) |++One pixel path, N sinks ⇒ the "two divergent compositors" problem of §5 becomes *unconstructible*. This also means the unified compositor must absorb the **preview's** webcam and cursor (currently DOM), not just the export path.++### 10. Preview fluidity — priority 1, engineered as three separate problems++| mode | requirement | mechanism |+|---|---|---|+| **tweak** — drag a slider, move the webcam | ≤ 1 frame latency at display Hz | parameter changes are **uniform-only**: no re-layout, no re-decode, no cache invalidation except the touched cache (shadow on geometry change). Redraw = pass P2 alone ⇒ 120 Hz is trivial |+| **play** | 60 fps with A/V lock | audio is the master clock; decode-ahead ring of 3–4 frames per stream; late *video* frames drop, audio never skips |+| **scrub** | perceived-instant seek | (a) keyframe-aware seek + decode-forward; (b) a **pre-generated low-res proxy strip** (thumbnail keyframes every N ms) displayed instantly while the exact frame decodes; (c) seek coalescing — only the last requested time is decoded |++The proxy strip is the one genuinely new component: screen recordings have long GOPs, so exact-seek latency is decode-bound and irreducible — the proxy is what makes scrubbing *feel* instant anyway. No prior spec addressed scrubbing at all.++### 11. Export speed — priority 2++With both seams on-device and the compositor ≤2 ms, the pipeline is **encoder-bound by construction** — the correct steady state. Pipeline, don't await: keep encoder queue depth ≥ 2; never sync the device per frame; the only backpressure is the encoder's own.++Projection on the weakest measured machine: 213 fps encoder ceiling ⇒ a 546-frame export in **~2.6–3.3 s** (vs 94.6 s at the start of this project, ×30). Parallel GOP-segment encoding stays in the drawer — at 213 fps it buys nothing at 1080p.++### 12. Stack — decided last, and made reversible++Evaluated against the seams, the three preview modes, one-compositor parity, a small OSS team, and full platform coverage:++| candidate | seams | verdict |+|---|---|---|+| **A. Web platform done right** (Electron, one WebGPU context, WebCodecs) | S1+S2 measured at 213 fps — *faster than the native encode leg (165 fps) on the same machine* | **launch host** |+| B. Rust core (wgpu) + Tauri webview UI | S2 better in principle (texture → AMF/VideoToolbox directly), **but** a new seam appears — composited frames must reach the webview viewport — and the wgpu(D3D12)↔AMF(D3D11) interop is unmeasured | open, behind a spike gate |+| C. Full native per platform | optimal seams, three compositors, three CI matrices | eliminated on cost for this team, not on merit |++**The reversibility mechanism — the one instruction that shapes code written today:**++> **Write the compositor in WGSL (WebGPU), not GLSL/Pixi. Keep `evaluate` pure and host-agnostic.**++WGSL runs unmodified in the browser (WebGPU) *and* natively (wgpu). The evaluator and the shader — the product's actual substance — become portable by construction. Only the shell, the Media I/O bindings and the encoder binding are host-locked. Electron-vs-Tauri stops being an architectural bet and becomes a bindings swap behind pre-committed triggers:++| gate | trigger | response |+|---|---|---|+| G-A | after the §8b compositor ships, export < 100 fps on the reference machine *and* profiling pins the loss inside Chromium's S1/S2 | run the B spike: wgpu renders a triangle → native texture handle → AMF → mp4 (~200 lines, no compositor, no UI). If the handoff holds, move Media I/O + encode to a Rust core; WGSL + evaluator move unchanged |+| G-B | tweak mode can't hold display Hz with uniform-only updates | same |+| G-C | a platform ships hardware codecs Chromium won't expose | per-codec encoder *sidecar* — no host change |+| none | — | host question stays closed |++### 13. Ship order++**Step 0 — the data-loss bug, before any of this.** `writeProject` (`src/lib/.../document-service.ts`) allows two concurrent saves to interleave (`O_TRUNC` + offset writes), which has already destroyed a real project file (valid JSON prefix + tail of a longer version; effects unrecoverable). Fix: serialise saves + atomic write (temp file + rename). Audit every writer in the file. **A performance spec is worthless next to projects that destroy themselves on save.**++**Step 1 — G0** (§7.1): the fence. 10 lines. If it fails, stop.++**Step 2 — exact fixes, ~50 lines total, byte-identical output, no parity review** (details §7.2):++| fix | site |+|---|---|+| pre-blur wallpaper at init; per-frame draw = plain blit with `globalCompositeOperation='copy'` | `frameRenderer.ts:1007–1017` |+| shadow: render the same 3-filter chain **once per geometry** onto a white rounded-rect silhouette, cache by `(rect, radius, intensity)`, per-frame = 2 `drawImage` | `:1045` (and `:533`) |+| delete the always-zero `BlurFilter`; attach `motionBlurFilter` only when `velocity > 0` (pattern: `pixiCursorRenderer.ts:568`) | `:235/238/240` |+| reuse one GL texture, stop create/destroy per frame (pattern: `threeDPass.ts`) | `:409–415` |+| rebuild mask only on layout change | `:769–771` |++Do **not** replace the shadow with an SDF/`smoothstep` approximation: the cascaded falloff is exact-cached instead, because this codebase has already been burned twice by shadow-falloff/corner-AA approximations (see the comments in `threeDPass.ts`).++Projected result: 14.5 → ~4 ms compositing ⇒ **~90 fps export**, still inside Electron, zero architecture change. *Projection, not measurement* — hence:++**Step 3 — measure.** Re-run the layer bench (G1). Measure **L7 (animated zoom)** — the missing row — because it decides everything downstream: the shadow cache misses during zooms (geometry changes every frame), so the fraction of zoomed frames determines whether Step 4 exists.++- zoom frames ≲ 20 % of a typical timeline → the cache captured ~90 % of the win → **stop here**; ship+- zoom frames ≳ 50 % → the per-frame shadow is still the wall where it matters → Step 4++Also owed: one bench run on a discrete GPU and on Intel QSV (G3) — every number in this document is from a single iGPU laptop.++**Step 4 (conditional) — the unified WGSL compositor** (§8b + §9): one context, two passes, caches; absorbs the preview's webcam + cursor; text via cached atlas textures. Built inside Electron/WebGPU, where a working baseline exists to measure against — and where the WGSL is already the portable artifact if gate G-A ever fires.++**Step 5 (gated) — host swap**, only if a §12 gate fires, only after its spike passes.++### 14. Non-goals++Audio internals (WSOLA/AAC/sync — orthogonal, untouched) · cuts & speed regions (they select source frames; not compositing) · the `.axcut` document format · the React shell · HEVC/AV1 (behind the sink decision) · parallel segment encoding (nothing to gain at current ceilings).++---++*Provenance: every number in Part II is a gated measurement on the reference machine; §7.1's closing arithmetic is a deduction with G0 as its named falsifier; the 213-fps-beats-165-fps comparison is same-machine, same-frames. The two prior specs' full measurement reports remain the source of record for methodology details.*diff --git a/electron/media/ffmpegExportIpc.ts b/electron/media/ffmpegExportIpc.tsindex a9598f53d..ce82342fb 100644--- a/electron/media/ffmpegExportIpc.ts+++ b/electron/media/ffmpegExportIpc.ts@@ -12,9 +12,14 @@ import {* IPC surface for the native export encoder.** The renderer composites and extracts frames but cannot spawn ffmpeg — it is- * sandboxed and stays that way (see docs/architecture/native-core-tauri-spec.md- * §3.2: dropping the sandbox buys ~2x and costs the lock that guards- * user-supplied media). So frames cross here and main feeds ffmpeg's stdin.+ * sandboxed and stays that way. Dropping the sandbox (option A') was measured+ * and buys nothing: with the crossing at exactly zero the pipeline still loses+ * to WebCodecs, because the wall is the compositor, not this path. See+ * docs/architecture/export-pipeline.md §5.+ *+ * This whole path is REFUTED (§5): feeding native ffmpeg from the renderer is+ * 2.1x SLOWER than what we ship. It survives as bench scaffolding, not as a+ * plan.** Frames are `send`, not `invoke`: they are one-way and there is nothing to* return. Flow control is the renderer's credit window (8 frames in flight),diff --git a/scripts/fetch-ffmpeg.mjs b/scripts/fetch-ffmpeg.mjsindex d03a1090b..1e91f0896 100644--- a/scripts/fetch-ffmpeg.mjs+++ b/scripts/fetch-ffmpeg.mjs@@ -28,10 +28,14 @@// we got before vendoring. Never swap in a "gpl" asset for the extra encoders:// there is nothing in them we need — the hardware encoders are all LGPL.//-// macOS: BtbN publishes no macOS target, so darwin is not handled here. It has-// to be built and notarised separately — see docs/architecture/-// export-pipeline-v2-spec.md, Phase 3. Native encode ships on all three-// platforms; there is no "macOS keeps WebCodecs" option.+// NOTE: the plan this was vendored for is REFUTED. Feeding native ffmpeg from+// the renderer measured 2.1x SLOWER than the WebCodecs path it was to replace —+// the wall is the compositor, not the encoder. See+// docs/architecture/export-pipeline.md §5. The binary stays because the bench's+// `native` arms use it, and because a future native core would still need a+// licence-gated H.264 encoder; nothing here ships on the export path today.+//+// macOS: BtbN publishes no macOS target, so darwin is not handled here.import { spawnSync } from "node:child_process";import crypto from "node:crypto";@@ -205,8 +209,8 @@ async function main() {if (process.platform === "darwin") {console.error("macOS is not provisioned by this script: BtbN publishes no macOS build.\n" +- "It must be built and notarised separately (docs/architecture/export-pipeline-v2-spec.md,\n" +- "Phase 3). A VideoToolbox-only build is inherently x264-free, so the LGPL gate is easy there.",+ "It would have to be built and notarised separately. Note the native-encode plan\n" ++ "is refuted (docs/architecture/export-pipeline.md §5), so this is bench-only today.",);process.exit(1);}diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.tsindex e3f27fe94..81da1c6a7 100644--- a/src/lib/exporter/videoExporter.ts+++ b/src/lib/exporter/videoExporter.ts@@ -88,18 +88,20 @@ function nativeEncodeEnabled(): boolean {}/**- * Diagnostic: extract every frame to RAM, then throw it away.+ * Diagnostic: extract every frame to RAM, then throw it away. Writes no file.*- * Produces no video — it measures the CEILING of any architecture that gets- * pixels to the CPU, by pricing the descent with the crossing set to exactly- * zero. That bounds every "remove the crossing" proposal at once — option A'- * (sandbox:false, spawning ffmpeg from the renderer), shared memory, a- * transferable that Electron won't transfer — without building any of them,- * because none of them can avoid the readback: ffmpeg needs the pixels in RAM- * whoever spawns it.+ * Pairs with compositeOnly, and the PAIR is the point: this arm is that one plus+ * a full copyTo(), so the difference between them is what the descent actually+ * costs. Measured: 0.03 ms/frame — nothing.*- * If this ceiling sits below the WebCodecs arm, every such proposal is dead and- * the only way out is not descending at all (native-core-tauri-spec.md).+ * That result bounds every "remove the crossing" proposal at once (option A'+ * sandbox:false, shared memory, a transferable Electron won't transfer) without+ * building any of them — but not for the reason this arm was built. It was built+ * to price the descent; it proved there is nothing there to price, and that the+ * 32 seconds previously blamed on readback were the compositor finishing its GPU+ * work at the first stage that forced a sync.+ *+ * See docs/architecture/export-pipeline.md §3.** localStorage.setItem("openscreen.dropFrames", "1")*/