Repository navigation
Convert with WebCodecs instead of ffmpeg.wasm (2.4.0) (#78) - #79
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #78.
Adds a native browser conversion pipeline (
cdgraphics+ WebCodecsVideoEncoder+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:
@ffmpeg/core0.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.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 deadSupport 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.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
cdgraphicsdecoder. Verified pixel-by-pixel on the real rip, at native 300x216 before any scaling or encoding:ffmpeg -r 30samples the middle of each frame's display interval, not the start, because itsfpsfilter rounds to nearest.renderTimeForFramereproduces 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
tpadbehaviour from #69 came free: the video runs for the audio's duration andcdgraphicsholds its last drawn state once its packets run out.Notable finds along the way
A rendering bug that only showed up as file size.
drawImagedefaults 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.test/files/sample-key.cdgand 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:
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
terminate()stops the encode mid-frame and drops every buffer, so there are no cooperative cancel checks in the encode loop.pipeline; every event including pageviews carriesnative_capable, so the rollout's reach is visible across all visitors rather than only those who convert.output_mb_bucketwas too coarse to see any of this — 6.1 MB and 4.7 MB are both "5-20" — sooutput_kbps(size normalized by song length, rounded to 25 kbps) was added, along withaudio_codec(AAC vs MP3-remuxed, which are not equally playable) andpipeline_retry_used.Testing
113 unit tests, 10 e2e, all passing. The e2e suite probes
isConfigSupportedand skips or inverts rather than assuming: CI installs Playwright's own Chromium, and a build without proprietary codecs hasVideoEncoderwith 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
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.