Library Overview
ConvAvif provides a comprehensive API for converting images to the AVIF format. The library is designed to be used directly from C++ or through WebAssembly bindings in JavaScript/TypeScript.
Key Features
Support for JPEG and PNG input formats
Configurable encoding parameters
Multiple codec options (AOM, SVT)
Quality and performance tuning options
Key Components
EncodeConfig: Configuration for the AVIF encoder
ImageGuru: Image format detection and conversion
Error: Error handling and reporting
ImageBuffer: Image data buffer management
-
struct AvifEncoderDeleter
- #include <avif_helper.h>
Custom deleter for avifEncoder objects.
This functor is used with std::unique_ptr to properly clean up avifEncoder resources when the unique_ptr goes out of scope.
Public Functions
-
inline void operator()(avifEncoder *enc)
Deletes an avifEncoder object.
- Parameters:
enc – Pointer to the avifEncoder to destroy
-
inline void operator()(avifEncoder *enc)
-
struct AvifImageDeleter
- #include <avif_helper.h>
Custom deleter for avifImage objects.
This functor is used with std::unique_ptr to properly clean up avifImage resources when the unique_ptr goes out of scope.
Public Functions
-
inline void operator()(avifImage *img)
Deletes an avifImage object.
- Parameters:
img – Pointer to the avifImage to destroy
-
inline void operator()(avifImage *img)
-
struct EncodeConfig
- #include <encoder_config.h>
Main configuration structure for AVIF encoding.
This structure contains all the parameters that control the AVIF encoding process, including quality settings, codec choice, and various encoder-specific parameters.
Public Functions
-
inline void setQuality(int q)
Set the quality value with validation.
- Parameters:
q – New quality value
-
inline void setMinQuantizer(int q)
Set the minimum quantizer value with validation.
- Parameters:
q – New minimum quantizer value
-
inline void setMaxQuantizer(int q)
Set the maximum quantizer value with validation.
- Parameters:
q – New maximum quantizer value
-
inline void setTileRowsLog2(int t)
Set the tile rows log2 value with validation.
- Parameters:
t – New tile rows log2 value
-
inline void setTileColsLog2(int t)
Set the tile columns log2 value with validation.
- Parameters:
t – New tile columns log2 value
-
inline void setSharpness(int s)
Set the sharpness value with validation.
- Parameters:
s – New sharpness value
-
inline int getQuality() const
Get the current quality value.
- Returns:
Current quality value
-
inline int getMinQuantizer() const
Get the current minimum quantizer value.
- Returns:
Current minimum quantizer value
-
inline int getMaxQuantizer() const
Get the current maximum quantizer value.
- Returns:
Current maximum quantizer value
-
inline int getTileRowsLog2() const
Get the current tile rows log2 value.
- Returns:
Current tile rows log2 value
-
inline int getTileColsLog2() const
Get the current tile columns log2 value.
- Returns:
Current tile columns log2 value
-
inline int getSharpness() const
Get the current sharpness value.
- Returns:
Current sharpness value
-
inline int getSpeed() const
Get the current speed value.
- Returns:
Current speed value
-
inline void setPreset(SpeedPreset newPreset)
Set a new speed preset and update speed settings.
- Parameters:
newPreset – New speed preset
-
inline SpeedPreset getPreset() const
Get the current speed preset.
- Returns:
Current speed preset
-
inline void updateSpeed(int new_speed, SpeedPreset newPreset)
Update speed settings with new values.
- Parameters:
new_speed – New speed value
newPreset – New speed preset
-
inline CodecChoice getCodecChoice() const
Get the current codec choice.
- Returns:
Current codec choice
-
inline void setCodecChoice(CodecChoice choice)
Set a new codec choice and update speed settings.
- Parameters:
choice – New codec choice
-
inline void printConfig() const
Print the current configuration to stdout.
Useful for debugging and logging purposes
Public Members
-
int quality = 30
Quality value (0-100, higher is better quality)
-
int qualityAlpha = -1
Alpha channel quality (-1 means use quality value)
-
int sharpness = 0
Sharpness filter strength (0-7)
-
avifPixelFormat pixelFormat = AVIF_PIXEL_FORMAT_YUV420
YUV pixel format.
-
CodecChoice codecChoice
Selected codec (AOM, SVT, AUTO)
-
SpeedPreset preset
Speed preset.
-
int minQuantizer = -1
Minimum quantizer (0-63, -1 for default)
-
int maxQuantizer = -1
Maximum quantizer (0-63, -1 for default)
-
int tileRowsLog2 = 0
Log2 of tile rows (0 = 1 tile row, 1 = 2 rows, etc)
-
int tileColsLog2 = 0
Log2 of tile columns.
-
Tune tune = Tune::TUNE_DEFAULT
Encoder tuning option.
Private Functions
-
inline int validatedQuality(int q) const
Validate and clamp quality value to valid range.
- Parameters:
q – Quality value to validate
- Returns:
Clamped quality value
-
inline int validatedQuantizer(int q) const
Validate and clamp quantizer value to valid range.
- Parameters:
q – Quantizer value to validate
- Returns:
Clamped quantizer value or -1 if default value is specified
-
inline int validatedTileLog2(int t) const
Validate and clamp tile log2 value to valid range.
- Parameters:
t – Tile log2 value to validate
- Returns:
Clamped tile log2 value
-
inline int validatedSharpness(int s) const
Validate and clamp sharpness value to valid range.
- Parameters:
s – Sharpness value to validate
- Returns:
Clamped sharpness value
Private Members
-
Speed speed = Speed(CodecChoice::AOM, SpeedPreset::Good)
Speed settings.
-
inline void setQuality(int q)
-
class Error
- #include <error.h>
Error class for reporting conversion errors.
This class encapsulates an error code, a descriptive message, and optional stack trace information for debugging.
Public Functions
-
Error(ConverterError c, const std::string &msg, const std::string &trace = "")
Constructor for Error objects.
- Parameters:
c – Error code identifying the error type
msg – Human-readable error message
trace – Optional function name or call stack information
Public Members
-
ConverterError code
Error code identifying the error type.
-
std::string message
Human-readable error message.
-
std::string stackTrace
Function call stack or context information.
-
Error(ConverterError c, const std::string &msg, const std::string &trace = "")
-
class ImageBuffer
- #include <imagebuffer.h>
Container class for image binary data.
This class encapsulates a vector of bytes representing image data and provides methods to access this data from both C++ and JavaScript.
Public Functions
-
inline ImageBuffer(std::vector<uint8_t> data)
Constructor that takes ownership of image data.
- Parameters:
data – Vector containing the binary image data (typically AVIF encoded)
-
inline emscripten::val getData() const
Get the image data as a JavaScript typed array.
Note
This creates a view into the existing memory without copying
- Returns:
JavaScript typed array (Uint8Array) view of the image data
-
inline size_t getSize() const
Get the size of the image data in bytes.
- Returns:
Size of the image data in bytes
-
inline const std::vector<uint8_t> &getRawData() const
Get direct access to the underlying data vector.
- Returns:
Const reference to the underlying byte vector
Private Members
-
std::vector<uint8_t> data_
The binary image data.
-
inline ImageBuffer(std::vector<uint8_t> data)
-
class ImageGuru
- #include <imageGuru.h>
Utility class for image format detection and support checking.
This class provides static methods to detect image formats from binary data and check whether specific formats are supported for conversion to AVIF.
Public Static Functions
-
static inline ImageType GetImageType(const std::vector<uint8_t> &data)
Detect the image format from binary data.
Examines the file header/magic bytes in the provided data to determine the image format.
- Parameters:
data – Binary image data to analyze
- Returns:
Detected ImageType, or ImageType::UNKNOWN if format isn’t recognized
-
static inline bool IsValid(const std::vector<uint8_t> &data)
Check if binary data appears to be a valid image.
- Parameters:
data – Binary data to check
- Returns:
true if the data appears to be a recognized image format, false otherwise
-
static inline bool IsSpecificType(const std::vector<uint8_t> &data, ImageType type)
Check if binary data matches a specific image format.
- Parameters:
data – Binary data to check
type – Specific ImageType to check for
- Returns:
true if the data matches the specified format, false otherwise
Private Static Attributes
-
static std::array<imageSupport, 8> supported_image = {{{ImageType::JPEG, true}, {ImageType::PNG, true}, {ImageType::GIF, false}, {ImageType::BMP, false}, {ImageType::TIFF, false}, {ImageType::WEBP, false}, {ImageType::AVIF, true}, {ImageType::UNKNOWN, false}}}
Array defining which image formats are supported for conversion.
This array maps each ImageType to a boolean indicating whether that format can be converted to AVIF by the library.
-
static inline ImageType GetImageType(const std::vector<uint8_t> &data)
-
struct imageSupport
- #include <imageGuru.h>
Structure for tracking image format support status.
-
struct jsResult
- #include <result.h>
JavaScript-friendly result structure.
This structure wraps the C++ Result variant and provides helper methods for JavaScript bindings to easily check result status and extract data.
Public Functions
-
inline bool hasError() const
Check if the result contains an error.
- Returns:
true if the result is an error, false otherwise
-
inline bool hasImage() const
Check if the result contains an image.
- Returns:
true if the result is an image, false otherwise
-
inline Error getError() const
Get the error from the result.
- Returns:
The Error object
- Pre:
The result must contain an error (check with hasError() first)
-
inline ImgaePtr getImage() const
Get the image from the result.
- Returns:
The image buffer pointer
- Pre:
The result must contain an image (check with hasImage() first)
-
inline bool hasError() const
-
struct Speed
- #include <encoder_config.h>
Speed settings manager for AVIF encoding.
This class manages speed settings based on the selected codec and preset. Different codecs have different optimal speed ranges for various quality/speed tradeoffs.
Public Functions
-
inline Speed(CodecChoice codec, SpeedPreset preset)
Constructor that sets appropriate speed ranges based on codec and preset.
- Parameters:
codec – The selected codec (AOM, SVT, AUTO)
preset – The desired speed preset (Good, MemoryHungry, RealTime)
-
inline int getDefault() const
Get the default speed value.
- Returns:
Current default speed value
-
inline void setSpeedRange(const SpeedRange &range)
Set a new speed range.
- Parameters:
range – New speed range to use
-
inline SpeedRange getRange() const
Get the current speed range.
- Returns:
Current speed range
-
inline bool isValid(int speed)
Check if a speed value is within the valid range.
- Parameters:
speed – Speed value to check
- Returns:
true if speed is valid, false otherwise
-
inline SpeedPreset getPreset() const
Get the current speed preset.
- Returns:
Current SpeedPreset value
-
inline void set(int ns)
Set a new speed value if it’s valid.
- Parameters:
ns – New speed value to set
Public Members
-
SpeedPreset preset_ = SpeedPreset::Good
Current speed preset.
-
int default_speed = 5
Default speed value.
-
SpeedRange speed_range = {5, 6}
Valid speed range.
-
inline Speed(CodecChoice codec, SpeedPreset preset)
-
struct SpeedRange
- #include <encoder_config.h>
Structure to define the range of valid speed values.
Public Members
-
int min
Minimum valid speed value.
-
int max
Maximum valid speed value.
-
int min
- file avif_helper.h
- #include “result.h”#include <avif/avif.h>#include <memory>
Helper utilities for AVIF library integration.
This file provides utility classes and functions to simplify working with the AVIF library, including RAII wrappers for AVIF objects and helper functions for common operations.
- Author
ConvAvif Developer
- Date
2025
Typedefs
-
using UniqueAvifEncoder = std::unique_ptr<avifEncoder, AvifEncoderDeleter>
Unique pointer type for AVIF encoders with automatic cleanup.
This type ensures that avifEncoder objects are properly destroyed when they are no longer needed.
-
using UniqueAvifImage = std::unique_ptr<avifImage, AvifImageDeleter>
Unique pointer type for AVIF images with automatic cleanup.
This type ensures that avifImage objects are properly destroyed when they are no longer needed.
Functions
-
inline Result SetAvifOption(avifEncoder *encoder, const char *key, const char *value, const std::string &humanReadableOption, const char *callerFunction = __func__)
Set a codec-specific option on an AVIF encoder.
This function wraps the avifEncoderSetCodecSpecificOption function with error handling and detailed error messages.
- Parameters:
encoder – The AVIF encoder to set the option on
key – The option key (specific to the codec)
value – The option value to set
humanReadableOption – Human-readable description of the option (for error messages)
callerFunction – Name of the calling function (for error context)
- Returns:
- file constants.h
Global constants used throughout the ConvAvif project.
This file defines the key constant values used for image conversion configuration, including RGB depth, quality ranges, and encoder-specific parameter limits.
- Author
ConvAvif Developer
- Date
2025
Variables
-
static int RGB_DEPTH = 8
Bit depth for RGB image processing.
Standard 8-bit per channel depth used for input/output RGB images
-
static int MIN_SPEED = 0
Minimum encoder speed setting.
Slowest speed setting (best quality, highest compression)
-
static int MAX_SPEED = 9
Maximum encoder speed setting.
Fastest speed setting (lowest quality, fastest encoding)
-
static int MAX_QUALITY = 99
Maximum quality value.
Highest possible quality setting (99 out of 100)
-
static int MAX_QUANTIZER = 63
Maximum quantizer value.
Highest quantizer value for the encoder (63) Higher values mean lower quality but better compression
-
static int MAX_TILE_LOG2 = 6
Maximum tile log2 value.
Controls maximum number of tiles as 2^MAX_TILE_LOG2
-
static int MAX_SHARPNESS = 7
Maximum sharpness filter value.
Controls the strength of the sharpness filter (0-7)
- file encoder_config.h
- #include “constants.h”#include <algorithm>#include <avif/avif.h>#include <string>
Configuration parameters and settings for AVIF encoding.
This file defines the configuration structures and enums that control the AVIF encoding process, including codec selection, quality settings, and various encoder-specific parameters.
- Author
ConvAvif Developer
- Date
2025
Enums
-
enum class CodecChoice
Codecs available for AVIF encoding.
Values:
-
enumerator AUTO
-
enumerator AOM
-
enumerator SVT
-
enumerator AUTO
-
enum class Tune
Tuning options for the encoder.
Values:
-
enumerator TUNE_DEFAULT
-
enumerator TUNE_PSNR
-
enumerator TUNE_SSIM
-
enumerator TUNE_DEFAULT
-
enum class SpeedPreset : int
Speed presets for encoding with different performance/quality tradeoffs.
Values:
-
enumerator Good
-
enumerator MemoryHungry
-
enumerator RealTime
-
enumerator Good
Functions
-
template<typename T>
void setField(T &field, T minVal, T maxVal) Helper template function to clamp a field value between minimum and maximum values.
- Template Parameters:
T – The type of the field (typically int)
- Parameters:
field – Reference to the field to be clamped
minVal – Minimum allowed value
maxVal – Maximum allowed value
- file error.h
- #include <avif/avif.h>#include <emscripten/val.h>#include <string>
Error handling for AVIF conversion operations.
This file defines error types, error codes, and helper functions for handling and reporting errors during AVIF conversion operations.
- Author
ConvAvif Developer
- Date
2025
Enums
-
enum class ConverterError
Error codes for the image converter.
These error codes identify different failure modes in the conversion process. Error codes 100-199 are specific to the converter, while codes 200+ are mapped from the AVIF library.
Values:
-
enumerator OK
No error, operation successful.
-
enumerator INVALID_DIMENSIONS
Image dimensions are invalid (too small/large)
-
enumerator UNSUPPORTED_IMAGETYPE
Image format is not supported.
-
enumerator IMAGE_LOAD_FAILED
Failed to load/decode the input image.
-
enumerator ENCODER_CREATION_FAILED
Failed to create the AVIF encoder.
-
enumerator CONVERSION_FAILED
Failed during the RGB to YUV conversion.
-
enumerator ENCODING_FAILED
Failed during the encoding process.
-
enumerator INVALID_ARGUMENT
Invalid argument provided to a function.
-
enumerator OUT_OF_MEMORY
Memory allocation failed.
-
enumerator INVALID_QUANTIZER_VALUES
Invalid quantizer values (e.g., min > max)
-
enumerator UNKNOWN_ERROR
Unspecified error.
-
enumerator AVIF_ERROR_START
Start of error codes mapped from avifResult.
-
enumerator OK
Functions
-
ConverterError avifToConverterError(avifResult result)
Converts an AVIF library error code to a ConverterError.
Maps the native AVIF library error codes to the application’s error enum.
- Parameters:
result – AVIF library result code
- Returns:
Equivalent ConverterError code
-
std::string getErrorMessage(ConverterError error)
Get a human-readable error message for an error code.
- Parameters:
error – Error code to get the message for
- Returns:
Standard error message for the given code
-
emscripten::val toJsError(const Error &e)
Convert a C++ Error object to a JavaScript error object.
Creates a JavaScript error object with properties for code, message, and stackTrace suitable for returning to JavaScript code.
- Parameters:
e – The C++ Error object to convert
- Returns:
JavaScript object representing the error
- file imagebuffer.h
- #include <emscripten.h>#include <emscripten/bind.h>#include <memory>#include <vector>
Image buffer management for AVIF conversion results.
This file defines the ImageBuffer class which encapsulates the raw binary data of a converted image and provides methods to access it from both C++ and JavaScript contexts.
- Author
ConvAvif Developer
- Date
2025
- file imageconverter.h
- #include “avif_helper.h”#include “constants.h”#include “encoder_config.h”#include “error.h”#include “imageGuru.h”#include “imagebuffer.h”#include “result.h”#include <algorithm>#include <avif/avif.h>#include <string>
Header for image conversion functionality to AVIF format.
Provides functions to convert various image formats to AVIF using the AVIF library with configurable encoding parameters.
- Author
ConvAvif Developer
- Date
2025
Functions
-
Result convert_image(ImageType type, const std::vector<uint8_t> &input_data, int width, int height, const EncodeConfig &config)
Converts an image to AVIF format with specified parameters.
This function handles the complete conversion pipeline:
Validates input dimensions
Loads and decodes input image data
Resizes image if necessary
Configures the AVIF encoder based on provided settings
Converts RGB data to YUV colorspace
Encodes image to AVIF format
Note
Image dimensions are limited to 1-8192px
- Parameters:
type – The type of input image (e.g., PNG, JPEG)
input_data – Vector containing the raw image data
width – Desired width of the output image (will resize if different from source)
height – Desired height of the output image (will resize if different from source)
config – Encoding configuration parameters
type – The type of input image (e.g., PNG, JPEG)
input_data – Vector containing the raw image data
width – Desired width of the output image
height – Desired height of the output image
config – Encoding configuration parameters
- Returns:
Result object containing either the encoded image data on success or an Error on failure
- Returns:
Result object containing either the encoded image data or an Error
-
emscripten::val convertImageDirect(emscripten::val jsData, int width, int height, const EncodeConfig &config)
JavaScript binding wrapper for image conversion.
Takes JavaScript Uint8Array input and returns JavaScript object with result data.
This function:
Converts JavaScript data to C++ vector
Detects the image type
Validates the image can be processed
Calls convert_image to perform the actual conversion
Returns JavaScript object with result
- Parameters:
jsData – JavaScript array/TypedArray containing image data
width – Desired width of the output image
height – Desired height of the output image
config – Encoding configuration parameters
jsData – JavaScript array/TypedArray containing image data
width – Desired width of the output image
height – Desired height of the output image
config – Encoding configuration parameters
- Returns:
JavaScript object containing either the encoded image buffer or error information
- Returns:
JavaScript object containing either the encoded image buffer or error information
- file imageGuru.h
- #include <algorithm>#include <array>#include <string>#include <vector>
Image format detection and type management.
This file provides utilities for detecting image formats from binary data and checking format support status for the AVIF conversion process.
- Author
ConvAvif Developer
- Date
2025
Enums
-
enum class ImageType
Enumeration of supported image types.
Lists all the image formats that can be detected by the ImageGuru, regardless of whether they can be converted to AVIF.
Values:
-
enumerator JPEG
-
enumerator PNG
-
enumerator GIF
-
enumerator BMP
-
enumerator TIFF
-
enumerator WEBP
-
enumerator AVIF
-
enumerator UNKNOWN
-
enumerator JPEG
- file result.h
- #include “error.h”#include “imagebuffer.h”#include <memory>#include <variant>
Result handling utilities for the AVIF conversion process.
This file defines the Result type and related structures used to handle the outcome of image conversion operations, which can be either a successfully converted image or an error.
- Author
ConvAvif Developer
- Date
2025
Typedefs
-
using ImgaePtr = std::shared_ptr<ImageBuffer>
Shared pointer to an ImageBuffer, representing a successfully converted image.
This type alias is used as the success case in the Result variant.
- file bind.cpp
- #include “encoder_config.h”#include “error.h”#include “imagebuffer.h”#include “imageconverter.h”#include “result.h”#include <emscripten/bind.h>
Functions
-
EMSCRIPTEN_BINDINGS(ImageBuffer)
-
EMSCRIPTEN_BINDINGS(ImageConverter)
-
EMSCRIPTEN_BINDINGS(avif_enums)
-
EMSCRIPTEN_BINDINGS(ErrorHandling)
-
EMSCRIPTEN_BINDINGS(ImageBuffer)
- file error.cpp
- #include “error.h”
Functions
-
ConverterError avifToConverterError(avifResult result)
Converts an AVIF library error code to a ConverterError.
Maps the native AVIF library error codes to the application’s error enum.
- Parameters:
result – AVIF library result code
- Returns:
Equivalent ConverterError code
-
std::string getErrorMessage(ConverterError error)
Get a human-readable error message for an error code.
- Parameters:
error – Error code to get the message for
- Returns:
Standard error message for the given code
-
emscripten::val toJsError(const Error &e)
Convert a C++ Error object to a JavaScript error object.
Creates a JavaScript error object with properties for code, message, and stackTrace suitable for returning to JavaScript code.
- Parameters:
e – The C++ Error object to convert
- Returns:
JavaScript object representing the error
-
ConverterError avifToConverterError(avifResult result)
- file imageconverter.cpp
- #include “imageconverter.h”#include <avif/avif.h>#include <cmath>#include <cstdlib>#include <emscripten/bind.h>#include <emscripten/emscripten.h>#include <emscripten/heap.h>#include <emscripten/threading.h>#include <emscripten/val.h>#include <stb_image.h>#include <stb_image_resize2.h>#include <vector>
Implementation of image conversion functionality to AVIF format.
- Author
ConvAvif Developer
- Date
2025
Functions
-
Result convert_image(ImageType type, const std::vector<uint8_t> &input_data, int width, int height, const EncodeConfig &config)
Converts an image to AVIF format with specified parameters.
This function handles the complete conversion pipeline:
Validates input dimensions
Loads and decodes input image data
Resizes image if necessary
Configures the AVIF encoder based on provided settings
Converts RGB data to YUV colorspace
Encodes image to AVIF format
- Parameters:
type – The type of input image (e.g., PNG, JPEG)
input_data – Vector containing the raw image data
width – Desired width of the output image
height – Desired height of the output image
config – Encoding configuration parameters
- Returns:
Result object containing either the encoded image data or an Error
-
emscripten::val convertImageDirect(emscripten::val jsData, int width, int height, const EncodeConfig &config)
JavaScript binding wrapper for image conversion.
This function:
Converts JavaScript data to C++ vector
Detects the image type
Validates the image can be processed
Calls convert_image to perform the actual conversion
Returns JavaScript object with result
- Parameters:
jsData – JavaScript array/TypedArray containing image data
width – Desired width of the output image
height – Desired height of the output image
config – Encoding configuration parameters
- Returns:
JavaScript object containing either the encoded image buffer or error information
Variables
-
thread_local const emscripten::val Uint8Array = emscripten::val::global("Uint8Array")
Thread-local Uint8Array reference from JavaScript.
Used for efficient data transfer between C++ and JavaScript
- file pthread_stubs.c
- dir include
- dir src