How to Set AVIF Keyframe Interval with libavif

This article explains how to specify the keyframe interval—also known as the Group of Pictures (GOP) size—when encoding animated AVIF files using the libavif library and its command-line tool, avifenc. Properly configuring this setting allows you to optimize the balance between file size, compression efficiency, and seeking performance in animated AVIF images.


Understanding Keyframe Interval (GOP) in AVIF

In animated AVIF files, keyframes (I-frames) are fully self-contained images, while intermediate frames (P-frames or B-frames) only store the differences between consecutive frames.

The keyframe interval determines how often a full keyframe is forced into the animation sequence. * A shorter interval (more keyframes) results in larger file sizes but allows for faster seeking and rendering when scrubbing through an animation. * A longer interval (fewer keyframes) improves compression and reduces file size, but makes seeking slower because the decoder must reconstruct images from the nearest preceding keyframe.

Using the --gop Flag in avifenc

The standard tool provided by libavif to encode images is avifenc. To specify the maximum keyframe interval, use the -g or --gop option followed by the number of frames.

Command Syntax:

avifenc -g <frame_count> input.gif output.avif

Example:

To set a keyframe interval of 60 frames (meaning a keyframe will be inserted at least once every 60 frames):

avifenc --gop 60 input.gif output.avif

Advanced Control with Encoder-Specific Parameters

libavif acts as a wrapper around various AV1 encoders, such as aom, rav1e, or svt-av1. If you need more granular control over keyframe placement, you can pass parameters directly to the underlying encoder using the --aom-params, --rav1e-params, or --svt-params flags.

For the default AOM encoder, you can set the minimum and maximum keyframe intervals explicitly:

avifenc --aom-params kf-max-dist=60:kf-min-dist=30 input.gif output.avif