I run NativeConvert, a set of file converters where every video and audio conversion happens inside the browser tab with FFmpeg compiled to WebAssembly. Nothing is uploaded. Getting ffmpeg.wasm to work reliably in production took more than npm install, so here are the notes I wish I had on day one: the headers, a threading deadlock, the copy-before-encode fallbacks, and a caching mistake that made returning visitors re-download 10 MB after every deploy.
The setup in one paragraph
We use @ffmpeg/ffmpeg 0.12 with the multithreaded @ffmpeg/core-mt build. The core is one ffmpeg-core.wasm file of about 32.7 MB (roughly 10 MB compressed on the wire), plus a small JS loader and a pthread worker script. It runs inside a dedicated Web Worker so the page never freezes. The user's file is written into FFmpeg's in-memory file system, FFmpeg runs with ordinary command-line arguments, and the output is read back and handed to the page as a Blob.
Cross-origin isolation is not optional
The multithreaded core needs SharedArrayBuffer, and browsers only expose it on cross-origin isolated pages. That means two headers: Cross-Origin-Opener-Policy: same-origin and a Cross-Origin-Embedder-Policy. Forget them and the core fails to load with an error that never mentions headers.
The embedder policy is the painful one because it applies to everything the page loads. require-corp makes every cross-origin script, image and iframe opt in, which breaks most third-party embeds. credentialless allows cross-origin requests but sends them without cookies. We ended up with a split in next.config.js:
// next.config.js (simplified)
{ source: '/convert/:path*',
headers: [
{ key: 'Cross-Origin-Opener-Policy', value: 'same-origin' },
{ key: 'Cross-Origin-Embedder-Policy', value: 'require-corp' },
] },
{ source: '/((?!convert|contact).*)',
headers: [
{ key: 'Cross-Origin-Opener-Policy', value: 'same-origin' },
{ key: 'Cross-Origin-Embedder-Policy', value: 'credentialless' },
] },
The one page with a third-party form embed is excluded entirely. Any new embed gets checked against these headers before it ships.
Self-host the core
The docs load the core from a public CDN. That's convenient until isolation is on: every cross-origin file must then arrive with headers that satisfy your embedder policy, and worker scripts have their own same-origin rules. We sidestepped it by self-hosting: a postinstall script copies the core files from node_modules into public/ffmpeg, and the worker turns each one into a same-origin blob URL with toBlobURL before ffmpeg.load(). Bonus: no dependency on a CDN being up, and no request about the user's conversion goes to a third party.
One worker, one FFmpeg instance, message ids
FFmpeg is created once per worker and reused, because loading the core takes longer than most audio conversions. The page talks to the worker with a small typed protocol: each request carries an id, the worker answers with progress/result/error messages tagged with that id, and the component ignores anything that doesn't match the request it's waiting for. That kills the classic race where a user drops a second file while the first is converting and the old result overwrites the new one.
Results come back as an ArrayBuffer in the transfer list of postMessage, so the output is moved, not copied. For a 200 MB video that's the difference between a smooth download and a memory spike.
The deadlock: why our multithreaded build encodes on one thread
The most expensive lesson. Some conversions (GIF to MP4 among them) hung forever at 0% with no error. The multithreaded core has a fixed pthread pool, and when the filter graph and x264 each spawned their own threads they asked for more than the pool holds and waited on each other.
The fix is to cap threads explicitly, and placement matters: -threads before -i applies to the decoder. To limit the encoder and filter graph it has to be an output option, after the input:
// H.264 "maximum compatibility" encode
[
'-threads', '1', '-i', input,
'-filter_threads', '1', '-threads', '1', // output-side: prevents the deadlock
'-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', // H.264 needs even dimensions
'-pix_fmt', 'yuv420p',
'-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '23',
'-c:a', 'aac', '-b:a', '128k',
'-movflags', '+faststart',
output,
]
The same rule bit us again later: in an audit of all 161 converter pairs, several video pairs were silently broken because one command path was missing the output-side -threads 1.
Copy first, encode last
Encoding in WebAssembly is slow: CPU only, no hardware encoder. So the converter avoids encoding whenever it can. MOV to MP4 or MKV to MP4 first tries a plain stream copy, which only rewrites the container and takes seconds even for big files. If that fails (an MKV with subtitle tracks MP4 can't hold, say), it retries with fewer streams, and only then falls back to a full re-encode with the ultrafast x264 preset.
Copying has a catch: a MOV from a modern iPhone is usually HEVC, and a copy keeps it HEVC. The MP4 is valid but won't play in some older players. We read the input codec from FFmpeg's own log while it runs:
export function parseVideoCodec(log: string): string | undefined {
return log.match(/Stream #\d+:\d+[^:]*: Video: ([a-z0-9_]+)/i)?.[1]?.toLowerCase();
}
If the result still holds HEVC, the page says so and offers a "maximum compatibility" re-encode to H.264. Another HEVC trap we hit later: HEVC copied out of MKV gets the hev1 tag, which QuickTime and iPhones refuse. Adding -tag:v hvc1 on remux fixes it.
Small fixes that added up
- The very first video conversion after load can abort inside WebAssembly; the worker retries a failed first attempt once before reporting an error.
- Audio trimming copies the stream and adds
-vn, because MP3s with embedded album art otherwise fail to stream-copy in the wasm build. - Some video tools cap input at 500 MB: the file, FFmpeg's working copy and the output all live in the tab's memory at once.
- Progress is capped at 95%; the last 5% is reading the output back, so the bar never sits at 100 while nothing happens.
The caching mistake
The 32 MB core was served with Cache-Control: max-age=0. Browsers revalidated it on every visit, which is cheap when the server answers 304. But each deploy copies a fresh build, which gives the file a new mtime and a new ETag, so every deploy (several a day) made every returning visitor download ~10 MB again.
The standard fix: version in the URL, cache forever.
export const FFMPEG_CORE_VERSION = '0.12.10';
export const ffmpegCoreUrl = (file: string) => `/ffmpeg/${file}?v=${FFMPEG_CORE_VERSION}`;
// next.config.js
{ source: '/ffmpeg/:path*',
headers: [{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }] },
A unit test fails if the version in the URL drifts from the installed package.
Testing with real files on every deploy
Unit tests caught argument mistakes, not the bugs that hurt most, like a button that silently did nothing. Every deploy now ends with a smoke test: headless Chrome via playwright-core opens ~200 tool pages on the live site, drops real files in (a generated PDF, a PNG, a WAV, a 36 KB MP4 kept in the repo), clicks the button and waits for an actual download. Any failure rolls the deploy back automatically.
What WebAssembly still can't do well
Long or high-resolution video is much slower than HandBrake: no hardware encoding, and after the deadlock fix encoding runs on one thread. Memory is the hard ceiling; a multi-gigabyte file isn't realistic in a tab. And the first engine download is large on a slow mobile connection, even if it now happens once.
For the jobs most people actually have (a phone video to MP4, a voice memo to MP3, a clip trimmed for a chat app) those limits rarely matter, and in exchange the file never leaves the device. You can check that yourself: open DevTools → Network while a conversion runs, and no request carries the file.
Happy to answer questions about any of this in the comments.
Top comments (0)