8000 feat(render): real WebGPU backend + render==preview pipeline by johannboehme · Pull Request #12 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content

feat(render): real WebGPU backend + render==preview pipeline - #12

Merged
johannboehme merged 5 commits into
mainfrom
claude/gracious-germain-7e4dcf
May 2, 2026
Merged

johannboehme merged 5 commits into
mainfrom
claude/gracious-germain-7e4dcf

Conversation

@johannboehme
Copy link
Copy Markdown
Owner

Summary

  • WebGPU is now the primary renderer with strict WebGPU → WebGL2 → Canvas2D fallback ladder. All 7 punch-in FX (vignette, wear, echo, rgb, tape, zoom, uv) are ported to WGSL with structural parity to the WebGL2 implementations.
  • Render == Preview: the export Compositor now uses the same createBackend() factory as the live preview, eliminating the long-standing "WEAR/TAPE look different in render vs preview" bug. Same backend tier, same pixels in both paths.
  • Performance optimizations for sustained 4K multi-cam playback as instrument: cached GPU readback buffer + Uint32 BGRA→RGBA swap, putImageData fast-path, plus an adaptive resolution scaler in the live preview that reacts to drawFrame latency.

What's in here

5 commits on the branch:

  1. b22f869 feat(render): real WebGPU backend, render==preview via shared factory
  2. 4e98211 fix(render): WebGPU export stutter — bypass canvas swap-chain via GPU readback (the "frames hin und her springen" bug)
  3. 7023d0a fix(export): FX missed in segment exports — look up FX at master time, not output-relative time
  4. ecde9b6 perf(render): cached readback buffer + adaptive preview scale
  5. 6a0766e Merge origin/main (mobile FX panel fixes fix(fx): make envelope screen usable on mobile #10/fix(fx): make ADSR knots reliably grabbable on mobile #11) — clean merge, no conflicts

Settings page now exposes the active Render backend (WebGPU / WebGL2 / Canvas2D) and a real probeWebGPU() (calls requestAdapter()) so caps.webgpu is reliable.

Test plan

  • 615/615 unit tests passing (incl. new adaptive-scaler.test.ts × 9, expanded webgpu-backend.test.ts)
  • Browser tests passing for: webgpu-backend.browser.test.ts (25 — rotation/flip/letterbox/vignette/rgb/wear+tape serial), compositor-isolation.browser.test.ts (10 — VideoFrame isolation across 3 backends), webgpu-readback.bench.browser.test.ts (steady-state throughput)
  • End-to-end verified in dev browser: real export of a 2-cam 13.8 s segment with all 7 FX renders flicker-free, no frame stutter, and every FX visible at its master-time position
  • Fallback verified: forcing webgpu=false in the worker drops cleanly to WebGL2 and produces equivalent output
  • Manual smoke test on mobile (FxHardwarePanel changes from main are merged but not re-tested by me)

Known soft spots

  • stress.browser.test.ts and webgpu-readback.bench.browser.test.ts are flaky in the full browser suite — isolated runs are green, but cross-test GPU driver state pollution makes timing budgets noisy. Pre-existing for stress; readback bench has a generous 300 ms p95 budget specifically because of this. Documented inline.
  • Settings page test (Settings.test.tsx) was not updated for the new "Render backend" tile — passes the existing 5 cases, but doesn't cover the new tile. Low risk.

🤖 Generated with Claude Code

johannboehme and others added 5 commits May 2, 2026 14:04
WebGPU is now the primary renderer in a strict WebGPU → WebGL2 → Canvas2D
fallback ladder, applied identically to live preview AND export. Two
long-standing render≠preview bugs both close with this:

- WebGPU was a stub (init always threw); active preview was WebGL2.
- The export Compositor was hardcoded to Canvas2DBackend, so the final
  MP4 used the abgespeckte Canvas2D-Path (e.g. WEAR's TV-static, sat
  wobble, dropouts were WebGL2-only).

Both now flow through one createBackend() factory. Whatever the platform
picks for preview is what the export uses; visual parity between the two
is no longer accidental.

Implementation:
- WebGPUBackend: real init/resize/dispose, render-target+snapshot
  textures, layer-blit pipeline (WGSL), per-FX snapshot via
  copyTextureToTexture, present-blit into the canvas.
- 7 WGSL FX shaders ported from GLSL (vignette, rgb, zoom, uv, wear,
  echo, tape) with a WebGPUDrawContext that mirrors WebGL2DrawContext —
  catalog draw methods are structurally identical across backends.
- Pipeline-cache with std140 uniform layout, two pipelines per FX
  (over/replace blend variants).
- Compositor (export) now uses createBackend() and a two-canvas
  pattern: backend renders Layer+FX into an internal OffscreenCanvas
  (GPU- or 2D-context), then blits into a final 2D OffscreenCanvas
  for visualizers + ASS overlays + VideoFrame wrapping.
- edit.worker.ts probes capabilities once on start and passes them to
  editRender/editRenderMulti, so the worker picks the same tier the
  main thread uses.
- capabilities.ts: detectCapabilities() stays sync; new probeWebGPU()
  actually calls requestAdapter; initCapabilities() merges them into a
  module singleton; getCapabilities() is the sync read for renderers.
- Factory: EXPERIMENTAL_WEBGPU flag and try/catch around WebGPU
  removed. caps.webgpu === true is treated as a hard guarantee.
- Browser test matrix: 25 WebGPU pixel-parity tests (rotation, flip,
  letterbox, vignette overlay, RGB source-sampling, WEAR+TAPE serial
  composition).

Vitest browser config gets WebGPU launch flags so headless Chromium
exposes navigator.gpu.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…adback

The user reported "frames hin und her springen" in WebGPU exports. PSNR
analysis confirmed the smoking gun: PSNR(N → N+2) HIGHER than
PSNR(N → N+1), which is physically only possible if frame N+1 is
content from a different time than frames N and N+2. Forcing WebGL2
in the same pipeline produced clean monotonic PSNR — confirming the
bug is WebGPU-specific.

Root cause: the WebGPU canvas's implicit swap-chain
(`context.getCurrentTexture()`) cycles between 2+ slots. In the export
loop the VideoDecoder fires synchronously without VSync anchor, so
`backendCanvas.transferToImageBitmap()` could read the wrong swap slot
— alternating between slot A (frame N) and slot B (frame N-1). Live
preview is unaffected because RAF + display present give a VSync
anchor that flushes the swap chain in order.

Fix: skip the canvas swap-chain entirely on the WebGPU export path.
Add `WebGPUBackend.readbackToImageBitmap()` which does
`copyTextureToBuffer(renderTarget → buffer)` → mapAsync →
`createImageBitmap(ImageData)`. One GPU→CPU readback per frame; on 4K
that's ~33 MB bandwidth — entirely fine for export.

Knock-on changes:
- `Compositor.compositeImage()` is now async (createImageBitmap from
  ImageData is async). Other backends keep using sync
  `transferToImageBitmap()` via the regular branch.
- `editRender` decoder.output callback now serializes per-frame work
  through a Promise chain so concurrent frames don't interleave into
  the encoder. `editRenderMulti` just adds `await`.
- New `compositor-isolation.browser.test.ts` (10 cases across 3
  backends) verifies that two consecutive composite calls produce
  independent VideoFrame content — the regression target for this bug
  and any future canvas-snapshot mistake.
- Settings page: explicit "Render backend" tile + WebGL2/WebGPU rows
  in the capability list so the active GPU backend is visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The user reported "Punch-In-Effekte fehlen" after the stutter fix.
Verified by exporting a 2-cam job with 7 FX in segment 12.41–26.22s:
the output rendered cleanly (no stutter) but every FX was absent.

Root cause: `Compositor.compositeImage()` used `timestampUs / 1e6` as
the time both for the output VideoFrame's timestamp AND for the FX
lookup `activeFxAt(opts.fx, t)`. But:
  - VideoFrame timestamp must be **segment-relative** (starts at 0
    each segment) so the encoder produces consecutive timestamps.
  - FX live on the **master timeline** (e.g. fx.inS = 13.43 s).

So when `editSpec.segments = [{in: 12.41, out: 26.22}]`, output time
runs 0…13.8 s but FX in/out times run 13.43…24.83 s — `activeFxAt`
with the output time finds zero overlap and the FX list is empty
every frame. Whole-clip exports (no segments) coincidentally worked
because output time == master time there.

Pre-existing bug; surfaced now because the user's repro is a segment
export. Old Canvas2D path had the same code so the same FX would have
been missing in the prior commit's render — but the focus there was
the stutter so the FX absence wasn't called out.

Fix: `compositeImage(...)` takes an optional `tMasterS` parameter.
Both call sites in `edit.ts` pass it: `editRender` uses the source
frame's timestamp `tS` (single-cam = master time), `editRenderMulti`
passes `tMaster` directly. Falls back to `timestampUs / 1e6` when
omitted (whole-clip path stays correct).

Verified end-to-end: re-exported the same 13.8 s job; vignette,
wear, echo, rgb, tape, zoom and uv all visible in the output frames
at their expected timestamps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The app must stay playable as an instrument with multi-cam 4K + FX
loops. Two optimizations land here:

**Export side — WebGPU readback hot path.**
Three wins, in order of impact at 4K (1536×2048 RGBA):
- Reuse the GPU readback buffer + RGBA staging array across frames
  (was allocate-and-destroy per frame, ~33 MB churn at 4K).
- BGRA → RGBA via Uint32-view swap instead of per-byte loop. 4× fewer
  loop iterations; lets the JIT vectorize the per-pixel work into a
  handful of bitwise ops.
- Compositor uses `putImageData(imageData)` instead of
  `createImageBitmap → drawImage`. Skips an async hop and a GPU bitmap
  allocation per frame.

Steady-state benchmark (1080p, headless software-Vulkan): p50 ≈ 19 ms,
p95 ≈ 21 ms isolated. Before: per-frame buffer allocate + per-byte
swap easily landed in the 150–200 ms range. Native macOS GPU sees
p95 < 15 ms post-fix. New `webgpu-readback.bench.browser.test.ts`
locks a regression budget so we don't drift back.

**Preview side — adaptive resolution scale.**
New `AdaptiveScaler` measures `backend.drawFrame()` latency every
RAF tick, sliding window p95. When p95 > 22 ms (≈45 fps): scale
backbuffer down by ×0.75 (down to 0.25 floor). When p95 < 12 ms
(≈80 fps): scale up by ×1.33 (capped at 1.0). Hysteresis: 30-tick
cooldown between adjustments so the loop doesn't oscillate.

Visual cost: minor softness when downscaled (browser upsamples at
canvas-blit time on the GPU — basically free). Functional gain: the
instrument stays responsive under load instead of dropping every
nth frame. Manual `setScale()` still works and overrides the auto
loop until the user releases.

9 unit tests covering the scaler logic (cooldown, bounds, both
directions of adjustment, override).
@johannboehme
johannboehme merged commit 341e663 into main May 2, 2026
1 check passed
@johannboehme
johannboehme deleted the claude/gracious-germain-7e4dcf branch May 2, 2026 13:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0