Set Keyframe Interval in FFmpeg

Controlling keyframe (I-frame) intervals in FFmpeg is crucial for optimizing video streaming latency, seeking performance, and compression efficiency. This article explains how to define the maximum and minimum keyframe intervals using the -g and -keyint_min flags, including practical command-line examples for your video encoding workflows.

Understanding Keyframe Intervals (GOP)

In video compression, keyframes (also known as I-frames) are full images stored in the video stream, while the frames between them only store the differences between frames. The distance between keyframes is called the Group of Pictures (GOP) size. Managing this distance is essential: shorter intervals allow for faster seeking and better streaming adaptation, while longer intervals improve compression and reduce file size.

Setting the Maximum Keyframe Interval

The maximum keyframe interval defines the maximum number of frames allowed between keyframes. In FFmpeg, this is set using the -g option.

To calculate the value for -g, multiply your video’s frame rate (FPS) by the desired interval in seconds. For example, if your video is 30 FPS and you want a maximum keyframe interval of 2 seconds, the GOP size should be 60.

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

Setting the Minimum Keyframe Interval

FFmpeg automatically inserts keyframes at scene cuts to maintain visual quality. The minimum keyframe interval prevents FFmpeg from placing keyframes too close together, which would otherwise waste bandwidth. This is set using the -keyint_min option.

To set a minimum interval of 1 second on a 30 FPS video (30 frames), use the following command:

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

Enforcing a Fixed Keyframe Interval

If you are encoding for adaptive bitrate streaming (like HLS or DASH), you often need a strictly fixed keyframe interval where keyframes occur exactly at the specified interval without scene-change detection.

To force a fixed interval, set -g and -keyint_min to the same value, and disable scene-change detection by setting -sc_threshold to 0:

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

By mastering these three parameters, you can precisely control keyframe placement to suit your specific playback, streaming, or storage requirements.