Files

This section describes the source files in the ConvAvif library.

Header Files

encoder_config.h

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
enum class Tune

Tuning options for the encoder.

Values:

enumerator TUNE_DEFAULT
enumerator TUNE_PSNR
enumerator TUNE_SSIM
enum class SpeedPreset : int

Speed presets for encoding with different performance/quality tradeoffs.

Values:

enumerator Good
enumerator MemoryHungry
enumerator RealTime

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

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.

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:

speedSpeed 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.

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.

error.h

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.

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:

errorError 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

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:
  • cError 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.

imageGuru.h

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
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

static inline bool isSupported(const ImageType type)

Check if a specific image type is supported for conversion.

Parameters:

type – The ImageType to check support for

Returns:

true if the format is supported for conversion, false otherwise

static inline std::string typeToString(const ImageType type)

Convert an ImageType enum to a string representation.

Parameters:

type – The ImageType to convert

Returns:

String representation of the image type

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.

struct imageSupport
#include <imageGuru.h>

Structure for tracking image format support status.

Public Members

ImageType type

Type of image format.

bool supported

Whether conversion is supported.

imagebuffer.h

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

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.

imageconverter.h

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:

  1. Validates input dimensions

  2. Loads and decodes input image data

  3. Resizes image if necessary

  4. Configures the AVIF encoder based on provided settings

  5. Converts RGB data to YUV colorspace

  6. 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:

  1. Converts JavaScript data to C++ vector

  2. Detects the image type

  3. Validates the image can be processed

  4. Calls convert_image to perform the actual conversion

  5. 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

result.h

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.

using Result = std::variant<ImgaePtr, avifResult, Error>

Result type that can hold either an image buffer or an error.

This variant type is used as the return value for conversion operations, allowing functions to return either a successful result (image data) or an error condition.

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)

Public Members

Result result

The wrapped Result variant.

avif_helper.h

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:

Result containing either OK status or an Error with details

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

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

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)

Implementation Files

error.cpp

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:

errorError 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

bind.cpp

Functions

EMSCRIPTEN_BINDINGS(ImageBuffer)
EMSCRIPTEN_BINDINGS(ImageConverter)
EMSCRIPTEN_BINDINGS(avif_enums)
EMSCRIPTEN_BINDINGS(ErrorHandling)

imageconverter.cpp

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:

  1. Validates input dimensions

  2. Loads and decodes input image data

  3. Resizes image if necessary

  4. Configures the AVIF encoder based on provided settings

  5. Converts RGB data to YUV colorspace

  6. 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:

  1. Converts JavaScript data to C++ vector

  2. Detects the image type

  3. Validates the image can be processed

  4. Calls convert_image to perform the actual conversion

  5. 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