Back to Blog
Technicalffmpegwebassemblybrowser

How FFmpeg Runs Entirely in Your Browser

How FFmpeg compiled to WebAssembly runs entirely in the browser: the single and multi-threaded builds, why cross-origin isolation matters, the in-memory filesystem, and the memory limits compared with native encoding.

LoopalooPublished April 3, 202610 min read

FFmpeg is a C program. It has been the workhorse of video encoding for two decades, and for most of that time the only way to use it was from a command line on a server or your own machine. So it is a little surprising the first time you compress a video on a website and watch the network tab stay quiet: no upload, no result file coming back from a server, just your laptop fans spinning up. The whole encoder is running inside the browser tab.

That works because FFmpeg has been compiled to WebAssembly. The ffmpeg.wasm project (published on npm as @ffmpeg/ffmpeg) wraps a WASM build of the real FFmpeg source in a JavaScript API that mirrors the command-line tool you already know. You write files into a virtual filesystem, hand FFmpeg an argument array (-i input.mov ... output.mp4), and read the result back out. No bytes leave the page.

This post covers how that works in practice: how the WASM core gets loaded, why it needs special HTTP headers to run multithreaded, how the in-memory filesystem behaves, and where the real tradeoffs sit compared with native or server-side encoding.

The two builds: single-threaded and multi-threaded

ffmpeg.wasm ships its core in two flavors, and the difference matters a lot for performance. The single-threaded core (@ffmpeg/core) runs anywhere. The multi-threaded core (@ffmpeg/core-mt) uses Web Workers plus a SharedArrayBuffer to spread encoding across CPU threads. The multi-threaded build is faster for CPU-bound work like H.264 encoding, but it has a hard prerequisite: the page must be cross-origin isolated.

That makes feature detection the first step. Before deciding which build to fetch, check whether the page can use threads at all:

function canUseThreads() {
  return typeof SharedArrayBuffer !== 'undefined'
    && globalThis.crossOriginIsolated === true;
}

const variant = canUseThreads() ? 'multi-threaded' : 'single-threaded';

Both conditions matter. The presence of SharedArrayBuffer alone is not a reliable signal, because browsers have differed over whether they expose the constructor on pages that are not isolated. crossOriginIsolated is the browser's authoritative answer. If either check fails, the sensible move is to drop to the single-threaded build rather than fail outright, and that graceful degradation is the main reason to keep both cores available.

The multi-threaded core consists of three files (ffmpeg-core.js, ffmpeg-core.wasm and ffmpeg-core.worker.js); the single-threaded core needs only the first two. The worker script is what spawns the additional threads.

Why cross-origin isolation is required

SharedArrayBuffer is memory that multiple threads (the main thread and Web Workers) can read and write at the same time. Shared memory also lets a page build an extremely precise timer, and precise timers are exactly what made the Spectre family of CPU side-channel attacks practical in browsers. Browser vendors responded by disabling SharedArrayBuffer by default and re-enabling it only for pages that opt into a stricter security context called cross-origin isolation.

You opt in with two response headers on the HTML document:

HeaderTypical valueEffect
Cross-Origin-Opener-Policysame-originSevers the link to cross-origin windows and popups that opened the page or were opened by it
Cross-Origin-Embedder-Policyrequire-corp or credentiallessRestricts which cross-origin subresources the page may load

When both are present, the browser sets crossOriginIsolated to true and unlocks SharedArrayBuffer. On the wire they are just two lines in the response:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: credentialless

Where those lines come from depends on how the site is served. A Node or edge server can add them in middleware. A site deployed as static files has to get them from the host or CDN, usually through a headers configuration file, because no application code runs at request time to add them. A common trap is to set the headers in a framework's development server, watch threading work locally, and then lose it in production because the static host never sends them. Typing crossOriginIsolated into the console of the deployed page is the quickest way to confirm.

While you are configuring headers, give the core files long-lived caching. The WASM binary is several megabytes and never changes unless you upgrade, so serving it from a versioned path with an immutable Cache-Control header means returning visitors skip the download entirely.

The COEP value deserves a moment of thought. The strict option, require-corp, blocks any cross-origin resource (an image, a font, an analytics beacon) that does not send a Cross-Origin-Resource-Policy header back. credentialless is the more forgiving alternative: it still grants isolation, but instead of demanding a CORP header it loads no-cors cross-origin requests without cookies or other credentials. For a real site that pulls in third-party images and fonts, it is often the pragmatic choice. It arrived later than require-corp, so check browser support for your audience before relying on it.

Loading the core

The load() method accepts a URL for each core file. The pattern the ffmpeg.wasm documentation uses is to fetch each file and hand the library a blob URL instead of a plain path:

import { FFmpeg } from '@ffmpeg/ffmpeg';
import { toBlobURL } from '@ffmpeg/util';

const ffmpeg = new FFmpeg();
const base = '/vendor/ffmpeg-core-mt'; // wherever you host the core files

await ffmpeg.load({
  coreURL: await toBlobURL(`${base}/ffmpeg-core.js`, 'text/javascript'),
  wasmURL: await toBlobURL(`${base}/ffmpeg-core.wasm`, 'application/wasm'),
  workerURL: await toBlobURL(`${base}/ffmpeg-core.worker.js`, 'text/javascript'),
});

A blob URL is same-origin with the page, which sidesteps the browser's refusal to start a worker from a cross-origin script, so the same code works whether the files come from your own server or a public CDN. Fetching the files yourself also stops you from depending on how a bundler treats the library's dynamic import of the core, a frequent source of setup trouble.

Two habits make loading sturdy:

  • Load once, then reuse the instance. The core takes a noticeable moment to download and compile. Keep one FFmpeg instance per page, and if several parts of the interface might ask for it at the same time, have them share a single in-flight promise so the core downloads exactly once.
  • Fall back in layers. Try the multi-threaded core when the page is isolated, then the single-threaded one. Self-hosting the files and keeping a public CDN copy as a backup means a blocked request costs speed, not the whole feature.

The shared promise takes only a few lines:

let ready = null;

function getFFmpeg() {
  ready ??= loadCore(); // does the feature check and load() shown above
  return ready;
}

The virtual filesystem: writeFile and readFile

FFmpeg the C program reads from and writes to a filesystem. The WASM build keeps that assumption, so the library gives you an in-memory filesystem (Emscripten's MEMFS) that lives entirely in the WASM heap. You stage inputs with writeFile, run the command, then pull results out with readFile. Nothing touches your real disk.

A complete conversion takes only a few calls:

import { fetchFile } from '@ffmpeg/util';

await ffmpeg.writeFile('input.wav', await fetchFile(file)); // stage the input
await ffmpeg.exec(['-i', 'input.wav', 'output.mp3']);        // run the command
const data = await ffmpeg.readFile('output.mp3');           // pull the result out

await ffmpeg.deleteFile('input.wav');                       // free heap memory
await ffmpeg.deleteFile('output.mp3');

const blob = new Blob([data], { type: 'audio/mpeg' });

fetchFile (from @ffmpeg/util) turns a browser File, Blob or URL into the Uint8Array that writeFile expects. readFile returns a Uint8Array, which you wrap in a Blob so the browser can offer it as a download or feed it to an <audio> or <video> element. FFmpeg picks a default encoder from the output extension, so a one-line command is enough for a basic format conversion.

The filesystem also holds files that FFmpeg expects to find by name, not just media:

  • Concat lists. To join clips with the concat demuxer, write a plain-text manifest in FFmpeg's file '...' syntax, for example with writeFile('list.txt', new TextEncoder().encode(list)), then read it with -f concat -safe 0 -i list.txt.
  • Fonts. The drawtext filter needs a real font file. Inside the browser there is no system font directory to fall back on, so you fetch a TTF over HTTP, write it into the virtual filesystem, and point the filter at it with fontfile=font.ttf.

Because every byte lives in the WASM heap, cleanup is memory management rather than housekeeping. Delete inputs and outputs after each operation, and consider a sweep that lists the root directory and removes anything an error left behind. A large input that is never deleted stays in the heap until something removes it, and on a memory-bound encode that can be the difference between success and an out-of-memory abort.

Running exec: the same arguments you would type

exec takes the same argument array you would pass to FFmpeg on a native command line, which is what makes existing FFmpeg knowledge transfer directly. A typical compression job builds its arguments conditionally:

const args = ['-i', 'input.mp4'];
if (maxHeight) {
  args.push('-vf', `scale=-2:${maxHeight}`); // keep the aspect ratio, even width
}
args.push(
  '-c:v', 'libx264',
  '-crf', '28',
  '-preset', 'veryfast',
  '-threads', '0',
  '-c:a', 'aac',
  '-b:a', '128k',
  '-movflags', '+faststart',
  'output.mp4'
);
const exitCode = await ffmpeg.exec(args);

A few of those flags deserve a word. -crf sets a quality target rather than a file size: lower numbers mean better quality and bigger files, 23 is x264's default, and around 18 is usually indistinguishable from the source. -preset trades compression efficiency for speed, which matters more when the encoder runs in software and competes for a single tab's CPU budget than it does on a build server. The extremes are rarely worth it, though: ultrafast can produce a far larger file than a middle preset at the same CRF. -threads 0 lets FFmpeg pick the thread count automatically, which only pays off on the multi-threaded core. -movflags +faststart moves the MP4 index to the front of the file so playback can begin before the whole file has downloaded.

You can follow progress and logs through events. ffmpeg.on('progress', ...) reports a fraction between 0 and 1 for driving a progress bar, and ffmpeg.on('log', ...) streams FFmpeg's console output. Depending on the build, you may not have a separate ffprobe binary, so a common trick for learning a clip's duration is to read the Duration: line out of the log. exec resolves with FFmpeg's exit code, so a non-zero value means the command failed.

The progress figures are estimates. They can jump, stall, or move backwards on some operations, so smooth and clamp them before they reach the interface. A progress bar that only ever moves forward feels far more trustworthy, even though it says nothing new about real throughput.

The tradeoff: no upload, bounded by browser memory

The reason to do any of this is privacy and friction. Your video never leaves the device, there is no upload wait on a slow connection, and there is no server bill that scales with how many people encode 4K footage. For a free tool that is a very good deal: the user's own CPU does the work.

The cost is just as real, and it is mostly about memory. A WebAssembly heap has a ceiling. The standard 32-bit WASM build addresses memory with 32-bit pointers, which caps the heap at 4 GB in theory and lower in practice, and the browser tab has limits of its own on top of that. FFmpeg often needs several times the size of a clip in working memory, especially for operations that buffer many frames. The reverse filter is the textbook case: it has to hold every decoded frame in memory to play them backwards. The usual workaround is to split a long clip into short segments, reverse each one, and concatenate them in reverse order, so no single step holds more than a few seconds of frames. Watching for an out-of-memory abort and retrying with the segmented approach is a reasonable pattern for any frame-hungry filter.

Side by side:

Browser (WASM)Native / server FFmpeg
File leaves deviceNoYes (upload)
Startup costDownload multi-MB WASM core onceNone for you; server provisioned
ParallelismWeb Workers, needs cross-origin isolationFull OS threads, no isolation needed
Memory ceilingWASM heap + tab limits (low GBs)Machine RAM
Hardware encoders (NVENC, QSV)NoYes, if present
Cost modelUser's CPUYour servers and their bandwidth

There is no hardware-accelerated encoding in the WASM build. Everything runs in software through libx264 and friends, which is another reason to favor the faster presets. The core download is a one-time cost per visit (or close to once ever, with good caching) that a server-side tool never pays. For short and medium clips those tradeoffs are well worth it. For hour-long 4K masters, a server still wins.

Where this shows up on Loopaloo

Several Loopaloo tools run FFmpeg in the tab this way. The Video Compressor lets you pick a quality level from Smallest to Near lossless (with a CRF slider for fine tuning), an encoding speed, a maximum frame size, and whether to keep, re-encode or remove the audio. The Video Format Converter turns a clip into MP4, WebM, OGG, MOV, AVI or MKV and shows you the source and output codecs before you convert. The Audio Format Converter handles MP3, WAV, OGG Vorbis, AAC, M4A and FLAC, and after each conversion it reports what was actually written: file size, effective bitrate, sample rate and channel count. In every case the file is processed on your own machine and never uploaded.

Related Tools

Related Articles