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(poc): a full-shader compositor POC, instrumented with honest GPU timestamps

Etienne Lescot63d510866fec
diff --git a/.claude/launch.json b/.claude/launch.json
new file mode 100644
index 000000000..d237bed95
--- /dev/null
+++ b/.claude/launch.json
@@ -0,0 +1,18 @@
+{
+ "version": "0.0.1",
+ "configurations": [
+ {
+ "name": "vite-dev",
+ "runtimeExecutable": "npm",
+ "runtimeArgs": ["run", "dev", "--", "--port", "5199", "--strictPort"],
+ "port": 5199,
+ "env": { "NO_ELECTRON": "1" }
+ },
+ {
+ "name": "poc",
+ "runtimeExecutable": "npx",
+ "runtimeArgs": ["vite", "--config", "poc/vite.config.js"],
+ "port": 5210
+ }
+ ]
+}
diff --git a/.gitignore b/.gitignore
index d687e2c66..3e8ed9666 100644
--- a/.gitignore
+++ b/.gitignore
@@ -88,3 +88,10 @@ result-*
opencode.json
opencode.json
+
+# Frames dumped by `npm run bench:export -- --dumpFrame=N`, for eyes only.
+bench-frame-*.png
+
+# POC inputs (real recordings) and outputs — big, and not source.
+poc/media/
+poc/out/
diff --git a/poc/composite.wgsl b/poc/composite.wgsl
new file mode 100644
index 000000000..fc793f70a
--- /dev/null
+++ b/poc/composite.wgsl
@@ -0,0 +1,198 @@
+// The compositor. Two sources, one layout, three effects — written from zero.
+//
+// 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
+ a : vec4f,
+ // screenRect: x, y, w, h — already carries the zoom (scale + pan)
+ screen : vec4f,
+ // webcamRect: x, y, w, h — already carries the layout animation
+ webcam : vec4f,
+ // shadowIntensity | bgBlurPx | shadowOffsetY | shadowSpread
+ fx : vec4f,
+ // webcamRadius | motionBlurPx | webcamCoverScale | unused
+ b : vec4f,
+};
+
+@group(0) @binding(0) var<uniform> u : U;
+@group(0) @binding(1) var samp : sampler;
+@group(0) @binding(2) var screenTex : texture_external;
+@group(0) @binding(3) var webcamTex : texture_external;
+
+struct VsOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+};
+
+// Full-screen triangle: three vertices, no vertex buffer.
+@vertex
+fn vs(@builtin(vertex_index) i : u32) -> VsOut {
+ 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);
+ return out;
+}
+
+// ---- geometry ---------------------------------------------------------------
+
+/** Signed distance to a rounded box. Negative inside. */
+fn sdRoundBox(p : vec2f, half : vec2f, r : f32) -> f32 {
+ let rr = min(r, min(half.x, half.y));
+ let q = abs(p) - half + vec2f(rr);
+ return length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0) - rr;
+}
+
+/** Antialiased coverage from a signed distance: one pixel of ramp. */
+fn cover(d : f32) -> f32 {
+ return clamp(0.5 - d, 0.0, 1.0);
+}
+
+// ---- 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.
+
+fn gradient(uv : vec2f, t : f32) -> 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);
+ 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 {
+ if (radiusPx < 0.5) {
+ return gradient(uv, t);
+ }
+ let px = radiusPx / u.a.xy;
+ var acc = vec3f(0.0);
+ let taps = 16;
+ let golden = 2.39996;
+ for (var i = 0; i < taps; i = i + 1) {
+ 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);
+ }
+ return acc / f32(taps);
+}
+
+// ---- 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 {
+ 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;
+ var acc = 0.0;
+ let taps = 12;
+ let golden = 2.39996;
+ for (var i = 0; i < taps; i = i + 1) {
+ let fi = f32(i);
+ 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));
+ }
+ 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.
+
+/**
+ * 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));
+}
+
+/**
+ * Directional motion blur, applied while the camera moves.
+ *
+ * Skipped entirely at rest: a branch is free next to nine texture fetches.
+ */
+fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
+ let uv0 = (px - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
+ if (blurPx < 0.5) {
+ return textureSampleBaseClampToEdge(screenTex, samp, clamp(uv0, vec2f(0.0), vec2f(1.0))).rgb;
+ }
+ var acc = vec3f(0.0);
+ 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));
+ 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 {
+ 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);
+ }
+
+ // 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);
+ }
+
+ return vec4f(colour, 1.0);
+}
diff --git a/poc/index.html b/poc/index.html
new file mode 100644
index 000000000..99041806c
--- /dev/null
+++ b/poc/index.html
@@ -0,0 +1,70 @@
+<!doctype html>
+<html lang="fr">
+ <head>
+ <meta charset="utf-8" />
+ <title>POC full-shader — 2 sources, 1 layout, 3 effets</title>
+ <style>
+ body {
+ font-family: ui-sans-serif, system-ui, sans-serif;
+ background: #14141a;
+ color: #e8e8ee;
+ margin: 0;
+ padding: 24px;
+ }
+ h1 { font-size: 17px; font-weight: 500; margin: 0 0 4px; }
+ .sub { color: #8b8b9a; font-size: 13px; margin: 0 0 20px; }
+ .row { display: flex; gap: 20px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 20px; }
+ label { font-size: 12px; color: #8b8b9a; display: block; margin-bottom: 4px; }
+ input { width: 70px; background: #22222c; color: #e8e8ee; border: 1px solid #33333f; border-radius: 6px; padding: 6px 8px; font-size: 13px; }
+ button { background: #3d7dff; color: #fff; border: 0; border-radius: 6px; padding: 9px 18px; font-size: 13px; font-weight: 500; cursor: pointer; }
+ button:disabled { background: #33333f; color: #6a6a78; cursor: default; }
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; margin-bottom: 18px; }
+ .stat { background: #1c1c24; border-radius: 8px; padding: 12px 14px; }
+ .stat .k { font-size: 11px; color: #8b8b9a; text-transform: uppercase; letter-spacing: 0.04em; }
+ .stat .v { font-size: 22px; font-weight: 500; margin-top: 3px; }
+ .hero .v { color: #4ade80; font-size: 32px; }
+ pre { background: #1c1c24; border-radius: 8px; padding: 14px; font-size: 12px; line-height: 1.55; min-height: 90px; overflow-x: auto; margin: 0 0 18px; }
+ video, canvas { width: 100%; max-width: 860px; border-radius: 8px; display: block; background: #000; }
+ canvas { margin-bottom: 14px; }
+ a { color: #3d7dff; font-size: 13px; }
+ </style>
+ </head>
+ <body>
+ <h1>POC full-shader — 2 sources, 1 layout, 3 effets</h1>
+ <p class="sub">
+ écran + webcam → un programme WGSL (flou, ombre, masque) → mp4. Aucun Electron, aucun
+ code de l'app.
+ </p>
+
+ <div class="row">
+ <div><label for="seconds">secondes</label><input id="seconds" type="number" value="4" min="1" max="30" /></div>
+ <div><label for="padding">padding</label><input id="padding" type="number" value="45" min="0" max="90" /></div>
+ <div><label for="shadow">ombre</label><input id="shadow" type="number" value="0.65" min="0" max="1" step="0.05" /></div>
+ <div><label for="blur">flou fond (px)</label><input id="blur" type="number" value="40" min="0" max="200" /></div>
+ <div>
+ <label for="instrument">instrumenté</label>
+ <input id="instrument" 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
+ </button>
+ </div>
+
+ <div class="stats">
+ <div class="stat hero"><div class="k">fps</div><div class="v" id="fps">—</div></div>
+ <div class="stat"><div class="k">par image</div><div class="v" id="perframe">—</div></div>
+ <div class="stat"><div class="k">composite</div><div class="v" id="render">—</div></div>
+ <div class="stat"><div class="k">décodage</div><div class="v" id="decode">—</div></div>
+ <div class="stat"><div class="k">encodage</div><div class="v" id="encode">—</div></div>
+ <div class="stat"><div class="k">frames</div><div class="v" id="progress">—</div></div>
+ </div>
+
+ <pre id="log"></pre>
+ <canvas id="stage"></canvas>
+ <video id="result" controls hidden></video>
+ <a id="download" hidden>télécharger poc.mp4</a>
+
+ <script type="module" src="./main.js"></script>
+ </body>
+</html>
diff --git a/poc/main.js b/poc/main.js
new file mode 100644
index 000000000..dfe0f7ce2
--- /dev/null
+++ b/poc/main.js
@@ -0,0 +1,592 @@
+// POC: two videos, one layout, three effects, full shader. Standalone.
+//
+// No Electron, no app code, no old paradigm: decode (mediabunny) → WebGPU →
+// encode (mediabunny) → an mp4 you can watch, and one number: fps.
+//
+// The layout is 40 lines of arithmetic written here, not imported: the point is
+// to prove the paradigm reconstructs the product, not to reuse what exists.
+
+import {
+ ALL_FORMATS,
+ BufferTarget,
+ Input,
+ Mp4OutputFormat,
+ Output,
+ UrlSource,
+ VideoSampleSink,
+} from "mediabunny";
+
+const OUT = { width: 1920, height: 1080, fps: 30 };
+const log = (msg) => {
+ document.querySelector("#log").textContent += `${msg}\n`;
+};
+const setStat = (id, value) => {
+ document.querySelector(`#${id}`).textContent = value;
+};
+
+// ---- evaluate: (scene, t) → the frame's geometry. Written from zero. --------
+//
+// Pure arithmetic, no GPU, no canvas. Everything the shader needs is decided
+// here, so the same function can drive a preview later without a second
+// implementation to keep in sync.
+
+const easeInOut = (x) => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2);
+
+/** Ramp 0→1→0 across a region, eased in and out over `ramp` seconds. */
+function regionStrength(t, start, end, ramp) {
+ if (t <= start || t >= end) return 0;
+ const inRamp = Math.min(1, (t - start) / ramp);
+ const outRamp = Math.min(1, (end - t) / ramp);
+ return easeInOut(Math.min(inRamp, outRamp));
+}
+
+const lerp = (a, b, t) => a + (b - a) * t;
+const lerpRect = (a, b, t) => ({
+ x: lerp(a.x, b.x, t),
+ y: lerp(a.y, b.y, t),
+ w: lerp(a.w, b.w, t),
+ h: lerp(a.h, b.h, t),
+});
+
+/** The base layout: recording centred with padding, webcam docked bottom-right. */
+function baseLayout(stage, padding) {
+ const s = 1 - (padding / 100) * 0.4;
+ const w = stage.width * s;
+ const h = stage.height * s;
+ const screen = { x: (stage.width - w) / 2, y: (stage.height - h) / 2, w, h };
+ const size = Math.round(stage.height * 0.22);
+ const margin = Math.round(stage.height * 0.04);
+ const webcam = {
+ x: stage.width - size - margin,
+ y: stage.height - size - margin,
+ w: size,
+ h: size,
+ };
+ return { screen, webcam };
+}
+
+/**
+ * The whole timeline of this POC, as data.
+ *
+ * Two things move, and they are the two the product actually has:
+ * - a ZOOM on the recording: scale + focus point, eased in and out;
+ * - a LAYOUT ANIMATION on the webcam: it grows from the docked bubble to a
+ * large panel and its shape morphs from circle to rounded rect on the way.
+ */
+function scene(stage, padding) {
+ return {
+ stage,
+ padding,
+ zooms: [
+ { start: 1.0, end: 3.2, scale: 1.7, focus: { x: 0.62, y: 0.42 }, ramp: 0.55 },
+ { start: 4.4, end: 6.5, scale: 2.3, focus: { x: 0.3, y: 0.7 }, ramp: 0.5 },
+ ],
+ layoutMoves: [{ start: 2.4, end: 5.0, ramp: 0.6 }],
+ };
+}
+
+function evaluate(sc, t, prev) {
+ const base = baseLayout(sc.stage, sc.padding);
+
+ // --- zoom: strongest region wins, eased ---
+ let zoomScale = 1;
+ let focus = { x: 0.5, y: 0.5 };
+ let strength = 0;
+ for (const z of sc.zooms) {
+ const s = regionStrength(t, z.start, z.end, z.ramp);
+ if (s > strength) {
+ strength = s;
+ zoomScale = lerp(1, z.scale, s);
+ focus = z.focus;
+ }
+ }
+ // Scale about the focus point, then keep the recording covering the stage:
+ // a zoom that reveals the background behind the video is a bug, not a look.
+ const fx = base.screen.x + base.screen.w * focus.x;
+ const fy = base.screen.y + base.screen.h * focus.y;
+ const screen = {
+ x: fx - (fx - base.screen.x) * zoomScale,
+ y: fy - (fy - base.screen.y) * zoomScale,
+ w: base.screen.w * zoomScale,
+ h: base.screen.h * zoomScale,
+ };
+
+ // --- layout animation: the webcam grows into a panel and un-rounds ---
+ let move = 0;
+ for (const m of sc.layoutMoves) {
+ move = Math.max(move, regionStrength(t, m.start, m.end, m.ramp));
+ }
+ const panelW = Math.round(sc.stage.width * 0.34);
+ const panelH = Math.round(panelW * 0.75);
+ const margin = Math.round(sc.stage.height * 0.04);
+ const panel = {
+ x: sc.stage.width - panelW - margin,
+ y: sc.stage.height - panelH - margin,
+ w: panelW,
+ h: panelH,
+ };
+ const webcam = lerpRect(base.webcam, panel, move);
+ // Circle when docked (radius = half the bubble), rounded rect when grown.
+ const webcamRadius = lerp(Math.min(base.webcam.w, base.webcam.h) / 2, 26, move);
+
+ // --- velocity: what the motion blur is for ---
+ const cx = screen.x + screen.w / 2;
+ const cy = screen.y + screen.h / 2;
+ let velocity = 0;
+ if (prev) {
+ velocity = Math.hypot(cx - prev.cx, cy - prev.cy) + Math.abs(screen.w - prev.w) * 0.5;
+ }
+
+ return {
+ screen,
+ webcam,
+ webcamRadius,
+ zoomScale,
+ motionBlurPx: Math.min(velocity * 0.35, 24),
+ memo: { cx, cy, w: screen.w },
+ };
+}
+
+// ---- decode ----------------------------------------------------------------
+
+async function openVideo(url) {
+ const input = new Input({ source: new UrlSource(url), formats: ALL_FORMATS });
+ const track = await input.getPrimaryVideoTrack();
+ if (!track) throw new Error(`no video track in ${url}`);
+ const sink = new VideoSampleSink(track);
+ return { input, track, sink };
+}
+
+// ---- run -------------------------------------------------------------------
+
+async function run(override = {}) {
+ const started = performance.now();
+ document.querySelector("#run").disabled = true;
+ log("opening sources…");
+
+ const [screen, webcam] = await Promise.all([
+ openVideo("media/screen.mp4"),
+ openVideo("media/webcam.mp4"),
+ ]);
+ const seconds = Number(document.querySelector("#seconds").value);
+ const screenDuration = await screen.track.computeDuration();
+ const duration = Math.min(seconds, screenDuration);
+ const totalFrames = Math.floor(duration * OUT.fps);
+ log(
+ `screen ${screen.track.displayWidth}x${screen.track.displayHeight} · ${screenDuration.toFixed(1)}s`,
+ );
+ log(`webcam ${webcam.track.displayWidth}x${webcam.track.displayHeight}`);
+ log(`rendering ${totalFrames} frames @ ${OUT.fps}fps (${duration.toFixed(1)}s)`);
+
+ // ---- GPU ----
+ if (!navigator.gpu) throw new Error("WebGPU unavailable");
+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
+ // timestamp-query is the only honest way to price the shader: a CPU timer
+ // around submit() measures SUBMISSION, and the work lands on whoever syncs
+ // next. These are counters the GPU writes itself, around the pass.
+ const canTimestamp = adapter.features.has("timestamp-query");
+ const device = await adapter.requestDevice({
+ requiredFeatures: canTimestamp ? ["timestamp-query"] : [],
+ });
+ const info = adapter.info ?? {};
+ log(`gpu: ${info.vendor ?? "?"} ${info.architecture ?? ""} · timestamps: ${canTimestamp}`);
+
+ const querySet = canTimestamp ? device.createQuerySet({ type: "timestamp", count: 2 }) : null;
+ const resolveBuffer = canTimestamp
+ ? device.createBuffer({
+ size: 16,
+ usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
+ })
+ : null;
+ const readBuffer = canTimestamp
+ ? device.createBuffer({ size: 16, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ })
+ : null;
+
+ // OffscreenCanvas: no document, no presentation, no compositor.
+ //
+ // This is a measurement decision, not a detail. A canvas in the page is
+ // PRESENTED every frame — the browser composites 2 Mpx into the layout and the
+ // swapchain waits on the display's refresh. Measured here: 34.9 ms/frame of
+ // fixed cost with every effect switched OFF, eight times the effects
+ // themselves. An export presents nothing to anyone, so a measurement that pays
+ // for presentation is measuring a different program.
+ const canvas = new OffscreenCanvas(OUT.width, OUT.height);
+ const ctx = canvas.getContext("webgpu");
+ const format = navigator.gpu.getPreferredCanvasFormat();
+ ctx.configure({ device, format, alphaMode: "opaque" });
+
+ const previewCanvas = document.querySelector("#stage");
+ previewCanvas.width = 640;
+ previewCanvas.height = 360;
+ const preview = previewCanvas.getContext("2d");
+
+ 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 }] },
+ primitive: { topology: "triangle-list" },
+ });
+ const shaderError = await device.popErrorScope();
+ if (shaderError) throw new Error(`shader: ${shaderError.message}`);
+
+ const sampler = device.createSampler({ magFilter: "linear", minFilter: "linear" });
+ // 5 vec4 = 80 bytes. All-vec4 on purpose: WGSL pads mixed structs and the CPU
+ // packing has to reproduce the holes exactly — get one offset wrong and the
+ // shader reads a radius where a rect belongs, draws nothing, and reports no
+ // error at all.
+ const uniforms = new Float32Array(20);
+ const uniformBuffer = device.createBuffer({
+ size: uniforms.byteLength,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ });
+
+ // ---- encode ----
+ const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
+ const { CanvasSource, QUALITY_HIGH } = await import("mediabunny");
+ const source = new CanvasSource(canvas, { codec: "avc", bitrate: QUALITY_HIGH });
+ output.addVideoTrack(source, { frameRate: OUT.fps });
+ await output.start();
+
+ const sc = scene(OUT, Number(document.querySelector("#padding").value));
+ const shadowIntensity = Number(document.querySelector("#shadow").value);
+ const bgBlur = Number(document.querySelector("#blur").value);
+ const camAspect = webcam.track.displayWidth / webcam.track.displayHeight;
+ let memo = null;
+
+ // ---- 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.
+ // Measured at 122 ms/frame — 3x the cost of everything else combined. These
+ // videos are read start to end, so read them start to end: two generators,
+ // each advanced to the frame the output clock is asking for.
+ const screenStream = screen.sink.samples(0, duration);
+ const webcamStream = webcam.sink.samples(0, duration);
+ const nextFrom = async (stream, holder, t) => {
+ // Advance while the NEXT sample still starts at or before t.
+ while (
+ !holder.done &&
+ (!holder.current || holder.current.timestamp + holder.current.duration <= t)
+ ) {
+ const { value, done } = await stream.next();
+ if (done) {
+ holder.done = true;
+ break;
+ }
+ holder.current?.close();
+ holder.current = value;
+ }
+ return holder.current ?? null;
+ };
+ const screenHolder = { current: null, done: false };
+ const webcamHolder = { current: null, done: false };
+
+ // ---- the loop ----
+ // Every phase is timed on its own, and the whole frame is recorded, because
+ // two questions need different data: "what does a frame cost once warm" is a
+ // distribution, not a mean, and "where does the frame go" is a breakdown.
+ //
+ // INSTRUMENTED vs CLEAN, because the instruments are not free and two of them
+ // change the very thing they measure:
+ // - onSubmittedWorkDone() per frame is a FENCE. It is the only way to bill
+ // the GPU honestly, and it also forbids decode/composite/encode from ever
+ // overlapping — a cost the real loop would not pay.
+ // - mapAsync() to read the timestamps is a GPU→CPU sync, per frame.
+ // So the clean pass keeps the same work and drops both, and fps is compared
+ // 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 frames = [];
+ const t0 = performance.now();
+ let rendered = 0;
+
+ for (let i = 0; i < totalFrames; i++) {
+ const t = i / OUT.fps;
+ const fStart = performance.now();
+ const p = {};
+ const mark = () => (instrumented ? performance.now() : 0);
+
+ let m = mark();
+ const screenSample = await nextFrom(screenStream, screenHolder, t);
+ const webcamSample = await nextFrom(webcamStream, webcamHolder, t);
+ p.decode = mark() - m;
+ if (!screenSample) break;
+
+ // toVideoFrame + importExternalTexture: the decode→GPU seam. Timed apart
+ // because "zero copy" is a claim, and this is where it would fail.
+ m = mark();
+ const screenFrame = screenSample.toVideoFrame();
+ const webcamFrame = webcamSample ? webcamSample.toVideoFrame() : null;
+ const screenTex = device.importExternalTexture({ source: screenFrame });
+ const webcamTex = device.importExternalTexture({ source: webcamFrame ?? screenFrame });
+ p.import = mark() - m;
+
+ m = mark();
+ const f = evaluate(sc, t, memo);
+ memo = f.memo;
+ // Field n at float 4n — the struct is all-vec4 so this stays true.
+ uniforms.set([OUT.width, OUT.height, t, 28], 0); // stage | time | radius
+ 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);
+ device.queue.writeBuffer(uniformBuffer, 0, uniforms);
+ const bind = device.createBindGroup({
+ layout: pipeline.getBindGroupLayout(0),
+ entries: [
+ { binding: 0, resource: { buffer: uniformBuffer } },
+ { binding: 1, resource: sampler },
+ { binding: 2, resource: screenTex },
+ { binding: 3, resource: webcamTex },
+ ],
+ });
+ p.evaluate = mark() - m;
+
+ m = mark();
+ const encoder = device.createCommandEncoder();
+ const view = ctx.getCurrentTexture().createView();
+ p.acquire = mark() - m;
+
+ m = mark();
+ const useQueries = instrumented && querySet;
+ const pass = encoder.beginRenderPass({
+ colorAttachments: [
+ { view, clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: "clear", storeOp: "store" },
+ ],
+ ...(useQueries
+ ? { timestampWrites: { querySet, beginningOfPassWriteIndex: 0, endOfPassWriteIndex: 1 } }
+ : {}),
+ });
+ pass.setPipeline(pipeline);
+ pass.setBindGroup(0, bind);
+ pass.draw(3);
+ pass.end();
+ if (useQueries) {
+ encoder.resolveQuerySet(querySet, 0, 2, resolveBuffer, 0);
+ if (readBuffer.mapState === "unmapped")
+ encoder.copyBufferToBuffer(resolveBuffer, 0, readBuffer, 0, 16);
+ }
+ device.queue.submit([encoder.finish()]);
+ p.submit = mark() - m;
+
+ // The fence: everything above only QUEUED work, this is where it executes.
+ // Instrumented only — it is what makes the breakdown honest, and it is also
+ // what stops the pipeline from overlapping anything.
+ if (instrumented) {
+ m = performance.now();
+ await device.queue.onSubmittedWorkDone();
+ p.fence = performance.now() - m;
+
+ // What the GPU says about itself: the pass's duration in ns, written by
+ // the GPU around the pass. mapAsync is a GPU→CPU sync, so this too only
+ // exists while measuring.
+ if (querySet && readBuffer.mapState === "unmapped") {
+ await readBuffer.mapAsync(GPUMapMode.READ);
+ const ts = new BigUint64Array(readBuffer.getMappedRange().slice(0));
+ readBuffer.unmap();
+ p.gpuPass = Number(ts[1] - ts[0]) / 1e6;
+ }
+ }
+
+ m = mark();
+ await source.add(t, 1 / OUT.fps);
+ p.encode = mark() - m;
+
+ // The VideoFrames are ours; the samples belong to the streams, which close
+ // them when they advance.
+ screenFrame.close();
+ webcamFrame?.close();
+
+ p.total = performance.now() - fStart;
+ frames.push(p);
+ 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.
+ preview.drawImage(canvas, 0, 0, previewCanvas.width, previewCanvas.height);
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ }
+
+ const wallMs = performance.now() - t0;
+ await output.finalize();
+
+ // ---- report ----
+ //
+ // Average fps answers "how long did THIS export take". Cruise fps answers "how
+ // fast does it run" — the number that compares across exports. A short export
+ // amortises the first frames' one-off costs (pipeline warm-up, first
+ // allocations, JIT) over few frames, so the mean drags. Both are reported, and
+ // the gap between them IS the startup cost.
+ const median = (xs) => {
+ const s = [...xs].sort((a, b) => a - b);
+ return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
+ };
+ const totals = frames.map((f) => f.total);
+ // Cruise = the steady state: drop the first quarter, then take the MEDIAN, so
+ // one scheduler hiccup cannot move the number.
+ const warm = frames.slice(Math.ceil(frames.length / 4));
+ const cruiseMs = median(warm.map((f) => f.total));
+ const cruiseFps = 1000 / cruiseMs;
+ const avgFps = rendered / (wallMs / 1000);
+
+ 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`);
+
+ log(
+ `\n=== [${instrumented ? "INSTRUMENTED" : "CLEAN"}] cruise ${cruiseFps.toFixed(1)} fps — ${cruiseMs.toFixed(1)} ms/frame (median of the last ${warm.length}) ===`,
+ );
+ log(
+ `average ${avgFps.toFixed(1)} fps over all ${rendered} frames (${(wallMs / 1000).toFixed(2)}s wall)`,
+ );
+ log(
+ `first frames: ${totals
+ .slice(0, 4)
+ .map((x) => `${x.toFixed(0)}ms`)
+ .join(" · ")}`,
+ );
+ const drag = totals.reduce((a, b) => a + b, 0) - cruiseMs * totals.length;
+ log(
+ `one-off cost inside the loop: ${drag.toFixed(0)} ms total → ${(drag / rendered).toFixed(1)} ms/frame of drag on this export`,
+ );
+ log(
+ `setup before the loop: ${((t0 - started) / 1000).toFixed(2)}s (open sources, decoder init, pipeline, encoder)`,
+ );
+
+ if (!instrumented) {
+ log("\n(clean pass: no fence, no timestamp readback, no phase timers.");
+ log(" fps is the only number this pass can honestly report — and it is the");
+ log(" one that says what the loop actually does when nobody is watching.)");
+ } else {
+ log("\n--- where a cruise frame goes (median ms) ---");
+ for (const k of ["decode", "import", "evaluate", "acquire", "submit", "fence", "encode"]) {
+ const v = median(warm.map((f) => f[k] ?? 0));
+ const pct = (v / cruiseMs) * 100;
+ log(
+ `${k.padEnd(9)}${v.toFixed(1).padStart(6)} ms ${"█".repeat(Math.round(pct / 2)).padEnd(50)}${pct.toFixed(0)}%`,
+ );
+ }
+ if (frames[0]?.gpuPass !== undefined) {
+ const gpu = median(warm.map((f) => f.gpuPass ?? 0));
+ log(`\nGPU pass itself: ${gpu.toFixed(2)} ms — measured BY the GPU, around the pass.`);
+ log(
+ `${(cruiseMs - gpu).toFixed(1)} ms of the ${cruiseMs.toFixed(1)} ms frame is not the shader.`,
+ );
+ }
+ log("\nNOTE: this pass paid for its own instruments — a fence and a buffer map");
+ log("per frame. Re-run with `instrumenté` off: if the fps moves, the breakdown");
+ log("above describes a program that only exists while being measured.");
+ }
+
+ const blob = new Blob([output.target.buffer], { type: "video/mp4" });
+ const url = URL.createObjectURL(blob);
+ const player = document.querySelector("#result");
+ player.src = url;
+ player.hidden = false;
+ const dl = document.querySelector("#download");
+ dl.href = url;
+ dl.download = "poc.mp4";
+ dl.hidden = false;
+
+ // On disk too: a blob URL dies with the tab, and the output has to be
+ // watchable outside this page.
+ const written = await fetch("/save?name=poc.mp4", { method: "POST", body: blob }).then((r) =>
+ r.text(),
+ );
+ log(`output: ${(blob.size / 1e6).toFixed(1)} MB → ${written}`);
+
+ // Give it ALL back. A run that leaks its device is a run that poisons the next
+ // one: six back-to-back runs kept six GPU devices, six decoder pipelines and
+ // six encoders alive, and the rate decayed 19.9 → 8.6 → 7.5 fps across an
+ // interleaved comparison. That decay is not the machine drifting, it is this
+ // function forgetting — and it invalidated the very A/B it was there to serve.
+ screenHolder.current?.close();
+ webcamHolder.current?.close();
+ await screenStream.return?.();
+ await webcamStream.return?.();
+ screen.input.dispose();
+ webcam.input.dispose();
+ device.destroy();
+
+ document.querySelector("#run").disabled = false;
+ return { cruiseMs, cruiseFps, avgFps, instrumented };
+}
+
+/**
+ * Do the instruments change the answer? Interleaved A/B/A/B, because they can
+ * only be compared against 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.
+ */
+async function compare(rounds = 3) {
+ const median = (xs) => {
+ const s = [...xs].sort((a, b) => a - b);
+ 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: [] };
+
+ // 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],
+ ]) {
+ const res = await run({ instrumented });
+ if (r > 0) arms[name].push(res.cruiseFps);
+ }
+ }
+
+ document.querySelector("#log").textContent = "";
+ log("=== do the instruments change the answer? (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)) {
+ 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));
+}
+
+document.querySelector("#run").addEventListener("click", () => {
+ document.querySelector("#log").textContent = "";
+ run().catch((error) => {
+ log(`\nFAILED: ${error.message}`);
+ console.error(error);
+ document.querySelector("#run").disabled = false;
+ });
+});
+
+document.querySelector("#compare").addEventListener("click", () => {
+ document.querySelector("#log").textContent = "comparing, please wait…\n";
+ compare().catch((error) => {
+ log(`\nFAILED: ${error.message}`);
+ console.error(error);
+ document.querySelector("#run").disabled = false;
+ });
+});
diff --git a/poc/vite.config.js b/poc/vite.config.js
new file mode 100644
index 000000000..cc87d1305
--- /dev/null
+++ b/poc/vite.config.js
@@ -0,0 +1,39 @@
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+/**
+ * POST /save?name=x → poc/out/x.
+ *
+ * The output has to be watchable on disk, not just a blob URL that dies with the
+ * tab. Dev-only, and it writes exactly one directory.
+ */
+const save = {
+ name: "poc-save",
+ configureServer(server) {
+ server.middlewares.use("/save", (req, res) => {
+ const name = new URL(req.url, "http://x").searchParams.get("name") ?? "out.bin";
+ const chunks = [];
+ req.on("data", (c) => chunks.push(c));
+ req.on("end", () => {
+ const body = Buffer.concat(chunks);
+ const dir = join(here, "out");
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, name.replace(/[^\w.-]/g, "_"));
+ writeFileSync(file, body);
+ console.log(`[poc] wrote ${file} (${body.length} bytes)`);
+ res.end(file);
+ });
+ });
+ },
+};
+
+// The POC serves itself. Nothing here knows about the app: no aliases, no
+// electron plugin, no shared config — the isolation is the point.
+export default {
+ root: here,
+ plugins: [save],
+ server: { port: 5210, strictPort: true },
+};
diff --git a/scripts/bench-export.mjs b/scripts/bench-export.mjs
index b7495986f..a99b06ea7 100644
--- a/scripts/bench-export.mjs
+++ b/scripts/bench-export.mjs
@@ -13,7 +13,7 @@
*/
import { spawn, spawnSync } from "node:child_process";
-import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import { existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -212,6 +212,7 @@ async function main() {
// capped runs compare per-frame, or against runs with the SAME cap.
...(args.clip ? { clip: args.clip } : {}),
...(args.warmup ? { warmup: args.warmup } : {}),
+ ...(args.dumpFrame ? { dumpFrame: args.dumpFrame } : {}),
arms: args.arms ?? "webcodecs,native",
runs: args.runs ?? "2",
fps: args.fps ?? "60",
@@ -237,6 +238,7 @@ async function main() {
const results = [];
let fatal = null;
let buffer = "";
+ let currentArm = "unknown";
// 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.
@@ -252,8 +254,15 @@ 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 .*|shadow .*)$/.exec(line);
+ const note = /\[export perf\] (canvas .*|native encode .*|shadow .*|WGSL .*|G0 .*)$/.exec(
+ line,
+ );
if (note) console.log(` · ${note[1]}`);
+ // The WGSL compositor's own diagnostics. Shown always, not just on
+ // failure: a validation error draws NOTHING and reports no error to
+ // the caller, which reads as a very fast compositor rendering black.
+ const wgsl = /\[wgsl\] (.*)$/.exec(line);
+ if (wgsl) console.log(` · wgsl: ${wgsl[1]}`);
continue;
}
let event;
@@ -270,6 +279,14 @@ async function main() {
console.log(` ${event.arm} run ${event.run}: ${status}`);
} else if (event.event === "fatal") {
fatal = event.error;
+ } else if (event.event === "armStart") {
+ currentArm = event.arm;
+ } else if (event.event === "frame") {
+ // Written next to the run, named for the arm that drew it, so two arms
+ // leave two pictures to compare.
+ const file = path.join(ROOT, `bench-frame-${currentArm}-${event.index}.png`);
+ writeFileSync(file, Buffer.from(event.png.split(",")[1], "base64"));
+ console.log(` frame ${event.index} of ${currentArm} -> ${path.basename(file)}`);
} else if (event.event === "warmup") {
console.log(` (warm-up) ${event.arm}: ${Math.round(event.wallMs)}ms — discarded`);
} else if (event.event === "start") {
diff --git a/src/bench/runBench.ts b/src/bench/runBench.ts
index 0dece59c2..c14ac9a7d 100644
--- a/src/bench/runBench.ts
+++ b/src/bench/runBench.ts
@@ -36,6 +36,8 @@ export interface BenchArm {
gpuFence?: boolean;
/** Diagnostic: shadow path minus the gaussians. Renders no shadow. */
shadowNoFilter?: boolean;
+ /** The §8b compositor: one WGSL program. POC — renders no text/cursor/3D. */
+ wgslCompositor?: boolean;
/**
* Effects this arm adds to --effects, so an effect can be A/B'd INSIDE one
* interleaved run.
@@ -93,6 +95,9 @@ const BENCH_PARAMS = {
// same-arm spread that voided the run all by itself, while the arm that merely
// went second looked better. One warm-up costs ~5 s at --clip=4.
warmup: Number(params.get("warmup") ?? "1"),
+ // Emit this frame of every arm as a PNG, so the pictures can be compared. The
+ // only thing that says a compositor WORKS; fps says only that it ran.
+ dumpFrame: params.get("dumpFrame"),
};
/**
@@ -114,6 +119,11 @@ const EFFECT_PATCHES: Record<string, Record<string, unknown>> = {
blur: { showBlur: true },
radius: { borderRadius: 24 },
motionBlur: { motionBlurAmount: 1 },
+ // Without padding the recording covers the whole stage, so the background, the
+ // rounded corners and the shadow are all computed and then hidden behind it.
+ // The COST is real either way — which is why the timing arms never needed this
+ // — but a parity check has to be able to SEE what it is comparing.
+ padding: { padding: 45 },
// Turning an effect OFF is not the same as omitting it: a saved project has
// its own appearance (this bench's reference carries shadowIntensity 0.52 and
// motionBlurAmount 0.31), so an arm that "doesn't add shadow" still renders
@@ -311,6 +321,45 @@ const ARMS: Record<string, BenchArm> = {
shadowNoFilter: true,
addEffects: ["zoom"],
},
+ // The POC (Step 4). Pair each against its Canvas2D twin above — same decode,
+ // same encoder, same document, one interleaved run — and the difference is the
+ // compositor and nothing else. The zoom pair is the one that matters: it is
+ // the case the 2D cache cannot hold and the shader has no cache to miss.
+ wgsl: { nativeEncode: false, readFrequently: false, wgslCompositor: true },
+ // The parity gate, not a speed arm: the native sink WRITES AN MP4, so this pair
+ // produces one file each — same timeline, same encoder, same bitrate, one
+ // compositor apart — and the two pictures can be diffed. The descent to ffmpeg
+ // makes them slow, which does not matter: nobody is timing a correctness check.
+ "wgsl-native-zoom": {
+ nativeEncode: true,
+ readFrequently: false,
+ wgslCompositor: true,
+ addEffects: ["zoom"],
+ },
+ "native-zoom": { nativeEncode: true, readFrequently: false, addEffects: ["zoom"] },
+ "wgsl-fence": {
+ nativeEncode: false,
+ readFrequently: false,
+ gpuFence: true,
+ wgslCompositor: true,
+ },
+ "wgsl-fence-zoom": {
+ nativeEncode: false,
+ readFrequently: false,
+ gpuFence: true,
+ wgslCompositor: true,
+ addEffects: ["zoom"],
+ },
+ // The shader compositor minus the shadow cascade. Against `wgsl-fence` it
+ // prices the cascade — 18 full-frame passes, which is the naive version of an
+ // algorithm whose whole point was that it is cheap on a GPU.
+ "wgsl-fence-noshadow": {
+ nativeEncode: false,
+ readFrequently: false,
+ gpuFence: true,
+ wgslCompositor: true,
+ addEffects: ["noShadow"],
+ },
// 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
@@ -326,6 +375,9 @@ function applyArm(arm: BenchArm): void {
localStorage.setItem("openscreen.legacyCompositor", arm.legacyCompositor ? "1" : "0");
localStorage.setItem("openscreen.gpuFence", arm.gpuFence ? "1" : "0");
localStorage.setItem("openscreen.shadowNoFilter", arm.shadowNoFilter ? "1" : "0");
+ localStorage.setItem("openscreen.wgslCompositor", arm.wgslCompositor ? "1" : "0");
+ if (BENCH_PARAMS.dumpFrame) localStorage.setItem("openscreen.dumpFrame", BENCH_PARAMS.dumpFrame);
+ else localStorage.removeItem("openscreen.dumpFrame");
}
/**
@@ -559,6 +611,9 @@ export async function runBench(): Promise<void> {
for (let run = 1; run <= BENCH_PARAMS.runs; run++) {
for (const armName of BENCH_PARAMS.arms) {
const arm = ARMS[armName];
+ // The runner needs to know whose frame a dumped PNG is: the exporter
+ // emits it mid-run, before the result that would have named the arm.
+ emit("armStart", { arm: armName, run });
const result = await runOnce(docFor(arm), armName, arm, run);
results.push(result);
emit("run", result);
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 9bed88c0f..259e774a2 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -27,6 +27,7 @@ import { StreamingVideoDecoder } from "./streamingDecoder";
import { computeKeepSegments, splitBySpeed } from "./timelineSegments";
import { TimestampedVideoFrameQueue } from "./timestampedVideoFrameQueue";
import type { ExportConfig, ExportProgress, ExportResult } from "./types";
+import { WgslFrameRenderer } from "./wgslFrameRenderer";
const ENCODER_STALL_TIMEOUT_MS = 15_000;
const ENCODER_FLUSH_TIMEOUT_MS = 20_000;
@@ -158,6 +159,61 @@ function gpuFenceEnabled(): boolean {
}
}
+/**
+ * The §8b compositor: one WGSL program instead of Pixi + four Canvas2D surfaces
+ * + a second GL context.
+ *
+ * POC (rendering-architecture.md Step 4). It renders no captions, annotations,
+ * cursor or 3D rotation yet — so its OUTPUT is not yet the product's, and it must
+ * never become a default by accident. It shares the exporter's decode, encode,
+ * mux and audio, so the bench can run it against the Canvas2D compositor in one
+ * interleaved pass and the difference is the compositor alone.
+ *
+ * localStorage.setItem("openscreen.wgslCompositor", "1")
+ */
+function wgslCompositorEnabled(): boolean {
+ try {
+ return localStorage.getItem("openscreen.wgslCompositor") === "1";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Emit frame N of the export as a PNG on the console, for eyes.
+ *
+ * A compositor that runs and renders garbage produces a clean fps number, so a
+ * speed arm cannot tell you whether it works. This is the cheapest path to the
+ * only thing that can: the picture. It goes through the console because the
+ * renderer has no file access and the alternative — encoding an mp4 — drags in a
+ * 100 MB ffmpeg download to look at one frame.
+ *
+ * localStorage.setItem("openscreen.dumpFrame", "60")
+ */
+function dumpFrameIndex(): number | null {
+ try {
+ const raw = localStorage.getItem("openscreen.dumpFrame");
+ if (!raw) return null;
+ const n = Number(raw);
+ return Number.isFinite(n) && n >= 0 ? n : null;
+ } catch {
+ return null;
+ }
+}
+
+async function dumpFrameToConsole(canvas: HTMLCanvasElement, index: number): Promise<void> {
+ // Via a 2D surface, so this works for the WebGPU canvas and the Canvas2D one
+ // alike — drawImage is what both have in common.
+ const out = document.createElement("canvas");
+ out.width = canvas.width;
+ out.height = canvas.height;
+ const ctx = out.getContext("2d");
+ if (!ctx) return;
+ ctx.drawImage(canvas, 0, 0);
+ const png = out.toDataURL("image/png");
+ console.warn(`[bench] ${JSON.stringify({ event: "frame", index, png })}`);
+}
+
async function probeOneEncoder(opts: {
label: string;
width: number;
@@ -1181,7 +1237,14 @@ export class VideoExporter {
// One renderer for the whole export — output size is fixed; only the
// source-dependent fields change per segment via renderer.setSource().
- const renderer = new FrameRenderer({
+ const useWgsl = wgslCompositorEnabled();
+ if (useWgsl) {
+ console.warn("[export perf] WGSL compositor: POC — no captions, annotations, cursor or 3D");
+ }
+ const RendererClass = useWgsl
+ ? (WgslFrameRenderer as unknown as typeof FrameRenderer)
+ : FrameRenderer;
+ const renderer = new RendererClass({
width: this.config.width,
height: this.config.height,
wallpaper: plan.appearance.wallpaper,
@@ -1229,6 +1292,7 @@ export class VideoExporter {
if (gpuFence) {
console.warn("[export perf] G0 fence: GPU synced after compositing, per frame");
}
+ const dumpAt = dumpFrameIndex();
let sink: NativeFrameSink | null = null;
let extractor: CanvasFrameExtractor | null = null;
if (useNative && api && compositeOnly) {
@@ -1467,6 +1531,10 @@ export class VideoExporter {
stopFence();
}
+ if (dumpAt !== null && frameIndex === dumpAt) {
+ await dumpFrameToConsole(renderer.getCanvas(), frameIndex);
+ }
+
// 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.
diff --git a/src/lib/exporter/wgsl/composite.wgsl.ts b/src/lib/exporter/wgsl/composite.wgsl.ts
new file mode 100644
index 000000000..bf1fcd036
--- /dev/null
+++ b/src/lib/exporter/wgsl/composite.wgsl.ts
@@ -0,0 +1,186 @@
+// The compositor: one WGSL program, one draw call, every pixel of the frame.
+//
+// WGSL and not GLSL/Pixi on purpose (rendering-architecture.md §12): this text
+// runs unmodified in the browser (WebGPU) and natively (wgpu), so the shader and
+// the evaluator — the product's actual substance — stay portable, and the host
+// question stays a bindings swap rather than an architectural bet.
+//
+// Everything here is a pure function of the uniforms. There is no cache, and that
+// is the point: a shader recomputes 2 Mpx per frame at a cost the Canvas2D path
+// paid to AVOID recomputing. The 2D cache existed because a CSS filter cost 14 ms;
+// the paradigm does not carry over.
+//
+// The shadow is the exception worth reading (see shadowCascade.wgsl.ts): it needs
+// a real blur, so it is prepared in its own passes and sampled here.
+
+export const COMPOSITE_WGSL = /* wgsl */ `
+
+/**
+ * Every member is a vec4f, and that is deliberate.
+ *
+ * WGSL aligns a vec4f to 16 bytes and a vec2f to 8, so a struct of mixed scalars
+ * and vectors has padding holes the CPU side must reproduce EXACTLY — get one
+ * offset wrong and the shader reads a radius where a rectangle should be, draws
+ * nothing, and reports no error. (It happened: the first version of this file
+ * packed 24 sequential floats against a struct whose real layout was 128 bytes
+ * with holes at 8, 36 and 92.) All-vec4 has no holes to get wrong: field n is at
+ * byte 16n, always. Flags travel as floats for the same reason — no u32/f32
+ * interleaving to mis-pack.
+ */
+struct Uniforms {
+ // stage.xy | videoRadius | shadowIntensity
+ a : vec4f,
+ // The recording's box AFTER the camera: x, y, w, h
+ videoRect : vec4f,
+ // Source crop, normalised: x, y, w, h
+ crop : vec4f,
+ // Webcam destination: x, y, w, h
+ webcamRect : vec4f,
+ // webcamRadius | motionBlur.x | motionBlur.y | unused
+ b : vec4f,
+ // webcamShape | webcamMirrored | hasWebcam | hasShadow (0/1 as floats)
+ flags : vec4f,
+};
+
+@group(0) @binding(0) var<uniform> u : Uniforms;
+@group(0) @binding(1) var samp : sampler;
+@group(0) @binding(2) var videoTex : texture_external;
+@group(0) @binding(3) var webcamTex : texture_external;
+@group(0) @binding(4) var bgTex : texture_2d<f32>;
+@group(0) @binding(5) var shadowTex : texture_2d<f32>;
+
+struct VsOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+};
+
+// Full-screen triangle. No vertex buffer: three points, clipped to the viewport.
+@vertex
+fn vs(@builtin(vertex_index) i : u32) -> VsOut {
+ 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);
+ return out;
+}
+
+/**
+ * Signed distance to a rounded box, negative inside.
+ *
+ * This is geometry, not a shadow approximation: it decides which pixels the
+ * recording covers, exactly as the Canvas2D mask's rounded rect did. §13's ban is
+ * on approximating the shadow's FALLOFF with an SDF, and this never touches it.
+ */
+fn sdRoundBox(p : vec2f, halfSize : vec2f, r : f32) -> f32 {
+ let rr = min(r, min(halfSize.x, halfSize.y));
+ let q = abs(p) - halfSize + vec2f(rr);
+ return length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0) - rr;
+}
+
+/** Coverage of a shape at a pixel, antialiased over one pixel of distance. */
+fn coverage(dist : f32) -> f32 {
+ return clamp(0.5 - dist, 0.0, 1.0);
+}
+
+fn shapeDistance(px : vec2f, rect : vec4f, radius : f32, shape : f32) -> f32 {
+ let centre = rect.xy + rect.zw * 0.5;
+ let half = rect.zw * 0.5;
+ let p = px - centre;
+ if (shape > 1.5 && shape < 2.5) {
+ // Circle: an ellipse inscribed in the rect, so a non-square webcam still
+ // masks to the shape the layout asked for.
+ let n = p / max(half, vec2f(1.0));
+ return (length(n) - 1.0) * min(half.x, half.y);
+ }
+ if (shape > 2.5) {
+ let s = min(half.x, half.y);
+ return sdRoundBox(p, vec2f(s), 0.0);
+ }
+ if (shape > 0.5) {
+ return sdRoundBox(p, half, radius);
+ }
+ return sdRoundBox(p, half, 0.0);
+}
+
+/** Map a stage pixel to the recording's source UV, through the crop. */
+fn videoUv(px : vec2f) -> vec2f {
+ let local = (px - u.videoRect.xy) / max(u.videoRect.zw, vec2f(1.0));
+ return u.crop.xy + local * u.crop.zw;
+}
+
+fn sampleVideo(px : vec2f) -> vec4f {
+ return textureSampleBaseClampToEdge(videoTex, samp, videoUv(px));
+}
+
+/**
+ * The recording, with directional motion blur when the camera is moving.
+ *
+ * Taps are skipped entirely at rest — the common case must not pay for the rare
+ * one, and a branch is free next to nine texture fetches.
+ */
+fn sampleVideoBlurred(px : vec2f) -> vec4f {
+ let motion = u.b.yz;
+ if (length(motion) < 0.5) {
+ return sampleVideo(px);
+ }
+ var acc = vec4f(0.0);
+ let taps = 9;
+ for (var i = 0; i < taps; i = i + 1) {
+ let t = (f32(i) / f32(taps - 1)) - 0.5;
+ acc = acc + sampleVideo(px + motion * t);
+ }
+ return acc / f32(taps);
+}
+
+fn overComposite(dst : vec4f, src : vec4f) -> vec4f {
+ let a = src.a + dst.a * (1.0 - src.a);
+ let rgb = src.rgb * src.a + dst.rgb * dst.a * (1.0 - src.a);
+ return vec4f(select(rgb / a, vec3f(0.0), a <= 0.0), a);
+}
+
+@fragment
+fn fs(in : VsOut) -> @location(0) vec4f {
+ let px = in.uv * u.a.xy;
+
+ // 1. Background. Pre-blurred at init if the document asks for blur: it is a
+ // still image, so blurring it per frame would be work with no output.
+ var colour = textureSample(bgTex, samp, in.uv);
+ colour = vec4f(colour.rgb, 1.0);
+
+ // 2. Shadow, prepared by the cascade passes. Under everything, cut to nothing
+ // where the recording will cover it anyway.
+ if (u.flags.w > 0.5) {
+ let s = textureSample(shadowTex, samp, in.uv).a;
+ colour = overComposite(colour, vec4f(0.0, 0.0, 0.0, s));
+ }
+
+ // 3. The recording: rounded, masked, motion-blurred.
+ let vd = sdRoundBox(
+ px - (u.videoRect.xy + u.videoRect.zw * 0.5),
+ u.videoRect.zw * 0.5,
+ u.a.z
+ );
+ let vc = coverage(vd);
+ if (vc > 0.0) {
+ let video = sampleVideoBlurred(px);
+ colour = overComposite(colour, vec4f(video.rgb, vc));
+ }
+
+ // 4. The webcam, on top, in its own shape.
+ if (u.flags.z > 0.5) {
+ let wd = shapeDistance(px, u.webcamRect, u.b.x, u.flags.x);
+ let wc = coverage(wd);
+ if (wc > 0.0) {
+ var wuv = (px - u.webcamRect.xy) / max(u.webcamRect.zw, vec2f(1.0));
+ if (u.flags.y > 0.5) {
+ wuv.x = 1.0 - wuv.x;
+ }
+ let cam = textureSampleBaseClampToEdge(webcamTex, samp, clamp(wuv, vec2f(0.0), vec2f(1.0)));
+ colour = overComposite(colour, vec4f(cam.rgb, wc));
+ }
+ }
+
+ return vec4f(colour.rgb, 1.0);
+}
+`;
diff --git a/src/lib/exporter/wgsl/evaluate.ts b/src/lib/exporter/wgsl/evaluate.ts
new file mode 100644
index 000000000..503a47d13
--- /dev/null
+++ b/src/lib/exporter/wgsl/evaluate.ts
@@ -0,0 +1,383 @@
+// evaluate — (document appearance, t) → FrameState. Pure CPU, no GPU, no canvas.
+//
+// The architecture's load-bearing idea (rendering-architecture.md §8a): every
+// per-frame appearance decision is a deterministic function of the document and
+// a time. Extracting it means preview and export cannot drift on layout, easing
+// or timing, because there is only one place that decides them.
+//
+// This is an EXTRACTION, not a rewrite: the geometry already lives in pure
+// modules (computeCompositeLayout, zoomSpring, zoomTransform, cameraFullscreen).
+// evaluate() calls exactly what FrameRenderer.updateLayout/updateAnimationState
+// call, in the same order, so the WGSL compositor inherits their behaviour rather
+// than reimplementing it — including the spring, which is the part nobody would
+// reproduce identically by eye.
+//
+// The one thing this file owns that FrameRenderer does not: `velocity`, and the
+// SHAPE of the output. The state is a plain struct, sized to become ~200 bytes of
+// uniforms.
+
+import type {
+ CameraFullscreenRegion,
+ CropRegion,
+ Rotation3D,
+ WebcamMaskShape,
+ ZoomRegion,
+} from "@/components/video-editor/types";
+import { DEFAULT_ROTATION_3D, getZoomScale, lerpRotation3D } from "@/components/video-editor/types";
+import { computeCameraFullscreenProgress } from "@/components/video-editor/videoPlayback/cameraFullscreenUtils";
+import {
+ AUTO_FOLLOW_PARAMS,
+ DEFAULT_FOCUS,
+} from "@/components/video-editor/videoPlayback/constants";
+import { advanceFollowFocus } from "@/components/video-editor/videoPlayback/cursorFollowUtils";
+import { clampFocusToScale } from "@/components/video-editor/videoPlayback/focusUtils";
+import { findDominantRegion } from "@/components/video-editor/videoPlayback/zoomRegionUtils";
+import {
+ createZoomSpringState,
+ resetZoomSpring,
+ stepZoomSpring,
+ type ZoomSpringState,
+} from "@/components/video-editor/videoPlayback/zoomSpring";
+import {
+ computeFocusFromTransform,
+ computeZoomTransform,
+} from "@/components/video-editor/videoPlayback/zoomTransform";
+import {
+ computeCameraFullscreenTargetRect,
+ computeCompositeLayout,
+ lerpRect,
+ reactiveWebcamScale,
+ type Size,
+ type StyledRenderRect,
+ type WebcamLayoutPreset,
+ type WebcamSizePreset,
+} from "@/lib/compositeLayout";
+
+/** Everything about the document that does not depend on `t`. */
+export interface EvaluateScene {
+ outputSize: Size;
+ videoSize: Size;
+ webcamSize: Size | null;
+ cropRegion: CropRegion;
+ padding: number;
+ borderRadius: number;
+ shadowIntensity: number;
+ motionBlurAmount: number;
+ zoomRegions: ZoomRegion[];
+ cameraFullscreenRegions: CameraFullscreenRegion[];
+ webcamLayoutPreset: WebcamLayoutPreset;
+ webcamSizePreset: WebcamSizePreset;
+ webcamMaskShape: WebcamMaskShape;
+ webcamPosition: { cx: number; cy: number } | null;
+ webcamMirrored: boolean;
+ webcamReactiveZoom: boolean;
+ cursorTelemetry?: import("@/components/video-editor/types").CursorTelemetryPoint[];
+}
+
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface FrameState {
+ /** Where the (cropped) recording lands on the stage, before the camera moves. */
+ screenRect: Rect;
+ /** Corner radius of the recording, in output pixels, BEFORE the camera scales it. */
+ borderRadius: number;
+ /** The camera: applied (spring-smoothed) scale + translation, in output pixels. */
+ camera: { scale: number; x: number; y: number };
+ /** The recording's on-screen box WITH the camera applied — what the shadow follows. */
+ cameraRect: Rect;
+ cameraBorderRadius: number;
+ /** Source-space crop, normalised 0..1. */
+ crop: CropRegion;
+ /** Webcam destination, already carrying reactive-zoom shrink and Full Camera growth. */
+ webcamRect: (StyledRenderRect & { shape: WebcamMaskShape }) | null;
+ webcamMirrored: boolean;
+ /** Per-frame camera movement, normalised. Drives motion blur; 0 on a still frame. */
+ velocity: number;
+ motionBlurAmount: number;
+ shadowIntensity: number;
+ rotation3D: Rotation3D;
+ cameraFullscreenProgress: number;
+}
+
+/**
+ * The parts of the animation that depend on the PREVIOUS frame.
+ *
+ * evaluate() is a pure function of (scene, t, prev) — not of (scene, t) alone,
+ * because the zoom spring and the auto-focus smoother are integrators: they chase
+ * their target over time. Threading their state through the signature keeps the
+ * function pure and, more to the point, keeps it honest — a renderer that seeks
+ * must reset this, and the type makes that impossible to forget.
+ */
+export interface EvaluateMemory {
+ spring: ZoomSpringState;
+ prevTimeMs: number | null;
+ prevTargetProgress: number;
+ smoothedAutoFocus: { cx: number; cy: number } | null;
+ prevCamera: { scale: number; x: number; y: number } | null;
+}
+
+export function createEvaluateMemory(): EvaluateMemory {
+ return {
+ spring: createZoomSpringState(),
+ prevTimeMs: null,
+ prevTargetProgress: 0,
+ smoothedAutoFocus: null,
+ prevCamera: null,
+ };
+}
+
+/** Layout is independent of `t`, so it is computed once per (scene, webcam presence). */
+export function evaluateLayout(scene: EvaluateScene, hasWebcam: boolean) {
+ const { width, height } = scene.outputSize;
+ const crop = scene.cropRegion;
+ const croppedVideo = {
+ width: scene.videoSize.width * crop.width,
+ height: scene.videoSize.height * crop.height,
+ };
+
+ // Padding is a percentage (0-100) where 50% ~ 0.8 scale; vertical stack is
+ // full-bleed and ignores it. Same constants as the Canvas2D path, on purpose.
+ const effectivePadding = scene.webcamLayoutPreset === "vertical-stack" ? 0 : scene.padding;
+ const paddingScale = 1.0 - (effectivePadding / 100) * 0.4;
+
+ const layout = computeCompositeLayout({
+ canvasSize: { width, height },
+ maxContentSize: { width: width * paddingScale, height: height * paddingScale },
+ screenSize: croppedVideo,
+ webcamSize: hasWebcam ? scene.webcamSize : null,
+ layoutPreset: scene.webcamLayoutPreset,
+ webcamSizePreset: scene.webcamSizePreset,
+ webcamPosition: scene.webcamPosition,
+ webcamMaskShape: scene.webcamMaskShape,
+ });
+ if (!layout) return null;
+
+ const screenRect = layout.screenRect;
+ const scale = layout.screenCover
+ ? Math.max(screenRect.width / croppedVideo.width, screenRect.height / croppedVideo.height)
+ : screenRect.width / croppedVideo.width;
+
+ // The mask is the visible box of the recording: the cropped source at `scale`,
+ // centred in screenRect, clipped to it. Cover mode overflows and is cut.
+ const displayed = { width: croppedVideo.width * scale, height: croppedVideo.height * scale };
+ const maskRect = {
+ x: screenRect.x + Math.max(0, (screenRect.width - displayed.width) / 2),
+ y: screenRect.y + Math.max(0, (screenRect.height - displayed.height) / 2),
+ width: Math.min(screenRect.width, displayed.width),
+ height: Math.min(screenRect.height, displayed.height),
+ };
+
+ return {
+ stageSize: { width, height },
+ maskRect,
+ borderRadius: scene.borderRadius,
+ webcamRect: layout.webcamRect ?? null,
+ };
+}
+
+export type EvaluateLayout = NonNullable<ReturnType<typeof evaluateLayout>>;
+
+export function evaluate(
+ scene: EvaluateScene,
+ layout: EvaluateLayout,
+ timeMs: number,
+ memory: EvaluateMemory,
+): FrameState {
+ const cameraFullscreenProgress = computeCameraFullscreenProgress(
+ scene.cameraFullscreenRegions,
+ timeMs,
+ );
+
+ const { region, strength, blendedScale, rotation3D, transition } = findDominantRegion(
+ scene.zoomRegions,
+ timeMs,
+ { connectZooms: true, cursorTelemetry: scene.cursorTelemetry },
+ );
+
+ let targetScale = 1;
+ let targetFocus = { ...DEFAULT_FOCUS };
+ let targetProgress = 0;
+ const currentRotation3D =
+ region && strength > 0
+ ? lerpRotation3D(DEFAULT_ROTATION_3D, rotation3D, strength)
+ : { ...DEFAULT_ROTATION_3D };
+
+ const dtMs = memory.prevTimeMs != null ? timeMs - memory.prevTimeMs : 0;
+
+ if (region && strength > 0) {
+ const zoomScale = blendedScale ?? getZoomScale(region);
+ targetScale = zoomScale;
+ targetFocus = clampFocusToScale(region.focus, zoomScale);
+ targetProgress = strength;
+
+ if (region.focusMode === "auto" && !transition) {
+ const raw = targetFocus;
+ const isZoomingIn = targetProgress < 0.999 && targetProgress >= memory.prevTargetProgress;
+ if (targetProgress >= 0.999 || !isZoomingIn) {
+ const prev = memory.smoothedAutoFocus ?? raw;
+ const smoothed = advanceFollowFocus(prev, raw, dtMs, AUTO_FOLLOW_PARAMS);
+ memory.smoothedAutoFocus = smoothed;
+ targetFocus = smoothed;
+ } else {
+ memory.smoothedAutoFocus = raw;
+ }
+ } else if (region.focusMode !== "auto") {
+ memory.smoothedAutoFocus = null;
+ }
+ memory.prevTargetProgress = targetProgress;
+
+ if (transition) {
+ const start = computeZoomTransform({
+ stageSize: layout.stageSize,
+ baseMask: layout.maskRect,
+ zoomScale: transition.startScale,
+ zoomProgress: 1,
+ focusX: transition.startFocus.cx,
+ focusY: transition.startFocus.cy,
+ });
+ const end = computeZoomTransform({
+ stageSize: layout.stageSize,
+ baseMask: layout.maskRect,
+ zoomScale: transition.endScale,
+ zoomProgress: 1,
+ focusX: transition.endFocus.cx,
+ focusY: transition.endFocus.cy,
+ });
+ const t = transition.progress;
+ const interpolated = {
+ scale: start.scale + (end.scale - start.scale) * t,
+ x: start.x + (end.x - start.x) * t,
+ y: start.y + (end.y - start.y) * t,
+ };
+ targetScale = interpolated.scale;
+ targetFocus = computeFocusFromTransform({
+ stageSize: layout.stageSize,
+ baseMask: layout.maskRect,
+ zoomScale: interpolated.scale,
+ x: interpolated.x,
+ y: interpolated.y,
+ });
+ targetProgress = 1;
+ }
+ }
+
+ const projected = computeZoomTransform({
+ stageSize: layout.stageSize,
+ baseMask: layout.maskRect,
+ zoomScale: targetScale,
+ zoomProgress: targetProgress,
+ focusX: targetFocus.cx,
+ focusY: targetFocus.cy,
+ });
+
+ // Spring-chase the eased target, exactly as the preview does, so the export
+ // glides past the jerk at the steep start of the ease instead of snapping to
+ // the target every frame. Snapped on the first frame or any large time jump
+ // (a seek): integrating across a gap would fling the camera.
+ let camera: { scale: number; x: number; y: number };
+ if (memory.prevTimeMs == null || dtMs <= 0 || dtMs > 80) {
+ resetZoomSpring(memory.spring, projected);
+ camera = { scale: projected.scale, x: projected.x, y: projected.y };
+ } else {
+ camera = stepZoomSpring(memory.spring, projected, dtMs);
+ }
+
+ const prev = memory.prevCamera;
+ const velocity = prev
+ ? Math.max(
+ Math.abs(camera.scale - prev.scale),
+ Math.abs(camera.x - prev.x) / Math.max(1, layout.stageSize.width),
+ Math.abs(camera.y - prev.y) / Math.max(1, layout.stageSize.height),
+ )
+ : 0;
+ memory.prevCamera = { ...camera };
+ memory.prevTimeMs = timeMs;
+
+ // The recording's box with the camera applied. The shader needs this directly:
+ // it is what the rounded corners, the mask and the shadow are all cut from.
+ const m = layout.maskRect;
+ const cameraRect = {
+ x: camera.x + camera.scale * m.x,
+ y: camera.y + camera.scale * m.y,
+ width: camera.scale * m.width,
+ height: camera.scale * m.height,
+ };
+
+ return {
+ screenRect: m,
+ borderRadius: layout.borderRadius,
+ camera,
+ cameraRect,
+ cameraBorderRadius: layout.borderRadius * camera.scale,
+ crop: scene.cropRegion,
+ webcamRect: evaluateWebcamRect(scene, layout, camera.scale, cameraFullscreenProgress),
+ webcamMirrored: scene.webcamMirrored,
+ velocity,
+ motionBlurAmount: scene.motionBlurAmount,
+ shadowIntensity: scene.shadowIntensity,
+ rotation3D: currentRotation3D,
+ cameraFullscreenProgress,
+ };
+}
+
+/**
+ * Where the webcam lands: docked PiP, shrunk by the zoom, or grown to fill the
+ * stage during a Full Camera region.
+ *
+ * Both movements are the reason the shadow cache could never hold on this
+ * product's real timelines: they change the webcam's geometry every frame of an
+ * animation, and the user's answer to §13 is that they are the norm.
+ */
+function evaluateWebcamRect(
+ scene: EvaluateScene,
+ layout: EvaluateLayout,
+ appliedScale: number,
+ fullscreenProgress: number,
+): (StyledRenderRect & { shape: WebcamMaskShape }) | null {
+ const base = layout.webcamRect;
+ if (!base) return null;
+ const shape = base.maskShape ?? scene.webcamMaskShape ?? "rectangle";
+
+ if (fullscreenProgress > 0) {
+ // Full Camera owns size and position outright; reactive zoom is ignored for
+ // the frame (mixing "shrink for zoom" and "grow to full" means nothing).
+ const target = computeCameraFullscreenTargetRect(scene.outputSize, base);
+ const full: StyledRenderRect = {
+ x: target.x,
+ y: target.y,
+ width: target.width,
+ height: target.height,
+ borderRadius: 0,
+ maskShape: base.maskShape,
+ };
+ const r = lerpRect(base, full, fullscreenProgress);
+ return { ...r, shape };
+ }
+
+ const reactive =
+ scene.webcamReactiveZoom && scene.webcamLayoutPreset === "picture-in-picture"
+ ? reactiveWebcamScale(appliedScale)
+ : 1;
+ if (!(reactive < 1)) return { ...base, shape };
+
+ // Anchor the shrink to the docked corner (bottom-right by default), like the
+ // preview, so the bubble stays flush with the edges instead of drifting toward
+ // the centre. Same bias rule as the Canvas2D path — deliberately identical.
+ const pos = scene.webcamPosition;
+ const biasX = (pos ? pos.cx >= 0.5 : true) ? 1 : 0;
+ const biasY = (pos ? pos.cy >= 0.5 : true) ? 1 : 0;
+ return {
+ ...base,
+ x: base.x + base.width * (1 - reactive) * biasX,
+ y: base.y + base.height * (1 - reactive) * biasY,
+ width: base.width * reactive,
+ height: base.height * reactive,
+ borderRadius: base.borderRadius * reactive,
+ shape,
+ };
+}
diff --git a/src/lib/exporter/wgsl/shadowCascade.wgsl.ts b/src/lib/exporter/wgsl/shadowCascade.wgsl.ts
new file mode 100644
index 000000000..a01c3c084
--- /dev/null
+++ b/src/lib/exporter/wgsl/shadowCascade.wgsl.ts
@@ -0,0 +1,195 @@
+// The drop shadow, computed — not cached.
+//
+// The Canvas2D path chains three CSS drop-shadows over the video, at 14.2 ms per
+// moving frame (Annex B.1), and caches the result by geometry to avoid paying it.
+// That cache is a 2D artefact: it exists because the filter is expensive, and a
+// moving camera — which the product says is the norm — misses it by construction.
+// On the GPU there is nothing to cache: the shadow is redrawn every frame.
+//
+// EXACTNESS is the constraint (§13). The ban is on approximating the falloff with
+// an SDF/smoothstep — a DIFFERENT shape. It is not a ban on another implementation
+// of the same shape. CSS `drop-shadow(0 dy blur rgba)` is feGaussianBlur on
+// SourceAlpha with stdDeviation = blur/2, and the SVG filter spec defines that,
+// for our radii, as three successive BOX blurs of a stated width:
+//
+// d = floor(s * 3 * sqrt(2*PI) / 4 + 0.5)
+// d odd : three box-blurs of width d, centred.
+// d even : two box-blurs of width d (centred left, then right), then one of d+1.
+//
+// That is what runs below — the spec's own algorithm, on the device that suits it.
+// Box blurs are separable and cheap here; nothing is approximated.
+//
+// Whether Chromium's Skia follows the spec's letter is NOT assumed: the pixel-diff
+// against the Canvas2D output is the gate, and it is what makes this file
+// falsifiable rather than merely plausible.
+
+/** One CSS drop-shadow stage: blur radius (px), y offset (px), alpha. */
+export interface ShadowStage {
+ blur: number;
+ offsetY: number;
+ alpha: number;
+}
+
+/**
+ * The three stages, matching shadowFilterChain() in frameRenderer.ts exactly.
+ *
+ * Duplicated deliberately rather than imported: the Canvas2D chain is the thing
+ * under test, and a shared constant would make the two agree by construction and
+ * prove nothing. If they drift, the pixel-diff must fail.
+ */
+export function shadowStages(intensity: number): ShadowStage[] {
+ const offset = 12 * intensity;
+ return [
+ { blur: 48 * intensity, offsetY: offset, alpha: 0.7 * intensity },
+ { blur: 16 * intensity, offsetY: offset / 3, alpha: 0.5 * intensity },
+ { blur: 8 * intensity, offsetY: offset / 6, alpha: 0.3 * intensity },
+ ];
+}
+
+/**
+ * The SVG filter spec's box widths for a gaussian of stdDeviation `s`.
+ *
+ * Returns the three box widths and their centring offsets. The even case is the
+ * subtle one: the spec compensates a box of even width by centring it left, then
+ * right, then widening the third — which is why this is a table and not a loop.
+ */
+export function boxesForStdDeviation(s: number): { width: number; offset: number }[] {
+ if (s <= 0) return [];
+ const d = Math.floor((s * 3 * Math.sqrt(2 * Math.PI)) / 4 + 0.5);
+ if (d < 1) return [];
+ if (d % 2 === 1) {
+ const half = (d - 1) / 2;
+ return [
+ { width: d, offset: -half },
+ { width: d, offset: -half },
+ { width: d, offset: -half },
+ ];
+ }
+ return [
+ { width: d, offset: -d / 2 },
+ { width: d, offset: -d / 2 + 1 },
+ { width: d + 1, offset: -d / 2 },
+ ];
+}
+
+/** stdDeviation of a CSS drop-shadow's blur radius. */
+export const stdDeviationForBlur = (blur: number) => blur / 2;
+
+export const SHADOW_WGSL = /* wgsl */ `
+
+// All-vec4, for the same reason as composite.wgsl.ts: no alignment holes for the
+// CPU packing to get wrong. The first version declared (vec2f, vec4f, f32, f32)
+// and WGSL laid it out at 48 bytes with a hole at 8 — against a 32-byte buffer.
+// That is a validation error, a black frame, and no exception anywhere.
+struct SilhouetteU {
+ // stage.xy | radius | unused
+ a : vec4f,
+ // rect: x, y, w, h
+ rect : vec4f,
+};
+
+struct BlurU {
+ // Texel step: (1/width, 0) horizontal, (0, 1/height) vertical.
+ step : vec2f,
+ // Box width in texels, and where the box starts relative to the pixel.
+ width : i32,
+ offset : i32,
+};
+
+struct StageU {
+ // offsetY (in texels, along v) | alpha | unused | unused
+ a : vec4f,
+};
+
+struct VsOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+};
+
+@vertex
+fn vs(@builtin(vertex_index) i : u32) -> VsOut {
+ 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);
+ return out;
+}
+
+// ---- pass 1: the silhouette -------------------------------------------------
+// The alpha the CSS chain actually blurs. The video is opaque and masked by a
+// rounded rect, so its alpha IS that rounded rect — no video pixel takes part.
+
+@group(0) @binding(0) var<uniform> su : SilhouetteU;
+
+fn sdRoundBox(p : vec2f, halfSize : vec2f, r : f32) -> f32 {
+ let rr = min(r, min(halfSize.x, halfSize.y));
+ let q = abs(p) - halfSize + vec2f(rr);
+ return length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0) - rr;
+}
+
+@fragment
+fn fsSilhouette(in : VsOut) -> @location(0) vec4f {
+ let px = in.uv * su.a.xy;
+ let d = sdRoundBox(px - (su.rect.xy + su.rect.zw * 0.5), su.rect.zw * 0.5, su.a.z);
+ let a = clamp(0.5 - d, 0.0, 1.0);
+ return vec4f(0.0, 0.0, 0.0, a);
+}
+
+// ---- pass 2: one box blur, one axis ----------------------------------------
+// Separable, so a d x d box costs 2d taps rather than d*d. Three of these per
+// gaussian, per the SVG spec.
+
+@group(0) @binding(0) var<uniform> bu : BlurU;
+@group(0) @binding(1) var blurSamp : sampler;
+@group(0) @binding(2) var blurSrc : texture_2d<f32>;
+
+@fragment
+fn fsBox(in : VsOut) -> @location(0) vec4f {
+ var acc = vec4f(0.0);
+ for (var i = 0; i < bu.width; i = i + 1) {
+ let o = f32(bu.offset + i);
+ acc = acc + textureSample(blurSrc, blurSamp, in.uv + bu.step * o);
+ }
+ return acc / f32(bu.width);
+}
+
+// ---- pass 3: one cascade stage ---------------------------------------------
+// stage_out = source OVER shadow(source), where shadow is the blurred alpha,
+// offset down and tinted. Each stage shadows the PREVIOUS stage's output — its
+// own shadow included. That cascade is what gives the falloff, and it is why
+// this cannot collapse into a single blur.
+
+@group(0) @binding(0) var<uniform> stu : StageU;
+@group(0) @binding(1) var stageSamp : sampler;
+@group(0) @binding(2) var stageSrc : texture_2d<f32>; // the un-blurred source
+@group(0) @binding(3) var stageBlur : texture_2d<f32>; // its blurred alpha
+
+@fragment
+fn fsStage(in : VsOut) -> @location(0) vec4f {
+ let src = textureSample(stageSrc, stageSamp, in.uv);
+ let shadowAlpha = textureSample(stageBlur, stageSamp, in.uv - vec2f(0.0, stu.a.x)).a * stu.a.y;
+ // src is black-tinted throughout, so only alpha needs compositing.
+ let a = src.a + shadowAlpha * (1.0 - src.a);
+ return vec4f(0.0, 0.0, 0.0, a);
+}
+
+// ---- pass 4: strip the silhouette ------------------------------------------
+// The cascade's output is "silhouette OVER shadows". The compositor draws the
+// recording on top, which covers the silhouette exactly — but only where the
+// recording is opaque. Subtracting it here keeps the shadow honest under the
+// antialiased corners instead of double-darkening them.
+
+@group(0) @binding(0) var<uniform> fu : SilhouetteU;
+@group(0) @binding(1) var finalSamp : sampler;
+@group(0) @binding(2) var finalSrc : texture_2d<f32>;
+
+@fragment
+fn fsStrip(in : VsOut) -> @location(0) vec4f {
+ let px = in.uv * fu.a.xy;
+ let d = sdRoundBox(px - (fu.rect.xy + fu.rect.zw * 0.5), fu.rect.zw * 0.5, fu.a.z);
+ let sil = clamp(0.5 - d, 0.0, 1.0);
+ let a = textureSample(finalSrc, finalSamp, in.uv).a;
+ return vec4f(0.0, 0.0, 0.0, max(a - sil, 0.0));
+}
+`;
diff --git a/src/lib/exporter/wgslFrameRenderer.ts b/src/lib/exporter/wgslFrameRenderer.ts
new file mode 100644
index 000000000..4e443bbf8
--- /dev/null
+++ b/src/lib/exporter/wgslFrameRenderer.ts
@@ -0,0 +1,724 @@
+// WgslFrameRenderer — the §8b compositor, as a POC.
+//
+// Drop-in for FrameRenderer: same methods, same canvas out, so the existing
+// decode / encode / mux / audio pipeline is untouched and the bench can put the
+// two compositors in one interleaved run. That is the whole point of matching the
+// interface — a POC that cannot be measured against what it replaces is a demo.
+//
+// What it is: WebGPU device, four textures, one uniform block, one draw call
+// (plus the shadow's own passes). No Pixi, no Canvas2D, no six surfaces, no two GL
+// contexts, no per-geometry cache.
+//
+// Both seams (§8c) stay on the device: the decoded VideoFrame enters as an
+// external texture (zero copy), and the composited canvas leaves as
+// `new VideoFrame(canvas)` to the encoder. Nothing descends to CPU RAM.
+//
+// NOT in the POC: captions/annotations (glyph rasterisation — a texture upload,
+// cheap to add later), 3D rotation, the cursor. Scoped out with the user, and
+// none of them changes the shape of what is measured here.
+
+import type {
+ AnnotationRegion,
+ CameraFullscreenRegion,
+ CropRegion,
+ SpeedRegion,
+ WebcamMaskShape,
+ ZoomRegion,
+} from "@/components/video-editor/types";
+import type { Size, WebcamLayoutPreset, WebcamSizePreset } from "@/lib/compositeLayout";
+import { COMPOSITE_WGSL } from "./wgsl/composite.wgsl";
+import {
+ createEvaluateMemory,
+ type EvaluateLayout,
+ type EvaluateMemory,
+ type EvaluateScene,
+ evaluate,
+ evaluateLayout,
+ type FrameState,
+} from "./wgsl/evaluate";
+import {
+ boxesForStdDeviation,
+ SHADOW_WGSL,
+ shadowStages,
+ stdDeviationForBlur,
+} from "./wgsl/shadowCascade.wgsl";
+
+export interface WgslFrameRenderConfig {
+ width: number;
+ height: number;
+ wallpaper: string;
+ zoomRegions: ZoomRegion[];
+ cameraFullscreenRegions?: CameraFullscreenRegion[];
+ annotationRegions?: AnnotationRegion[];
+ speedRegions?: SpeedRegion[];
+ showShadow: boolean;
+ shadowIntensity: number;
+ showBlur: boolean;
+ motionBlurAmount?: number;
+ borderRadius?: number;
+ padding?: number;
+ cropRegion: CropRegion;
+ videoWidth: number;
+ videoHeight: number;
+ webcamSize?: Size | null;
+ webcamLayoutPreset?: WebcamLayoutPreset;
+ webcamMaskShape?: WebcamMaskShape;
+ webcamMirrored?: boolean;
+ webcamReactiveZoom?: boolean;
+ webcamSizePreset?: WebcamSizePreset;
+ webcamPosition?: { cx: number; cy: number } | null;
+ cursorTelemetry?: import("@/components/video-editor/types").CursorTelemetryPoint[];
+ platform: string;
+}
+
+const MASK_SHAPE_CODE: Record<string, number> = {
+ rectangle: 0,
+ rounded: 1,
+ circle: 2,
+ square: 3,
+};
+
+/** Uniform block: 24 floats = 96 bytes. §8b budgets ~200; there is room. */
+const UNIFORM_FLOATS = 24;
+
+export class WgslFrameRenderer {
+ private config: WgslFrameRenderConfig;
+ private canvas: HTMLCanvasElement | null = null;
+ private context: GPUCanvasContext | null = null;
+ private device: GPUDevice | null = null;
+
+ private compositePipeline: GPURenderPipeline | null = null;
+ private uniformBuffer: GPUBuffer | null = null;
+ private uniformData = new Float32Array(UNIFORM_FLOATS);
+ private sampler: GPUSampler | null = null;
+ private backgroundTexture: GPUTexture | null = null;
+ /** Stands in for an absent webcam: an external texture binding cannot be null. */
+ private blankTexture: GPUTexture | null = null;
+
+ private shadow: ShadowPasses | null = null;
+
+ private layout: EvaluateLayout | null = null;
+ private layoutHasWebcam: boolean | null = null;
+ private memory: EvaluateMemory = createEvaluateMemory();
+ /** WebGPU reports validation failures out-of-band: a broken pass draws nothing
+ * and says nothing, which reads as a fast compositor rendering black. Scoped
+ * on the first frame only — enough to catch a structural mistake, and the
+ * popErrorScope sync is not something the steady state should pay for. */
+ private firstFrame = true;
+
+ constructor(config: WgslFrameRenderConfig) {
+ this.config = config;
+ }
+
+ async initialize(): Promise<void> {
+ if (!navigator.gpu) {
+ throw new Error("WebGPU unavailable: navigator.gpu is missing (needs a secure context)");
+ }
+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
+ if (!adapter) throw new Error("WebGPU unavailable: no adapter");
+ const device = await adapter.requestDevice();
+ this.device = device;
+ // A device lost mid-export must not surface as a black frame or a silent
+ // hang: it is a failed export and must say so.
+ device.lost.then((info) => {
+ console.error(`[wgsl] GPU device lost: ${info.reason} — ${info.message}`);
+ });
+
+ const canvas = document.createElement("canvas");
+ canvas.width = this.config.width;
+ canvas.height = this.config.height;
+ this.canvas = canvas;
+
+ const context = canvas.getContext("webgpu");
+ if (!context) throw new Error("WebGPU unavailable: canvas has no webgpu context");
+ this.context = context;
+ context.configure({
+ device,
+ format: navigator.gpu.getPreferredCanvasFormat(),
+ alphaMode: "opaque",
+ // The composited texture is read back by `new VideoFrame(canvas)` — the
+ // encoder seam. Without COPY_SRC that read is illegal.
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
+ });
+
+ this.sampler = device.createSampler({
+ magFilter: "linear",
+ minFilter: "linear",
+ addressModeU: "clamp-to-edge",
+ addressModeV: "clamp-to-edge",
+ });
+
+ this.uniformBuffer = device.createBuffer({
+ size: UNIFORM_FLOATS * 4,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ });
+
+ const module = device.createShaderModule({ code: COMPOSITE_WGSL, label: "composite" });
+ this.compositePipeline = device.createRenderPipeline({
+ label: "composite",
+ layout: "auto",
+ vertex: { module, entryPoint: "vs" },
+ fragment: {
+ module,
+ entryPoint: "fs",
+ targets: [{ format: navigator.gpu.getPreferredCanvasFormat() }],
+ },
+ primitive: { topology: "triangle-list" },
+ });
+
+ this.blankTexture = device.createTexture({
+ size: [1, 1],
+ format: "rgba8unorm",
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
+ });
+
+ await this.loadBackground();
+
+ this.shadow = new ShadowPasses(device, this.config.width, this.config.height);
+ }
+
+ /**
+ * The wallpaper, blurred ONCE at init.
+ *
+ * This is not the 2D cache in disguise: the wallpaper is a still image, so
+ * blurring it per frame would be recomputing a constant. The shadow is not a
+ * constant — it follows the camera — which is exactly why it is not cached.
+ */
+ private async loadBackground(): Promise<void> {
+ const device = this.device;
+ if (!device) return;
+ const { width, height } = this.config;
+
+ const surface = document.createElement("canvas");
+ surface.width = width;
+ surface.height = height;
+ const ctx = surface.getContext("2d");
+ if (!ctx) throw new Error("2d context unavailable for wallpaper preparation");
+
+ const wallpaper = this.config.wallpaper;
+ if (wallpaper && !wallpaper.startsWith("#") && !wallpaper.includes("gradient")) {
+ const url =
+ wallpaper.startsWith("/") || wallpaper.includes("://")
+ ? wallpaper
+ : `/wallpapers/${wallpaper}`;
+ try {
+ const image = await loadImage(url);
+ if (this.config.showBlur) ctx.filter = "blur(6px)";
+ ctx.drawImage(image, 0, 0, width, height);
+ ctx.filter = "none";
+ } catch (error) {
+ console.warn(`[wgsl] wallpaper ${url} failed to load, falling back to flat:`, error);
+ ctx.fillStyle = "#1e1e1e";
+ ctx.fillRect(0, 0, width, height);
+ }
+ } else {
+ ctx.fillStyle = wallpaper || "#1e1e1e";
+ ctx.fillRect(0, 0, width, height);
+ }
+
+ this.backgroundTexture = device.createTexture({
+ size: [width, height],
+ format: "rgba8unorm",
+ usage:
+ GPUTextureUsage.TEXTURE_BINDING |
+ GPUTextureUsage.COPY_DST |
+ GPUTextureUsage.RENDER_ATTACHMENT,
+ });
+ device.queue.copyExternalImageToTexture(
+ { source: surface },
+ { texture: this.backgroundTexture },
+ [width, height],
+ );
+ }
+
+ setSource(source: {
+ videoWidth: number;
+ videoHeight: number;
+ webcamSize?: Size | null;
+ zoomRegions?: ZoomRegion[];
+ annotationRegions?: AnnotationRegion[];
+ speedRegions?: SpeedRegion[];
+ cursorRecordingData?: unknown;
+ cursorScale?: number;
+ }): void {
+ this.config = {
+ ...this.config,
+ videoWidth: source.videoWidth,
+ videoHeight: source.videoHeight,
+ webcamSize: source.webcamSize ?? null,
+ zoomRegions: source.zoomRegions ?? this.config.zoomRegions,
+ annotationRegions: source.annotationRegions ?? this.config.annotationRegions,
+ speedRegions: source.speedRegions ?? this.config.speedRegions,
+ };
+ // A new segment is a new source: geometry must be recomputed, and the
+ // spring must not integrate across the cut.
+ this.layout = null;
+ this.layoutHasWebcam = null;
+ this.memory = createEvaluateMemory();
+ }
+
+ setCropRegion(crop: CropRegion): void {
+ this.config = { ...this.config, cropRegion: crop };
+ this.layout = null;
+ }
+
+ private scene(): EvaluateScene {
+ return {
+ outputSize: { width: this.config.width, height: this.config.height },
+ videoSize: { width: this.config.videoWidth, height: this.config.videoHeight },
+ webcamSize: this.config.webcamSize ?? null,
+ cropRegion: this.config.cropRegion,
+ padding: this.config.padding ?? 0,
+ borderRadius: this.config.borderRadius ?? 0,
+ shadowIntensity: this.config.showShadow ? this.config.shadowIntensity : 0,
+ motionBlurAmount: this.config.motionBlurAmount ?? 0,
+ zoomRegions: this.config.zoomRegions,
+ cameraFullscreenRegions: this.config.cameraFullscreenRegions ?? [],
+ webcamLayoutPreset: this.config.webcamLayoutPreset ?? "picture-in-picture",
+ webcamSizePreset: this.config.webcamSizePreset ?? 25,
+ webcamMaskShape: this.config.webcamMaskShape ?? "rectangle",
+ webcamPosition: this.config.webcamPosition ?? null,
+ webcamMirrored: this.config.webcamMirrored ?? false,
+ webcamReactiveZoom: this.config.webcamReactiveZoom ?? true,
+ cursorTelemetry: this.config.cursorTelemetry,
+ };
+ }
+
+ async renderFrame(
+ videoFrame: VideoFrame,
+ timestampUs: number,
+ webcamFrame?: VideoFrame | null,
+ ): Promise<void> {
+ const device = this.device;
+ const context = this.context;
+ const pipeline = this.compositePipeline;
+ if (!device || !context || !pipeline || !this.uniformBuffer || !this.sampler) {
+ throw new Error("Renderer not initialized");
+ }
+
+ const scene = this.scene();
+ const hasWebcam = !!webcamFrame;
+ if (!this.layout || this.layoutHasWebcam !== hasWebcam) {
+ this.layout = evaluateLayout(scene, hasWebcam);
+ this.layoutHasWebcam = hasWebcam;
+ }
+ if (!this.layout) throw new Error("Layout could not be evaluated");
+
+ const timeMs = timestampUs / 1000;
+ const state = evaluate(scene, this.layout, timeMs, this.memory);
+ if (this.firstFrame) {
+ device.pushErrorScope("validation");
+ console.warn(
+ `[wgsl] frame 0 @${timeMs.toFixed(0)}ms: stage ${this.config.width}x${this.config.height}` +
+ ` · padding ${scene.padding} · preset ${scene.webcamLayoutPreset}` +
+ ` · maskRect ${fmtRect(this.layout.maskRect)}` +
+ ` · camera scale=${state.camera.scale.toFixed(3)} x=${state.camera.x.toFixed(0)} y=${state.camera.y.toFixed(0)}` +
+ ` · videoRect ${fmtRect(state.cameraRect)} r=${state.cameraBorderRadius.toFixed(1)}` +
+ ` · shadow ${state.shadowIntensity} · webcam ${
+ state.webcamRect ? fmtRect(state.webcamRect) : "none"
+ }`,
+ );
+ }
+
+ // Seam S1: the decoded frame becomes a texture without leaving the device.
+ // External textures are valid for this task only — imported per frame, by
+ // design, and free.
+ const videoTex = device.importExternalTexture({ source: videoFrame });
+ const webcamTex = webcamFrame ? device.importExternalTexture({ source: webcamFrame }) : null;
+
+ const encoder = device.createCommandEncoder({ label: "frame" });
+
+ let shadowView: GPUTextureView;
+ if (state.shadowIntensity > 0 && this.shadow) {
+ shadowView = this.shadow.encode(encoder, state);
+ } else {
+ shadowView = this.shadow!.outputTexture.createView();
+ }
+
+ this.writeUniforms(state, hasWebcam);
+ device.queue.writeBuffer(this.uniformBuffer, 0, this.uniformData);
+
+ const bindGroup = device.createBindGroup({
+ layout: pipeline.getBindGroupLayout(0),
+ entries: [
+ { binding: 0, resource: { buffer: this.uniformBuffer } },
+ { binding: 1, resource: this.sampler },
+ { binding: 2, resource: videoTex },
+ {
+ binding: 3,
+ resource: webcamTex ?? device.importExternalTexture({ source: blankFrame() }),
+ },
+ { binding: 4, resource: this.backgroundTexture!.createView() },
+ { binding: 5, resource: shadowView },
+ ],
+ });
+
+ const pass = encoder.beginRenderPass({
+ colorAttachments: [
+ {
+ view: context.getCurrentTexture().createView(),
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
+ loadOp: "clear",
+ storeOp: "store",
+ },
+ ],
+ });
+ pass.setPipeline(pipeline);
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(3);
+ pass.end();
+
+ device.queue.submit([encoder.finish()]);
+
+ if (this.firstFrame) {
+ this.firstFrame = false;
+ const error = await device.popErrorScope();
+ if (error) console.error(`[wgsl] VALIDATION ERROR on frame 0: ${error.message}`);
+ else console.warn("[wgsl] frame 0 submitted with no validation error");
+ }
+ }
+
+ /**
+ * Pack the uniform block. Field n lives at float 4n — the struct is all vec4f
+ * precisely so this can be true (see composite.wgsl.ts).
+ */
+ private writeUniforms(state: FrameState, hasWebcam: boolean): void {
+ const u = this.uniformData;
+ const w = state.webcamRect;
+ // Motion blur, in pixels, along the camera's direction of travel. The 2D
+ // path drives a Pixi filter from the same velocity; same input, same look.
+ const blurPx = state.velocity * (state.motionBlurAmount ?? 0) * 400;
+
+ // a: stage.xy | videoRadius | shadowIntensity
+ u[0] = this.config.width;
+ u[1] = this.config.height;
+ u[2] = state.cameraBorderRadius;
+ u[3] = state.shadowIntensity;
+ // videoRect
+ u[4] = state.cameraRect.x;
+ u[5] = state.cameraRect.y;
+ u[6] = state.cameraRect.width;
+ u[7] = state.cameraRect.height;
+ // crop
+ u[8] = state.crop.x;
+ u[9] = state.crop.y;
+ u[10] = state.crop.width;
+ u[11] = state.crop.height;
+ // webcamRect
+ u[12] = w?.x ?? 0;
+ u[13] = w?.y ?? 0;
+ u[14] = w?.width ?? 0;
+ u[15] = w?.height ?? 0;
+ // b: webcamRadius | motionBlur.xy | unused. Blur runs along x: the camera's
+ // travel is dominated by the pan, and a single axis is what the 2D filter
+ // applies too.
+ u[16] = w?.borderRadius ?? 0;
+ u[17] = blurPx;
+ u[18] = 0;
+ u[19] = 0;
+ // flags: shape | mirrored | hasWebcam | hasShadow — floats, not u32, so the
+ // whole block is one Float32Array with no type interleaving.
+ u[20] = w ? (MASK_SHAPE_CODE[w.shape] ?? 0) : 0;
+ u[21] = state.webcamMirrored ? 1 : 0;
+ u[22] = hasWebcam && w ? 1 : 0;
+ u[23] = state.shadowIntensity > 0 ? 1 : 0;
+ }
+
+ getCanvas(): HTMLCanvasElement {
+ if (!this.canvas) throw new Error("Renderer not initialized");
+ return this.canvas;
+ }
+
+ /** Gate G0's fence, for arm parity with the Canvas2D renderer. */
+ finishGpuWork(): void {
+ // onSubmittedWorkDone is the device's own fence; the caller awaits nothing
+ // here because the encoder's VideoFrame(canvas) is the real sync point.
+ void this.device?.queue.onSubmittedWorkDone();
+ }
+
+ /** No cache to report. Kept so the exporter can treat both renderers alike. */
+ shadowCacheStats(): { hits: number; misses: number } {
+ return { hits: 0, misses: 0 };
+ }
+
+ destroy(): void {
+ this.backgroundTexture?.destroy();
+ this.blankTexture?.destroy();
+ this.shadow?.destroy();
+ this.uniformBuffer?.destroy();
+ this.device?.destroy();
+ this.device = null;
+ this.context = null;
+ this.canvas = null;
+ }
+}
+
+/**
+ * The shadow's passes: silhouette → 3 cascade stages, each a gaussian (3 box
+ * blurs, separable) then a composite → strip the silhouette.
+ *
+ * Six textures, allocated once. Two of them exist for a reason worth stating: a
+ * pass may not read and write the same texture, and a cascade stage reads BOTH
+ * its source and that source's blur. So the blur chain ping-pongs in its own pair
+ * (blurA/blurB) and never touches the stage's pair (stageA/stageB) — a single
+ * shared ping-pong silently overwrites the stage's source on the blur's second
+ * pass, which is a black shadow and a long afternoon.
+ */
+class ShadowPasses {
+ readonly outputTexture: GPUTexture;
+ private device: GPUDevice;
+ private width: number;
+ private height: number;
+ private silhouette: GPUTexture;
+ private blurA: GPUTexture;
+ private blurB: GPUTexture;
+ private stageA: GPUTexture;
+ private stageB: GPUTexture;
+ private silhouettePipeline: GPURenderPipeline;
+ private boxPipeline: GPURenderPipeline;
+ private stagePipeline: GPURenderPipeline;
+ private stripPipeline: GPURenderPipeline;
+ private sampler: GPUSampler;
+ private silhouetteBuffer: GPUBuffer;
+ private stripBuffer: GPUBuffer;
+ private boxBuffers: GPUBuffer[] = [];
+ private stageBuffers: GPUBuffer[] = [];
+ private boxCursor = 0;
+ private stageCursor = 0;
+
+ constructor(device: GPUDevice, width: number, height: number) {
+ this.device = device;
+ this.width = width;
+ this.height = height;
+
+ const make = (label: string) =>
+ device.createTexture({
+ label,
+ size: [width, height],
+ format: "rgba8unorm",
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT,
+ });
+ this.silhouette = make("shadow-silhouette");
+ this.blurA = make("shadow-blur-a");
+ this.blurB = make("shadow-blur-b");
+ this.stageA = make("shadow-stage-a");
+ this.stageB = make("shadow-stage-b");
+ this.outputTexture = make("shadow-out");
+
+ const module = device.createShaderModule({ code: SHADOW_WGSL, label: "shadow" });
+ const target: GPUColorTargetState[] = [{ format: "rgba8unorm" }];
+ const makePipeline = (entry: string, label: string) =>
+ device.createRenderPipeline({
+ label,
+ layout: "auto",
+ vertex: { module, entryPoint: "vs" },
+ fragment: { module, entryPoint: entry, targets: target },
+ primitive: { topology: "triangle-list" },
+ });
+ this.silhouettePipeline = makePipeline("fsSilhouette", "shadow-silhouette");
+ this.boxPipeline = makePipeline("fsBox", "shadow-box");
+ this.stagePipeline = makePipeline("fsStage", "shadow-stage");
+ this.stripPipeline = makePipeline("fsStrip", "shadow-strip");
+
+ this.sampler = device.createSampler({
+ magFilter: "nearest",
+ minFilter: "nearest",
+ addressModeU: "clamp-to-edge",
+ addressModeV: "clamp-to-edge",
+ });
+ this.silhouetteBuffer = device.createBuffer({
+ size: 32,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ });
+ this.stripBuffer = device.createBuffer({
+ size: 32,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ });
+ }
+
+ private boxBuffer(): GPUBuffer {
+ // One buffer per box pass per frame: a bind group must not read a buffer
+ // that a later pass in the same submit has overwritten.
+ if (this.boxCursor >= this.boxBuffers.length) {
+ this.boxBuffers.push(
+ this.device.createBuffer({
+ size: 16,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ }),
+ );
+ }
+ return this.boxBuffers[this.boxCursor++];
+ }
+
+ private stageBuffer(): GPUBuffer {
+ if (this.stageCursor >= this.stageBuffers.length) {
+ this.stageBuffers.push(
+ this.device.createBuffer({
+ size: 16,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ }),
+ );
+ }
+ return this.stageBuffers[this.stageCursor++];
+ }
+
+ encode(encoder: GPUCommandEncoder, state: FrameState): GPUTextureView {
+ this.boxCursor = 0;
+ this.stageCursor = 0;
+ const device = this.device;
+ const rect = state.cameraRect;
+ const radius = state.cameraBorderRadius;
+
+ // a: stage.xy | radius | unused, then rect — vec4 each, no holes.
+ const geom = new Float32Array(8);
+ geom[0] = this.width;
+ geom[1] = this.height;
+ geom[2] = radius;
+ geom[3] = 0;
+ geom[4] = rect.x;
+ geom[5] = rect.y;
+ geom[6] = rect.width;
+ geom[7] = rect.height;
+ device.queue.writeBuffer(this.silhouetteBuffer, 0, geom);
+ device.queue.writeBuffer(this.stripBuffer, 0, geom);
+
+ // 1. The silhouette.
+ this.drawInto(encoder, this.silhouettePipeline, this.silhouette, [
+ { binding: 0, resource: { buffer: this.silhouetteBuffer } },
+ ]);
+
+ // 2. The cascade. Each stage blurs its input's alpha and composites the
+ // input back over it — so stage k+1 shadows stage k's shadow. That
+ // recursion is the falloff; it cannot collapse into one blur.
+ let current = this.silhouette;
+ let stageIndex = 0;
+ for (const stage of shadowStages(state.shadowIntensity)) {
+ const blurred = this.blur(encoder, current, stdDeviationForBlur(stage.blur));
+ // Alternating stage textures: dest is never `current` (the previous
+ // stage's output) and never `blurred` (which lives in the blur pair).
+ const dest = stageIndex % 2 === 0 ? this.stageA : this.stageB;
+
+ const buffer = this.stageBuffer();
+ const data = new Float32Array(4);
+ data[0] = stage.offsetY / this.height;
+ data[1] = stage.alpha;
+ device.queue.writeBuffer(buffer, 0, data);
+
+ this.drawInto(encoder, this.stagePipeline, dest, [
+ { binding: 0, resource: { buffer } },
+ { binding: 1, resource: this.sampler },
+ { binding: 2, resource: current.createView() },
+ { binding: 3, resource: blurred.createView() },
+ ]);
+ current = dest;
+ stageIndex++;
+ }
+
+ // 3. Remove the silhouette; the recording covers that area itself.
+ this.drawInto(encoder, this.stripPipeline, this.outputTexture, [
+ { binding: 0, resource: { buffer: this.stripBuffer } },
+ { binding: 1, resource: this.sampler },
+ { binding: 2, resource: current.createView() },
+ ]);
+ return this.outputTexture.createView();
+ }
+
+ /**
+ * One gaussian = three box blurs, per the SVG filter spec. Separable, so a
+ * d x d box costs 2d taps rather than d².
+ *
+ * Ping-pongs strictly inside (blurA, blurB): `src` belongs to the caller and
+ * is read again by the cascade stage after this returns, so it must survive.
+ */
+ private blur(encoder: GPUCommandEncoder, src: GPUTexture, stdDeviation: number): GPUTexture {
+ const boxes = boxesForStdDeviation(stdDeviation);
+ if (boxes.length === 0) return src;
+ let current = src;
+ let pass = 0;
+ for (const box of boxes) {
+ for (const axis of [0, 1]) {
+ const dest = pass % 2 === 0 ? this.blurA : this.blurB;
+ const buffer = this.boxBuffer();
+ const data = new ArrayBuffer(16);
+ const f = new Float32Array(data, 0, 2);
+ const i = new Int32Array(data, 8, 2);
+ f[0] = axis === 0 ? 1 / this.width : 0;
+ f[1] = axis === 0 ? 0 : 1 / this.height;
+ i[0] = box.width;
+ i[1] = box.offset;
+ this.device.queue.writeBuffer(buffer, 0, data);
+ this.drawInto(encoder, this.boxPipeline, dest, [
+ { binding: 0, resource: { buffer } },
+ { binding: 1, resource: this.sampler },
+ { binding: 2, resource: current.createView() },
+ ]);
+ current = dest;
+ pass++;
+ }
+ }
+ return current;
+ }
+
+ private drawInto(
+ encoder: GPUCommandEncoder,
+ pipeline: GPURenderPipeline,
+ target: GPUTexture,
+ entries: GPUBindGroupEntry[],
+ ): void {
+ const pass = encoder.beginRenderPass({
+ colorAttachments: [
+ {
+ view: target.createView(),
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
+ loadOp: "clear",
+ storeOp: "store",
+ },
+ ],
+ });
+ pass.setPipeline(pipeline);
+ pass.setBindGroup(
+ 0,
+ this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries }),
+ );
+ pass.draw(3);
+ pass.end();
+ }
+
+ destroy(): void {
+ this.silhouette.destroy();
+ this.blurA.destroy();
+ this.blurB.destroy();
+ this.stageA.destroy();
+ this.stageB.destroy();
+ this.outputTexture.destroy();
+ this.silhouetteBuffer.destroy();
+ this.stripBuffer.destroy();
+ for (const b of this.boxBuffers) b.destroy();
+ for (const b of this.stageBuffers) b.destroy();
+ }
+}
+
+const fmtRect = (r: { x: number; y: number; width: number; height: number }) =>
+ `${r.x.toFixed(0)},${r.y.toFixed(0)} ${r.width.toFixed(0)}x${r.height.toFixed(0)}`;
+
+function loadImage(url: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ image.crossOrigin = "anonymous";
+ image.onload = () => resolve(image);
+ image.onerror = () => reject(new Error(`failed to load ${url}`));
+ image.src = url;
+ });
+}
+
+let blank: VideoFrame | null = null;
+/** An external texture binding cannot be null, so an absent webcam gets 1x1 of nothing. */
+function blankFrame(): VideoFrame {
+ if (!blank) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 1;
+ canvas.height = 1;
+ blank = new VideoFrame(canvas, { timestamp: 0 });
+ }
+ return blank;
+}