How to Set Keyframe Interval in FFmpeg libx264

This article explains how to configure the minimum and maximum keyframe intervals (also known as Group of Pictures or GOP size) using the libx264 encoder in FFmpeg. You will learn the specific command-line options required to control keyframe placement, why these settings matter for streaming and editing, and how to disable scene-change detection for a strictly constant keyframe interval.

The Keyframe Interval Parameters

In FFmpeg’s libx264 encoder, keyframe intervals are controlled by two primary parameters:

1. Setting the Maximum Keyframe Interval (-g)

The -g option sets the maximum number of frames allowed between keyframes. If a keyframe has not been naturally inserted due to a scene change, the encoder will force one at this limit.

For example, to set a maximum keyframe interval of 250 frames:

ffmpeg -i input.mp4 -c:v libx264 -g 250 output.mp4

If your video’s framerate is 25 frames per second (fps), a -g value of 250 results in a maximum keyframe interval of 10 seconds (250 frames / 25 fps). For modern web streaming (like HLS or DASH), a shorter interval of 2 seconds (e.g., -g 50 for 25 fps) is standard.

2. Setting the Minimum Keyframe Interval (-keyint_min)

The -keyint_min option sets the minimum distance before another keyframe can be inserted. This prevents the encoder from wasting bitrate by placing keyframes too close together, which can happen during high-motion scenes or rapid cuts.

For example, to set the minimum keyframe interval to 25 frames:

ffmpeg -i input.mp4 -c:v libx264 -g 250 -keyint_min 25 output.mp4

Generally, a standard practice for variable keyframe placement is to set -keyint_min to match your video’s frame rate (e.g., 24, 25, or 30), and -g to ten times that value.


Configuring a Strict Constant Keyframe Interval (Fixed GOP)

By default, libx264 uses “scene cut detection” to dynamically insert keyframes at the start of new scenes. If you require a strict, fixed keyframe interval where keyframes occur exactly every \(N\) frames without deviation (crucial for adaptive bitrate streaming like HLS and DASH), you must disable scene cut detection.

To disable scene cut detection and force a constant keyframe interval, set the -sc_threshold option to 0 and make both -g and -keyint_min identical.

For a strict 2-second keyframe interval on a 30 fps video (60 frames):

ffmpeg -i input.mp4 -c:v libx264 -g 60 -keyint_min 60 -sc_threshold 0 output.mp4

Parameter Breakdown for Fixed GOP: