How to Set GOP Size in FFmpeg libvpx

This article explains how to configure the Group of Pictures (GOP) size, also known as the keyframe interval, when encoding video using the libvpx (VP8) and libvpx-vp9 (VP9) encoders in FFmpeg. You will learn the specific command-line parameters required to control both the minimum and maximum keyframe intervals to optimize your video for streaming or playback compatibility.

In FFmpeg, the GOP size is primary controlled using the -g option, which sets the maximum distance between keyframes (I-frames). For the libvpx and libvpx-vp9 encoders, you can configure either a variable GOP size (allowing the encoder to insert keyframes at scene cuts) or a strict, fixed GOP size (crucial for adaptive bitrate streaming like HLS or DASH).

Configuring a Variable GOP Size

By default, FFmpeg allows the encoder to insert keyframes dynamically when a scene change is detected. To set a maximum limit on the GOP size while allowing dynamic keyframes, use the -g and -keyint_min flags:

ffmpeg -i input.mp4 -c:v libvpx-vp9 -g 120 -keyint_min 60 output.webm

In this example: * -g 120: Sets the maximum GOP size to 120 frames. If your video is 30 frames per second (fps), this guarantees a keyframe at least every 4 seconds. * -keyint_min 60: Sets the minimum distance between keyframes to 60 frames (2 seconds at 30 fps), preventing the encoder from placing keyframes too close together during rapid scene changes.

Configuring a Strict, Fixed GOP Size

For HTTP Live Streaming (HLS) or Dynamic Adaptive Streaming over HTTP (DASH), you must enforce a strict, fixed GOP size so that segments align perfectly across different bitrates. To force a constant keyframe interval, you must disable scene change detection by setting -sc_threshold 0 and matching the minimum and maximum keyframe intervals:

ffmpeg -i input.mp4 -c:v libvpx-vp9 -g 60 -keyint_min 60 -sc_threshold 0 output.webm

In this configuration: * -g 60 and -keyint_min 60: Locks the keyframe interval to exactly every 60 frames (exactly 2 seconds for a 30 fps video). * -sc_threshold 0: Disables scene change detection, preventing the encoder from inserting extra, non-aligned keyframes at scene cuts.