ffmpegvideo-compressionapi

Compress video to a specific size: it's arithmetic, not two-pass

··11 min read
Compress video to a specific size: it's arithmetic, not two-pass

Your upload cap is 10 MB. The clip is nine minutes and 180 MB. Every guide hands you a two-pass command that assumes both passes share a disk.

Quick answer: Compressing a video to a specific size is arithmetic, not a two-pass trick: convert the cap into a bitrate with (target MB × 8192) ÷ duration in seconds = total kbps, minus your audio bitrate. Leave 5 to 8 percent headroom, encode with -b:v, -maxrate and -bufsize, then check the output's real byte count and re-run a notch lower if it missed. FFmpeg Micro runs each attempt as one API call, metered on input seconds.

The formula, and the unit question that breaks the math

Compressing a video to a specific size comes down to three numbers: the cap in bytes, the duration in seconds, and the audio bitrate you're willing to spend. Size is roughly bitrate times duration, so solving for bitrate is the whole job.

The shorthand everyone publishes is (target MB × 8192) / duration = total kbps. The exact version avoids the unit trap: target_bytes × 8 / duration / 1000 = total kbps. Those two disagree by about 2.4 percent, and the direction depends on what your platform means by "MB".

10 MB is 10,000,000 bytes. 10 MiB is 10,485,760 bytes. That's a 4.9 percent gap, wider than the headroom you planned to leave. The IEC standardized the binary prefixes in 1999 because the two kept getting confused (Wikipedia).

If the cap is decimal, the 8192 shorthand starts you 2.4 percent over. If it's binary, it gifts you 2.3 percent of headroom. When you can't tell, assume decimal: it's the smaller number.

A 90-second clip against a 10,000,000-byte cap with 128 kbps AAC: 80,000,000 bits ÷ 90 = 888 kbps total, minus 128 for audio, leaves 760 kbps for video. Trim 7 percent and you set -b:v 700k.

Why you leave 5 to 8 percent on the table

Encoders overshoot a bitrate target, and the MP4 container charges rent on top. Rate control aims for an average and only ever lands close to it, and the muxer adds a moov atom with per-sample tables that scale with frame count.

One developer measured this against a 10 MB target: the naive formula came in 9.17 percent over, and subtracting the audio bitrate properly brought it to 1.74 percent over at 10 MB and 0.28 percent over at 25 MB (dev.to). Container overhead itself, counted with ffprobe, runs from a fraction of a percent to a few percent depending on the file (dev.to).

Five percent is enough on a 100 MB cap, where absolute slack is large. Use eight on a 10 MB cap or on anything short, where one oversized keyframe is a measurable fraction of the file.

Two-pass dies at the API boundary, and the stats file is why

Two-pass encoding is the recommended way to hit an exact size. The first run writes statistics into a log file that the second run reads back. FFmpeg names the default prefix ffmpeg2pass and the file PREFIX-N.log. The project's H.264 guide recommends two-pass for a specific output file size, because libx264 does not strictly control maximum bitrate in a single-pass encode (FFmpeg wiki).

Locally that's two commands:

ffmpeg -y -i input.mp4 -c:v libx264 -b:v 760k -pass 1 -an -f null /dev/null
ffmpeg -i input.mp4 -c:v libx264 -b:v 760k -pass 2 -c:a aac -b:a 128k out.mp4

Now submit those as two jobs to any stateless job API. Pass 1 runs in a container, writes ffmpeg2pass-0.log, and that container goes away. Pass 2 runs somewhere else, finds nothing to read, and silently degrades to a plain ABR encode. A submit-and-poll API has nowhere to keep the stats file between calls. Hosted transcoders that offer two-pass run both passes inside one job, which is why Google's Transcoder API exposes it as a rate_control_mode on the codec settings instead of as a job you call twice (Google Cloud docs).

A production Discord-targeting tool added stats reuse on size retries, where only the bitrate changed, and clocked retries at roughly twice as fast with x265, 40 percent faster with x264 and 25 percent faster with vp9 (ffmpeg4discord PR 145). Speed, not accuracy, is the first casualty.

Two tempting shortcuts aren't. FFmpeg's -fs option is not a target-size control: it stops writing once the limit is exceeded, so the output ends up slightly larger than you asked for and truncated besides (ffmpeg.org). HandBrake removed its target-file-size mode in 0.9.6 and has no plans to bring it back, so its users do this arithmetic by hand too (HandBrake issue 4622).

What single-pass with -maxrate and -bufsize actually buys

Single-pass average bitrate lands roughly within 2 percent of target, against about 0.5 percent for two-pass. On a measured 60-second x264 clip, single-pass came in 0.66 percent and 0.35 percent under target once audio was subtracted properly (dev.to). Undershooting is the outcome you want when there's a hard ceiling.

-maxrate sets the ceiling and -bufsize sets the window the encoder averages over. Set -maxrate equal to -b:v and -bufsize to twice that, and the encoder can't spend more than about two seconds' worth of budget on a busy stretch. Halve bufsize and compliance tightens while quality on high-motion scenes drops. The FFmpeg wiki documents that pairing as constrained encoding:

ffmpeg -i input.mp4 -c:v libx264 -b:v 700k -maxrate 700k -bufsize 1400k \
  -c:a aac -b:a 128k -movflags +faststart output.mp4

The same encode as one API call, in FFmpeg Micro's advanced mode:

{
  "inputs": [{ "url": "gs://<YOUR_BUCKET>/1763400000-input.mp4" }],
  "outputFormat": "mp4",
  "options": [
    { "option": "-c:v", "argument": "libx264" },
    { "option": "-b:v", "argument": "700k" },
    { "option": "-maxrate", "argument": "700k" },
    { "option": "-bufsize", "argument": "1400k" },
    { "option": "-c:a", "argument": "aac" },
    { "option": "-b:a", "argument": "128k" },
    { "option": "-movflags", "argument": "+faststart" }
  ]
}

The pipeline: read, compute, submit, verify, re-run

Compressing a video to a specific size reliably is a loop with a measurement in it, not a command. Five steps, runnable from code, a shell script, or an n8n or Make scenario where no FFmpeg binary exists.

  1. Read the duration first. The number has to come from the file, not from whatever your CMS claims. If ffprobe isn't installed, parse it out of the container header: Get video duration and codec in PHP without ffprobe installed walks that.
  2. Compute the video bitrate. Cap in bytes × 8 ÷ duration ÷ 1000, minus your audio bitrate, minus 5 to 8 percent. Round down to a clean number.
  3. Submit the job with -b:v, -maxrate, -bufsize and your audio settings, then poll until status is completed or failed. A failed status here is usually input, not arithmetic: why your transcode job failed covers what to branch on in the poll loop.
  4. Verify the bytes before you ship. Ask for the download URL and read Content-Length off a HEAD request instead of downloading: curl -sI "$DOWNLOAD_URL" | grep -i content-length. In n8n or Make that's an IF node comparing one number to your cap.
  5. Re-run a notch lower if it missed. Cut the video bitrate by the overshoot percentage plus 2, and resubmit. A production target-size tool uses the same rule, trimming the target by at least 2 percent on every retry (ffmpeg4discord PR 80).

The honest part is step 5's cost. FFmpeg Micro meters 1 token per 10 seconds of input video, per second with no rounding up, so a 90-second clip costs 9 tokens whether you compress it to 10 MB or 100 MB, and a second attempt costs the same 9 tokens as the first. Failed jobs are never billed (pricing). Compare that to a per-output-minute or per-rendition meter, where a retry and a quality ladder both multiply the bill.

Check these against your own cap before you encode

Most missed targets trace back to an assumption nobody checked. Walk this list once per cap, not once per file.

  • Is the cap decimal MB or binary MiB? Assume decimal when the platform doesn't say.
  • Does the cap apply to the file or to the request, which may include multipart overhead?
  • Is your audio bitrate fixed? VBR audio drifts, and the drift comes out of your video budget.
  • Is the duration from the actual file, including any trim you're applying in the same job?
  • Does the destination re-encode what you send? Then overshooting quality downward is cheap and missing the cap is fatal.
  • Have you set -maxrate as well as -b:v? -b:v alone is a suggestion.
  • Does your verification read the output's byte count, or does it trust the job status?

Three caps you can copy the arithmetic from

The formula for compressing a video to a specific size gives different answers per platform only because the cap and the typical clip length change. These three are worked end to end elsewhere on this blog.

CapClip lengthAudioSet `-b:v` toWorked example
10 MB60 s128 kbps1100k[Compress video for Discord](/blog/compress-video-for-discord-hit-10-50-or-500-mb-on-purpose)
25 MB180 s128 kbps900k[Compress video for email](/blog/how-to-compress-video-for-email-gmail-and-outlook-25-mb-limit)
16 MB45 s128 kbps2500k[Compress for WhatsApp Business API](/blog/how-to-compress-video-for-whatsapp-business-api-under-16-mb)

A 4 MB ad-network limit or a 30 MB background-video cap isn't a different problem: put your own two numbers into the same three lines.

When the arithmetic can't save you

Bitrate math fails when the budget per second is too small for the resolution, and no rate control setting fixes that. Ten minutes into a 10 MB cap is 133 kbps total, which is not a 1080p video no matter how you distribute it. The levers then are duration, resolution and frame rate, in that order: trim first, scale to 720p or 480p, then drop to 24 fps.

Single file, one machine, quality matters more than throughput? Run real two-pass locally and take the tighter 0.5 percent accuracy. The stateless method earns its keep when the job repeats: 500 clips a week, a workflow with no shell, or a queue you don't want babysitting an encoder binary.

FAQ about compressing video to an exact file size

How do I compress a video to exactly 10 MB?

To compress a video to 10 MB, divide 80,000,000 bits by the clip's duration in seconds, subtract your audio bitrate, subtract 7 percent, and encode with -b:v and a matching -maxrate. A 60-second clip with 128 kbps audio lands at about 1100 kbps of video. Check the output's byte count afterward: rate control aims for an average, not a guarantee.

Does FFmpeg have a target file size option?

FFmpeg has no target file size option. The -fs flag looks like one but stops writing once the limit is exceeded, which produces a truncated file that is still slightly over. Hitting a specific size means converting that size into a bitrate yourself, which is also why HandBrake dropped its own target-size mode in 0.9.6.

Can I run two-pass encoding through a video API?

Two-pass encoding can't span two separate API jobs, because pass 1 writes a statistics log that pass 2 must read from the same filesystem. Hosted transcoders that support two-pass run both passes inside one job as a rate control setting. On a stateless submit-and-poll API, use single-pass with -b:v, -maxrate and -bufsize, then verify the output size.

Does a failed size target cost me twice?

On a meter that bills per second of input video, a retry costs exactly what the first attempt cost, because the input is the same length. FFmpeg Micro charges 1 token per 10 seconds of input, metered per second, and never bills a failed job. On per-output-minute or per-render pricing, a retry is a second full charge.

Take the cap you're actually fighting, read the duration off one real file, and let the first encode land where it lands: the byte check tells you whether to ship it or drop two percent and go again. Sign up free starts you with 200 tokens, roughly 33 minutes of input video, no card and no FFmpeg to install. At 9 tokens per attempt on that 90-second clip, that's 22 shots at a cap you only need to hit once.

About Javid Jamae

Founder & CEO at FFmpeg Micro

Javid is a software engineer, author, and entrepreneur with over 25 years of professional software development experience across enterprise, startup, and consulting environments. He founded FFmpeg Micro to make video processing accessible to developers through a simple, automation-first REST API.

Software EngineeringVideo ProcessingFFmpegCloud ArchitectureAPI DesignAutomation

Ready to process videos at scale?

Start using FFmpeg Micro's simple API today. No infrastructure required.

Get Started Free