Configure GOP Size in FFmpeg libx264
This article explains how to configure the Group of Pictures (GOP)
size, also known as the keyframe interval, in FFmpeg using the
libx264 video encoder. You will learn the specific
command-line parameters used to set the maximum and minimum GOP sizes,
understand how scene-cut detection influences these intervals, and view
practical examples for setting both variable and strictly fixed GOP
sizes.
In video compression, the GOP size determines the distance between keyframes (I-frames). Configuring this interval is crucial for balancing compression efficiency, video quality, and playback seeking performance, especially for adaptive bitrate streaming like HLS or DASH.
The Key Parameters
To control the GOP size in libx264, FFmpeg provides
three primary parameters:
-g: Defines the maximum GOP size (the maximum distance between keyframes).-keyint_min: Defines the minimum GOP size (the minimum distance before another keyframe can be inserted).-sc_threshold: Controls the scene-cut threshold. A value of0disables scene-cut detection, which is necessary for creating a strictly fixed GOP size.
Setting a Variable GOP Size
By default, libx264 uses scene-cut detection to insert
keyframes at natural scene transitions to optimize visual quality.
However, you should still define a maximum GOP limit so that keyframes
are forced if no scene cuts occur for a long duration. A common standard
is setting the maximum GOP to roughly 10 times the video’s frame rate
(fps) for general distribution, or 1 to 2 times the frame rate for
streaming.
To set a maximum GOP size of 250 frames (which is 10 seconds of video at 25 fps), use the following command:
ffmpeg -i input.mp4 -c:v libx264 -g 250 output.mp4In this configuration, FFmpeg will insert keyframes at scene cuts, but will never go more than 250 frames without inserting one.
Setting a Fixed GOP Size
For streaming protocols like HTTP Live Streaming (HLS) or Dynamic Adaptive Streaming over HTTP (DASH), you need a strictly fixed GOP size. This ensures that segment files align perfectly across different bitrates.
To force a fixed GOP size, you must set -g and
-keyint_min to the exact same value and disable scene-cut
detection by setting -sc_threshold to 0.
To set a strict keyframe interval of every 50 frames, use this command:
ffmpeg -i input.mp4 -c:v libx264 -g 50 -keyint_min 50 -sc_threshold 0 output.mp4With these settings, libx264 is forced to place an
I-frame exactly every 50 frames, regardless of scene changes, ensuring
perfect alignment for multi-bitrate streaming packages.