How Libavif Handles Lossless Image Encoding

This article explains how the libavif library utilizes the AV1 video codec to achieve pixel-perfect, lossless image compression. It covers the essential configuration settings required for lossless encoding, the internal mechanisms of the AV1 codec that bypass lossy compression steps, and the critical role of color space selection in maintaining exact data replication.

Disabling Quantization

The core mechanism of lossless encoding in libavif involves disabling quantization. In lossy compression, quantization reduces the precision of pixel or frequency data to save space, which permanently discards information. To achieve lossless compression, libavif configures the underlying AV1 encoder (such as aom or rav1e) to set the Quantization Parameter (QP) to zero. By setting the quantizer values to 0 for both the color (luma/chroma) and alpha channels, the encoder ensures that no data is discarded during the compression process.

Transform Bypass and Prediction

In standard lossy encoding, spatial pixel data is converted into frequency data using Discrete Cosine Transforms (DCT) or Asymmetric Discrete Sine Transforms (ADST). For lossless encoding, libavif utilizes AV1’s transform bypass mode. Instead of transforming the pixels, the encoder predicts the values of neighboring pixels and calculates the difference (residual). This residual data is then encoded directly using AV1’s lossless arithmetic entropy coder. Because no mathematical transformation or rounding occurs, the original pixels can be reconstructed exactly.

Color Space Preservation

Achieving true lossless encoding requires careful configuration of the image’s color space. Standard lossy AVIF images often convert RGB data to YUV (specifically YCbCr) and perform chroma subsampling (like 4:2:0), which discards color resolution. To prevent this in lossless mode, libavif supports:

Implementation via libavif API

In practical application, developers trigger lossless encoding in libavif by setting specific properties in the encoder configuration. The library simplifies this by providing high-level helper functions or constants, such as setting the encoder quality to AVIF_QUALITY_LOSSLESS (which maps to a value of 100) and ensuring the matrix coefficients are set to identity (for RGB) or that chroma subsampling is configured to 4:4:4. This instructs the encoder to automatically apply the zero-quantizer and transform-bypass settings required for a pixel-perfect output.