Initialize and Configure avifEncoder in libavif

This article provides a straightforward guide on how to initialize and configure the avifEncoder struct using the libavif library in C. It covers the essential API calls required to allocate the encoder, set key compression parameters such as quality and speed, and properly manage memory to ensure efficient AVIF image generation.

Initializing the avifEncoder

To begin encoding an AVIF image, you must first allocate and initialize the avifEncoder structure. The libavif library provides a dedicated function for this purpose, which sets all internal parameters to safe, standard default values.

avifEncoder * encoder = avifEncoderCreate();
if (!encoder) {
    // Handle allocation failure
}

The avifEncoderCreate() function dynamically allocates memory for the encoder. Always check if the returned pointer is null to prevent segmentation faults in your application.

Configuring Encoding Parameters

Once initialized, you can customize the encoding process by directly modifying the member variables of the avifEncoder struct. The most commonly configured parameters include:

Example Configuration

Here is a practical code snippet demonstrating how to apply these settings to your encoder instance:

// Set encoding speed to 6 (balanced)
encoder->speed = 6;

// Set image quality to 80 (high quality, lossy compression)
encoder->quality = 80;

// Set alpha quality to 80 (if the image has transparency)
encoder->qualityAlpha = 80;

// Enable multi-threading using up to 4 threads
encoder->maxThreads = 4;

Advanced Configuration

For advanced use cases, such as creating animated AVIFs or configuring specific codec behavior, you can adjust additional struct members:

Cleaning Up Memory

To prevent memory leaks, you must free the resources allocated for the encoder once the encoding process is complete. Use the avifEncoderDestroy() function:

avifEncoderDestroy(encoder);

This function safely releases all internal allocations and the encoder structure itself, ensuring clean memory management in your application.