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
feat(bench): a headless export bench — the measurements that exclude options A and A'
Etienne Lescot32b4191c49f1
diff --git a/docs/architecture/export-native-encode-measurement.md b/docs/architecture/export-native-encode-measurement.mdnew file mode 100644index 000000000..b9309680d--- /dev/null+++ b/docs/architecture/export-native-encode-measurement.md@@ -0,0 +1,236 @@+# 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. 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?** That is the load‑bearing assumption of the whole native‑core case, and it is currently unmeasured. It should be prototyped and benched *before* committing to a Tauri 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.diff --git a/docs/architecture/export-pipeline-v2-spec.md b/docs/architecture/export-pipeline-v2-spec.mdindex f3f6a9843..7ac2e6b6c 100644--- a/docs/architecture/export-pipeline-v2-spec.md+++ b/docs/architecture/export-pipeline-v2-spec.md@@ -1,6 +1,20 @@# Export Pipeline v2 — Multi‑Asset Rendering + PerformanceStatus: **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 teamScope: the `.axcut` (AI‑edition) export path only. The legacy `components/video-editor` exporter is out of scope.@@ -287,7 +301,16 @@ Each phase is independently shippable and independently verifiable.- 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** ← *next*+### 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.@@ -310,7 +333,15 @@ Replace the WebCodecs encoder + JS muxer with a bundled LGPL ffmpeg subprocess (- **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)+### 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.diff --git a/docs/architecture/native-core-tauri-spec.md b/docs/architecture/native-core-tauri-spec.mdindex 9af38b01d..410440c2e 100644--- a/docs/architecture/native-core-tauri-spec.md+++ b/docs/architecture/native-core-tauri-spec.md@@ -4,6 +4,26 @@ Status: **Exploratory / for decision.** This is a product-architecture proposal,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 existsdiff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex 4d0366ecb..79937b14d 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -27,6 +27,8 @@ interface Window {invokeNativeBridge: <TData = unknown>(request: import("../src/native/contracts").NativeBridgeRequest,) => Promise<import("../src/native/contracts").NativeBridgeResponse<TData>>;+ /** Export bench only (--bench=): tells main the run is over so it can quit. */+ benchFinished?: () => Promise<void>;getSources: (opts: Electron.SourcesOptions) => Promise<ProcessedDesktopSource[]>;switchToEditor: () => Promise<void>;switchToHud: () => Promise<void>;diff --git a/electron/main.ts b/electron/main.tsindex 676d4ad51..199782072 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -657,5 +657,19 @@ appReady?.then(async () => {await loadAndRegisterGlobalShortcut(showMainWindow);+ // --bench=<query>: run the export bench instead of the app. Opens the real+ // editor window (same webPreferences, same preload) pointed at the bench+ // entry, and quits when it reports back. See src/bench/runBench.ts.+ const benchArg = process.argv.find((a) => a.startsWith("--bench="));+ if (benchArg) {+ ipcMain.handle("bench:finished", () => {+ // Let the reply reach the renderer before the process goes away.+ setTimeout(() => app.exit(0), 100);+ });+ const query = Object.fromEntries(new URLSearchParams(benchArg.slice("--bench=".length)));+ mainWindow = createEditorWindow({ ...query, windowType: "bench" });+ return;+ }+createWindow();});diff --git a/electron/media/ffmpegExportService.ts b/electron/media/ffmpegExportService.tsindex 4481ba001..5ab2bb706 100644--- a/electron/media/ffmpegExportService.ts+++ b/electron/media/ffmpegExportService.ts@@ -22,7 +22,15 @@ import { type FfmpegEncodeSession, startFfmpegEncodeSession } from "./ffmpegEnco*/export interface StartExportRequest {- outputPath: string;+ /**+ * Omit to have main write to a temp file and return the path.+ *+ * The renderer is sandboxed and does not get to name a path main will write+ * to — that would hand a compromised renderer an arbitrary file write. A+ * user-chosen destination must come from a main-side save dialog, and the+ * finished temp file is moved there.+ */+ outputPath?: string;width: number;height: number;frameRate: number;@@ -35,6 +43,8 @@ export interface StartExportRequest {export interface StartExportResult {sessionId: string;encoder: VideoEncoderId;+ /** Where ffmpeg is actually writing — main's choice when the caller omitted one. */+ outputPath: string;}/** Resolved once per process: the probe costs a few spawns, the answer never changes. */@@ -130,6 +140,8 @@ let nextId = 1;export async function startExport(req: StartExportRequest): Promise<StartExportResult> {const { ffmpegPath, encoder } = await resolveExportCapabilities();+ const sessionId = `export-${nextId++}`;+let audioPath: string | null = null;let tmpDir: string | null = null;if (req.audio && req.audio.pcm.byteLength > 0) {@@ -140,10 +152,14 @@ export async function startExport(req: StartExportRequest): Promise<StartExportRawait fs.writeFile(audioPath, Buffer.from(req.audio.pcm));}+ // Deliberately NOT inside tmpDir: dispose() wipes that, and the output has to+ // outlive the session so it can be moved to the user's destination.+ const outputPath = req.outputPath ?? path.join(os.tmpdir(), `openscreen-${sessionId}.mp4`);+const session = startFfmpegEncodeSession({ffmpegPath,encoder,- outputPath: req.outputPath,+ outputPath,width: req.width,height: req.height,frameRate: req.frameRate,@@ -160,9 +176,8 @@ export async function startExport(req: StartExportRequest): Promise<StartExportR: undefined,});- const sessionId = `export-${nextId++}`;sessions.set(sessionId, { session, audioPath, tmpDir });- return { sessionId, encoder };+ return { sessionId, encoder, outputPath };}function requireSession(sessionId: string): LiveSession {diff --git a/electron/preload.ts b/electron/preload.tsindex a756d94d4..667f4ba0d 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -30,7 +30,11 @@ contextBridge.exposeInMainWorld("electronAPI", {exportCapabilities: () =>ipcRenderer.invoke("export:capabilities") as Promise<{ encoder: string }>,exportStart: (req: unknown) =>- ipcRenderer.invoke("export:start", req) as Promise<{ sessionId: string; encoder: string }>,+ ipcRenderer.invoke("export:start", req) as Promise<{+ sessionId: string;+ encoder: string;+ outputPath: string;+ }>,exportWriteFrame: (sessionId: string, frame: ArrayBuffer) => {// send() structured-clones, i.e. copies the frame. That is not an oversight// and it is not fixable here: Electron's transfer list takes MessagePort[]@@ -49,6 +53,8 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("export:finish", sessionId) as Promise<{ outputPath: string }>,exportCancel: (sessionId: string) =>ipcRenderer.invoke("export:cancel", sessionId) as Promise<void>,+ /** Export bench only (--bench=): tells main the run is over so it can quit. */+ benchFinished: () => ipcRenderer.invoke("bench:finished") as Promise<void>,invokeNativeBridge: <TData>(request: NativeBridgeRequest) => {return ipcRenderer.invoke(NATIVE_BRIDGE_CHANNEL, request) as Promise<TData>;},diff --git a/electron/windows.ts b/electron/windows.tsindex a421f4add..99ea88744 100644--- a/electron/windows.ts+++ b/electron/windows.ts@@ -225,8 +225,13 @@ export function createHudOverlayWindow(): BrowserWindow {/*** Main editor window. Starts maximised with a hidden title bar on macOS; not* always-on-top and appears in the taskbar/dock.+ *+ * `query` overrides the renderer's routing params. The export bench passes+ * windowType=bench so it runs under THIS window's webPreferences — same+ * preload, same sandbox, same backgroundThrottling:false — because a bench that+ * configures its own window measures a different app than the one we ship.*/-export function createEditorWindow(): BrowserWindow {+export function createEditorWindow(query: Record<string, string> = {}): BrowserWindow {const isMac = process.platform === "darwin";const win = new BrowserWindow({@@ -281,12 +286,11 @@ export function createEditorWindow(): BrowserWindow {win?.webContents.send("main-process-message", new Date().toLocaleString());});+ const routing = { windowType: "editor", ...query };if (VITE_DEV_SERVER_URL) {- win.loadURL(VITE_DEV_SERVER_URL + "?windowType=editor");+ win.loadURL(`${VITE_DEV_SERVER_URL}?${new URLSearchParams(routing).toString()}`);} else {- win.loadFile(path.join(RENDERER_DIST, "index.html"), {- query: { windowType: "editor" },- });+ win.loadFile(path.join(RENDERER_DIST, "index.html"), { query: routing });}return win;diff --git a/package.json b/package.jsonindex 1c2997772..0f76c1067 100644--- a/package.json+++ b/package.json@@ -52,7 +52,8 @@"test:e2e": "playwright test","test:e2e:windows-native-checklist": "playwright test tests/e2e/windows-native-checklist.spec.ts","prepare": "husky",- "fetch:ffmpeg": "node scripts/fetch-ffmpeg.mjs"+ "fetch:ffmpeg": "node scripts/fetch-ffmpeg.mjs",+ "bench:export": "node scripts/bench-export.mjs"},"dependencies": {"@fix-webm-duration/fix": "^1.0.1",diff --git a/scripts/bench-export.mjs b/scripts/bench-export.mjsnew file mode 100644index 000000000..1e1223877--- /dev/null+++ b/scripts/bench-export.mjs@@ -0,0 +1,275 @@+#!/usr/bin/env node+/**+ * Export bench runner: one command, real pipeline, numbers on stdout.+ *+ * npm run bench:export -- --project=os_parity --arms=webcodecs,native --runs=3+ *+ * Drives the app's own export path (see src/bench/runBench.ts) inside a real+ * Electron window, so the GPU, the sandbox, the preload and the main-process+ * ffmpeg are all the ones we ship. It exists because driving this through the+ * UI cost ~5 minutes a run and kept injecting confounds.+ *+ * Assumes a vite dev server is already up (npm run dev with NO_ELECTRON=1).+ */++import { spawn, spawnSync } from "node:child_process";+import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const DEV_URL = process.env.VITE_DEV_SERVER_URL ?? "http://localhost:5199/";++function parseArgs(argv) {+ const out = {};+ for (const arg of argv) {+ const m = /^--([^=]+)=(.*)$/.exec(arg);+ if (m) out[m[1]] = m[2];+ }+ return out;+}++/**+ * A leftover lock DIRECTORY is stale and safe to remove. A leftover PROCESS is+ * not: it holds the real single-instance lock, and the bench launch then exits 0+ * having done nothing — a silent no-op that looks like a bench bug. Detect it+ * and say so rather than deleting someone's running app.+ */+function checkSingleInstance() {+ const lock = path.join(os.tmpdir(), `openscreen-single-instance-${os.userInfo().username}.lock`);+ const running = spawnSync("tasklist", ["/FI", "IMAGENAME eq electron.exe", "/NH"], {+ encoding: "utf8",+ });+ if (running.stdout?.includes("electron.exe")) {+ throw new Error(+ "An Electron instance is already running and holds the single-instance lock;\n" ++ "the bench would launch, exit 0 and report nothing. Close the app first.",+ );+ }+ if (existsSync(lock)) rmSync(lock, { recursive: true, force: true });+}++/**+ * Refuse to run against a main bundle older than its sources.+ *+ * vite-plugin-electron rebuilds dist-electron asynchronously, so launching too+ * soon after an edit runs the PREVIOUS main process against the new renderer.+ * This has cost two full debugging detours already: once the export IPC was+ * "not registered" (main predated the handler), once the bench flag did nothing+ * and the app opened its normal HUD instead. Both looked like code bugs. A+ * stale bundle must be a loud error, never a silently different measurement.+ */+function assertFreshMainBundle() {+ const stub = path.join(ROOT, "dist-electron", "main.js");+ if (!existsSync(stub)) throw new Error("dist-electron/main.js missing — start the dev server.");+ const chunkName = /from "\.\/(main-[^"]+)"/.exec(readFileSync(stub, "utf8"))?.[1];+ const chunk = chunkName && path.join(ROOT, "dist-electron", chunkName);+ if (!chunk || !existsSync(chunk)) throw new Error("Cannot resolve the built main chunk.");+ const builtAt = statSync(chunk).mtimeMs;++ let newest = 0;+ let newestFile = "";+ const walk = (dir) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name !== "node_modules") walk(full);+ } else if (entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {+ const m = statSync(full).mtimeMs;+ if (m > newest) {+ newest = m;+ newestFile = path.relative(ROOT, full);+ }+ }+ }+ };+ walk(path.join(ROOT, "electron"));++ if (newest > builtAt) {+ const lag = Math.round((newest - builtAt) / 1000);+ throw new Error(+ `Main bundle is STALE: ${newestFile} changed ${lag}s after ${chunkName} was built.\n` ++ "The bench would measure the previous main process. Let vite finish rebuilding\n" ++ "(watch the dev-server log for 'build started' -> done), then re-run.",+ );+ }+}++/** A dead dev server yields a blank window and a bench that reports nothing. */+async function assertViteUp() {+ try {+ const res = await fetch(DEV_URL, { method: "GET" });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ } catch (error) {+ throw new Error(+ `No vite dev server at ${DEV_URL} (${error.message}).\n` ++ "Start it with NO_ELECTRON=1 (see .claude/launch.json 'vite-dev').",+ );+ }+}++function median(values) {+ const sorted = [...values].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}++/**+ * Spread across an arm's repeats, as a fraction of the median.+ *+ * This is the gate, not a decoration: on this machine two identical runs came+ * out 26% apart while the battery charged, which was enough to invert the+ * comparison. If spread is anywhere near the gap between arms, the run says+ * nothing and must be repeated in a steadier state.+ */+function spread(values) {+ if (values.length < 2) return 0;+ const m = median(values);+ return m === 0 ? 0 : (Math.max(...values) - Math.min(...values)) / m;+}++function report(results) {+ const arms = [...new Set(results.map((r) => r.arm))];+ const failed = results.filter((r) => !r.ok);+ for (const f of failed) console.log(` FAILED ${f.arm} run ${f.run}: ${f.error}`);++ const rows = [];+ for (const arm of arms) {+ const runs = results.filter((r) => r.arm === arm && r.ok);+ if (runs.length === 0) continue;+ const walls = runs.map((r) => r.wallMs);+ rows.push({+ arm,+ runs: runs.length,+ wallMs: Math.round(median(walls)),+ fps: +median(runs.map((r) => r.fps)).toFixed(1),+ spread: `${(spread(walls) * 100).toFixed(0)}%`,+ frames: runs[0].frames,+ raw: walls.map((w) => Math.round(w)).join(" / "),+ });+ }+ console.log("\n=== export bench ===");+ console.table(rows);++ const stageKeys = [...new Set(results.flatMap((r) => Object.keys(r.stages ?? {})))];+ const stageRows = stageKeys.map((stage) => {+ const row = { stage };+ for (const arm of arms) {+ const runs = results.filter((r) => r.arm === arm && r.ok && r.stages?.[stage] != null);+ if (runs.length) row[arm] = `${Math.round(median(runs.map((r) => r.stages[stage])))}ms`;+ }+ return row;+ });+ if (stageRows.length) {+ console.log("stage totals (median):");+ console.table(stageRows);+ }++ const worst = Math.max(...rows.map((r) => Number.parseFloat(r.spread)));+ if (worst >= 10) {+ console.log(+ `\n!! Same-arm spread reaches ${worst.toFixed(0)}% — larger than most effects worth\n` ++ " measuring. Treat this run as VOID and repeat on a steady machine.",+ );+ }+ return { rows, worst };+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ const query = new URLSearchParams({+ ...(args.project ? { project: args.project } : {}),+ arms: args.arms ?? "webcodecs,native",+ runs: args.runs ?? "2",+ fps: args.fps ?? "60",+ quality: args.quality ?? "1080p",+ }).toString();++ // Every guard here exists because its absence already produced a confident,+ // wrong answer at least once.+ checkSingleInstance();+ await assertViteUp();+ assertFreshMainBundle();++ const electron = path.join(ROOT, "node_modules", "electron", "dist", "electron.exe");+ if (!existsSync(electron)) throw new Error(`Electron not found at ${electron}`);++ console.log(`bench: ${query}\nvite: ${DEV_URL}`);+ const child = spawn(electron, [".", `--bench=${query}`], {+ cwd: ROOT,+ env: { ...process.env, VITE_DEV_SERVER_URL: DEV_URL },+ stdio: ["ignore", "pipe", "pipe"],+ });++ const results = [];+ let fatal = null;+ let buffer = "";+ // The app's own stdout/stderr, kept so a failure can show WHY. Dropping it+ // once cost a long detour: listProjects was warning that it had skipped the+ // very project being benched, and the runner threw that line away.+ const appLog = [];+ const consume = (chunk) => {+ buffer += chunk;+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ const m = /\[bench\] (\{.*\})\s*$/.exec(line);+ if (!m) {+ if (line.trim()) appLog.push(line);+ // Configuration the exporter reports about itself (which encoder, what+ // the canvas actually granted). Always shown: an arm that silently+ // no-ops must not be mistaken for an arm that was tested and lost.+ const note = /\[export perf\] (canvas .*|native encode .*)$/.exec(line);+ if (note) console.log(` · ${note[1]}`);+ continue;+ }+ let event;+ try {+ event = JSON.parse(m[1]);+ } catch {+ continue; // A truncated line is not worth killing the run over.+ }+ if (event.event === "run") {+ results.push(event);+ const status = event.ok+ ? `${Math.round(event.wallMs)}ms · ${event.frames}f · ${event.fps.toFixed(1)}fps`+ : `FAILED: ${event.error}`;+ console.log(` ${event.arm} run ${event.run}: ${status}`);+ } else if (event.event === "fatal") {+ fatal = event.error;+ } else if (event.event === "start") {+ console.log(` project: ${event.project}`);+ console.log(` arms: ${event.arms.join(", ")} x${event.runs}\n`);+ }+ }+ };+ child.stdout.on("data", (c) => consume(String(c)));+ child.stderr.on("data", (c) => consume(String(c)));++ const code = await new Promise((resolve) => child.on("close", resolve));+ const dumpAppLog = () => {+ const noise = /Electron Security Warning|DevTools|deprecat/i;+ const interesting = appLog.filter((l) => !noise.test(l));+ if (interesting.length) {+ console.error("\n--- app output (tail) ---");+ for (const line of interesting.slice(-25)) console.error(` ${line}`);+ }+ };+ if (fatal) {+ console.error(`\nbench failed: ${fatal}`);+ dumpAppLog();+ process.exit(1);+ }+ if (results.length === 0) {+ console.error(`\nbench produced no results (electron exited ${code}).`);+ dumpAppLog();+ process.exit(1);+ }+ report(results);+}++main().catch((error) => {+ console.error(error);+ process.exit(1);+});diff --git a/src/bench/runBench.ts b/src/bench/runBench.tsnew file mode 100644index 000000000..00f28766a--- /dev/null+++ b/src/bench/runBench.ts@@ -0,0 +1,293 @@+/**+ * Headless export bench — the real pipeline, driven from a command line.+ *+ * Runs inside the app's own editor window (windowType=bench), so it exercises+ * the real preload, the real sandbox, the real GPU and the real main-process+ * ffmpeg. It loads a real saved project and calls exportAxcutDocument, the same+ * entry point ExportDialog uses — nothing about the export path is simulated.+ *+ * Why it exists: driving the export through the UI costs ~5 minutes a run and+ * silently injects confounds (an open DevTools panel handicapped one arm of the+ * first A/B; a window that lost focus stole another). A command gives repeats+ * cheaply, and repeats are what tell drift apart from effect.+ *+ * Deliberately NOT React: the bench replaces the app's UI entirely, so nothing+ * renders alongside the export.+ *+ * npm run bench:export -- --project=os_parity --arms=webcodecs,native --runs=3+ */++import { exportAxcutDocument } from "@/lib/ai-edition/exporter/documentExporter";+import type { AxcutDocument } from "@/lib/ai-edition/schema";+import type { ExportQuality } from "@/lib/exporter";+import { nativeBridgeClient } from "@/native/client";++export interface BenchArm {+ /** localStorage flags applied before the run — the levers under test. */+ nativeEncode: boolean;+ readFrequently: boolean;+ /** Extract every frame and discard it. Diagnostic only — writes no file. */+ dropFrames?: boolean;+}++export interface BenchRunResult {+ arm: string;+ run: number;+ ok: boolean;+ error?: string;+ /** The exporter's frame-loop wall — what the arms are compared on. */+ wallMs: number;+ /** Everything outside the loop (project load, renderer init), reported not compared. */+ setupMs?: number;+ frames: number;+ fps: number;+ /** Per-stage totals in ms, keyed as StageTimings names it. */+ stages: Record<string, number>;+}++const params = new URLSearchParams(window.location.search);++/** The dialog's labels, so the bench is asked for what the UI shows. */+const QUALITY: Record<string, ExportQuality> = {+ "720p": "medium",+ "1080p": "good",+ source: "source",+};++const BENCH_PARAMS = {+ project: params.get("project"),+ arms: (params.get("arms") ?? "webcodecs,native").split(",").filter(Boolean),+ runs: Number(params.get("runs") ?? "2"),+ fps: Number(params.get("fps") ?? "60"),+ // "good" is the dialog's own default, i.e. what the UI A/B measured.+ quality: QUALITY[params.get("quality") ?? "1080p"] ?? "good",+};++const ARMS: Record<string, BenchArm> = {+ // The path we ship today: WebCodecs encodes straight off the GPU texture.+ webcodecs: { nativeEncode: false, readFrequently: false },+ // Frames descend to the CPU and cross to ffmpeg.+ native: { nativeEncode: true, readFrequently: false },+ // Native, but with CPU-backed canvases (what Linux already does) so the+ // per-frame descent is a memcpy rather than a GPU round-trip.+ "native-cpu": { nativeEncode: true, readFrequently: true },+ // Control: isolates the canvas change from the encoder change. Without this+ // arm a native-cpu win could be the canvas, the encoder, or neither.+ "webcodecs-cpu": { nativeEncode: false, readFrequently: true },+ // Ceiling, not a candidate: descend every frame to RAM, then discard it —+ // the crossing costs exactly zero. Bounds EVERY "remove the crossing"+ // proposal at once (option A' sandbox:false, shared memory, zero-copy+ // transfer), because none of them can skip the readback. Writes no file.+ "readback-ceiling": { nativeEncode: true, readFrequently: false, dropFrames: true },+};++function applyArm(arm: BenchArm): void {+ localStorage.setItem("openscreen.nativeEncode", arm.nativeEncode ? "1" : "0");+ localStorage.setItem("openscreen.readFrequently", arm.readFrequently ? "1" : "0");+ localStorage.setItem("openscreen.dropFrames", arm.dropFrames ? "1" : "0");+}++/**+ * aiEdition.get() reports failure as {success:false, error} rather than+ * throwing, so an unchecked read of .document turns every load error into a+ * silent null — which is exactly how "project not found" masked the real reason+ * once already. Surface it.+ */+async function loadDocument(id: string): Promise<AxcutDocument> {+ const result = (await nativeBridgeClient.aiEdition.get(id)) as {+ success?: boolean;+ document?: AxcutDocument;+ error?: string;+ };+ if (!result?.success || !result.document) {+ throw new Error(`Cannot load project ${id}: ${result?.error ?? "no document returned"}`);+ }+ return result.document;+}++/**+ * Accepts a project id, an id prefix, or a title.+ *+ * Titles need care: a summary's title is the name the project was CREATED with+ * ("Recording 15/07/2026 18:38:53") and does not follow a rename, so the one+ * shown in the editor — the document's own project.title — may match nothing in+ * the summary list. Hence the fallback that opens documents to check. It is the+ * slow path on purpose: only reached when the cheap matches miss.+ */+async function resolveDocument(projectRef: string | null): Promise<AxcutDocument> {+ const projects = await nativeBridgeClient.aiEdition.listProjects();+ if (projects.length === 0) throw new Error("No saved projects to bench against");+ if (!projectRef) return loadDocument(projects[0].id);++ const summary =+ projects.find((p) => p.id === projectRef) ??+ projects.find((p) => p.id.startsWith(projectRef)) ??+ projects.find((p) => p.title === projectRef);+ if (summary) return loadDocument(summary.id);++ const failures: string[] = [];+ for (const p of projects) {+ try {+ const doc = await loadDocument(p.id);+ if (doc.project?.title === projectRef) return doc;+ } catch (error) {+ failures.push(error instanceof Error ? error.message : String(error));+ }+ }+ throw new Error(+ `Project "${projectRef}" not found by id, id prefix, or title ` ++ `(${projects.length} searched, ${failures.length} failed to load).` ++ (failures.length ? `\nFirst load failure: ${failures[0]}` : ""),+ );+}++/**+ * Largest source on the timeline — mirrors ExportDialog's referenceSource so+ * "Source" quality picks the same output size the UI would.+ */+function referenceSource(doc: AxcutDocument): { width?: number; height?: number } {+ let best: { width?: number; height?: number } = {};+ let bestArea = 0;+ for (const asset of doc.assets ?? []) {+ const w = asset.video?.width;+ const h = asset.video?.height;+ if (!w || !h) continue;+ if (w * h > bestArea) {+ bestArea = w * h;+ best = { width: w, height: h };+ }+ }+ return best;+}++interface Captured {+ stages: Record<string, number>;+ /** The exporter's own loop numbers, which exclude the bench's setup. */+ loop: { wallMs: number; frames: number; fps: number } | null;+ restore: () => void;+}++/** The perf line the exporter prints is for humans; the bench needs the numbers. */+function captureStages(): Captured {+ const captured: Captured = {+ stages: {},+ loop: null,+ restore: () => {+ console.warn = original;+ },+ };+ const original = console.warn;+ console.warn = (...args: unknown[]) => {+ const text = args.map(String).join(" ");+ if (text.includes("[export perf]")) {+ // "[export perf] wall 77557ms · 546 frames · 7.0 fps"+ const head = /wall\s+([\d.]+)ms\D+(\d+)\s+frames\D+([\d.]+)\s+fps/.exec(text);+ if (head) {+ captured.loop = {+ wallMs: Number(head[1]),+ frames: Number(head[2]),+ fps: Number(head[3]),+ };+ }+ for (const line of text.split("\n")) {+ // " render 1680.0 3.0% 3.08 n=546"+ const m = /^\s*([a-zA-Z]+)\s+([\d.]+)\s+[\d.]+%/.exec(line);+ if (m && m[1] !== "TOTAL") captured.stages[m[1]] = Number(m[2]);+ }+ }+ original(...args);+ };+ return captured;+}++async function runOnce(+ doc: AxcutDocument,+ armName: string,+ arm: BenchArm,+ run: number,+): Promise<BenchRunResult> {+ applyArm(arm);+ const src = referenceSource(doc);+ const capture = captureStages();+ const started = performance.now();+ try {+ const result = await exportAxcutDocument(doc, {+ format: "mp4",+ quality: BENCH_PARAMS.quality,+ frameRate: BENCH_PARAMS.fps,+ codec: "h264",+ sourceWidth: src.width,+ sourceHeight: src.height,+ });+ const wallMs = performance.now() - started;+ // The native arm returns no blob (ffmpeg wrote the file itself), so a+ // missing blob is not a failure here the way it is in ExportDialog.+ if (!result.success) throw new Error(result.error ?? "export failed");+ if (!capture.loop) throw new Error("exporter printed no [export perf] line");+ return {+ arm: armName,+ run,+ ok: true,+ // The exporter's own loop wall, not the bench's: comparing arms means+ // comparing the frame loop, not project loading.+ wallMs: capture.loop.wallMs,+ setupMs: wallMs - capture.loop.wallMs,+ frames: capture.loop.frames,+ fps: capture.loop.fps,+ stages: capture.stages,+ };+ } catch (error) {+ return {+ arm: armName,+ run,+ ok: false,+ error: error instanceof Error ? error.message : String(error),+ wallMs: performance.now() - started,+ frames: 0,+ fps: 0,+ stages: capture.stages,+ };+ } finally {+ capture.restore();+ }+}++/**+ * Interleaves arms rather than running each arm's repeats together: A,B,A,B.+ * Same-arm repeats then bracket the other arm in time, so drift shows up as+ * disagreement between a run and its own repeat instead of masquerading as the+ * effect under test. The first A/B on this machine drifted 26% between two+ * identical runs — enough to invert the conclusion.+ */+export async function runBench(): Promise<void> {+ const results: BenchRunResult[] = [];+ const emit = (event: string, payload: unknown) =>+ // Picked up by the runner off stdout; console.warn is what the app's+ // console forwarder actually relays to the main process.+ console.warn(`[bench] ${JSON.stringify({ event, ...(payload as object) })}`);++ try {+ for (const armName of BENCH_PARAMS.arms) {+ if (!ARMS[armName]) throw new Error(`Unknown arm "${armName}"`);+ }+ // Loaded once and shared by every run: each arm must see byte-identical+ // input, and the title fallback can open every project on disk.+ const doc = await resolveDocument(BENCH_PARAMS.project);+ emit("start", {+ arms: BENCH_PARAMS.arms,+ runs: BENCH_PARAMS.runs,+ project: doc.project?.title ?? "(untitled)",+ });+ for (let run = 1; run <= BENCH_PARAMS.runs; run++) {+ for (const armName of BENCH_PARAMS.arms) {+ const result = await runOnce(doc, armName, ARMS[armName], run);+ results.push(result);+ emit("run", result);+ }+ }+ emit("done", { results });+ } catch (error) {+ emit("fatal", { error: error instanceof Error ? error.message : String(error) });+ }+ await window.electronAPI?.benchFinished?.();+}diff --git a/src/lib/exporter/frameExtract.ts b/src/lib/exporter/frameExtract.tsnew file mode 100644index 000000000..bee21b493--- /dev/null+++ b/src/lib/exporter/frameExtract.ts@@ -0,0 +1,87 @@+/**+ * Pulls composited pixels off the canvas as raw bytes for the native encoder.+ *+ * `new VideoFrame(canvas)` is LAZY — it does not read anything back; the+ * GPU->CPU descent happens inside copyTo(). Timing the constructor measures+ * nothing (that mistake is why the v2 spec originally blamed readback for a+ * cost it does not have).+ *+ * Chromium will only hand us BGRA here: copyTo({format: "NV12"}) throws+ * NotSupportedError. Packing to NV12 on the GPU before extraction is the next+ * step (3.0 MB/frame instead of 7.9, measured ~2x end to end) — see the v2+ * spec's Phase 4.+ */++export interface FrameLayoutPlane {+ offset: number;+ stride: number;+}++/**+ * Raw video has no stride: ffmpeg reads width*4 bytes per row, forever. If+ * Chromium ever pads rows, feeding the buffer through unchanged would skew+ * every frame into diagonal garbage — visibly broken, but only at runtime and+ * only on whatever machine pads. Fail loudly instead.+ */+export function assertTightBgraLayout(+ layout: readonly FrameLayoutPlane[],+ width: number,+ height: number,+ byteLength: number,+): void {+ if (layout.length !== 1) {+ throw new Error(`Expected 1 BGRA plane from the canvas, got ${layout.length}`);+ }+ const plane = layout[0];+ const tightStride = width * 4;+ if (plane.stride !== tightStride) {+ throw new Error(+ `Canvas frame is padded (stride ${plane.stride}, expected ${tightStride}). ` ++ "Raw video cannot carry stride; the frame would be skewed.",+ );+ }+ if (plane.offset !== 0) {+ throw new Error(`Canvas frame plane starts at ${plane.offset}, expected 0`);+ }+ const expected = tightStride * height;+ if (byteLength !== expected) {+ throw new Error(`Canvas frame is ${byteLength} bytes, expected ${expected}`);+ }+}++/**+ * Reusable extraction buffer. The frame is copied by IPC during send(), so the+ * caller may refill this as soon as the sink's write() resolves — which saves+ * allocating (and collecting) ~8 MB per frame.+ */+export class CanvasFrameExtractor {+ private buffer: ArrayBuffer | null = null;++ constructor(+ private readonly width: number,+ private readonly height: number,+ ) {}++ /** BGRA is what Chromium yields from a canvas; ffmpeg is told to expect it. */+ readonly pixelFormat = "bgra" as const;++ async extract(canvas: HTMLCanvasElement | OffscreenCanvas): Promise<ArrayBuffer> {+ const frame = new VideoFrame(canvas as HTMLCanvasElement, { timestamp: 0 });+ try {+ const size = frame.allocationSize();+ this.buffer ??= new ArrayBuffer(size);+ if (this.buffer.byteLength !== size) {+ // Output size is fixed for the whole export; a change here means the+ // renderer was reconfigured mid-flight and ffmpeg's -s is now wrong.+ throw new Error(+ `Frame size changed mid-export (${this.buffer.byteLength} -> ${size} bytes)`,+ );+ }+ const layout = await frame.copyTo(this.buffer);+ assertTightBgraLayout(layout, this.width, this.height, size);+ return this.buffer;+ } finally {+ frame.close();+ }+ }+}diff --git a/src/lib/exporter/frameRenderer.ts b/src/lib/exporter/frameRenderer.tsindex 5c6356899..90a5b0b2a 100644--- a/src/lib/exporter/frameRenderer.ts+++ b/src/lib/exporter/frameRenderer.ts@@ -77,6 +77,29 @@ import {import { createThreeDPass, type ThreeDPass } from "./threeDPass";import { drawWebcamFrameImage } from "./webcamFrameDrawing";+/**+ * Ask for CPU-backed 2D canvases (`willReadFrequently`) outside Linux.+ *+ * The default is GPU-backed, which makes compositing cheap and reading back+ * expensive. That is the right trade for WebCodecs, which encodes straight from+ * the GPU texture and never descends. It is the wrong trade for the native+ * encoder, which needs the pixels on the CPU for EVERY frame — there, the+ * readback measured 54-87ms/frame and became ~75% of the loop.+ *+ * Read at runtime so one app session can measure both settings:+ * localStorage.setItem("openscreen.readFrequently", "1")+ *+ * Temporary scaffold: once the native path is the only path, this becomes a+ * plain constant rather than a question.+ */+function cpuCanvasRequested(): boolean {+ try {+ return localStorage.getItem("openscreen.readFrequently") === "1";+ } catch {+ return false;+ }+}+interface FrameRenderConfig {width: number;height: number;@@ -171,10 +194,13 @@ export class FrameRenderer {private zoomSpringState = createZoomSpringState();private prevTargetProgress = 0;private isLinux = false;+ /** CPU-backed 2D canvases — see cpuCanvasRequested(). Fixed per instance. */+ private cpuCanvas = false;constructor(config: FrameRenderConfig) {this.config = config;this.isLinux = config.platform === "linux";+ this.cpuCanvas = this.isLinux || cpuCanvasRequested();this.animationState = {scale: 1,focusX: DEFAULT_FOCUS.cx,@@ -282,15 +308,25 @@ export class FrameRenderer {this.compositeCanvas.width = this.config.width;this.compositeCanvas.height = this.config.height;- // On Linux getImageData() runs frequently, so hint frequent CPU readback+ // Hint frequent CPU readback: Linux exports via getImageData every frame,+ // and so does the native encoder path (see cpuCanvasRequested).this.compositeCtx = this.compositeCanvas.getContext("2d", {- willReadFrequently: this.isLinux,+ willReadFrequently: this.cpuCanvas,});if (!this.compositeCtx) {throw new Error("Failed to get 2D context for composite canvas");}+ // willReadFrequently is a HINT: report what Chromium actually granted, not+ // what we asked for. An arm that silently no-ops would otherwise read as+ // "the lever does not help" when it means "the lever was never pulled".+ console.warn(+ `[export perf] canvas requested willReadFrequently=${this.cpuCanvas} granted=${+ this.compositeCtx.getContextAttributes?.()?.willReadFrequently+ }`,+ );+this.rasterCanvas = document.createElement("canvas");this.rasterCanvas.width = this.config.width;this.rasterCanvas.height = this.config.height;@@ -304,8 +340,11 @@ export class FrameRenderer {this.foregroundCanvas = document.createElement("canvas");this.foregroundCanvas.width = this.config.width;this.foregroundCanvas.height = this.config.height;+ // Flips WITH the composite canvas, never against it: a GPU-backed+ // foreground drawn onto a CPU-backed composite would force its own+ // readback on every drawImage — worse than either setting alone.this.foregroundCtx = this.foregroundCanvas.getContext("2d", {- willReadFrequently: this.isLinux,+ willReadFrequently: this.cpuCanvas,});if (!this.foregroundCtx) {throw new Error("Failed to get 2D context for foreground canvas");diff --git a/src/lib/exporter/nativeFrameSink.test.ts b/src/lib/exporter/nativeFrameSink.test.tsnew file mode 100644index 000000000..1a1d66a73--- /dev/null+++ b/src/lib/exporter/nativeFrameSink.test.ts@@ -0,0 +1,202 @@+import { describe, expect, it } from "vitest";+import { CREDIT_WINDOW, NativeFrameSink, type NativeSinkApi } from "./nativeFrameSink";++/**+ * A stand-in for the main process: records frames, and only acks when told to,+ * so a test can hold the window full and observe the sender blocking.+ */+function fakeMain(over: Partial<NativeSinkApi> = {}) {+ let ack: ((sessionId: string, error: string | null) => void) | null = null;+ const state = {+ frames: [] as number[],+ pending: [] as number[],+ finished: false,+ cancelled: false,+ unsubscribed: false,+ listenerAtFirstFrame: null as boolean | null,+ };+ const api: NativeSinkApi = {+ exportStart: async () => ({ sessionId: "s1", encoder: "h264_amf" }),+ exportWriteFrame: (_id, frame) => {+ state.listenerAtFirstFrame ??= ack !== null;+ state.frames.push(frame.byteLength);+ state.pending.push(frame.byteLength);+ },+ exportOnFrameAck: (cb) => {+ ack = cb;+ return () => {+ state.unsubscribed = true;+ };+ },+ exportFinish: async () => {+ state.finished = true;+ return { outputPath: "/tmp/out.mp4" };+ },+ exportCancel: async () => {+ state.cancelled = true;+ },+ ...over,+ };+ /** Ack `n` frames as the main process would, one message each. */+ const flush = (n = state.pending.length, error: string | null = null) => {+ for (let i = 0; i < n; i++) {+ state.pending.shift();+ ack?.("s1", error);+ }+ };+ /** Deliver an ack exactly as the main process would, for any session id. */+ const ackAs = (sessionId: string, error: string | null = null) => ack?.(sessionId, error);+ return { api, state, flush, ackAs };+}++const OPTS = {+ outputPath: "/tmp/out.mp4",+ width: 1920,+ height: 1080,+ frameRate: 60,+ bitrate: 8_000_000,+ pixelFormat: "nv12" as const,+};++/** Lets pending microtasks settle so a blocked write() can be observed as blocked. */+const settle = () => new Promise((r) => setTimeout(r, 0));++describe("NativeFrameSink", () => {+ it("subscribes to acks before the first frame can be sent", async () => {+ const { api, state } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ await sink.write(new ArrayBuffer(16));+ // If the listener were registered after the first send, an ack arriving+ // promptly would be dropped and the window would never refill.+ expect(state.listenerAtFirstFrame).toBe(true);+ });++ it("keeps exactly CREDIT_WINDOW frames in flight and blocks the next one", async () => {+ const { api, state, flush } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);++ for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));+ expect(state.frames.length).toBe(CREDIT_WINDOW);++ let sent = false;+ const blocked = sink.write(new ArrayBuffer(1)).then(() => {+ sent = true;+ });+ await settle();+ // The window is full: this write must not have gone out.+ expect(sent).toBe(false);+ expect(state.frames.length).toBe(CREDIT_WINDOW);++ flush(1);+ await blocked;+ expect(state.frames.length).toBe(CREDIT_WINDOW + 1);+ });++ it("does not block below the window — the whole point over stop-and-wait", async () => {+ const { api, state } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ // No acks at all: the first CREDIT_WINDOW writes must still all resolve.+ for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));+ expect(state.frames.length).toBe(CREDIT_WINDOW);+ });++ it("ignores acks addressed to another session", async () => {+ const { api, state, ackAs } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));++ let sent = false;+ void sink.write(new ArrayBuffer(1)).then(() => {+ sent = true;+ });+ // The ack channel is renderer-wide. A concurrent export's ack must not hand+ // us a credit we did not earn, or we would overrun our own window.+ ackAs("some-other-session");+ await settle();+ expect(sent).toBe(false);+ expect(state.frames.length).toBe(CREDIT_WINDOW);++ // Our own ack still works, proving the guard is on the id, not on everything.+ ackAs("s1");+ await settle();+ expect(sent).toBe(true);+ });++ it("drains every in-flight frame before finishing", async () => {+ const { api, state, flush } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ for (let i = 0; i < 3; i++) await sink.write(new ArrayBuffer(1));++ let done = false;+ const finishing = sink.finish().then((r) => {+ done = true;+ return r;+ });+ await settle();+ // Finishing with frames still in flight would close ffmpeg's stdin early+ // and truncate the file.+ expect(done).toBe(false);+ expect(state.finished).toBe(false);++ flush();+ await expect(finishing).resolves.toEqual({ outputPath: "/tmp/out.mp4" });+ expect(state.finished).toBe(true);+ });++ it("finishes immediately when nothing is in flight", async () => {+ const { api } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ await expect(sink.finish()).resolves.toEqual({ outputPath: "/tmp/out.mp4" });+ });++ it("unsubscribes from the ack channel on finish", async () => {+ const { api, state } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ await sink.finish();+ expect(state.unsubscribed).toBe(true);+ });++ it("surfaces an ffmpeg write failure to the writer rather than hanging", async () => {+ const { api, flush } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));++ const blocked = sink.write(new ArrayBuffer(1));+ flush(1, "ffmpeg exited: Cannot load nvcuda.dll");+ // The parked write must reject, not resume: ffmpeg is gone.+ await expect(blocked).rejects.toThrow(/nvcuda/);+ });++ it("reports the ffmpeg failure from finish() instead of the file it never wrote", async () => {+ const { api, state, flush } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ await sink.write(new ArrayBuffer(1));+ flush(1, "ffmpeg died");+ await expect(sink.finish()).rejects.toThrow(/ffmpeg died/);+ // A dead session must be cancelled, not finished — finishing waits on a+ // process that will never exit cleanly.+ expect(state.finished).toBe(false);+ expect(state.cancelled).toBe(true);+ });++ it("cancel() releases a writer parked on a credit that will never arrive", async () => {+ const { api, state } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));++ const blocked = sink.write(new ArrayBuffer(1));+ await sink.cancel();+ // Without the wake in cancel(), this write would hang forever and the+ // export loop would never unwind.+ await expect(blocked).rejects.toThrow(/closed/);+ expect(state.cancelled).toBe(true);+ expect(state.unsubscribed).toBe(true);+ });++ it("is idempotent on cancel", async () => {+ const { api } = fakeMain();+ const sink = await NativeFrameSink.start(OPTS, api);+ await sink.cancel();+ await expect(sink.cancel()).resolves.toBeUndefined();+ });+});diff --git a/src/lib/exporter/nativeFrameSink.ts b/src/lib/exporter/nativeFrameSink.tsnew file mode 100644index 000000000..eb8b675d5--- /dev/null+++ b/src/lib/exporter/nativeFrameSink.ts@@ -0,0 +1,124 @@+/**+ * Renderer side of the native export encoder: ships composited frames to the+ * main process, which feeds them to ffmpeg's stdin.+ *+ * Flow control is a credit window rather than stop-and-wait. Waiting for each+ * frame's ack before sending the next leaves the crossing idle for a full+ * round-trip per frame; keeping N frames in flight measured +56%. The window+ * saturates at 8 (32 adds nothing), because the crossing is bandwidth-bound —+ * IPC structured-clones every frame — not round-trip-bound.+ */++/** Frames in flight. Measured: 8 saturates the crossing, 32 buys nothing. */+export const CREDIT_WINDOW = 8;++export interface NativeSinkApi {+ exportStart: (req: unknown) => Promise<{+ sessionId: string;+ encoder: string;+ outputPath: string;+ }>;+ exportWriteFrame: (sessionId: string, frame: ArrayBuffer) => void;+ exportOnFrameAck: (cb: (sessionId: string, error: string | null) => void) => () => void;+ exportFinish: (sessionId: string) => Promise<{ outputPath: string }>;+ exportCancel: (sessionId: string) => Promise<void>;+}++export interface NativeSinkOptions {+ /** Omitted: main writes to a temp file and reports the path back. */+ outputPath?: string;+ width: number;+ height: number;+ frameRate: number;+ bitrate: number;+ pixelFormat: "nv12" | "bgra" | "rgba";+}++export class NativeFrameSink {+ private inFlight = 0;+ private waiters: Array<() => void> = [];+ private failure: Error | null = null;+ private unsubscribe: (() => void) | null = null;+ private closed = false;++ private constructor(+ private readonly api: NativeSinkApi,+ private readonly sessionId: string,+ readonly encoder: string,+ readonly outputPath: string,+ ) {}++ static async start(opts: NativeSinkOptions, api: NativeSinkApi): Promise<NativeFrameSink> {+ const { sessionId, encoder, outputPath } = await api.exportStart(opts);+ const sink = new NativeFrameSink(api, sessionId, encoder, outputPath);+ // Subscribe before any frame goes out: an ack for frame 0 must not race the+ // listener's registration, or the window never refills.+ sink.unsubscribe = api.exportOnFrameAck((id, error) => sink.onAck(id, error));+ return sink;+ }++ private onAck(sessionId: string, error: string | null): void {+ // One renderer-wide ack channel: ignore other sessions' traffic.+ if (sessionId !== this.sessionId) return;+ if (error) this.failure ??= new Error(error);+ this.inFlight--;+ this.wake();+ }++ /** Resolve every waiter and let each re-check its own condition. */+ private wake(): void {+ const waiters = this.waiters;+ this.waiters = [];+ for (const resolve of waiters) resolve();+ }++ private block(): Promise<void> {+ return new Promise<void>((resolve) => this.waiters.push(resolve));+ }++ /**+ * Ships one frame, blocking while the window is full.+ *+ * The buffer is handed to IPC, which copies it — the caller may reuse it as+ * soon as this returns.+ */+ async write(frame: ArrayBuffer): Promise<void> {+ if (this.failure) throw this.failure;+ if (this.closed) throw new Error("Export sink is closed");+ while (this.inFlight >= CREDIT_WINDOW) {+ await this.block();+ if (this.failure) throw this.failure;+ if (this.closed) throw new Error("Export sink is closed");+ }+ this.inFlight++;+ this.api.exportWriteFrame(this.sessionId, frame);+ }++ /** Waits for every in-flight frame to land, then closes ffmpeg's stdin. */+ async finish(): Promise<{ outputPath: string }> {+ if (this.closed) throw new Error("Export sink is closed");+ while (this.inFlight > 0 && !this.failure) {+ await this.block();+ }+ this.closed = true;+ this.unsubscribe?.();+ this.unsubscribe = null;+ // ffmpeg is already dying on its own; surface why rather than the timeout+ // that finishing a broken session would produce.+ if (this.failure) {+ await this.api.exportCancel(this.sessionId).catch(() => undefined);+ throw this.failure;+ }+ return this.api.exportFinish(this.sessionId);+ }++ async cancel(): Promise<void> {+ if (this.closed) return;+ this.closed = true;+ this.unsubscribe?.();+ this.unsubscribe = null;+ // Unblock anything parked on a credit: no further ack is coming.+ this.wake();+ await this.api.exportCancel(this.sessionId).catch(() => undefined);+ }+}diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.tsindex 9724a63d8..38d2548f9 100644--- a/src/lib/exporter/videoExporter.ts+++ b/src/lib/exporter/videoExporter.ts@@ -16,9 +16,11 @@ import type { CursorRecordingData } from "@/native/contracts";import { getPlatform } from "@/utils/platformUtils";import { AudioProcessor, downmixPlanarChannelsForExport } from "./audioEncoder";import { WsolaTimeStretcher } from "./audioTimeStretch";+import { CanvasFrameExtractor } from "./frameExtract";import { FrameRenderer } from "./frameRenderer";import { materializeLocalSourceFile, releaseLocalSourceFile } from "./localSourceFile";import { VideoMuxer, videoCodecFamily } from "./muxer";+import { NativeFrameSink, type NativeSinkApi } from "./nativeFrameSink";import { StageTimings } from "./perfTimings";import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";import { StreamingVideoDecoder } from "./streamingDecoder";@@ -63,7 +65,51 @@ export async function waitForEncoderQueueSpace(params: {// D4 diagnostic: measure the ENCODER ALONE (synthetic frames, no decode/render)// to separate platform encoder throughput from our pipeline's feeding path.// Temporary — flip off/remove once the bottleneck is identified.-const ENCODER_PROBE = true;+const ENCODER_PROBE = false;++/**+ * Route frames to the bundled native ffmpeg instead of WebCodecs.+ *+ * Read at runtime, from localStorage, ON PURPOSE: it lets one app session export+ * the same timeline both ways, so the A/B compares two runs that share a source,+ * a plan, a machine and a thermal state. A build-time constant would compare two+ * different sessions and invite us to believe the difference.+ *+ * localStorage.setItem("openscreen.nativeEncode", "1")+ *+ * Temporary scaffold: WebCodecs goes away once the numbers are in.+ */+function nativeEncodeEnabled(): boolean {+ try {+ return localStorage.getItem("openscreen.nativeEncode") === "1";+ } catch {+ return false;+ }+}++/**+ * Diagnostic: extract every frame to RAM, then throw it away.+ *+ * 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.+ *+ * 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).+ *+ * localStorage.setItem("openscreen.dropFrames", "1")+ */+function dropFramesEnabled(): boolean {+ try {+ return localStorage.getItem("openscreen.dropFrames") === "1";+ } catch {+ return false;+ }+}async function probeOneEncoder(opts: {label: string;@@ -672,6 +718,7 @@ export class VideoExporter {private renderer: FrameRenderer | null = null;private encoder: VideoEncoder | null = null;private muxer: VideoMuxer | null = null;+ private nativeSink: NativeFrameSink | null = null;private audioProcessor: AudioProcessor | null = null;private webcamDecoder: StreamingVideoDecoder | null = null;private cancelled = false;@@ -1123,7 +1170,39 @@ export class VideoExporter {this.renderer = renderer;await renderer.initialize();- await this.initializeEncoder(encoderPreference);+ // --- Frame sink: native ffmpeg, or the WebCodecs path it is replacing ---+ const api = window.electronAPI as unknown as NativeSinkApi | undefined;+ const useNative = nativeEncodeEnabled() && typeof api?.exportStart === "function";+ // Ceiling diagnostic: extract but never ship, and start no ffmpeg. The+ // export produces NO FILE — it exists to price the descent alone.+ const dropFrames = useNative && dropFramesEnabled();+ let sink: NativeFrameSink | null = null;+ let extractor: CanvasFrameExtractor | null = null;+ if (useNative && api) {+ extractor = new CanvasFrameExtractor(this.config.width, this.config.height);+ if (dropFrames) {+ console.warn("[export perf] readback ceiling: extract and discard, NO FILE WRITTEN");+ } else {+ sink = await NativeFrameSink.start(+ {+ width: this.config.width,+ height: this.config.height,+ frameRate: this.config.frameRate,+ // Same field the WebCodecs encoder is configured from, so the A/B+ // compares two runs at one bitrate.+ bitrate: this.config.bitrate,+ // BGRA is all Chromium will copy out of a canvas; NV12 packing is+ // the next step (see frameExtract.ts).+ pixelFormat: extractor.pixelFormat,+ },+ api,+ );+ this.nativeSink = sink;+ console.warn(`[export perf] native encode via ${sink.encoder} -> ${sink.outputPath}`);+ }+ } else {+ await this.initializeEncoder(encoderPreference);+ }// Audio pre-pass: decode each segment's audio to the common export layout// up-front, so we know whether to declare an audio track on the muxer (mp4@@ -1151,9 +1230,14 @@ export class VideoExporter {: null;const hasAudio = Boolean(audioExportCodec);- const muxer = new VideoMuxer(this.config, hasAudio, audioExportCodec?.muxerCodec);- this.muxer = muxer;- await muxer.initialize();+ // ffmpeg does its own muxing and writes the file, so the JS muxer only+ // exists on the WebCodecs path.+ let muxer: VideoMuxer | null = null;+ if (!useNative) {+ muxer = new VideoMuxer(this.config, hasAudio, audioExportCodec?.muxerCodec);+ this.muxer = muxer;+ await muxer.initialize();+ }const frameDuration = 1_000_000 / this.config.frameRate;const maxEncodeQueue =@@ -1319,52 +1403,70 @@ export class VideoExporter {await renderer.renderFrame(videoFrame, sourceTimestampMs * 1000, webcamFrame);stopRender();- const stopReadback = timings.start("readback");- const canvas = renderer.getCanvas();- let exportFrame: VideoFrame;- if (platform === "linux") {- const canvasCtx = canvas.getContext("2d")!;- const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);- exportFrame = new VideoFrame(imageData.data.buffer, {- format: "RGBA",- codedWidth: canvas.width,- codedHeight: canvas.height,- timestamp,- duration: frameDuration,- colorSpace: {- primaries: "bt709",- transfer: "iec61966-2-1",- matrix: "rgb",- fullRange: true,- },- });+ // Both paths report the same two stages so the A/B diffs stage by+ // stage: "readback" is getting pixels off the canvas, "encodeWait" is+ // blocking on the consumer — the encoder queue, or the credit window.+ if (extractor) {+ const stopExtract = timings.start("readback");+ // The GPU->CPU descent happens here, inside copyTo — not in the+ // VideoFrame constructor, which is lazy.+ const bytes = await extractor.extract(renderer.getCanvas());+ stopExtract();++ const stopShip = timings.start("encodeWait");+ // IPC copies the buffer during send(), so the extractor is free to+ // refill it as soon as this resolves. With no sink, the frame is+ // discarded here: that IS the ceiling arm — the crossing costs zero.+ if (sink) await sink.write(bytes);+ stopShip();} else {- exportFrame = new VideoFrame(canvas, { timestamp, duration: frameDuration });- }- stopReadback();-- const stopEncodeWait = timings.start("encodeWait");- try {- await waitForEncoderQueueSpace({- getQueueSize: () => this.encoder?.encodeQueueSize ?? 0,- maxEncodeQueue,- isCancelled: () => this.cancelled,- encoderPreference,- });- } catch (error) {- exportFrame.close();- throw error;- }- stopEncodeWait();+ const stopReadback = timings.start("readback");+ const canvas = renderer.getCanvas();+ let exportFrame: VideoFrame;+ if (platform === "linux") {+ const canvasCtx = canvas.getContext("2d")!;+ const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);+ exportFrame = new VideoFrame(imageData.data.buffer, {+ format: "RGBA",+ codedWidth: canvas.width,+ codedHeight: canvas.height,+ timestamp,+ duration: frameDuration,+ colorSpace: {+ primaries: "bt709",+ transfer: "iec61966-2-1",+ matrix: "rgb",+ fullRange: true,+ },+ });+ } else {+ exportFrame = new VideoFrame(canvas, { timestamp, duration: frameDuration });+ }+ stopReadback();++ const stopEncodeWait = timings.start("encodeWait");+ try {+ await waitForEncoderQueueSpace({+ getQueueSize: () => this.encoder?.encodeQueueSize ?? 0,+ maxEncodeQueue,+ isCancelled: () => this.cancelled,+ encoderPreference,+ });+ } catch (error) {+ exportFrame.close();+ throw error;+ }+ stopEncodeWait();- if (this.encoder && this.encoder.state === "configured") {- this.encodeQueue++;- const stopEncode = timings.start("encode");- this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });- stopEncode();- }+ if (this.encoder && this.encoder.state === "configured") {+ this.encodeQueue++;+ const stopEncode = timings.start("encode");+ this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });+ stopEncode();+ }- exportFrame.close();+ exportFrame.close();+ }frameIndex++;this.reportProgress({currentFrame: frameIndex,@@ -1394,12 +1496,19 @@ export class VideoExporter {}if (this.cancelled) {+ // Leaves no orphaned ffmpeg behind, and unblocks anything parked on a+ // credit that is never coming.+ await sink?.cancel();return { success: false, error: "Export cancelled" };}if (this.fatalEncoderError) {throw this.fatalEncoderError;}+ // Drain the in-flight window and close ffmpeg's stdin. This is where a+ // truncated file would come from, so it happens before anything else.+ const stopFlush = timings.start("flush");+ const nativeOutput = sink ? await sink.finish() : null;if (this.encoder && this.encoder.state === "configured") {await this.withTimeout(this.encoder.flush(),@@ -1409,6 +1518,7 @@ export class VideoExporter {: "The video encoder stopped responding while finalizing the export.",);}+ stopFlush();if (this.fatalEncoderError) {throw this.fatalEncoderError;}@@ -1435,7 +1545,13 @@ export class VideoExporter {stopAudioStretch();const stopAudioEncode = timings.start("audioEncode");- if (hasAudio && audioExportCodec && !this.cancelled) {+ // The decode and the WSOLA stretch above run on BOTH paths on purpose: they+ // share the video loop's CPU, so dropping them under native would hand the+ // native run a speedup the shipped product will never see. Only the encode+ // and mux are WebCodecs-only — ffmpeg will take the PCM as a second input+ // once the A/V-lock ordering is resolved (the plan needs the real frame+ // counts, which only exist after the loop).+ if (hasAudio && audioExportCodec && !this.cancelled && muxer) {const audioPlan = buildAudioConcatPlan(segments.map((s, i) => ({clipId: s.clipId,@@ -1471,7 +1587,19 @@ export class VideoExporter {timings.formatSummary({ frames: frameIndex, hardwareAcceleration: encoderPreference }),);- const blob = await muxer.finalize();+ if (dropFrames) {+ warnings.push("Readback ceiling diagnostic: frames were discarded, no file was written.");+ return { success: true, warnings };+ }+ if (nativeOutput) {+ // Scaffold: ffmpeg already wrote the file, so there is no blob to hand+ // back and the save flow does not yet know about it. The measurement is+ // the point here; the save path lands with the WebCodecs removal.+ warnings.push(`Native encode wrote ${nativeOutput.outputPath} (audio not muxed yet)`);+ return { success: true, warnings };+ }++ const blob = await muxer!.finalize();return { success: true, blob, warnings: warnings.length > 0 ? warnings : undefined };}@@ -1579,6 +1707,12 @@ export class VideoExporter {if (this.audioProcessor) {this.audioProcessor.cancel();}+ if (this.nativeSink) {+ // Fire-and-forget: cancel() is sync by contract. Main kills the ffmpeg+ // process tree, so an abandoned export leaves nothing running.+ void this.nativeSink.cancel();+ this.nativeSink = null;+ }this.cleanup();}diff --git a/src/main.tsx b/src/main.tsxindex 939360e62..5090c6353 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -8,6 +8,12 @@ import "./index.css";const windowType = new URLSearchParams(window.location.search).get("windowType") || "";+// The export bench replaces the UI entirely rather than rendering alongside it,+// so nothing competes with the export for the GPU or the main thread.+if (windowType === "bench") {+ void import("./bench/runBench").then((m) => m.runBench());+}+// Reclaim multi-GB OPFS source copies left behind by a previous session (they// are only pruned opportunistically during the next large-file load otherwise).// Nothing is referenced at startup, so everything stale is safe to remove.@@ -28,10 +34,12 @@ if (document.getElementById("root")?.style.setProperty("background", "transparent");}-ReactDOM.createRoot(document.getElementById("root")!).render(- <React.StrictMode>- <I18nProvider>- <App />- </I18nProvider>- </React.StrictMode>,-);+if (windowType !== "bench") {+ ReactDOM.createRoot(document.getElementById("root")!).render(+ <React.StrictMode>+ <I18nProvider>+ <App />+ </I18nProvider>+ </React.StrictMode>,+ );+}