Compressing Video to an Exact MB Target in the Browser with FFmpeg.wasm
If you have ever tried to compress a video to fit under a 25 MB email attachment limit or a 10 MB chat limit, you have probably noticed that FFmpeg's -crf flag cannot guarantee a file size. When we built the local video
If you have ever tried to compress a video to fit under a 25 MB email attachment limit or a 10 MB chat limit, you have probably noticed that FFmpeg's -crf flag cannot guarantee a file size.
When we built the local video compressor on VideoEditingTips using FFmpeg.wasm, our goal was simple: let users pick 10 MB, 25 MB, or a custom MB limit, process the file completely inside the browser (no server upload), and verify the real output byte count.
Here are the three practical details that made it reliable.
1. Budget for container and audio overhead first
A naive targetBytes * 8 / duration calculation almost always overshoots because of MP4 atom overhead (moov/mdat), audio bitrate, and x264 rate-control variance. We reserve 6% + 8 KB for container overhead and step down audio bitrate (128k -> 64k -> 32k) when the total budget is tight:
const targetBytes = Math.floor(targetMB * 1_000_000);
const totalKbps = ((targetBytes * 0.94 - 8192) * 8) / duration / 1000;
const audioKbps = totalKbps >= 512 ? 128 : totalKbps >= 256 ? 64 : 32;
const videoKbps = Math.min(50000, Math.floor(totalKbps - audioKbps));
2. Constrain x264 with maxrate and bufsize
Running single-pass ABR in WebAssembly is much faster than 2-pass, so we pair -b:v with -maxrate and a 2x -bufsize, plus -movflags +faststart and even-dimension scaling (scale=trunc(iw/2)*2:trunc(ih/2)*2) so odd-resolution screen recordings do not fail yuv420p.
3. Measure actual bytes and retry from the original input
Even with VBV constraints, high-motion clips can still land a few percent over target. Instead of silently returning an oversized file, we check data.byteLength <= targetBytes and retry up to 3 times — always encoding from the original input rather than re-encoding a lossy intermediate.
We extracted this bitrate-budgeting and retry helper into a small MIT package on GitHub: xie233/ffmpeg-target-size. If you want to test the full flow locally on your own clips (no uploads, no watermark), try the live browser video compressor or browse our copy-paste FFmpeg command recipes.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.