How to Set CRF in FFmpeg libx264
This guide explains how to configure the Constant Rate Factor (CRF)
for the libx264 encoder in FFmpeg. You will learn what CRF
is, how the scale works, and the exact FFmpeg commands required to
adjust visual quality and file size for your video transcodes.
Understanding CRF in libx264
Constant Rate Factor (CRF) is the default encoding mode for H.264
(libx264) in FFmpeg. Instead of targeting a specific file
size or bitrate, CRF targets a specific level of visual quality. It
achieves this by dynamically adjusting the bitrate throughout the video,
allocating more data to complex scenes and saving bandwidth on simple
ones.
The CRF Value Scale
The CRF scale for libx264 ranges from 0 to
51:
- 0: Truly lossless (produces very large file sizes).
- 18 to 28: The recommended range for most web and archival distribution.
- 23: The default value if you do not specify a CRF.
- 51: The worst possible quality.
A change of 6 CRF units roughly halves or doubles the file size. For example, decreasing the CRF from 23 to 17 will approximately double the bitrate, while increasing it from 23 to 29 will approximately halve it. For most general purposes, a CRF of 20 to 22 offers an optimal balance between high visual quality and reasonable file size.
Basic Command Syntax
To configure the CRF value, use the -crf flag in your
FFmpeg command followed by your desired number.
Here is the basic command template:
ffmpeg -i input.mp4 -c:v libx264 -crf 22 -c:a copy output.mp4In this command: * -i input.mp4: Specifies the input
file. * -c:v libx264: Selects the H.264 encoder. *
-crf 22: Sets the CRF quality to 22. *
-c:a copy: Copies the audio stream without re-encoding to
save time and quality. * output.mp4: Specifies the output
file.
Combining CRF with Presets
When configuring CRF, you should always pair it with the
-preset flag. Presets determine the encoding
speed-to-compression ratio. A slower preset provides better compression,
meaning you get a smaller file size for the same CRF quality value.
The available presets are: ultrafast,
superfast, veryfast, faster,
fast, medium (default), slow,
slower, and veryslow.
To run a high-quality encode using the slow preset and a
CRF of 20, use the following command:
ffmpeg -i input.mp4 -c:v libx264 -crf 20 -preset slow -c:a aac -b:a 128k output.mp4