Skip to content

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

perf(export): stop rebuilding per frame what never changes — the wall is the compositor

Etienne Lescotb42f8e9c0e6f
diff --git a/docs/architecture/export-native-encode-measurement.md b/docs/architecture/export-native-encode-measurement.md
index b9309680d..4d3d3bb76 100644
--- a/docs/architecture/export-native-encode-measurement.md
+++ b/docs/architecture/export-native-encode-measurement.md
@@ -229,8 +229,36 @@ Consequence: the project is unopenable in the editor today.
---
-## 11. Open questions
+## 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?** 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.
+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/native-core-tauri-spec.md b/docs/architecture/native-core-tauri-spec.md
index 410440c2e..e1d252fe7 100644
--- a/docs/architecture/native-core-tauri-spec.md
+++ b/docs/architecture/native-core-tauri-spec.md
@@ -56,6 +56,12 @@ 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 | — |
@@ -64,6 +70,16 @@ The real question is not *Electron vs Tauri*. It is:
| **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.)
diff --git a/scripts/bench-export.mjs b/scripts/bench-export.mjs
index 1e1223877..7783fbb2c 100644
--- a/scripts/bench-export.mjs
+++ b/scripts/bench-export.mjs
@@ -38,14 +38,20 @@ function parseArgs(argv) {
*/
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.",
- );
+ // Both names matter: the dev build runs as electron.exe, the INSTALLED app as
+ // openscreen.exe, and they share one userData — so one lock. Checking only
+ // electron.exe let the installed app hold it while the bench launched, exited
+ // 0 and reported nothing, with no log line to say why.
+ for (const image of ["electron.exe", "openscreen.exe"]) {
+ const running = spawnSync("tasklist", ["/FI", `IMAGENAME eq ${image}`, "/NH"], {
+ encoding: "utf8",
+ });
+ if (running.stdout?.includes(image)) {
+ throw new Error(
+ `${image} 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 });
}
@@ -180,6 +186,7 @@ async function main() {
const args = parseArgs(process.argv.slice(2));
const query = new URLSearchParams({
...(args.project ? { project: args.project } : {}),
+ ...(args.effects ? { effects: args.effects } : {}),
arms: args.arms ?? "webcodecs,native",
runs: args.runs ?? "2",
fps: args.fps ?? "60",
@@ -220,7 +227,7 @@ async function main() {
// 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);
+ const note = /\[export perf\] (canvas .*|native encode .*|shadow .*)$/.exec(line);
if (note) console.log(` · ${note[1]}`);
continue;
}
@@ -240,6 +247,7 @@ async function main() {
fatal = event.error;
} else if (event.event === "start") {
console.log(` project: ${event.project}`);
+ console.log(` effects: ${event.effects}`);
console.log(` arms: ${event.arms.join(", ")} x${event.runs}\n`);
}
}
diff --git a/src/bench/runBench.ts b/src/bench/runBench.ts
index 00f28766a..a28c00cbf 100644
--- a/src/bench/runBench.ts
+++ b/src/bench/runBench.ts
@@ -28,6 +28,10 @@ export interface BenchArm {
readFrequently: boolean;
/** Extract every frame and discard it. Diagnostic only — writes no file. */
dropFrames?: boolean;
+ /** Composite every frame and stop there. Diagnostic only — writes no file. */
+ compositeOnly?: boolean;
+ /** Undo the 2026-07-17 compositor fixes, to attribute them. */
+ legacyCompositor?: boolean;
}
export interface BenchRunResult {
@@ -61,8 +65,77 @@ const BENCH_PARAMS = {
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",
+ effects: (params.get("effects") ?? "").split(",").filter(Boolean),
};
+/**
+ * Appearance the exporter reads out of `legacyEditor`, patched onto an in-memory
+ * COPY of the document.
+ *
+ * Most saved projects carry no appearance at all, so the defaults apply:
+ * shadowIntensity 0, showBlur false, borderRadius 0, wallpaper "". Whole effects
+ * therefore never execute, and "fixing" them would have measured exactly zero on
+ * a project that never ran them. This turns them on without writing to the
+ * user's project store — nothing here reaches disk.
+ *
+ * --effects=shadow,blur,radius
+ */
+const EFFECT_PATCHES: Record<string, Record<string, unknown>> = {
+ // Three chained drop-shadows over the full frame, every frame.
+ shadow: { shadowIntensity: 1 },
+ // A static wallpaper, re-blurred every frame.
+ blur: { showBlur: true },
+ radius: { borderRadius: 24 },
+ motionBlur: { motionBlurAmount: 1 },
+};
+
+/**
+ * A zoom region, injected the same way: the saved projects have `zoomRanges: []`.
+ *
+ * It is not decoration. Zoom is the one effect that changes the composited
+ * GEOMETRY every frame, so it is what invalidates any geometry-keyed cache. A
+ * parity test on a project without zoom would happily pass with a broken cache
+ * key, because nothing would ever ask it to invalidate.
+ */
+function zoomRanges(doc: AxcutDocument): unknown[] {
+ const clips = (doc as { timeline?: { clips?: { timelineEndSec?: number }[] } }).timeline?.clips;
+ const endSec = clips?.[0]?.timelineEndSec ?? 5;
+ return [
+ {
+ id: "bench-zoom",
+ startMs: 500,
+ endMs: Math.max(1500, Math.round(endSec * 1000) - 500),
+ depth: "medium",
+ focus: { cx: 0.5, cy: 0.5 },
+ },
+ ];
+}
+
+function withEffects(doc: AxcutDocument, effects: string[]): AxcutDocument {
+ if (effects.length === 0) return doc;
+ const legacy: Record<string, unknown> = {
+ ...((doc as { legacyEditor?: Record<string, unknown> }).legacyEditor ?? {}),
+ };
+ let patched = doc;
+ for (const name of effects) {
+ if (name === "zoom") {
+ patched = { ...patched, zoomRanges: zoomRanges(doc) } as AxcutDocument;
+ continue;
+ }
+ const patch = EFFECT_PATCHES[name];
+ if (!patch) {
+ throw new Error(`Unknown effect "${name}". Known: ${Object.keys(EFFECT_PATCHES)}, zoom`);
+ }
+ Object.assign(legacy, patch);
+ }
+ // `blur` only does anything against a real wallpaper; a project with none
+ // would silently skip the very pass being measured.
+ if (effects.includes("blur") && !legacy.wallpaper) {
+ legacy.wallpaper = "wallpaper13.jpg";
+ }
+ return { ...patched, legacyEditor: legacy } as AxcutDocument;
+}
+
const ARMS: Record<string, BenchArm> = {
// The path we ship today: WebCodecs encodes straight off the GPU texture.
webcodecs: { nativeEncode: false, readFrequently: false },
@@ -79,12 +152,34 @@ const ARMS: Record<string, BenchArm> = {
// 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 },
+ // Prices the GPU compositing of the real effect set, with nothing downstream
+ // to absorb it. This is the number the native-core case rests on: a pipeline
+ // that composites on-device cannot beat decode + this + encode. Writes no file.
+ "composite-ceiling": { nativeEncode: true, readFrequently: false, compositeOnly: true },
+ // The same ceiling with the compositor fixes undone. Pairing these two in one
+ // interleaved run is the only honest way to price the fixes: across sessions
+ // this machine drifts further than they are worth.
+ "composite-ceiling-legacy": {
+ nativeEncode: true,
+ readFrequently: false,
+ compositeOnly: true,
+ legacyCompositor: true,
+ },
+ /** Today's shipping path, with the compositor fixes undone. */
+ "webcodecs-legacy": { nativeEncode: false, readFrequently: false, legacyCompositor: true },
+ // These two WRITE FILES, which is what makes them the parity gate: encode the
+ // same timeline with the old and new compositor through the same encoder at
+ // the same bitrate, then diff the results (SSIM). Unit tests never look at a
+ // pixel, and "obviously equivalent" is what this investigation keeps punishing.
+ "native-legacy": { nativeEncode: true, readFrequently: false, legacyCompositor: 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");
+ localStorage.setItem("openscreen.compositeOnly", arm.compositeOnly ? "1" : "0");
+ localStorage.setItem("openscreen.legacyCompositor", arm.legacyCompositor ? "1" : "0");
}
/**
@@ -272,11 +367,12 @@ export async function runBench(): Promise<void> {
}
// 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);
+ const doc = withEffects(await resolveDocument(BENCH_PARAMS.project), BENCH_PARAMS.effects);
emit("start", {
arms: BENCH_PARAMS.arms,
runs: BENCH_PARAMS.runs,
project: doc.project?.title ?? "(untitled)",
+ effects: BENCH_PARAMS.effects.length ? BENCH_PARAMS.effects.join("+") : "(project default)",
});
for (let run = 1; run <= BENCH_PARAMS.runs; run++) {
for (const armName of BENCH_PARAMS.arms) {
diff --git a/src/lib/exporter/frameRenderer.ts b/src/lib/exporter/frameRenderer.ts
index 90a5b0b2a..0b3f46a04 100644
--- a/src/lib/exporter/frameRenderer.ts
+++ b/src/lib/exporter/frameRenderer.ts
@@ -100,6 +100,44 @@ function cpuCanvasRequested(): boolean {
}
}
+/**
+ * Restore the pre-2026-07-17 compositor: a fresh GPU texture per frame, the mask
+ * retessellated per frame, and clearRect before every full-frame draw.
+ *
+ * Exists so the three fixes can be ATTRIBUTED. Comparing across bench sessions
+ * would not do: this machine drifts more between sessions than the fixes are
+ * worth, which is the failure mode this whole investigation keeps tripping over.
+ * With the flag, one interleaved run measures old against new on one thermal
+ * state, and the repeat proves it.
+ *
+ * localStorage.setItem("openscreen.legacyCompositor", "1")
+ */
+function legacyCompositorRequested(): boolean {
+ try {
+ return localStorage.getItem("openscreen.legacyCompositor") === "1";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The recording's drop shadow, as a CSS filter chain.
+ *
+ * Three chained shadows, each blurring the alpha of the PREVIOUS stage's output
+ * (its own shadow included) — that cascade is what gives the falloff, and it is
+ * why this cannot be swapped for an SDF without changing the picture.
+ *
+ * Was duplicated verbatim on the flat and the 3D path; they must not drift.
+ */
+function shadowFilterChain(intensity: number): string {
+ const offset = 12 * intensity;
+ return (
+ `drop-shadow(0 ${offset}px ${48 * intensity}px rgba(0,0,0,${0.7 * intensity})) ` +
+ `drop-shadow(0 ${offset / 3}px ${16 * intensity}px rgba(0,0,0,${0.5 * intensity})) ` +
+ `drop-shadow(0 ${offset / 6}px ${8 * intensity}px rgba(0,0,0,${0.3 * intensity}))`
+ );
+}
+
interface FrameRenderConfig {
width: number;
height: number;
@@ -167,6 +205,20 @@ export class FrameRenderer {
private cameraContainer: Container | null = null;
private videoContainer: Container | null = null;
private videoSprite: Sprite | null = null;
+ /** Source geometry behind videoSprite's texture — see renderFrame's reuse. */
+ private videoFrameSize: { width: number; height: number } | null = null;
+ /** Shape currently tessellated into maskGraphics, so it is rebuilt only on change. */
+ private maskShape: { width: number; height: number; radius: number } | null = null;
+ /** Bench-only: undo the compositor fixes so they can be measured. */
+ private legacyCompositor = legacyCompositorRequested();
+ /** Shadow filter output, keyed by the geometry it was computed for. */
+ private shadowCache: { key: string; canvas: HTMLCanvasElement } | null = null;
+ /** Scratch holding videoCanvas's alpha as an opaque black shape. */
+ private shadowSilhouetteCanvas: HTMLCanvasElement | null = null;
+ /** The wallpaper, blurred once. It is a still image — see blurredBackgroundLayer. */
+ private blurredBackground: HTMLCanvasElement | null = null;
+ /** Which backgroundSprite blurredBackground was built from, so a reload invalidates it. */
+ private blurredBackgroundSource: HTMLCanvasElement | null = null;
private backgroundSprite: HTMLCanvasElement | null = null;
private maskGraphics: Graphics | null = null;
private blurFilter: BlurFilter | null = null;
@@ -479,16 +531,37 @@ export class FrameRenderer {
this.currentVideoTime = timestamp / 1000000;
+ // Reuse the GPU texture across frames. Texture.from() allocates a new
+ // TextureSource per call (every VideoFrame is a distinct object, so nothing
+ // caches), and destroy(true) frees the GL texture behind it — an allocate +
+ // upload + free of a 1080p texture on every single frame. Swapping the
+ // resource re-uploads the pixels into the texture we already have.
+ //
+ // Only valid while the geometry is unchanged: segments can carry different
+ // source sizes, so a size change still rebuilds (and frees) the source.
+ const frameWidth = videoFrame.displayWidth;
+ const frameHeight = videoFrame.displayHeight;
+ const sizeUnchanged =
+ !this.legacyCompositor &&
+ this.videoFrameSize?.width === frameWidth &&
+ this.videoFrameSize?.height === frameHeight;
+
if (!this.videoSprite) {
const texture = Texture.from(videoFrame as unknown as TextureSourceLike);
this.videoSprite = new Sprite(texture);
this.videoContainer.addChild(this.videoSprite);
+ this.videoFrameSize = { width: frameWidth, height: frameHeight };
+ } else if (sizeUnchanged) {
+ const source = this.videoSprite.texture.source;
+ source.resource = videoFrame;
+ source.update();
} else {
// Destroy old texture before swapping to avoid a leak
const oldTexture = this.videoSprite.texture;
const newTexture = Texture.from(videoFrame as unknown as TextureSourceLike);
this.videoSprite.texture = newTexture;
oldTexture.destroy(true);
+ this.videoFrameSize = { width: frameWidth, height: frameHeight };
}
this.updateLayout(webcamFrame);
@@ -599,15 +672,11 @@ export class FrameRenderer {
const h = this.foregroundCanvas.height;
shadowCtx.clearRect(0, 0, w, h);
shadowCtx.save();
- const intensity = this.config.shadowIntensity;
- const baseBlur1 = 48 * intensity;
- const baseBlur2 = 16 * intensity;
- const baseBlur3 = 8 * intensity;
- const baseAlpha1 = 0.7 * intensity;
- const baseAlpha2 = 0.5 * intensity;
- const baseAlpha3 = 0.3 * intensity;
- const baseOffset = 12 * intensity;
- shadowCtx.filter = `drop-shadow(0 ${baseOffset}px ${baseBlur1}px rgba(0,0,0,${baseAlpha1})) drop-shadow(0 ${baseOffset / 3}px ${baseBlur2}px rgba(0,0,0,${baseAlpha2})) drop-shadow(0 ${baseOffset / 6}px ${baseBlur3}px rgba(0,0,0,${baseAlpha3}))`;
+ // NOT cacheable, unlike the flat path: this blurs foregroundCanvas, whose
+ // alpha carries the webcam, the cursor and the annotations — it changes
+ // every frame, so there is no geometry to key on. The 3D path stays at
+ // full price until it is restructured.
+ shadowCtx.filter = shadowFilterChain(this.config.shadowIntensity);
shadowCtx.drawImage(this.foregroundCanvas, 0, 0, w, h);
shadowCtx.restore();
if (this.compositeCtx) {
@@ -843,9 +912,25 @@ export class FrameRenderer {
? 0
: borderRadius * canvasScaleFactor;
- this.maskGraphics.clear();
- this.maskGraphics.roundRect(0, 0, screenRect.width, screenRect.height, scaledBorderRadius);
- this.maskGraphics.fill({ color: 0xffffff });
+ // Retessellate only when the shape actually changes. The mask is a rounded
+ // rect: while nothing zooms or resizes it is byte-identical from frame to
+ // frame, and clear()/roundRect()/fill() rebuilds its geometry every time.
+ // A zoom easing does change it per frame — that is the case this cannot help.
+ if (
+ this.legacyCompositor ||
+ this.maskShape?.width !== screenRect.width ||
+ this.maskShape?.height !== screenRect.height ||
+ this.maskShape?.radius !== scaledBorderRadius
+ ) {
+ this.maskGraphics.clear();
+ this.maskGraphics.roundRect(0, 0, screenRect.width, screenRect.height, scaledBorderRadius);
+ this.maskGraphics.fill({ color: 0xffffff });
+ this.maskShape = {
+ width: screenRect.width,
+ height: screenRect.height,
+ radius: scaledBorderRadius,
+ };
+ }
// baseOffset is the stage position of the full (uncropped) sprite's top-left, matching
// preview semantics, so consumers (e.g. cursor highlight) can map normalized
@@ -1057,6 +1142,122 @@ export class FrameRenderer {
// applyShadowToRecording is false when the 3D pass will rotate this canvas next;
// the shadow is re-applied after rotation to avoid aliasing.
+ /**
+ * The wallpaper, blurred once instead of 1418 times.
+ *
+ * backgroundSprite is rasterised once at load and never touched again — it is
+ * a still image. Blurring it per frame recomputes an identical result every
+ * time; measured at ~5 ms/frame.
+ *
+ * Byte-identical by construction: the original blurs while scaling to w*h, so
+ * the blur lands in destination space. Doing that once into a w*h canvas and
+ * blitting it 1:1 is the same operation, hoisted.
+ *
+ * Returns null when there is nothing to hoist (no blur), so the caller keeps
+ * drawing the sprite directly rather than through a pointless copy.
+ */
+ private blurredBackgroundLayer(w: number, h: number): HTMLCanvasElement | null {
+ if (!this.config.showBlur || !this.backgroundSprite || this.legacyCompositor) return null;
+ // Keyed on the sprite's identity, not just the size: loading a different
+ // wallpaper replaces the sprite, and a size-only check would keep serving
+ // the previous one's blur.
+ if (
+ this.blurredBackgroundSource === this.backgroundSprite &&
+ this.blurredBackground?.width === w &&
+ this.blurredBackground.height === h
+ ) {
+ return this.blurredBackground;
+ }
+ const canvas = document.createElement("canvas");
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return null;
+ ctx.filter = "blur(6px)"; // Canvas blur is weaker than CSS
+ ctx.drawImage(this.backgroundSprite, 0, 0, w, h);
+ ctx.filter = "none";
+ this.blurredBackground = canvas;
+ this.blurredBackgroundSource = this.backgroundSprite;
+ return canvas;
+ }
+
+ /**
+ * Everything the shadow's shape depends on. If two frames agree here, the
+ * filter output is identical and re-running it is pure waste.
+ *
+ * Taken from the world transforms rather than from the layout inputs, so a
+ * new way to move the recording cannot silently bypass the cache and serve a
+ * stale shadow. A zoom easing changes this every frame — by design: that case
+ * MUST miss.
+ */
+ private shadowGeometryKey(): string {
+ const v = this.videoContainer?.worldTransform;
+ const s = this.app?.stage?.worldTransform;
+ const m = this.maskShape;
+ return [
+ v ? `${v.a},${v.b},${v.c},${v.d},${v.tx},${v.ty}` : "-",
+ s ? `${s.a},${s.b},${s.c},${s.d},${s.tx},${s.ty}` : "-",
+ m ? `${m.width},${m.height},${m.radius}` : "-",
+ this.config.shadowIntensity,
+ ].join("|");
+ }
+
+ /**
+ * The shadow layer, rebuilt only when the geometry moves.
+ *
+ * drop-shadow reads SourceAlpha only, and videoCanvas's alpha is just the
+ * masked rounded rect — so the filter blurs 2M pixels of VIDEO to compute
+ * something that depends on nothing but the silhouette. Measured: ~30 ms per
+ * frame, twice the cost of the entire rest of the compositor.
+ *
+ * So it runs against the silhouette instead, and the silhouette is taken from
+ * videoCanvas's own alpha (source-in over black) rather than re-derived from
+ * the layout — same pixels, same anti-aliasing, nothing to keep in sync.
+ *
+ * Returns the filter output, which is `silhouette OVER shadow`: the caller
+ * draws videoCanvas on top, and it covers the silhouette exactly.
+ */
+ private cachedShadowLayer(
+ videoCanvas: HTMLCanvasElement,
+ w: number,
+ h: number,
+ ): HTMLCanvasElement | null {
+ const key = this.shadowGeometryKey();
+ if (this.shadowCache?.key === key) return this.shadowCache.canvas;
+
+ if (!this.shadowSilhouetteCanvas) {
+ this.shadowSilhouetteCanvas = document.createElement("canvas");
+ this.shadowSilhouetteCanvas.width = w;
+ this.shadowSilhouetteCanvas.height = h;
+ }
+ if (!this.shadowCache) {
+ const canvas = document.createElement("canvas");
+ canvas.width = w;
+ canvas.height = h;
+ this.shadowCache = { key: "", canvas };
+ }
+ const silCtx = this.shadowSilhouetteCanvas.getContext("2d");
+ const outCtx = this.shadowCache.canvas.getContext("2d");
+ if (!silCtx || !outCtx) return null;
+
+ // Silhouette: videoCanvas's exact alpha, filled black.
+ silCtx.globalCompositeOperation = "copy";
+ silCtx.drawImage(videoCanvas, 0, 0, w, h);
+ silCtx.globalCompositeOperation = "source-in";
+ silCtx.fillStyle = "#000";
+ silCtx.fillRect(0, 0, w, h);
+ silCtx.globalCompositeOperation = "source-over";
+
+ outCtx.globalCompositeOperation = "copy";
+ outCtx.filter = shadowFilterChain(this.config.shadowIntensity);
+ outCtx.drawImage(this.shadowSilhouetteCanvas, 0, 0, w, h);
+ outCtx.filter = "none";
+ outCtx.globalCompositeOperation = "source-over";
+
+ this.shadowCache.key = key;
+ return this.shadowCache.canvas;
+ }
+
private compositeWithShadows(
webcamFrame: VideoFrame | null | undefined,
applyShadowToRecording: boolean,
@@ -1081,24 +1282,37 @@ export class FrameRenderer {
// Background (compositeCanvas): wallpaper only. Stays flat, never touched by the
// 3D rotation pass, matching the preview.
- bgCtx.clearRect(0, 0, w, h);
+ //
+ // "copy" replaces the whole destination, so the clearRect that used to
+ // precede it is redundant: the draw below covers all w*h. Two full-frame
+ // passes become one. It is only safe BECAUSE the draw covers everything —
+ // hence the else branch below still clears explicitly.
+ if (this.legacyCompositor) bgCtx.clearRect(0, 0, w, h);
if (this.backgroundSprite) {
- const bgCanvas = this.backgroundSprite;
- if (this.config.showBlur) {
- bgCtx.save();
+ const bgCanvas = this.blurredBackgroundLayer(w, h) ?? this.backgroundSprite;
+ const stillNeedsBlur = this.config.showBlur && bgCanvas === this.backgroundSprite;
+ bgCtx.save();
+ if (!this.legacyCompositor) bgCtx.globalCompositeOperation = "copy";
+ if (stillNeedsBlur) {
bgCtx.filter = "blur(6px)"; // Canvas blur is weaker than CSS
- bgCtx.drawImage(bgCanvas, 0, 0, w, h);
- bgCtx.restore();
- } else {
- bgCtx.drawImage(bgCanvas, 0, 0, w, h);
}
+ bgCtx.drawImage(bgCanvas, 0, 0, w, h);
+ bgCtx.restore();
} else {
+ // Nothing is drawn, so this is the only thing dropping the previous frame.
+ bgCtx.clearRect(0, 0, w, h);
console.warn("[FrameRenderer] No background sprite found during compositing!");
}
// Foreground (transparent): recording + webcam. Shadow baked here only on the
// flat path; the 3D path applies it after rotation (see renderFrame).
- fgCtx.clearRect(0, 0, w, h);
+ //
+ // Same trick as the background: both branches below draw a full w*h image,
+ // so "copy" subsumes the clear. restore() puts source-over back before the
+ // webcam is drawn on top — with "copy" still set, it would wipe the frame.
+ if (this.legacyCompositor) fgCtx.clearRect(0, 0, w, h);
+ fgCtx.save();
+ if (!this.legacyCompositor) fgCtx.globalCompositeOperation = "copy";
if (
applyShadowToRecording &&
this.config.showShadow &&
@@ -1106,26 +1320,25 @@ export class FrameRenderer {
this.shadowCanvas &&
this.shadowCtx
) {
- const shadowCtx = this.shadowCtx;
- shadowCtx.clearRect(0, 0, w, h);
- shadowCtx.save();
-
- const intensity = this.config.shadowIntensity;
- const baseBlur1 = 48 * intensity;
- const baseBlur2 = 16 * intensity;
- const baseBlur3 = 8 * intensity;
- const baseAlpha1 = 0.7 * intensity;
- const baseAlpha2 = 0.5 * intensity;
- const baseAlpha3 = 0.3 * intensity;
- const baseOffset = 12 * intensity;
-
- shadowCtx.filter = `drop-shadow(0 ${baseOffset}px ${baseBlur1}px rgba(0,0,0,${baseAlpha1})) drop-shadow(0 ${baseOffset / 3}px ${baseBlur2}px rgba(0,0,0,${baseAlpha2})) drop-shadow(0 ${baseOffset / 6}px ${baseBlur3}px rgba(0,0,0,${baseAlpha3}))`;
- shadowCtx.drawImage(videoCanvas, 0, 0, w, h);
- shadowCtx.restore();
- fgCtx.drawImage(this.shadowCanvas, 0, 0, w, h);
+ const cached = this.legacyCompositor ? null : this.cachedShadowLayer(videoCanvas, w, h);
+ if (cached) {
+ // The filter ran once for this geometry; per frame this is one blit.
+ fgCtx.drawImage(cached, 0, 0, w, h);
+ fgCtx.globalCompositeOperation = "source-over";
+ fgCtx.drawImage(videoCanvas, 0, 0, w, h);
+ } else {
+ const shadowCtx = this.shadowCtx;
+ shadowCtx.clearRect(0, 0, w, h);
+ shadowCtx.save();
+ shadowCtx.filter = shadowFilterChain(this.config.shadowIntensity);
+ shadowCtx.drawImage(videoCanvas, 0, 0, w, h);
+ shadowCtx.restore();
+ fgCtx.drawImage(this.shadowCanvas, 0, 0, w, h);
+ }
} else {
fgCtx.drawImage(videoCanvas, 0, 0, w, h);
}
+ fgCtx.restore();
const webcamRect = this.layoutCache?.webcamRect ?? null;
if (webcamFrame && webcamRect) {
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 38d2548f9..e3f27fe94 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -111,6 +111,30 @@ function dropFramesEnabled(): boolean {
}
}
+/**
+ * Diagnostic: decode and composite every frame, then stop. No extract, no
+ * encode, no file.
+ *
+ * Prices the GPU compositing of the REAL effect set — the number the whole
+ * native-core case rests on. The `render` stage reads 1.7 ms/frame, but
+ * renderFrame is async: it returns before the GPU is done, so that figure may be
+ * charging someone else for the work. Here nothing downstream can absorb it, so
+ * the wall is the compositor's own throughput.
+ *
+ * Combined with the measured GPU decode+encode floor (234 fps with no
+ * compositing), this bounds a native GPU pipeline without building one:
+ * an architecture that composites on-device cannot beat decode + THIS + encode.
+ *
+ * localStorage.setItem("openscreen.compositeOnly", "1")
+ */
+function compositeOnlyEnabled(): boolean {
+ try {
+ return localStorage.getItem("openscreen.compositeOnly") === "1";
+ } catch {
+ return false;
+ }
+}
+
async function probeOneEncoder(opts: {
label: string;
width: number;
@@ -1173,12 +1197,15 @@ export class VideoExporter {
// --- 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();
+ // Ceiling diagnostics: extract but never ship, or do not even extract.
+ // Both produce NO FILE — they price one stage in isolation.
+ const compositeOnly = useNative && compositeOnlyEnabled();
+ const dropFrames = useNative && !compositeOnly && dropFramesEnabled();
let sink: NativeFrameSink | null = null;
let extractor: CanvasFrameExtractor | null = null;
- if (useNative && api) {
+ if (useNative && api && compositeOnly) {
+ console.warn("[export perf] composite ceiling: render only, NO EXTRACT, NO FILE WRITTEN");
+ } else 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");
@@ -1406,7 +1433,10 @@ export class VideoExporter {
// 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) {
+ if (compositeOnly) {
+ // Nothing downstream: the frame was composited and is dropped, so
+ // the wall measures the compositor and nothing else.
+ } else if (extractor) {
const stopExtract = timings.start("readback");
// The GPU->CPU descent happens here, inside copyTo — not in the
// VideoFrame constructor, which is lazy.
@@ -1587,6 +1617,10 @@ export class VideoExporter {
timings.formatSummary({ frames: frameIndex, hardwareAcceleration: encoderPreference }),
);
+ if (compositeOnly) {
+ warnings.push("Composite ceiling diagnostic: rendered only, no file was written.");
+ return { success: true, warnings };
+ }
if (dropFrames) {
warnings.push("Readback ceiling diagnostic: frames were discarded, no file was written.");
return { success: true, warnings };