What is the avifEncoderWrite Function in libavif
This article explains the purpose, functionality, and usage of the
avifEncoderWrite function within the libavif
library. It covers how this function facilitates the compression of
image data into the AVIF format and outlines its role in the overall
encoding pipeline.
Purpose of avifEncoderWrite
The avifEncoderWrite function is a core component of the
libavif library, which is the official open-source library
used to encode and decode AVIF (AV1 Image File Format) files.
The primary purpose of avifEncoderWrite is to take a raw
image, compress it using an AV1 encoder (such as aom,
rav1e, or svt-av1), and package the compressed
data into the standardized AVIF container format. It outputs the
finalized AVIF file data directly into a memory buffer.
Function Signature
In the C API of libavif, the function is declared as
follows:
avifResult avifEncoderWrite(avifEncoder * encoder, const avifImage * image, avifRWData * raw);Parameters
encoder: A pointer to an initialized and configuredavifEncoderstructure. This structure holds all the settings for the encoding process, such as the target quality (quantizer), compression speed, tiling, and choice of AV1 codec.image: A pointer to theavifImagestructure containing the source pixel data (usually in YUV or RGB format) along with metadata like color profiles (ICC profiles), alpha channels, and depth information.raw: A pointer to anavifRWDatastructure. This structure acts as the destination buffer where the function will write the final, fully assembled AVIF file bytes.
How it Works in the Encoding Pipeline
To use avifEncoderWrite, developers typically follow
these steps:
- Initialize Structures: Create and configure an
avifImageto hold the raw pixels, and anavifEncoderto define the compression parameters. - Call
avifEncoderWrite: Invoke the function, passing the encoder configuration, the source image, and an emptyavifRWDatabuffer. - Process the Output: Once the function executes
successfully, the
rawbuffer contains the complete AVIF image file. This buffer can then be written directly to a file on disk or sent over a network. - Clean Up: Free the allocated memory for the image,
encoder, and the output buffer using the library’s cleanup functions
(such as
avifRWDataFree).
Return Values
The function returns an avifResult status code.
AVIF_RESULT_OK: The encoding was successful, and the output buffer contains the valid AVIF data.- Error Codes: If the encoding fails (for example, due to out-of-memory errors, invalid image dimensions, or internal AV1 encoder failures), the function will return a specific error code indicating what went wrong, and the output buffer will remain empty.