Skip to content

Convert with WebCodecs instead of ffmpeg.wasm (2.4.0) (#78) - #79

Merged
liladas merged 8 commits into
mainfrom
webcodecs-pipeline
Aug 1, 2026
Merged

liladas merged 8 commits into
mainfrom
webcodecs-pipeline

Conversation

@liladas

@liladas liladas commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Closes #78.

Adds a native browser conversion pipeline (cdgraphics + WebCodecs VideoEncoder + mediabunny) alongside ffmpeg.wasm, and routes each device to whichever it can actually run. ffmpeg.wasm stays as the fallback, and is now also one click away if the native path fails.

11x faster than the path it replaces, and it works on the devices that could not convert at all.

Why

Two problems, one solution, per the issue:

  1. @ffmpeg/core 0.12.x ships a SIMD wasm, so a CPU without SSE4.1 cannot compile it at all. 16 of 136 conversion sessions never succeeded. Tell SIMD-less devices why the converter cannot run (2.3.7) #77 gave those users an honest error; this gives them a working converter.
  2. Everyone else waits on x264-in-wasm, single-threaded, behind a ~31 MB download.

The native path uses the browser's own H.264 encoder. No wasm engine, so the SIMD gate does not apply, and nothing to download.

Pipeline selection

flowchart TD
    A[Drop .zip or .cdg + .mp3] --> B{"?pipeline= in URL?"}
    B -->|yes| F[Use the forced pipeline]
    B -->|no| C{"VideoEncoder exists<br/>and isConfigSupported<br/>accepts H.264 at this size?"}

    C -->|yes| N["<b>Native pipeline</b><br/>cdgraphics → canvas → VideoEncoder → mediabunny<br/><i>runs in a worker, nothing to download</i>"]
    C -->|no| D{"hasWasmSimd()?"}

    D -->|yes| W["<b>ffmpeg.wasm</b><br/>~31 MB core, single-threaded x264"]
    D -->|no| E["<b>Dead end</b><br/>SIMD message + local ffmpeg command (#77)"]

    N --> S{Succeeded?}
    S -->|yes| OK([MP4])
    S -->|no| R["Error, plus<br/><b>Try the original converter</b>"]
    R -->|one click| W
    W --> OK

    classDef native fill:#1f7a4d,stroke:#0f3d27,color:#fff
    classDef wasm fill:#8a5a00,stroke:#4d3200,color:#fff
    classDef dead fill:#8a1f1f,stroke:#4d1111,color:#fff
    class N native
    class W wasm
    class E dead
Loading

Support floor for the native path: Chrome/Edge 94+, Safari 16.4+, Firefox 130+. Chrome 109 has it, which covers 8 of the 11 provably-dead sessions from the issue.

There is deliberately no engine picker. "WebCodecs vs ffmpeg" is not a choice a karaoke host can reason about, and the product is one drop and one quality knob. The escape hatch is offered at the only moment it helps: a failed native conversion shows Try the original converter, which re-runs the same input on ffmpeg.wasm. It is not offered when ffmpeg.wasm is what failed, nor for a bad input that would fail identically either way.

Measurements

End to end through the app, TRKD1502 (188s song) at 1080p, Chromium 149, M-series laptop. SSIM is against a lossless render of the same CDG.

wall clock output SSIM
Native (WebCodecs) 15.0s (12.5x realtime) 6.1 MB 0.9984
ffmpeg.wasm (today) 171.6s (1.1x realtime) 4.7 MB 0.9966
ffmpeg native binary, 8 cores (reference) 7.6s 4.7 MB 0.9966

Both figures above are same-machine, which is the only fair comparison. Encode speed varies a lot by hardware and by whether the platform's hardware encoder is used: the same file on a slower machine in branded Chrome took 51.3s / 3.6x realtime for 5.3 MB. Read the 11x as the gap on one machine, not a constant.

The native path is slightly the higher quality of the two for about 1.3x the bytes. x264's rate control is better than the browser's; matching its size costs measurably more quality than it gives up (0.9904 at 4.7 MB). I chose to keep the quality.

Fidelity

The issue's phase-1 gate was whether the JS renderer matches ffmpeg's cdgraphics decoder. Verified pixel-by-pixel on the real rip, at native 300x216 before any scaling or encoding:

  • 97% of frames pixel-identical.
  • Every remaining frame differs by under 0.1% of its pixels — part of a single 6x12 tile, where a lyric highlight lands either side of the sampling boundary.
  • The frame-timing model is a sharp optimum: one CDG packet in either direction drops the match rate to ~60%.

ffmpeg -r 30 samples the middle of each frame's display interval, not the start, because its fps filter rounds to nearest. renderTimeForFrame reproduces that exactly. Both pipelines are exact functions of the frame index, so neither drifts over a long song — the sync concern in the issue does not apply.

The tpad behaviour from #69 came free: the video runs for the audio's duration and cdgraphics holds its last drawn state once its packets run out.

Notable finds along the way

A rendering bug that only showed up as file size. drawImage defaults to source-over, and a CD+G title can declare its background colour transparent, so every frame was being composited onto the one before and nothing a transparent pixel covered was ever erased. Real rips accumulated every lyric ever drawn. One frame decoded to 31,461 distinct colours where the source has 5, with a mean per-channel error of 38 of 255.

distinct colours mean error pixels exact size
before 31,461 38.16 53.3% 7.8 MB
after 4,681 0.61 91.2% 6.1 MB
ffmpeg 2,317 0.27 91.8% 4.7 MB

test/files/sample-key.cdg and an e2e test pin this: it fails at 92% white (a full-width trail) when broken, against 4% when correct.

Keyframe interval was the size lever, not bitrate. mediabunny defaults to one every 2s; x264 defaults to 250 frames, which is what today's output already has. 8.2 MB → 6.1 MB, scoring marginally better against a lossless render.

Measured and rejected: variable frame durations (a real rip changes ~70% of its frames during lyrics, so it saved 0.1 MB of 6.1 MB and 13% of encode time — not worth handing a variable-rate file to an unknown TV or bar player).

Watching it work

The app was opaque while it ran. Every conversion now prints a short trace, which is what makes a "it failed" report from the feedback form actionable:

[cdg2mp4] pipeline: webcodecs · native H.264 encoder, nothing to download
[cdg2mp4] converting TRKD1502.zip at 1080p (1440x1080)
[cdg2mp4] encoding 1440x1080 H.264 in a worker
[cdg2mp4] audio: re-encoding the MP3 to AAC
[cdg2mp4] 5646 frames at 30fps · 188.2s of audio, 187.0s of graphics
[cdg2mp4] encoded 5.3 MB in 51.2s
[cdg2mp4] done in 51.3s · 5.3 MB, 3.6x realtime {pipeline, resolution, audio}

The wasm path traces its core download and the ffmpeg command it runs. Failures log the stage, the pipeline, and the underlying cause, which is exactly what the generic user-facing message deliberately hides.

Always on rather than behind a flag: it is only useful if it is already there when something goes wrong, and nobody reproduces a bug after being told a magic query parameter. That only works if it stays quiet, so the budget is a handful of lines per conversion. Nothing per frame, nothing per packet. Filenames appear; file contents never do.

Also in here

  • The pipeline runs in a worker. Beyond keeping the UI responsive, it makes cancellation exact: terminate() stops the encode mid-frame and drops every buffer, so there are no cooperative cancel checks in the encode loop.
  • The offline pill no longer offers a 30 MB download to devices that will never load it. On the native path it reads "Available offline" from the start.
  • The footer's "powered by ffmpeg.wasm" now credits whatever is actually converting, linking WebCodecs to MDN for the curious. Same for "this site uses ffmpeg compiled for your browser" in the command disclosure, which is now true only of the fallback. The local ffmpeg command stays either way, since that claim still holds.
  • The idle copy no longer promises "about a minute" to users for whom it takes fifteen seconds. An 11x spread cannot be described by one line, so it follows the pipeline.
  • Analytics. Every conversion event carries pipeline; every event including pageviews carries native_capable, so the rollout's reach is visible across all visitors rather than only those who convert. output_mb_bucket was too coarse to see any of this — 6.1 MB and 4.7 MB are both "5-20" — so output_kbps (size normalized by song length, rounded to 25 kbps) was added, along with audio_codec (AAC vs MP3-remuxed, which are not equally playable) and pipeline_retry_used.

Testing

113 unit tests, 10 e2e, all passing. The e2e suite probes isConfigSupported and skips or inverts rather than assuming: CI installs Playwright's own Chromium, and a build without proprietary codecs has VideoEncoder with no H.264 behind it, which is precisely the case the routing exists to handle.

New coverage: both pipelines agree on duration and dimensions from the same input; the transparent-background regression; the failure-then-retry recovery; and that the offline pill matches the chosen pipeline.

Not done

  • Whether this actually helps the target hardware. Chrome 150 on a pre-SSE4.1 CPU would fall back to software H.264, which is native and scalar-safe, so it should work. "Should" still needs either that machine or the PostHog split after rollout. This is the issue's open question and the reason phase 3 is watch-then-decide.
  • bitrateMode: "quantizer" is rejected by Chrome 149 for AVC, so the quantizer is inert and the bitrate ceiling is what runs. The code already prefers the quantizer and picks it up for free whenever Chrome ships it; worth a recheck in a few releases.
  • Demoting ffmpeg.wasm is explicitly out of scope, per the issue's non-goals.

liladas added 8 commits August 1, 2026 10:27
Convert CDG + MP3 with the browser's own H.264 encoder instead of
ffmpeg.wasm, falling back to the wasm core where WebCodecs is missing.

  CDG decode   cdgraphics 7 (JS) -> ImageData, 300x216
  scale        canvas drawImage, smoothing off (nearest-neighbor)
  video        VideoEncoder (H.264) via mediabunny CanvasSource
  audio        MP3 -> AudioDecoder -> AAC, or MP3 packets remuxed
  mux          mediabunny, MP4 with fast-start

This fixes the devices that cannot convert at all today: the SIMD core
never compiles on a CPU without SSE4.1, and no wasm engine is involved
here. It is also ~3x faster on the sample and downloads nothing.

Fidelity is verified rather than assumed. Rendering the whole sample CDG
both ways and comparing pixels showed the JS renderer is bit-exact with
ffmpeg's cdgraphics decoder; the only difference was which packet each
30fps frame samples, because ffmpeg's fps filter rounds to nearest.
renderTimeForFrame reproduces that, giving 183/183 pixel-identical
frames against `ffmpeg -vf fps=30`. Both are exact functions of the
frame index, so neither drifts over a long song.

- convert.ts picks the pipeline; ?pipeline= forces one for comparison.
- Every conversion event carries `pipeline`, so PostHog can compare the
  two rather than average them.
- The offline pill no longer offers a 30 MB download to devices that use
  the native path and would never load it.
Encode off the main thread. A 3-minute song is thousands of canvas draws
and encoder calls; on the main thread that competed with React and the
compositor, and needed an explicit event-loop yield in the encode loop to
keep the progress bar and Cancel alive. In a worker there is nothing to
yield to, and cancellation gets simpler as well: terminate() stops the
encode mid-frame and drops every buffer, so the cooperative cancel checks
are gone.

Split accordingly: webcodecs/encode.ts is the pipeline (no DOM, no main
thread), webcodecs/worker.ts runs it, webcodecs.ts owns detection and the
worker's lifecycle.

Output size: keyframes were the whole problem. CDG is near-static, so
inter frames cost almost nothing and the file is mostly keyframes.
mediabunny's 2s default produced 15.9 MB on a 188s 1080p rip; x264's own
default of 250 frames -- which the ffmpeg path already produces -- gives
8.0 MB, at an SSIM of 0.996 between the two. Rate control was never the
binding constraint: lowering the bitrate ceiling from 0.03 to 0.01
bits/px does not shrink the file. Chrome 149 also rejects
bitrateMode "quantizer" for AVC, so the quantizer is inert today and the
bitrate is what runs; the comment said otherwise and now says this.

Measured on TRKD1502 (188s) at 1080p: 13.1s to encode, 14x realtime,
8.0 MB. Frame fidelity on the same rip: 97% of frames pixel-identical to
`ffmpeg -vf fps=30`, every remaining frame differing by under 0.1% of its
pixels, and the render-time model is a sharp optimum -- one packet either
way drops the match rate to ~60%.
A CD+G title can declare its background color transparent. drawImage
defaults to source-over, so every frame was being painted on top of the
one before, and nothing a transparent pixel covered was ever erased.
Real rips accumulated every lyric ever drawn.

It was hiding in plain sight as a size problem. On a 188s rip at 1080p,
one frame decoded to 31,461 distinct colors where the source has 5, and
its mean per-channel error against a lossless render was 38 of 255.
Setting globalCompositeOperation to "copy" -- which is what ffmpeg's
decoder does when it drops the alpha and keeps the RGB:

               distinct colors   mean error   pixels exact   size
  before                31,461        38.16          53.3%   7.8 MB
  after                  4,681         0.61          91.2%   5.9 MB
  ffmpeg                 2,317         0.27          91.8%   4.7 MB

Whole-file SSIM against a lossless render is now 0.9984, against
ffmpeg's 0.9966, so this path is slightly the better of the two for
about 1.3x the bytes. Every earlier conclusion about output size was
drawn through this bug and has been re-measured: the keyframe interval
is still worth 8.2 -> 6.1 MB, and the bitrate ceiling still does not
bind until it starts costing quality.

Also measured and rejected: submitting only changed frames with longer
durations. A real rip changes ~70% of its frames during lyrics, so it
saved 0.1 MB of 6.1 MB and 13% of encode time, which is not worth
handing a variable-rate file to an unknown TV or bar player.

scripts/make-sample-cdg.py now also emits sample-key.cdg, which declares
its background transparent and erases a sweeping block to it. The e2e
test reading it fails at 92% white -- a full-width trail -- against 4%
when correct.
CI installs Playwright's own Chromium, not branded Chrome, and a build
without proprietary codecs has VideoEncoder with no H.264 encoder behind
it. That is precisely the case the routing exists to handle, so the
tests have to ask instead of assuming, or they fail on the configuration
they are meant to tolerate. The forced-webcodecs tests now skip when the
encoder is absent, and the routing test asserts whichever way the
browser actually goes.
Measured end to end through the app on a 188s rip at 1080p: 15.0s on the
native pipeline against 171.6s on ffmpeg.wasm. An 11x gap is too wide for
one line of copy to describe honestly, so the idle expectation now
follows the pipeline the device will actually use.
Two gaps, both about not breaking what works.

No engine picker: "WebCodecs vs ffmpeg" is not a choice a user can
reason about, and the product is one drop and one quality knob. Instead
a failed native conversion now offers "Try the original converter",
which re-runs the same input on ffmpeg.wasm. It appears only where it
helps -- not when ffmpeg.wasm is what failed, and not for a bad input
that would fail identically either way -- and pipeline_retry_used counts
how often anyone needs it.

Analytics could not have answered the questions this branch raised.
output_mb_bucket is <5/5-20/20-50/50+, so 6.1 MB and 4.7 MB are the same
bucket and the whole size question was invisible. Added output_kbps,
size normalized by song length and rounded to 25 kbps. Added audio_codec,
since AAC and MP3-in-MP4 are not equally playable and a device quietly
getting the second is a plausible cause of a "won't play" report. Added
native_capable as a super property, so the rollout's reach is visible
across all visitors rather than only those who convert.
The app is opaque while it runs: two pipelines, a capability probe that
picks between them, and up to three minutes of silence on the slow one.
When someone reports "it failed" through the feedback form, there was
nothing to tell us which pipeline ran or where it stopped.

Seven lines for a native conversion, six for a wasm one: the pipeline
choice and the reason for it, the frame count against the audio and
graphics lengths, the audio codec, and a closing line with size and
realtime factor. Failures log the stage and the underlying cause.

Always on rather than behind a flag, since it is only useful if it is
already there when something goes wrong, and nobody reproduces a bug
after being told a magic query parameter. That only works if it stays
quiet, so the budget is a handful of lines: nothing per frame, nothing
per packet. Filenames appear; file contents never do.

selectPipeline is asked by three callers before anyone drops a file, so
a decision is announced once rather than once per caller.
"powered by ffmpeg.wasm" in the footer and "this site uses ffmpeg
compiled for your browser" in the command disclosure were true of every
visitor when there was one pipeline. Most people now run no ffmpeg at
all, so both follow the pipeline: WebCodecs gets credited and linked to
MDN for anyone curious, ffmpeg.wasm keeps its credit where it is doing
the work, and neither name renders until the probe resolves so nothing
flashes. The local ffmpeg command stays either way, since that claim is
still true.

Four places now need the routing answer and all have to agree, each
growing its own copy of the same effect, so they share a usePipeline
hook. selectPipeline is memoized per size, so the extra callers are free.

The console trace used em dashes; it now uses the separator the build
line already uses.
@liladas
liladas merged commit fcafa82 into main Aug 1, 2026
3 checks passed
@liladas
liladas deleted the webcodecs-pipeline branch August 1, 2026 19:09
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.

Investigate a WebCodecs conversion pipeline (native encode, no Wasm SIMD requirement)

1 participant