How to Set libx265 Reference Frames in FFmpeg
Controlling the number of reference frames in FFmpeg’s
libx265 encoder is crucial for optimizing video compression
efficiency and ensuring playback compatibility with various hardware
decoders. This article provides a straightforward guide on how to
configure the reference frames parameter using FFmpeg commands,
explaining the specific syntax and the impact of these settings on your
encoding workflow.
The Standard Method: Using x265-params
To configure the reference frame count (often abbreviated as “ref”)
in libx265, you must pass the ref option
through the -x265-params argument. While FFmpeg has a
generic -refs flag, libx265 ignores this
generic flag in favor of its own internal parameters.
The basic syntax to set the reference frames is:
ffmpeg -i input.mp4 -c:v libx265 -x265-params ref=4 output.mp4In this command: * -c:v libx265 selects the H.265/HEVC
encoder. * -x265-params ref=4 instructs the encoder to use
a maximum of 4 reference frames.
Setting Multiple Parameters Together
If you need to configure other libx265 settings
alongside the reference frames, you can separate them with a colon
(:) inside the -x265-params argument.
For example, to set the reference frames to 3 and also specify a Constant Rate Factor (CRF) of 22:
ffmpeg -i input.mp4 -c:v libx265 -crf 22 -x265-params ref=3:bframes=4 output.mp4How Reference Frames Affect Your Video
When deciding how many reference frames to configure, keep the following trade-offs in mind:
- Lower Values (1 to 3): Offers faster encoding speeds and lower memory usage during both encoding and playback. This is highly recommended for older hardware decoders, mobile devices, and streaming sticks.
- Higher Values (4 to 16): Allows the encoder to search further back in the video timeline for matching blocks, which can significantly reduce file size for highly repetitive videos (like animation or presentation slides). However, this increases encoding time and requires more RAM from the playback device.
- Default Values: By default,
libx265automatically determines the number of reference frames based on the preset you choose (e.g.,medium,slow,veryslow). Manually settingrefoverrides the preset’s default value.