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(poc): bake the background and cull what cannot be seen — 85 fps

Etienne Lescot1170bb1d219e
diff --git a/docs/architecture/rendering-architecture.md b/docs/architecture/rendering-architecture.md
index 71981f58b..f1c27e000 100644
--- a/docs/architecture/rendering-architecture.md
+++ b/docs/architecture/rendering-architecture.md
@@ -545,6 +545,97 @@ its own bug, unrelated to rendering.
---
+## Annex C — The standalone POC, and the number Step 4 was waiting for
+
+`poc/` — its own directory, its own server, no Electron, no app code, nothing
+imported from the existing compositor. Two real recordings (screen + webcam), one
+layout, animated: two eased zooms with a focus point, and a layout move where the
+webcam grows from a docked circle into a panel, its shape morphing through the
+same SDF. Decode and mux via mediabunny, composite in WGSL, out to a watchable
+mp4. The layout, the easings and the effects are written from zero — the point was
+to prove the paradigm reconstructs the product, not to reuse what exists.
+
+**Measured by the product owner, on a visible window, interleaved A/B, one
+discarded warm-up round, 4-second exports at 1080p on an AMD RDNA-3 iGPU:**
+
+| arm | cruise | spread | runs |
+|---|---:|---:|---|
+| optimised | **85.1 fps** | 6 % | 88.9 / 84.0 / 85.1 |
+| naive | 46.3 fps | 35 % | 46.3 / 53.8 / 37.5 |
+
+**+84 % — it roughly doubles.** Read honestly: the naive arm's 35 % spread makes
+the *size* loose (85.1 against its best run is +58 %, against its worst +127 %);
+the direction and the order of magnitude are not in doubt. The optimised arm is
+steady at 6 % because it does less work, so it has less to vary.
+
+**Against the shipping compositor** (Annex B, different project — the comparison
+is an order of magnitude, not a measurement): 29.5 fps on a still frame, ~17 fps
+while the camera moves. The POC is 3–5× that, and it does not slow down when the
+camera moves, because there is no cache to miss.
+
+**85 fps at 1080p is past 60.** That is priority 1 of this document — preview
+fluidity — reachable on the *weakest* machine in the fleet, with room over.
+
+### C.1 — What produced the 84 %
+
+Three changes, all exact, all verified by the picture (optimised and naive render
+the same frame, checked on a zoomed frame where the culling is active):
+
+1. **The background was recomputing a constant.** 16 gradient evaluations per
+ pixel per frame, 210 times, for an image that never changes. Baked into a
+ texture once at init; the frame reads one texel. This is *not* the §7.2 shadow
+ cache in disguise, and the difference is the whole argument: a cache guesses
+ its input has not changed and needs a key to find out. A constant has no input.
+2. **The shadow ran everywhere.** 12 taps on every pixel, including under the
+ opaque video and far outside the rect where the answer is zero. Every tap lands
+ within `spread` of the pixel, so the box grown by spread bounds where any tap
+ can hit, and the box shrunk by spread bounds where all of them do — Minkowski
+ sums with the tap disc, the same number by arithmetic rather than by twelve
+ samples.
+3. **The frame was drawn as one fullscreen triangle with `if`s.** It paid for
+ every pixel of every effect and threw most of it away. Now each element is a
+ quad sized to its own rect: the rasterizer runs the fragment shader only where
+ the element is and clips what leaves the stage, in fixed function, with no
+ branch. A zoomed recording is 2.7× the stage — two thirds of it is off-screen
+ and now costs nothing. Plus CPU culling from the rects `evaluate` already
+ produced: when the recording covers the stage (every zoom), the background and
+ its shadow are not drawn at all; an off-stage webcam is not drawn at all.
+
+**§8b needs one correction.** Its cache list — "wallpaper 1× · **shadow
+per-geometry** · masks per-shape · …" — carries a 2D reflex into the target: the
+shadow cache exists because a CSS filter costs 14 ms on a CPU, and it misses by
+construction whenever the camera moves, which the product owner confirms is the
+norm. In a shader there is nothing to cache: the shadow is recomputed every frame
+and the frame still runs at 85 fps. The wallpaper entry stays — that one is a
+constant, not a cache.
+
+### C.2 — Measurement hazards this POC surfaced
+
+Every one of these produced a confident, wrong number first:
+
+- **A hidden tab is a throttled tab**, and Chromium escalates the longer it stays
+ hidden. Same code, same machine, one session: 58.3 → 42.8 → 35.5 → 6.0 fps, and
+ an A/B that reported 6.0 on *both* arms with a 401 % spread. The harness now
+ refuses to run when `document.hidden`. **Nothing measured from an agent-driven
+ browser pane is admissible; this annex's numbers were taken by a human, on a
+ visible window.**
+- **The instruments cost 17 %.** `onSubmittedWorkDone()` per frame is a fence that
+ forbids decode/composite/encode from overlapping; `mapAsync()` for the GPU
+ timestamps is a sync per frame. Both are switchable, and the harness measures
+ itself: instrumented 35.5 fps vs clean 42.8. The phase breakdown attributes; it
+ does not price.
+- **Average fps is not cruise fps.** The first frames of a 4-second export cost
+ 358/113/28/350 ms — 10.3 ms/frame of drag, and the mean lands 26 % under the
+ real rate. Cruise = median of the last three quarters.
+- **A canvas in the document is presented every frame** — 35 ms/frame of
+ compositing an export never does. The render target is an OffscreenCanvas.
+- **`getSample(t)` per frame is a seek per frame**: 122 ms/frame, three times
+ everything else combined, on a long-GOP screen recording. Forward streams: 0.6.
+- **The harness leaked its GPU device**, and six back-to-back runs decayed
+ 19.9 → 8.6 → 7.5 fps during the very A/B meant to settle a question.
+
+---
+
**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
diff --git a/poc/composite.wgsl b/poc/composite.wgsl
index fc793f70a..e0e6639f4 100644
--- a/poc/composite.wgsl
+++ b/poc/composite.wgsl
@@ -1,10 +1,20 @@
// The compositor. Two sources, one layout, three effects — written from zero.
//
+// Drawn the way a game draws: one quad per element, sized to the element. The
+// rasterizer then runs the fragment shader ONLY on the pixels that element
+// covers, and clips whatever falls outside the frame — for free, in fixed
+// function, with no branch. A zoomed recording is 2.7x the stage: two thirds of
+// it is off-screen and costs nothing.
+//
+// The alternative — one fullscreen triangle with `if`s — pays for every pixel of
+// every effect and then throws most of it away. That is what the first version of
+// this file did.
+//
// Everything is a pure function of the uniforms. No cache: a shader recomputes
// every pixel every frame, which is the point of the paradigm.
struct U {
- // stage.xy | time (s) | screenRadius
+ // stage.xy | unused | screenRadius
a : vec4f,
// screenRect: x, y, w, h — already carries the zoom (scale + pan)
screen : vec4f,
@@ -12,7 +22,7 @@ struct U {
webcam : vec4f,
// shadowIntensity | bgBlurPx | shadowOffsetY | shadowSpread
fx : vec4f,
- // webcamRadius | motionBlurPx | webcamCoverScale | unused
+ // webcamRadius | motionBlurPx | webcamCoverScale | optimised(0/1)
b : vec4f,
};
@@ -20,23 +30,60 @@ struct U {
@group(0) @binding(1) var samp : sampler;
@group(0) @binding(2) var screenTex : texture_external;
@group(0) @binding(3) var webcamTex : texture_external;
+@group(0) @binding(4) var bgTex : texture_2d<f32>;
struct VsOut {
@builtin(position) pos : vec4f,
+ // Stage-space uv (0..1 across the OUTPUT), not the quad's own uv: the fragment
+ // shaders all reason in stage pixels, and the quad is only there to bound them.
@location(0) uv : vec2f,
};
-// Full-screen triangle: three vertices, no vertex buffer.
-@vertex
-fn vs(@builtin(vertex_index) i : u32) -> VsOut {
+// ---- vertex: one quad per element ------------------------------------------
+
+/**
+ * Emit `rect` as two triangles in stage space.
+ *
+ * Clipping is the rasterizer's job: a rect that runs off the stage — every zoomed
+ * recording — is cut by fixed-function hardware before a single fragment is
+ * dispatched.
+ */
+fn quad(vi : u32, rect : vec4f) -> VsOut {
+ var corners = array<vec2f, 6>(
+ vec2f(0.0, 0.0), vec2f(1.0, 0.0), vec2f(0.0, 1.0),
+ vec2f(0.0, 1.0), vec2f(1.0, 0.0), vec2f(1.0, 1.0),
+ );
+ let c = corners[vi];
+ let px = rect.xy + c * rect.zw;
var out : VsOut;
- let x = f32((i << 1u) & 2u);
- let y = f32(i & 2u);
- out.uv = vec2f(x, y);
- out.pos = vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
+ out.pos = vec4f(px.x / u.a.x * 2.0 - 1.0, 1.0 - px.y / u.a.y * 2.0, 0.0, 1.0);
+ out.uv = px / u.a.xy;
return out;
}
+@vertex fn vsFull(@builtin(vertex_index) i : u32) -> VsOut {
+ return quad(i, vec4f(0.0, 0.0, u.a.x, u.a.y));
+}
+
+@vertex fn vsScreen(@builtin(vertex_index) i : u32) -> VsOut {
+ return quad(i, u.screen);
+}
+
+/** The shadow's quad: the rect, grown by the spread — its exact reach. */
+@vertex fn vsScreenShadow(@builtin(vertex_index) i : u32) -> VsOut {
+ let s = u.fx.w + 1.0;
+ return quad(i, vec4f(u.screen.xy - vec2f(s), u.screen.zw + vec2f(s * 2.0)) + vec4f(0.0, u.fx.z, 0.0, 0.0));
+}
+
+@vertex fn vsWebcam(@builtin(vertex_index) i : u32) -> VsOut {
+ return quad(i, u.webcam);
+}
+
+@vertex fn vsWebcamShadow(@builtin(vertex_index) i : u32) -> VsOut {
+ let s = u.fx.w + 1.0;
+ return quad(i, vec4f(u.webcam.xy - vec2f(s), u.webcam.zw + vec2f(s * 2.0)) + vec4f(0.0, u.fx.z, 0.0, 0.0));
+}
+
// ---- geometry ---------------------------------------------------------------
/** Signed distance to a rounded box. Negative inside. */
@@ -52,28 +99,28 @@ fn cover(d : f32) -> f32 {
}
// ---- effect 1: the background ----------------------------------------------
-// A gradient, animated, then blurred. Computed, never sampled from an image —
-// so there is nothing to cache and nothing to load.
+//
+// A blurred gradient, baked into a texture ONCE by fsBake. The frame reads one
+// texel — and only where the recording does not already cover it.
+//
+// It was 16 gradient evaluations per pixel per frame, every one recomputing a
+// CONSTANT. This is not the shadow cache in disguise, and the difference is the
+// whole argument: a cache guesses that its input has not changed and needs a key
+// to find out. This has no key because it has no input — the background IS a
+// constant. The shadow follows the camera, so it gets no such luxury.
-fn gradient(uv : vec2f, t : f32) -> vec3f {
+fn gradient(uv : vec2f) -> vec3f {
let a = vec3f(0.06, 0.11, 0.24);
let b = vec3f(0.35, 0.12, 0.42);
let c = vec3f(0.02, 0.35, 0.38);
- let w = 0.5 + 0.5 * sin(t * 0.4 + uv.x * 2.0);
+ let w = 0.5 + 0.5 * sin(uv.x * 2.0);
return mix(mix(a, b, uv.y), c, w * 0.45);
}
-/**
- * The blur, as a shader does it: sample the source at N offsets and average.
- *
- * The source is a FUNCTION here, not a texture, so the "blur" evaluates the
- * gradient N times instead of reading N texels. Same idea, no memory traffic.
- * 16 taps on a Fibonacci spiral: enough for a gradient, which has no detail to
- * lose.
- */
-fn blurredBackground(uv : vec2f, t : f32, radiusPx : f32) -> vec3f {
+fn blurredGradient(uv : vec2f) -> vec3f {
+ let radiusPx = u.fx.y;
if (radiusPx < 0.5) {
- return gradient(uv, t);
+ return gradient(uv);
}
let px = radiusPx / u.a.xy;
var acc = vec3f(0.0);
@@ -83,26 +130,52 @@ fn blurredBackground(uv : vec2f, t : f32, radiusPx : f32) -> vec3f {
let fi = f32(i);
let r = sqrt((fi + 0.5) / f32(taps));
let a = fi * golden;
- acc = acc + gradient(uv + vec2f(cos(a), sin(a)) * r * px, t);
+ acc = acc + gradient(uv + vec2f(cos(a), sin(a)) * r * px);
}
return acc / f32(taps);
}
+/** Init only. */
+@fragment fn fsBake(in : VsOut) -> @location(0) vec4f {
+ return vec4f(blurredGradient(in.uv), 1.0);
+}
+
+/** Per frame: one texel — or the naive 16 taps, for the A/B. */
+@fragment fn fsBackground(in : VsOut) -> @location(0) vec4f {
+ if (u.b.w > 0.5) {
+ return vec4f(textureSampleLevel(bgTex, samp, in.uv, 0.0).rgb, 1.0);
+ }
+ return vec4f(blurredGradient(in.uv), 1.0);
+}
+
// ---- effect 2: the drop shadow ----------------------------------------------
-// The shape is known analytically — a rounded rect — so its shadow does not need
-// a blur pass at all: the coverage of a rounded box, evaluated at a few offsets,
-// IS the shadow. No silhouette texture, no ping-pong, no 18 passes.
//
-// 12 taps on a ring, at increasing radius. It is a soft shape under an opaque
-// rectangle; the eye reads its falloff, not its exact profile.
-
-fn shadow(px : vec2f, rect : vec4f, radius : f32, intensity : f32) -> f32 {
+// The shape is known analytically — a rounded rect — so the shadow needs no blur
+// pass: the coverage of that box, sampled at a few offsets, IS the shadow. No
+// silhouette texture, no ping-pong, no 18 passes.
+//
+// The quad already bounds it to the rect + spread, so the "outside" case never
+// reaches a fragment. What is left is the inside: every tap lands within `spread`
+// of the pixel, so within the box SHRUNK by spread they all hit, and the answer
+// is `intensity` with no taps at all. That is the box's Minkowski difference with
+// the tap disc — the same number by arithmetic, not an approximation. Only the
+// band around the edge pays the twelve samples.
+
+fn shadowAt(px : vec2f, rect : vec4f, radius : f32, intensity : f32) -> f32 {
if (intensity <= 0.0) {
return 0.0;
}
let centre = rect.xy + rect.zw * 0.5 + vec2f(0.0, u.fx.z);
let half = rect.zw * 0.5;
let spread = u.fx.w;
+ let p = px - centre;
+
+ if (u.b.w > 0.5) {
+ if (sdRoundBox(p, max(half - vec2f(spread), vec2f(0.0)), max(radius - spread, 0.0)) < -0.5) {
+ return intensity;
+ }
+ }
+
var acc = 0.0;
let taps = 12;
let golden = 2.39996;
@@ -111,34 +184,24 @@ fn shadow(px : vec2f, rect : vec4f, radius : f32, intensity : f32) -> f32 {
let r = sqrt((fi + 0.5) / f32(taps)) * spread;
let a = fi * golden;
let o = vec2f(cos(a), sin(a)) * r;
- acc = acc + cover(sdRoundBox(px - centre + o, half, radius));
+ acc = acc + cover(sdRoundBox(p + o, half, radius));
}
return (acc / f32(taps)) * intensity;
}
-// ---- effect 3: the masks ----------------------------------------------------
-// Rounded rect for the recording, circle for the webcam. Both are the same SDF
-// with different parameters — which is the whole argument for computing shapes
-// instead of tessellating them.
+@fragment fn fsScreenShadow(in : VsOut) -> @location(0) vec4f {
+ return vec4f(0.0, 0.0, 0.0, shadowAt(in.uv * u.a.xy, u.screen, u.a.w, u.fx.x));
+}
-/**
- * The webcam's mask, morphing with the layout animation.
- *
- * radius drives the shape: a circle when radius == min(half), a rounded rect as
- * it drops. The animation is a single number, and the SDF interpolates the SHAPE
- * for free — this is the thing a tessellated 2D mask cannot do without rebuilding
- * geometry every frame.
- */
-fn webcamCover(px : vec2f, rect : vec4f, radius : f32) -> f32 {
- let centre = rect.xy + rect.zw * 0.5;
- let half = rect.zw * 0.5;
- return cover(sdRoundBox(px - centre, half, radius));
+@fragment fn fsWebcamShadow(in : VsOut) -> @location(0) vec4f {
+ return vec4f(0.0, 0.0, 0.0, shadowAt(in.uv * u.a.xy, u.webcam, u.b.x, u.fx.x * 0.8));
}
+// ---- effect 3: the masks + the sources --------------------------------------
+
/**
- * Directional motion blur, applied while the camera moves.
- *
- * Skipped entirely at rest: a branch is free next to nine texture fetches.
+ * Directional motion blur while the camera moves. Skipped at rest: a branch is
+ * free next to seven texture fetches, and it is uniform across the frame.
*/
fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
let uv0 = (px - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
@@ -149,50 +212,37 @@ fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
let taps = 7;
for (var i = 0; i < taps; i = i + 1) {
let t = (f32(i) / f32(taps - 1)) - 0.5;
- let p = px + vec2f(blurPx * t, 0.0);
- let uv = (p - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
+ let uv = ((px + vec2f(blurPx * t, 0.0)) - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
acc = acc + textureSampleBaseClampToEdge(screenTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0))).rgb;
}
return acc / f32(taps);
}
-fn over(dst : vec3f, src : vec3f, a : f32) -> vec3f {
- return mix(dst, src, clamp(a, 0.0, 1.0));
-}
-
-@fragment
-fn fs(in : VsOut) -> @location(0) vec4f {
+@fragment fn fsScreen(in : VsOut) -> @location(0) vec4f {
let px = in.uv * u.a.xy;
- let t = u.a.z;
-
- // 1. Background: a blurred animated gradient.
- var colour = blurredBackground(in.uv, t, u.fx.y);
-
- // 2. Shadow under the recording.
- let s = shadow(px, u.screen, u.a.w, u.fx.x);
- colour = over(colour, vec3f(0.0), s);
-
- // 3. The recording: zoomed (the rect already carries scale + pan), masked to a
- // rounded rect, motion-blurred while the camera travels.
- let sc = cover(sdRoundBox(px - (u.screen.xy + u.screen.zw * 0.5), u.screen.zw * 0.5, u.a.w));
- if (sc > 0.0) {
- colour = over(colour, sampleScreen(px, u.b.y), sc);
+ let c = cover(sdRoundBox(px - (u.screen.xy + u.screen.zw * 0.5), u.screen.zw * 0.5, u.a.w));
+ if (c <= 0.0) {
+ discard;
}
+ return vec4f(sampleScreen(px, u.b.y), c);
+}
- // 4. The webcam, its shape morphing with the layout animation, with its own
- // shadow.
- let ws = shadow(px, u.webcam, u.b.x, u.fx.x * 0.8);
- colour = over(colour, vec3f(0.0), ws);
- let wc = webcamCover(px, u.webcam, u.b.x);
- if (wc > 0.0) {
- // Cover-fit: a 4:3 source in a square hole would squash without this. Sample
- // the middle and let the mask crop, which is what the eye expects.
- let centre = u.webcam.xy + u.webcam.zw * 0.5;
- var uv = (px - centre) / max(u.webcam.zw, vec2f(1.0));
- uv = uv * vec2f(u.b.z, 1.0) + vec2f(0.5);
- let cam = textureSampleBaseClampToEdge(webcamTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0)));
- colour = over(colour, cam.rgb, wc);
+/**
+ * The webcam's mask, morphing with the layout animation: radius drives the shape,
+ * circle when docked and rounded rect when grown. The SDF interpolates the SHAPE
+ * for free — a tessellated 2D mask would rebuild geometry every frame for this.
+ */
+@fragment fn fsWebcam(in : VsOut) -> @location(0) vec4f {
+ let px = in.uv * u.a.xy;
+ let centre = u.webcam.xy + u.webcam.zw * 0.5;
+ let c = cover(sdRoundBox(px - centre, u.webcam.zw * 0.5, u.b.x));
+ if (c <= 0.0) {
+ discard;
}
-
- return vec4f(colour, 1.0);
+ // Cover-fit: a 4:3 source in a square hole would squash without this. Sample
+ // the middle and let the mask crop, which is what the eye expects.
+ var uv = (px - centre) / max(u.webcam.zw, vec2f(1.0));
+ uv = uv * vec2f(u.b.z, 1.0) + vec2f(0.5);
+ let cam = textureSampleBaseClampToEdge(webcamTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0)));
+ return vec4f(cam.rgb, c);
}
diff --git a/poc/index.html b/poc/index.html
index 99041806c..cac94faee 100644
--- a/poc/index.html
+++ b/poc/index.html
@@ -45,6 +45,10 @@
<label for="instrument">instrumenté</label>
<input id="instrument" type="checkbox" checked style="width: auto" />
</div>
+ <div>
+ <label for="optimise">optimisé</label>
+ <input id="optimise" type="checkbox" checked style="width: auto" />
+ </div>
<button id="run">Lancer</button>
<button id="compare" style="background: #22222c; border: 1px solid #33333f">
Comparer A/B
diff --git a/poc/main.js b/poc/main.js
index dfe0f7ce2..404715473 100644
--- a/poc/main.js
+++ b/poc/main.js
@@ -161,6 +161,16 @@ async function openVideo(url) {
async function run(override = {}) {
const started = performance.now();
+ // A hidden tab is a throttled tab. Chromium de-prioritises everything in one —
+ // the GPU work included — and clamps chained timers to a second. Measured
+ // here: the same code that cruises at 58 fps visible reports 6.0 fps hidden,
+ // on BOTH arms, with a 401% spread. Every number taken from a background tab
+ // is fiction, so this refuses rather than reports.
+ if (document.hidden) {
+ throw new Error(
+ "tab is hidden — Chromium throttles background tabs. Bring it to the front and re-run.",
+ );
+ }
document.querySelector("#run").disabled = true;
log("opening sources…");
@@ -223,12 +233,65 @@ async function run(override = {}) {
const code = await (await fetch("composite.wgsl")).text();
const module = device.createShaderModule({ code });
device.pushErrorScope("validation");
- const pipeline = device.createRenderPipeline({
- layout: "auto",
- vertex: { module, entryPoint: "vs" },
- fragment: { module, entryPoint: "fs", targets: [{ format }] },
+
+ // One explicit layout for every pass, so a shader that happens not to sample
+ // bgTex does not silently get a different bind group. `auto` derives the
+ // layout from what the entry point USES, which makes the layout an accident of
+ // dead-code elimination.
+ const bindGroupLayout = device.createBindGroupLayout({
+ entries: [
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: {} },
+ { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
+ { binding: 2, visibility: GPUShaderStage.FRAGMENT, externalTexture: {} },
+ { binding: 3, visibility: GPUShaderStage.FRAGMENT, externalTexture: {} },
+ { binding: 4, visibility: GPUShaderStage.FRAGMENT, texture: {} },
+ ],
+ });
+ const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] });
+
+ // Straight-alpha "over": the compositor's only blend.
+ const OVER = {
+ color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
+ alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" },
+ };
+ const makePass = (vs, fs, blend) =>
+ device.createRenderPipeline({
+ label: fs,
+ layout: pipelineLayout,
+ vertex: { module, entryPoint: vs },
+ fragment: { module, entryPoint: fs, targets: [{ format, ...(blend ? { blend } : {}) }] },
+ primitive: { topology: "triangle-list" },
+ });
+
+ // Five passes, each a quad sized to its element. The rasterizer clips whatever
+ // leaves the stage — which, during a zoom, is most of the recording.
+ const passes = {
+ background: makePass("vsFull", "fsBackground", null),
+ screenShadow: makePass("vsScreenShadow", "fsScreenShadow", OVER),
+ screen: makePass("vsScreen", "fsScreen", OVER),
+ webcamShadow: makePass("vsWebcamShadow", "fsWebcamShadow", OVER),
+ webcam: makePass("vsWebcam", "fsWebcam", OVER),
+ };
+
+ // The bake runs before any video exists, so it gets a layout of its own: the
+ // uniforms and nothing else.
+ const bakeLayout = device.createBindGroupLayout({
+ entries: [
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: {} },
+ ],
+ });
+ const bgPipeline = device.createRenderPipeline({
+ label: "bake",
+ layout: device.createPipelineLayout({ bindGroupLayouts: [bakeLayout] }),
+ vertex: { module, entryPoint: "vsFull" },
+ fragment: { module, entryPoint: "fsBake", targets: [{ format: "rgba8unorm" }] },
primitive: { topology: "triangle-list" },
});
+ const bgTexture = device.createTexture({
+ size: [OUT.width, OUT.height],
+ format: "rgba8unorm",
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
+ });
const shaderError = await device.popErrorScope();
if (shaderError) throw new Error(`shader: ${shaderError.message}`);
@@ -256,6 +319,35 @@ async function run(override = {}) {
const camAspect = webcam.track.displayWidth / webcam.track.displayHeight;
let memo = null;
+ // Bake the background. Once, here — not 210 times inside the loop.
+ uniforms.set([OUT.width, OUT.height, 0, 0], 0);
+ uniforms.set([shadowIntensity, bgBlur, 18, 42], 12);
+ device.queue.writeBuffer(uniformBuffer, 0, uniforms);
+ {
+ const enc = device.createCommandEncoder();
+ const pass = enc.beginRenderPass({
+ colorAttachments: [
+ {
+ view: bgTexture.createView(),
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
+ loadOp: "clear",
+ storeOp: "store",
+ },
+ ],
+ });
+ pass.setPipeline(bgPipeline);
+ pass.setBindGroup(
+ 0,
+ device.createBindGroup({
+ layout: bakeLayout,
+ entries: [{ binding: 0, resource: { buffer: uniformBuffer } }],
+ }),
+ );
+ pass.draw(3);
+ pass.end();
+ device.queue.submit([enc.finish()]);
+ }
+
// ---- decode: forward streams, not seeks ----
// getSample(t) per frame is a random-access SEEK per frame: on a long-GOP
// screen recording that means re-decoding from the last keyframe, every time.
@@ -298,6 +390,7 @@ async function run(override = {}) {
// across the two. If they disagree, the breakdown describes a program that
// only exists while being measured.
const instrumented = override.instrumented ?? document.querySelector("#instrument").checked;
+ const optimised = override.optimised ?? document.querySelector("#optimise").checked;
const frames = [];
const t0 = performance.now();
let rendered = 0;
@@ -331,15 +424,16 @@ async function run(override = {}) {
uniforms.set([f.screen.x, f.screen.y, f.screen.w, f.screen.h], 4);
uniforms.set([f.webcam.x, f.webcam.y, f.webcam.w, f.webcam.h], 8);
uniforms.set([shadowIntensity, bgBlur, 18, 42], 12); // intensity | bgBlur | offsetY | spread
- uniforms.set([f.webcamRadius, f.motionBlurPx, camAspect, 0], 16);
+ uniforms.set([f.webcamRadius, f.motionBlurPx, camAspect, optimised ? 1 : 0], 16);
device.queue.writeBuffer(uniformBuffer, 0, uniforms);
const bind = device.createBindGroup({
- layout: pipeline.getBindGroupLayout(0),
+ layout: bindGroupLayout,
entries: [
{ binding: 0, resource: { buffer: uniformBuffer } },
{ binding: 1, resource: sampler },
{ binding: 2, resource: screenTex },
{ binding: 3, resource: webcamTex },
+ { binding: 4, resource: bgTexture.createView() },
],
});
p.evaluate = mark() - m;
@@ -359,9 +453,42 @@ async function run(override = {}) {
? { timestampWrites: { querySet, beginningOfPassWriteIndex: 0, endOfPassWriteIndex: 1 } }
: {}),
});
- pass.setPipeline(pipeline);
+ // CULLING, on the CPU, before anything is submitted.
+ //
+ // The cheapest fragment is the one never dispatched. Two tests, both from
+ // the rects evaluate() already produced:
+ // - the recording covers the stage (every zoom does): nothing underneath
+ // can show, so the background and its shadow are not drawn at all. The
+ // test insets by the corner radius, because a rounded corner is where
+ // the background WOULD peek through.
+ // - the webcam is entirely off-stage: it and its shadow are not drawn.
+ const r = f.screen;
+ const rad = 28;
+ const screenCoversStage =
+ optimised &&
+ r.x + rad <= 0 &&
+ r.y + rad <= 0 &&
+ r.x + r.w - rad >= OUT.width &&
+ r.y + r.h - rad >= OUT.height;
+ const w = f.webcam;
+ const webcamVisible =
+ !optimised || (w.x < OUT.width && w.y < OUT.height && w.x + w.w > 0 && w.y + w.h > 0);
+
pass.setBindGroup(0, bind);
- pass.draw(3);
+ if (!screenCoversStage) {
+ pass.setPipeline(passes.background);
+ pass.draw(6);
+ pass.setPipeline(passes.screenShadow);
+ pass.draw(6);
+ }
+ pass.setPipeline(passes.screen);
+ pass.draw(6);
+ if (webcamVisible) {
+ pass.setPipeline(passes.webcamShadow);
+ pass.draw(6);
+ pass.setPipeline(passes.webcam);
+ pass.draw(6);
+ }
pass.end();
if (useQueries) {
encoder.resolveQuerySet(querySet, 0, 2, resolveBuffer, 0);
@@ -404,10 +531,17 @@ async function run(override = {}) {
rendered++;
if (i % 15 === 0) {
setStat("progress", `${i}/${totalFrames}`);
- // A 640px preview every 15 frames. It is OFF the clock — the frame's
- // timer has already stopped — and it never touches the render path.
+ // A 640px preview every 15 frames. OFF the clock — the frame's timer has
+ // already stopped — and it never touches the render path.
preview.drawImage(canvas, 0, 0, previewCanvas.width, previewCanvas.height);
- await new Promise((r) => setTimeout(r, 0));
+ // Yield through a MessageChannel, not setTimeout: a chained setTimeout is
+ // clamped to 1000 ms in a background tab, which would put eight seconds of
+ // pure waiting into a four-second export's wall.
+ await new Promise((r) => {
+ const ch = new MessageChannel();
+ ch.port1.onmessage = () => r();
+ ch.port2.postMessage(0);
+ });
}
}
@@ -436,9 +570,12 @@ async function run(override = {}) {
setStat("fps", cruiseFps.toFixed(1));
setStat("progress", `${rendered}/${totalFrames}`);
setStat("perframe", `${cruiseMs.toFixed(1)} ms`);
- setStat("render", `${median(warm.map((f) => f.fence)).toFixed(1)} ms`);
- setStat("decode", `${median(warm.map((f) => f.decode)).toFixed(1)} ms`);
- setStat("encode", `${median(warm.map((f) => f.encode)).toFixed(1)} ms`);
+ // `?? 0`: the clean pass has no phase timers by construction — that is what
+ // makes it clean. Reading them back as undefined is not an error, it is the
+ // point.
+ setStat("render", instrumented ? `${median(warm.map((f) => f.fence ?? 0)).toFixed(1)} ms` : "—");
+ setStat("decode", instrumented ? `${median(warm.map((f) => f.decode ?? 0)).toFixed(1)} ms` : "—");
+ setStat("encode", instrumented ? `${median(warm.map((f) => f.encode ?? 0)).toFixed(1)} ms` : "—");
log(
`\n=== [${instrumented ? "INSTRUMENTED" : "CLEAN"}] cruise ${cruiseFps.toFixed(1)} fps — ${cruiseMs.toFixed(1)} ms/frame (median of the last ${warm.length}) ===`,
@@ -513,6 +650,7 @@ async function run(override = {}) {
await webcamStream.return?.();
screen.input.dispose();
webcam.input.dispose();
+ bgTexture.destroy();
device.destroy();
document.querySelector("#run").disabled = false;
@@ -520,14 +658,17 @@ async function run(override = {}) {
}
/**
- * Do the instruments change the answer? Interleaved A/B/A/B, because they can
- * only be compared against drift.
+ * Interleaved A/B/A/B, because an effect can only be told apart from drift.
*
- * Two identical instrumented runs measured 34.8 and 28.3 fps on this machine —
- * 23% apart, which is the size of the effect under test. Back-to-back runs
- * therefore prove nothing: the arms have to alternate so drift shows up as a run
- * disagreeing with its OWN repeat, instead of masquerading as the instruments'
- * cost. Same rule, and same reason, as the app's export bench.
+ * Two identical runs measured 34.8 and 28.3 fps on this machine — 23% apart,
+ * which is the size of the effects under test. Sequential arms therefore prove
+ * nothing: they alternate so drift shows up as a run disagreeing with its OWN
+ * repeat instead of masquerading as the change. Same rule, and same reason, as
+ * the app's export bench.
+ *
+ * Both shader variants live in the same module, chosen by a uniform, so the two
+ * arms differ by that uniform and nothing else — no reload, no recompile, no
+ * second session.
*/
async function compare(rounds = 3) {
const median = (xs) => {
@@ -535,42 +676,43 @@ async function compare(rounds = 3) {
return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
const spread = (xs) => (Math.max(...xs) - Math.min(...xs)) / median(xs);
- const arms = { INSTRUMENTED: [], CLEAN: [] };
+ const arms = { OPTIMISED: [], NAIVE: [] };
// Round 0 is thrown away. Both arms climb monotonically across the first
// rounds — 15.0 → 28.4 → 33.3 and 27.9 → 37.2 → 42.0 — which is the browser
// and the GPU waking up, not the arms differing. Keeping it put a 64% spread
// on a 23% effect and voided the comparison by itself.
for (let r = 0; r <= rounds; r++) {
- for (const [name, instrumented] of [
- ["INSTRUMENTED", true],
- ["CLEAN", false],
+ for (const [name, optimised] of [
+ ["OPTIMISED", true],
+ ["NAIVE", false],
]) {
- const res = await run({ instrumented });
+ // Clean on both sides: the instruments cost 17%, and they are not what
+ // is being compared here.
+ const res = await run({ optimised, instrumented: false });
if (r > 0) arms[name].push(res.cruiseFps);
}
}
document.querySelector("#log").textContent = "";
- log("=== do the instruments change the answer? (interleaved A/B) ===\n");
+ log("=== baked background + shadow early-out, vs neither (interleaved A/B) ===\n");
for (const [name, xs] of Object.entries(arms)) {
log(
`${name.padEnd(13)} cruise ${median(xs).toFixed(1).padStart(5)} fps spread ${(spread(xs) * 100).toFixed(0)}% runs: ${xs.map((x) => x.toFixed(1)).join(" / ")}`,
);
}
- const cost = median(arms.CLEAN) - median(arms.INSTRUMENTED);
- const worst = Math.max(spread(arms.CLEAN), spread(arms.INSTRUMENTED)) * 100;
- log(
- `\ninstruments cost: ${cost.toFixed(1)} fps (${((cost / median(arms.CLEAN)) * 100).toFixed(0)}%)`,
- );
- if (worst >= Math.abs((cost / median(arms.CLEAN)) * 100)) {
+ const gain = median(arms.OPTIMISED) - median(arms.NAIVE);
+ const gainPct = (gain / median(arms.NAIVE)) * 100;
+ const worst = Math.max(spread(arms.OPTIMISED), spread(arms.NAIVE)) * 100;
+ log(`\ngain: ${gain > 0 ? "+" : ""}${gain.toFixed(1)} fps (${gainPct.toFixed(0)}%)`);
+ if (worst >= Math.abs(gainPct)) {
log(
`\n!! VOID: same-arm spread reaches ${worst.toFixed(0)}%, as large as the effect.\n This run says nothing. Repeat on a steadier machine.`,
);
} else {
log(`\nsame-arm spread ${worst.toFixed(0)}% — smaller than the effect, so the effect is real.`);
}
- setStat("fps", median(arms.CLEAN).toFixed(1));
+ setStat("fps", median(arms.OPTIMISED).toFixed(1));
}
document.querySelector("#run").addEventListener("click", () => {