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.avifExample:
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.avifAdvanced 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.avifkf-max-dist: The maximum distance between keyframes (equivalent to the GOP size).kf-min-dist: The minimum distance before another keyframe can be inserted, preventing the encoder from creating unnecessary keyframes in highly dynamic scenes.
Recommended Keyframe Intervals
- Standard Web Animations (under 5 seconds): Set the
GOP size to match the total frame count of the animation, or use a value
like
0(which often lets the encoder decide, or forces infinite GOP where only the first frame is a keyframe) to maximize compression. - Longer Clips / Video-like Animations: Use a
keyframe interval equal to 1 to 2 times the frame rate (e.g., a GOP of
30or60for a 30 fps animation) to ensure smooth playback and efficient seeking.