How to Set Max Keyframe Interval in libvpx

Controlling the keyframe interval—also known as the Group of Pictures (GOP) size—is essential for optimizing video streaming, compression efficiency, and seek performance. This article provides a straightforward guide on how to configure the maximum keyframe interval in libvpx (VP8/VP9) using both FFmpeg commands and the native libvpx C API.

Setting Maximum Keyframe Interval in FFmpeg

When encoding VP8 or VP9 video with FFmpeg using the libvpx or libvpx-vp9 encoders, you control the maximum keyframe interval using the -g (GOP) flag.

The -g Option

The -g option defines the maximum distance between keyframes in terms of frame count. For example, if your video has a frame rate of 30 frames per second (fps) and you want a maximum keyframe interval of 5 seconds, you would calculate the interval as \(30 \text{ fps} \times 5 \text{ seconds} = 150 \text{ frames}\).

Here is the FFmpeg command to set the maximum keyframe interval to 150 frames:

ffmpeg -i input.mp4 -c:v libvpx-vp9 -g 150 output.webm

Forcing Keyframes at Exact Intervals

By default, the encoder may still insert keyframes earlier than the maximum limit if it detects a scene change. If you want to force a strict, fixed keyframe interval (useful for adaptive bitrate streaming like DASH or HLS), you must also set the minimum keyframe interval (-keyint_min) to match the maximum interval, and disable scene change detection:

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

Setting Maximum Keyframe Interval in the libvpx API

If you are developing a custom application using the native libvpx C library, you configure the maximum keyframe interval via the encoder configuration structure (vpx_codec_enc_cfg_t).

You need to modify the kf_max_dist parameter.

C++ Code Example

#include <vpx/vpx_encoder.h>
#include <vpx/vp8cx.h>

// Initialize configuration
vpx_codec_enc_cfg_t cfg;
vpx_codec_enc_config_default(vpx_codec_vp9_cx(), &cfg, 0);

// Set the maximum distance between keyframes (e.g., 150 frames)
cfg.kf_max_dist = 150;

// Optional: Set the minimum distance to match for a fixed GOP size
cfg.kf_min_dist = 150;

// Initialize encoder with the configuration
vpx_codec_ctx_t codec;
vpx_codec_enc_init(&codec, vpx_codec_vp9_cx(), &cfg, 0);

By setting kf_max_dist, the encoder ensures that a keyframe is generated at least once every specified number of frames, maintaining optimal playback seeking and streaming chunk alignment.