Skip to content

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

feat(bench): gate G0 — fence the GPU before the encode timers, and cap the clip

Etienne Lescotbab502f086b7
diff --git a/docs/architecture/rendering-architecture.md b/docs/architecture/rendering-architecture.md
index 2f6bbf6de..0439d54b4 100644
--- a/docs/architecture/rendering-architecture.md
+++ b/docs/architecture/rendering-architecture.md
@@ -374,3 +374,49 @@ Audio internals (WSOLA/AAC/sync — orthogonal, untouched) · cuts & speed regio
---
*Provenance: every number in Part II is a gated measurement on the reference machine; §7.1's closing arithmetic is a deduction with G0 as its named falsifier; the 213-fps-beats-165-fps comparison is same-machine, same-frames. The two prior specs' full measurement reports remain the source of record for methodology details.*
+
+---
+
+## Annex A — Gate G0: PASSED (measured 2026-07-17)
+
+Run on the reference machine, real bench harness (`npm run bench:export`), four arms
+interleaved, 2 runs each, effects `shadow,blur,radius`, 1080p60, 820 frames.
+Project: `proj_5b3ac6bc` ("Recording 15/07/2026 18:38:53") — **not** the record's
+`os_parity`, which was found destroyed by the §13 Step-0 bug (see note below).
+This project is heavier than the record's: two clips, both with a visible webcam
+track — absolute numbers are therefore not comparable with §6; the arm-vs-arm
+attribution, which is all G0 claims, is.
+
+| arm | wall | fps | spread | encodeWait total | fence total |
+|---|---:|---:|---:|---:|---:|
+| webcodecs-legacy | 83.3 s | 9.8 | 5 % | 58 305 ms | — |
+| webcodecs-legacy-fence | 64.4 s | 12.8 | 8 % | **3 181 ms** | 44 538 ms |
+| webcodecs | 56.6 s | 14.6 | 5 % | 32 368 ms | — |
+| webcodecs-fence | 50.1 s | 16.4 | 9 % | **3 013 ms** | 28 199 ms |
+
+Per frame (820 frames): legacy `encodeWait` 71.1 → **3.9 ms** (×18 collapse), the
+difference reappearing under `fence` (54.3 ms/frame); shipping compositor 39.5 →
+**3.7 ms** (×10.7), `fence` 34.4 ms/frame. `encode` itself is ~0.03 ms/frame.
+
+**§7.1 is confirmed.** `encodeWait` was billing the compositor's GPU execution;
+the encoder's own residual wait is ~3.7–3.9 ms/frame on this machine. The wall is
+the compositor — here even more so than §7.1 estimated, because this project
+composites a webcam bubble on every frame of both clips.
+
+Two additional findings the gate did not ask for:
+
+1. **The fenced arms are FASTER end-to-end** (legacy −23 %, shipping −11 %).
+ Draining the GPU once per frame beats letting Chromium queue unboundedly —
+ deep uncontrolled pipelining is actively harmful here. §11's "pipeline, don't
+ await" needs the nuance: *bounded* in-flight work, not maximal.
+2. **The Step-2 fixes are confirmed in-run**: legacy 9.8 → shipping 14.6 fps
+ (+49 %) on a project whose per-frame webcam compositing they never touched.
+
+**Step-0 note (data loss, §13).** The record's reference project `os_parity`
+(`proj_de6ffaaa…openscreen`) was found corrupted with exactly the §13 signature:
+a complete, valid save (updatedAt 2026-07-16T18:00:26Z) followed by the tail of a
+longer, older version — `JSON.parse` fails at byte 3485 and the app can no longer
+list it. A byte-identical backup was taken (`….openscreen.corrupt.bak`, alongside
+an older victim `proj_05a4bb1c….corrupt.bak`). Recovery is mechanical — truncate
+to the valid 3485-byte prefix — pending the user's go-ahead. That is **two**
+destroyed project files; Step 0 stays the first line of the ship order.
diff --git a/scripts/bench-export.mjs b/scripts/bench-export.mjs
index 7783fbb2c..28efa53fe 100644
--- a/scripts/bench-export.mjs
+++ b/scripts/bench-export.mjs
@@ -187,6 +187,9 @@ async function main() {
const query = new URLSearchParams({
...(args.project ? { project: args.project } : {}),
...(args.effects ? { effects: args.effects } : {}),
+ // Iteration cap: bench only the first N seconds of timeline. Numbers from
+ // capped runs compare per-frame, or against runs with the SAME cap.
+ ...(args.clip ? { clip: args.clip } : {}),
arms: args.arms ?? "webcodecs,native",
runs: args.runs ?? "2",
fps: args.fps ?? "60",
@@ -248,6 +251,7 @@ async function main() {
} else if (event.event === "start") {
console.log(` project: ${event.project}`);
console.log(` effects: ${event.effects}`);
+ if (event.clip) console.log(` clip: first ${event.clip}s only (iteration cap)`);
console.log(` arms: ${event.arms.join(", ")} x${event.runs}\n`);
}
}
diff --git a/src/bench/runBench.ts b/src/bench/runBench.ts
index a28c00cbf..5ff461a1d 100644
--- a/src/bench/runBench.ts
+++ b/src/bench/runBench.ts
@@ -32,6 +32,8 @@ export interface BenchArm {
compositeOnly?: boolean;
/** Undo the 2026-07-17 compositor fixes, to attribute them. */
legacyCompositor?: boolean;
+ /** Gate G0: sync the GPU after compositing, in a `fence` stage of its own. */
+ gpuFence?: boolean;
}
export interface BenchRunResult {
@@ -66,6 +68,11 @@ const BENCH_PARAMS = {
// "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),
+ // Cap the timeline to its first N seconds (in memory). Iteration speed:
+ // per-frame stage attribution is a steady-state metric, so ~180 frames say
+ // what 820 say, at a quarter of the wait. Wall/fps from a capped run are NOT
+ // comparable with full-length runs — compare per-frame, or same-cap runs.
+ clip: params.get("clip") ? Number(params.get("clip")) : null,
};
/**
@@ -111,6 +118,49 @@ function zoomRanges(doc: AxcutDocument): unknown[] {
];
}
+/**
+ * Truncate the timeline to its first N seconds, on the in-memory copy only.
+ *
+ * Clips are 1:1 with source time in the v4 model (speed is applied later, from
+ * legacyEditor.speedRegions, by the export segment loop), so capping timeline
+ * and source together keeps the document coherent. Regions past the cap simply
+ * never fire, like on any short project. Nothing here reaches disk.
+ */
+function withClipCap(doc: AxcutDocument, seconds: number | null): AxcutDocument {
+ if (!seconds || !(seconds > 0)) return doc;
+ const timeline = (
+ doc as {
+ timeline?: {
+ clips?: {
+ sourceStartSec: number;
+ sourceEndSec: number;
+ timelineStartSec: number;
+ timelineEndSec: number;
+ }[];
+ };
+ }
+ ).timeline;
+ if (!timeline?.clips?.length) return doc;
+ const clips = [];
+ for (const clip of timeline.clips) {
+ if (clip.timelineStartSec >= seconds) continue;
+ if (clip.timelineEndSec <= seconds) {
+ clips.push(clip);
+ continue;
+ }
+ const keep = seconds - clip.timelineStartSec;
+ clips.push({
+ ...clip,
+ timelineEndSec: seconds,
+ sourceEndSec: clip.sourceStartSec + keep,
+ });
+ }
+ if (clips.length === 0) {
+ throw new Error(`--clip=${seconds} leaves no timeline at all`);
+ }
+ return { ...doc, timeline: { ...timeline, clips } } as AxcutDocument;
+}
+
function withEffects(doc: AxcutDocument, effects: string[]): AxcutDocument {
if (effects.length === 0) return doc;
const legacy: Record<string, unknown> = {
@@ -167,6 +217,23 @@ const ARMS: Record<string, BenchArm> = {
},
/** Today's shipping path, with the compositor fixes undone. */
"webcodecs-legacy": { nativeEncode: false, readFrequently: false, legacyCompositor: true },
+ // Gate G0 (rendering-architecture.md §7.1): the shipping path, but the GPU is
+ // forced to FINISH compositing before the encode timers start. The claim under
+ // test is pure attribution — encodeWait has been billing the compositor's
+ // execution. If §7.1 holds, encodeWait collapses to the encoder's own time and
+ // the difference reappears under `fence`; the wall itself may even worsen
+ // (the fence removes compositor/encoder overlap), which is fine — G0 is about
+ // where the time GOES, not how much there is. Run interleaved with its
+ // unfenced twin.
+ "webcodecs-fence": { nativeEncode: false, readFrequently: false, gpuFence: true },
+ // Same gate against the PRE-fix compositor — the arm the spec's numbers
+ // (encodeWait ~18.9 → ~6 ms) are actually quoted for.
+ "webcodecs-legacy-fence": {
+ nativeEncode: false,
+ readFrequently: false,
+ legacyCompositor: true,
+ gpuFence: 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
@@ -180,6 +247,7 @@ function applyArm(arm: BenchArm): void {
localStorage.setItem("openscreen.dropFrames", arm.dropFrames ? "1" : "0");
localStorage.setItem("openscreen.compositeOnly", arm.compositeOnly ? "1" : "0");
localStorage.setItem("openscreen.legacyCompositor", arm.legacyCompositor ? "1" : "0");
+ localStorage.setItem("openscreen.gpuFence", arm.gpuFence ? "1" : "0");
}
/**
@@ -367,12 +435,17 @@ 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 = withEffects(await resolveDocument(BENCH_PARAMS.project), BENCH_PARAMS.effects);
+ // Cap BEFORE effects, so the injected zoom fits inside the capped window.
+ const doc = withEffects(
+ withClipCap(await resolveDocument(BENCH_PARAMS.project), BENCH_PARAMS.clip),
+ 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)",
+ clip: BENCH_PARAMS.clip,
});
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 0b3f46a04..2acfb6499 100644
--- a/src/lib/exporter/frameRenderer.ts
+++ b/src/lib/exporter/frameRenderer.ts
@@ -1450,6 +1450,25 @@ export class FrameRenderer {
return this.compositeCanvas;
}
+ /**
+ * Bench-only sync point — gate G0, docs/architecture/rendering-architecture.md §7.1.
+ *
+ * Draw calls queue GPU work; the cost lands on whichever operation first needs
+ * the pixels, which today is the encoder — so the compositor's execution is
+ * billed to `encodeWait`. Forcing execution HERE moves that cost into the
+ * caller's `fence` timer and the stage table finally says where the time goes.
+ *
+ * gl.finish() drains the Pixi context. Canvas2D has no finish(): the 1×1
+ * getImageData is the equivalent — it forces the pending raster work of the
+ * whole surface chain (pixi canvas → shadow/foreground → composite) to
+ * complete, while transferring a single pixel.
+ */
+ finishGpuWork(): void {
+ const gl = (this.app?.renderer as unknown as { gl?: WebGLRenderingContext } | null)?.gl;
+ gl?.finish();
+ this.compositeCtx?.getImageData(0, 0, 1, 1);
+ }
+
destroy(): void {
if (this.videoSprite) {
this.videoSprite.destroy();
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 81da1c6a7..9abb98ad9 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -137,6 +137,27 @@ function compositeOnlyEnabled(): boolean {
}
}
+/**
+ * Gate G0 — docs/architecture/rendering-architecture.md §7.1.
+ *
+ * Force the GPU to FINISH compositing before the encode timers start, in a
+ * `fence` stage of its own. If §7.1 is right, `encodeWait` collapses to the
+ * encoder's own time and the difference reappears under `fence`; if it does
+ * not, the architecture document's premise is wrong and work on it stops.
+ *
+ * The fence serialises compositor and encoder (no overlap), so it perturbs the
+ * wall it measures: this is a measurement arm, never a shipping default.
+ *
+ * localStorage.setItem("openscreen.gpuFence", "1")
+ */
+function gpuFenceEnabled(): boolean {
+ try {
+ return localStorage.getItem("openscreen.gpuFence") === "1";
+ } catch {
+ return false;
+ }
+}
+
async function probeOneEncoder(opts: {
label: string;
width: number;
@@ -1203,6 +1224,11 @@ export class VideoExporter {
// Both produce NO FILE — they price one stage in isolation.
const compositeOnly = useNative && compositeOnlyEnabled();
const dropFrames = useNative && !compositeOnly && dropFramesEnabled();
+ // Gate G0: sync the GPU after compositing, before anything downstream runs.
+ const gpuFence = gpuFenceEnabled();
+ if (gpuFence) {
+ console.warn("[export perf] G0 fence: GPU synced after compositing, per frame");
+ }
let sink: NativeFrameSink | null = null;
let extractor: CanvasFrameExtractor | null = null;
if (useNative && api && compositeOnly) {
@@ -1432,6 +1458,15 @@ export class VideoExporter {
await renderer.renderFrame(videoFrame, sourceTimestampMs * 1000, webcamFrame);
stopRender();
+ // Gate G0: everything renderFrame queued must EXECUTE before the
+ // next timer starts, so `fence` absorbs the compositor's real cost
+ // and the stages below stop being billed for it.
+ if (gpuFence) {
+ const stopFence = timings.start("fence");
+ renderer.finishGpuWork();
+ stopFence();
+ }
+
// 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.