vcodecimxvpu_web_logo

VCodecImxVpu C++ library

v1.0.3

Table of contents

Overview

The VCodecImxVpu C++ library provides hardware video encoding for the H264 codec on NXP i.MX8M Mini-class boards using the Hantro H1 VPU encoder directly. The library is written using the C++17 standard and is supplied as source code only. It is a CMake project. The library supports only Linux and was tested on the i.MX8M Mini. The VCodecImxVpu video codec class inherits the interface and data structures from the VCodec interface library. The library depends on the VCodec library (codec interface), the Frame library (video frame class, used by VCodec), the Logger library (log messages) and the Hantro H1 encoder package of the board: the headers (h264encapi.h, ewl.h and others) in the /usr/include/hantro_enc folder and the libhantro_h1 library. The encoder uses the /dev/mxc_hantro_h1 device and DMA memory that libhantro_h1 allocates through a DMA memory device of the board (/dev/dma_heap/linux,cma-uncached on the test board with Linux 6.12): the application needs read and write access to both devices (root, or the access given to the user, for example by the group video). The source frames must have the NV12 pixel format, the result is an H264 Annex B byte stream.

VCodecImxVpu is general-purpose software: it is not tied to any sector or application, and the developer of a program decides what the program does with it.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 14.07.2026 First version.
1.0.1 12.10.2026 - Submodules updated.
1.0.2 19.10.2026 - Sub-repositories removed: the libraries Frame, VCodec and Logger are in the folders next to the repository or are added by the parent project.
- H1Encoder class moved into the library (src/impl).
- Frame rates with a fraction (29.97 FPS and others) fixed.
- Time increment of the encoder fixed for frame rates with a fraction.
- GOP size above 300 fixed.
- Checks of the parameters and of the source and result frames added.
- Size of the encoded data checked.
- SPS parsing checks added.
- Compiler warnings fixed, hardening compiler options added.
- Test application and example updated.
- Documentation updated.
1.0.3 21.11.2026 - CMake: hardening flags are checked with -Werror, the build with Clang 15 for AArch64 has no warnings.

Library files

The library is supplied as source code only. The user is provided with a set of files in the form of a CMake project (repository). The repository structure is shown below:

CMakeLists.txt ---------------- Main CMake file of the library.
src --------------------------- Folder with library source code.
    CMakeLists.txt ------------ CMake file of the library.
    VCodecImxVpu.h ------------ Main library header file.
    VCodecImxVpuVersion.h ----- Header file with library version.
    VCodecImxVpuVersion.h.in -- File for CMake to generate version header.
    VCodecImxVpu.cpp ---------- C++ implementation file.
    impl ---------------------- Folder with implementation files.
        H1Encoder.h ----------- Header file of the Hantro H1 encoder class.
        H1Encoder.cpp --------- C++ implementation file of the encoder class.
test -------------------------- Folder for test application.
    CMakeLists.txt ------------ CMake file for test application.
    main.cpp ------------------ Source C++ file of test application.
example ----------------------- Folder for simple example.
    CMakeLists.txt ------------ CMake file of example.
    main.cpp ------------------ Source C++ file of example.

VCodecImxVpu class description

VCodecImxVpu class declaration

The VCodecImxVpu class is declared in the VCodecImxVpu.h file. All methods are thread-safe (the calls of one object are executed one after another) and do not throw exceptions: a failure (also an out of memory condition) is reported by the return value. Class declaration:

namespace rapidpixel
{
class VCodecImxVpu : public VCodec
{
public:

    /// Class constructor.
    VCodecImxVpu();

    /// Class destructor.
    ~VCodecImxVpu() override;

    /// Copy and move are not allowed (the object owns an encoder).
    VCodecImxVpu(const VCodecImxVpu&) = delete;
    VCodecImxVpu(VCodecImxVpu&&) = delete;
    VCodecImxVpu& operator=(const VCodecImxVpu&) = delete;
    VCodecImxVpu& operator=(VCodecImxVpu&&) = delete;

    /// Get library version.
    static std::string getVersion();

    /// Encode video frame.
    bool transcode(Frame& src, Frame& dst) override;

    /// Set parameter value.
    bool setParam(VCodecParam id, float value) override;

    /// Get parameter value.
    float getParam(VCodecParam id) override;

    /// Execute command.
    bool executeCommand(VCodecCommand id) override;
};
}

getVersion method

The getVersion() method returns a string of the current version of the VCodecImxVpu class. Method declaration:

static std::string getVersion();

This method can be used without a VCodecImxVpu class instance:

std::cout << "VCodecImxVpu class version: " << rapidpixel::VCodecImxVpu::getVersion() << std::endl;

Console output:

VCodecImxVpu class version: 1.0.3

transcode method

The transcode(…) method is intended to encode video frames (Frame class). The video codec encodes video frame-by-frame. Method declaration:

bool transcode(Frame& src, Frame& dst) override;
Parameter Value
src Source video frame (see Frame class description). To encode video data, the src frame must have NV12 pixel format, a width that is a multiple of 4 and a height that is a multiple of 2 (both from 1 to 4096) and data (src.data is not nullptr) of at least width x height x 3 / 2 bytes (src.size). The method can not check that src.data is valid for src.size bytes. A frame size that the hardware does not support is rejected by the encoder (the H1 encoder of the test board: width from 136 to 1920, height from 96, at most 8192 macroblocks per frame).
dst Result video frame (see Frame class description). To encode video data, the dst frame must have H264 compressed format. If the width or the height of dst is not the one of src, or dst has no memory (dst.data is nullptr), dst gets new memory (width x height x 4 bytes, the memory of a Frame object for compressed formats). Otherwise the memory of dst is used and must have width x height x 4 bytes. After encoding dst has the width and the height of src, dst.size is the size of the encoded data (one Annex B access unit) and dst.frameId and dst.sourceId are the ones of src.

Returns: TRUE if the frame was encoded successfully or FALSE if not (invalid source or result frame, error of the encoder, for example no access to the devices of the encoder, not enough memory). If FALSE is returned dst is not changed.

The encoder is created for the first frame and is created again when the frame size changes, when BITRATE_KBPS, FPS, GOP or H264_PROFILE is set and after the RESET and MAKE_KEY_FRAME commands. The first frame of an encoder and every GOP-th frame after it are key (IDR) frames. If the encoder can not be created, the next frame tries again. An invalid source frame does not change the encoder: the stream continues with the next valid frame. The SPS and the PPS are in front of every key frame. The library checks the frame cropping of the SPS of the encoder: an SPS with a cropping that is not the one of the frame size (strict decoders reject it) is written again with the cropping of the frame size and without VUI, an SPS with the right cropping (with its VUI) is not changed.

setParam method

The setParam(…) method is designed to set new video codec parameter values. Method declaration:

bool setParam(VCodecParam id, float value) override;
Parameter Description
id Video codec parameter ID according to the VCodecParam enum.
value Video codec parameter value. Valid values depend on the parameter ID.

Returns: TRUE if the parameter was set successfully or FALSE if not (the parameter is not supported, also an ID outside of the VCodecParam enum, or the value is invalid: NaN, infinity, out of the range of Table 2, not an integer for a parameter with a list of values). If FALSE is returned the parameter is not changed. A value of BITRATE_KBPS, FPS, GOP or H264_PROFILE is applied to the next frame, also if the parameter already has this value: the encoder is created again, the next frame is a key frame. LOG_LEVEL is applied at once.

The VCodec.h file of the VCodec library defines IDs for parameters (VCodecParam enum) and IDs for commands (VCodecCommand enum). VCodecParam declaration:

namespace rapidpixel
{
enum class VCodecParam
{
    /// [read/write] Log level: 0 - Disable, 1 - Console, 2 - File,
    /// 3 - Console and file.
    LOG_LEVEL = 1,
    /// [read/write] Bitrate, kbps. For H264 and H265 codecs.
    BITRATE_KBPS,
    /// [read/write] Minimum bitrate, kbps. For variable bitrate mode.
    MIN_BITRATE_KBPS,
    /// [read/write] Maximum bitrate, kbps. For variable bitrate mode.
    MAX_BITRATE_KBPS,
    /// [read/write] Bitrate mode: 0 - constant bitrate, 1 - variable bitrate.
    BITRATE_MODE,
    /// [read/write] Quality 0-100%. For JPEG codecs.
    QUALITY,
    /// [read/write] FPS. For H264 and H265 codecs.
    FPS,
    /// [read/write] GOP size. For H264 and H265 codecs.
    GOP,
    /// [read/write] H264 profile: 0 - Baseline, 1 - Main, 2 - High.
    H264_PROFILE,
    /// [read/write] Codec type. Depends on implementation.
    TYPE,
    /// [read/write] Custom parameter 1. Depends on implementation.
    CUSTOM_1,
    /// [read/write] Custom parameter 2. Depends on implementation.
    CUSTOM_2,
    /// [read/write] Custom parameter 3. Depends on implementation.
    CUSTOM_3
};
}

Table 2 - Video codec parameters description. Some parameters are not supported by the VCodecImxVpu library.

Parameter Access Description
LOG_LEVEL read / write Logging mode (integer values only). Values:
0 - Disable (default).
1 - Only terminal (console).
2 - Only file.
3 - File and terminal.
The log file is written by the Logger library into the folder set by Logger::setSaveLogParams(…); without these settings no log file is written.
BITRATE_KBPS read / write Bitrate, kbps, from 100 to 60000 (limit of the rate control of the encoder); the integer part of the value is used. Default: 5000 kbps. According to this value, FPS, and GOP size, the video codec calculates parameters for H264 encoding.
MIN_BITRATE_KBPS read / write Not supported by the VCodecImxVpu library.
MAX_BITRATE_KBPS read / write Not supported by the VCodecImxVpu library.
BITRATE_MODE read / write Not supported by the VCodecImxVpu library.
QUALITY read / write Not supported by the VCodecImxVpu library.
FPS read / write Frames per second, from 1 to 1000. Default value is 30. The encoder gets the frame rate as a fraction with a denominator up to 1001 (for example 29.97 is 2997 / 100, 30000 / 1001 is exact). According to this value, bitrate, and GOP size, the video codec calculates parameters for H264 encoding.
GOP read / write GOP size (period of key frames), from 1; the integer part of the value is used. Value: 1 - each output frame is a key frame, 20 - each 20th frame is a key frame, etc. Default value is 30. The rate control of the encoder uses at most 300 frames as the distance of key frames.
H264_PROFILE read / write H264 profile for H264 encoding (integer values only):
0 - Baseline (default).
1 - Main.
2 - High.
TYPE read / write Not supported by the VCodecImxVpu library.
CUSTOM_1 read / write Not supported by the VCodecImxVpu library.
CUSTOM_2 read / write Not supported by the VCodecImxVpu library.
CUSTOM_3 read / write Not supported by the VCodecImxVpu library.

getParam method

The getParam(…) method is designed to obtain video codec parameter values. Method declaration:

float getParam(VCodecParam id) override;
Parameter Description
id Video codec parameter ID according to the VCodecParam enum (see Table 2).

Returns: Parameter value or -1 if the parameter is not supported by the VCodecImxVpu library (see Table 2).

executeCommand method

The executeCommand(…) method is designed to execute video codec commands. Method declaration:

bool executeCommand(VCodecCommand id) override;
Parameter Description
id Video codec command ID according to the VCodecCommand enum.

Returns: TRUE if the command was accepted or FALSE if not (unknown command ID).

The VCodec.h file of the VCodec library defines IDs for parameters (VCodecParam enum) and IDs for commands (VCodecCommand enum). VCodecCommand declaration:

enum class VCodecCommand
{
    /// Reset.
    RESET = 1,
    /// Generate key frame. For H264 and H265 codecs.
    MAKE_KEY_FRAME
};

Table 3 - Video codec commands description. Some commands may be unsupported by particular video codec classes.

Command Description
RESET Reset codec: the encoder is created again for the next frame, which is a key frame. The parameters are not changed.
MAKE_KEY_FRAME Generate a key frame for the H264 codec: the encoder is created again for the next frame, which is a key frame with the SPS and the PPS.

Build and connect to your project

The library is built on Linux only (CMake stops with an error on other systems). Before compiling, the Hantro H1 encoder package of the board must be available: the headers (h264encapi.h, ewl.h and others) in the /usr/include/hantro_enc folder and the libhantro_h1 library on the board, or the same files in the sysroot of the SDK of the board for a cross build. CMake finds them (see HANTRO_H1_INCLUDE_DIR and HANTRO_H1_LIB in CMake options) and stops with an error if they are not found.

Build stand alone

The repository does not contain sub-repositories. The libraries VCodecImxVpu depends on (Frame, VCodec, Logger) must be placed in the same folder as VCodecImxVpu: copy their folders, for example from the folder modules of the RapidPixel SDK. The folder structure must be:

<work folder>
    VCodecImxVpu
    Frame
    VCodec
    Logger

Typical commands to build the library, the test application and the example:

cd VCodecImxVpu
mkdir build
cd build
cmake ..
make

If VCodecImxVpu is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame, ../VCodec and ../Logger (in this order) before the library itself. If a folder does not exist CMake stops with an error. To build the library without the test application and the example, use the following command instead of cmake .. (see CMake options):

cmake .. -D_SUBMODULE_CACHE_OVERWRITE=OFF -D_VCODEC_IMX_VPU_TEST=OFF -D_VCODEC_IMX_VPU_EXAMPLE=OFF

CMake options

Table 4 - CMake options of the repository. In the options below ${PARENT} is the prefix defined by the top-level project (empty if VCodecImxVpu is the top-level project).

Option Default Description
${PARENT}_VCODEC_IMX_VPU ON Build the library.
${PARENT}_VCODEC_IMX_VPU_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_VCODEC_IMX_VPU_EXAMPLE ON (stand alone), OFF (included in other project) Build the example.
${PARENT}_SUBMODULE_CACHE_OVERWRITE ON Forced rewriting of the options above in the CMake cache. The top-level project sets it to OFF when it includes VCodecImxVpu as a sub-repository. A stand alone build changes the options above only with this option OFF.
CMAKE_BUILD_TYPE Release (if not specified) Build type.
HANTRO_H1_INCLUDE_DIR Folder of h264encapi.h found by CMake (hantro_enc subfolder of an include folder, /usr/include/hantro_enc on the board) Folder of the headers of the Hantro H1 encoder.
HANTRO_H1_LIB libhantro_h1 found by CMake Library of the Hantro H1 encoder.

Connect to your project

If you want to connect the VCodecImxVpu library to your CMake project as source code, you can follow these steps. For example, if your repository has the following structure:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp

Create folder 3rdparty in your repository and copy the folders of the libraries Frame, VCodec, Logger and VCodecImxVpu there (for example from the folder modules of the RapidPixel SDK). The new structure of your repository will be:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    Frame
    VCodec
    Logger
    VCodecImxVpu

Create a CMakeLists.txt file in the 3rdparty folder. It adds the libraries in the order of their dependencies (Frame before VCodec) and then VCodecImxVpu. The CMakeLists.txt should contain:

cmake_minimum_required(VERSION 3.13)

################################################################################
## 3RD-PARTY
## dependencies for the project
################################################################################
project(3rdparty LANGUAGES CXX)

################################################################################
## SETTINGS
## basic 3rd-party settings before use
################################################################################
# To inherit the top-level architecture when the project is used as a submodule.
SET(PARENT ${PARENT}_YOUR_PROJECT_3RDPARTY)
# Disable self-overwriting of parameters inside included subdirectories.
SET(${PARENT}_SUBMODULE_CACHE_OVERWRITE OFF CACHE BOOL "" FORCE)

################################################################################
## CONFIGURATION
## 3rd-party submodules configuration
################################################################################
SET(${PARENT}_SUBMODULE_FRAME                           ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_FRAME)
    SET(${PARENT}_FRAME                                 ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_FRAME_TEST                            OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VCODEC                          ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VCODEC)
    SET(${PARENT}_VCODEC                                ON  CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_LOGGER                          ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_LOGGER)
    SET(${PARENT}_LOGGER                                ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_LOGGER_EXAMPLE                        OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VCODEC_IMX_VPU                  ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VCODEC_IMX_VPU)
    SET(${PARENT}_VCODEC_IMX_VPU                        ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VCODEC_IMX_VPU_TEST                   OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VCODEC_IMX_VPU_EXAMPLE                OFF CACHE BOOL "" FORCE)
endif()

################################################################################
## INCLUDING SUBDIRECTORIES
## Adding subdirectories according to the 3rd-party configuration
################################################################################
if (${PARENT}_SUBMODULE_FRAME)
    add_subdirectory(Frame)
endif()

if (${PARENT}_SUBMODULE_VCODEC)
    add_subdirectory(VCodec)
endif()

if (${PARENT}_SUBMODULE_LOGGER)
    add_subdirectory(Logger)
endif()

if (${PARENT}_SUBMODULE_VCODEC_IMX_VPU)
    add_subdirectory(VCodecImxVpu)
endif()

The 3rdparty/CMakeLists.txt file adds the libraries to your project and excludes their test applications and examples (by default, the test application and example of VCodecImxVpu are excluded from compilation if VCodecImxVpu is included as a sub-repository). VCodecImxVpu does not add its dependencies when it is included in another project: your project must add them (if they are missing, the compiler stops with an error like VCodec.h: No such file or directory). Your repository’s new structure will be:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    Frame
    VCodec
    Logger
    VCodecImxVpu

Next, you need to include the 3rdparty folder in the main CMakeLists.txt file of your repository. Add the following line at the end of your main CMakeLists.txt:

add_subdirectory(3rdparty)

Next, you need to include the VCodecImxVpu library in your src/CMakeLists.txt file:

target_link_libraries(${PROJECT_NAME} VCodecImxVpu)

Done!

Simple example

This simple example generates frames in NV12 pixel format (required for the codec), encodes them and prints the size of every encoded frame. Source code:

#include <cstdint>
#include <iostream>
#include "Frame.h"
#include "VCodec.h"
#include "VCodecImxVpu.h"



namespace
{
/// Frame width, pixels.
constexpr int WIDTH{640};
/// Frame height, pixels.
constexpr int HEIGHT{480};
/// Number of frames to encode.
constexpr int FRAMES{100};
/// Number of encoding errors in a row after which the example stops.
constexpr int MAX_ERRORS{10};
}



int main()
{
    std::cout << "VCodecImxVpu v" << rapidpixel::VCodecImxVpu::getVersion() <<
    " example" << std::endl;

    // Create codec object and set params (the interface of VCodec).
    rapidpixel::VCodecImxVpu codec;
    rapidpixel::VCodec& encoder = codec;
    if (!encoder.setParam(rapidpixel::VCodecParam::BITRATE_KBPS, 10000.0f) ||
        !encoder.setParam(rapidpixel::VCodecParam::FPS, 20.0f) ||
        !encoder.setParam(rapidpixel::VCodecParam::GOP, 30.0f) ||
        !encoder.setParam(rapidpixel::VCodecParam::H264_PROFILE, 0.0f))
    {
        std::cout << "Can't set codec params" << std::endl;
        return -1;
    }

    // Source frame (NV12) and result frame (H264).
    rapidpixel::Frame srcFrame(WIDTH, HEIGHT, rapidpixel::Fourcc::NV12);
    rapidpixel::Frame dstFrame(WIDTH, HEIGHT, rapidpixel::Fourcc::H264);

    // Main loop.
    int errors = 0;
    for (int n = 0; n < FRAMES; ++n)
    {
        // Fill NV12 frame data: a pattern that moves from frame to frame.
        for (int i = 0; i < srcFrame.size; ++i)
        {
            srcFrame.data[i] = static_cast<uint8_t>(i + n);
        }
        srcFrame.frameId = n;

        // Encode data.
        if (!encoder.transcode(srcFrame, dstFrame))
        {
            std::cout << "Can't encode frame " << n << std::endl;
            if (++errors >= MAX_ERRORS)
            {
                std::cout << "Too many errors, stop" << std::endl;
                return -1;
            }
            continue;
        }
        errors = 0;

        // Show info.
        std::cout << "[" << dstFrame.frameId << "] Size " << dstFrame.size <<
        " Compression ratio: " <<
        int64_t{100} * dstFrame.size / srcFrame.size << "%" << std::endl;
    }

    return 0;
}

Test application

The test application (VCodecImxVpu/test/main.cpp) for the VCodecImxVpu C++ library checks the library: version, default parameters, accepted and rejected parameter values, commands, encoding of several frame sizes (also widths that are not a multiple of 16) and H264 profiles (key frames, SPS with the frame size, the profile and the level), key frames after commands and parameter changes, frame size changes, frame rates with a fraction, invalid source and result frames, calls from several threads and random calls with valid and invalid arguments. The test application must run on the board (it uses the Hantro H1 encoder). It prints the result of every test, writes no files and returns 0 if all tests passed (1 if not). To run the application, perform the following commands on Linux:

cd <application folder>
sudo chmod +x VCodecImxVpuTest
sudo ./VCodecImxVpuTest

After starting, you will see the following output (the number of frames of the thread test depends on the speed of the board):

=================================================
VCodecImxVpu v1.0.3 test
=================================================

Version:
Version 1.0.3
OK

Default parameters:
OK

Parameter ranges:
OK

Commands:
OK

Encoding:
320x240 profile 0: 12 frames
320x240 profile 1: 12 frames
320x240 profile 2: 12 frames
640x480 profile 0: 12 frames
640x480 profile 1: 12 frames
640x480 profile 2: 12 frames
1280x720 profile 0: 12 frames
1280x720 profile 1: 12 frames
1280x720 profile 2: 12 frames
1920x1080 profile 0: 12 frames
1920x1080 profile 1: 12 frames
1920x1080 profile 2: 12 frames
352x288 profile 0: 12 frames
352x288 profile 1: 12 frames
352x288 profile 2: 12 frames
1912x1078 profile 0: 12 frames
1912x1078 profile 1: 12 frames
1912x1078 profile 2: 12 frames
724x406 profile 0: 12 frames
724x406 profile 1: 12 frames
724x406 profile 2: 12 frames
OK

Key frames:
OK

Frame size change:
OK

Frame rates:
OK

Invalid source frames:
OK

Result frames:
OK

Threads:
Encoded frames: 459
OK

Random calls:
2000 calls
OK

All tests passed

Table of contents