vdecoderh264_web_logo

VDecoderH264 C++ library

v1.1.5

Table of contents

Overview

The VDecoderH264 C++ library provides a standalone software H.264 (AVC) video decoder for Linux, Windows, and embedded platforms. Key features:

  • No third-party decoding code: Contains complete, self-contained implementations of NAL parsing, Exp-Golomb bitstream reading, CABAC / CAVLC entropy decoding, inverse quantization, 4x4 / 8x8 IDCT transforms, Intra 4x4 / Intra 8x8 / Intra 16x16 / Chroma prediction, Inter motion compensation (sub-pel 6-tap FIR interpolation and bi-prediction), DPB (Decoded Picture Buffer) management, and an adaptive in-loop deblocking filter. No third-party media frameworks or OS-specific decoding services are required: the library uses only the C++ standard library and the libraries VCodec (codec interface) and Frame (video frame structure).
  • Pure C++ source code: Built from C++17 source code with SIMD intrinsics on x86 (SSE4.1, AVX2) and a portable C++ implementation of the same kernels. Uses no precompiled libraries, preloaded shared objects, or runtime dynamic loading (.dll, .so, LoadLibrary, dlopen).
  • Runs on any little-endian CPU: the pixel kernels are compiled for AVX2, SSE4.1 and portable C++ and the best level is selected at run time with CPUID; only the two kernel files get instruction-set flags, so the library never needs an instruction the CPU does not have. See SIMD acceleration and portability.
  • Cross-platform: Windows (MSVC, x86-64), Linux x86-64 (GCC, Clang) and other little-endian processors such as Linux ARM64 / AArch64 (GCC, Clang, portable C++ kernels). The decoded output is bit-identical on all platforms and for every SIMD level.
  • Supported streams: progressive 8-bit 4:2:0 Baseline, Main and High profile streams: CAVLC and CABAC, P and B slices, weighted prediction, 4x4 / 8x8 transforms, custom scaling matrices, constrained intra prediction, multiple slices. Progressive 8-bit 4:4:4 streams (High 4:4:4 Predictive profile, chroma_format_idc 3 with the colour components in one picture) with the 4x4 transform: Cb and Cr are decoded at full resolution like luma (separate CAVLC and CABAC contexts, intra prediction, motion compensation and deblocking of luma) and converted to the 4:2:0 chroma of NV12 by the rounded mean of 2 x 2 samples. Not supported (no output): streams with interlaced coding (frame_mbs_only_flag 0: PAFF, MBAFF), 4:2:2 / monochrome, 4:4:4 with separate colour planes or with the 8x8 transform (transform_8x8_mode_flag 1), bit depth above 8 or lossless coding, and pictures with slice groups (FMO) or redundant pictures. SP / SI slices and data partitions are not decoded: their macroblocks are copied from the most recent reference picture, like the macroblocks of lost or corrupted slices.
  • Motion Vector Extraction: Provides direct spatial motion vector extraction through the getMotionVector() method, returning [x, y, dx, dy] for every decoded macroblock.
  • NV12 Output: Decodes Annex B elementary streams into standard NV12 uncompressed video frames (Y plane followed by interleaved UV plane), ready for display or further processing.
  • Fast MV-Only Extraction: Supports lightweight motion vector extraction mode (CUSTOM_1 = 1.0f), which extracts motion vectors while bypassing NV12 frame allocation and memory copying, and a parse-only motion vector mode (CUSTOM_1 = 2.0f), which additionally skips all pixel reconstruction and deblocking (faster than CUSTOM_1 = 1.0f, same motion vectors).
  • Single-threaded by default, optional multi-threading: By default the decoder works only in the thread which calls transcode(...). Optionally (CUSTOM_2) the calling thread parses the bitstream while worker threads reconstruct and deblock the macroblock rows of the pictures (wavefront order, up to two pictures at a time). transcode(...) stays synchronous and returns exactly the same frames and motion vectors in the same calls (bit-identical output for any number of threads, also for damaged streams).
  • Standard VCodec Interface: Inherits from the rapidpixel::VCodec interface (VCodec library), so the decoder can be used wherever the SDK expects a VCodec.
  • C++17 Architecture: Uses the PIMPL pattern: the public header contains no internal decoder structures.

The VDecoderH264 class depends on the VCodec class, which defines the interface of video codecs, and on the Frame library, which defines the video frame structure. The example application uses SimpleUI for window display and drawing vector overlays, and a lightweight built-in H.264 elementary stream parser (H264Parser). The library uses the C++17 standard.

VDecoderH264 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 03.10.2026 - First version.
1.1.0 06.10.2026 - Decoding engine rewritten from the H.264 specification.
- Undefined behaviour of the previous engine removed (out-of-bounds neighbour access, misaligned loads, shifts of negative values, null pointer arithmetic, reachable assert).
- Multi-threading by macroblock rows with frame pipelining, identical output for any number of threads.
- The memory of the frames waiting for retrieval is limited.
- SIMD kernels selected at run time (AVX2, SSE4.1, portable C++): no global instruction-set flags, the library runs on any CPU.
- No compiler warnings (MSVC /W4, GCC, Clang).
1.1.1 16.10.2026 - No sub-repositories: the libraries Frame and VCodec (and SimpleUI for the example) are cloned next to the repository or added by the parent project.
- Fixed reference picture list modification: a picture already at its position was duplicated (wrong prediction).
- Fixed Exp-Golomb codes longer than 57 bits (values from 2^29 - 1), which were read with wrong bits.
- Fixed signed integer overflows of picture order counts in damaged streams (MMCO 5, temporal direct scaling, POC type 1).
- Fixed: long-term reference frames beyond max_num_ref_frames could fill the picture buffer and stop the decoding.
- The decoded picture buffer and the internal output queue are limited to the largest level (MaxDpbMbs 696320).
- Output of damaged streams identical for any number of threads.
- Worker threads are woken only when the progress they wait for is reached (high CPU load with 4 and 5 threads removed).
- Consistent state after memory allocation failures; transcode(...) does not change dst when it returns false; dst.sourceId is 0.
- setParam(...) rejects NaN, infinity and values other than the documented ones; executeCommand(RESET) returns false if memory can not be allocated.
- The compilation stops on big-endian CPUs (not supported).
- Strict compiler warnings and exploit mitigation flags, no global compiler definitions.
- Example: the H.264 file parser checks the sizes and syntax elements of the stream.
- Documentation corrected (multi-threading, unsupported streams, parameter values).
1.1.2 25.10.2026 - The library links the thread library (CMake target Threads::Threads): programs built on a C library older than glibc 2.34 no longer need -pthread.
1.1.3 11.11.2026 - Decoding of progressive 8-bit 4:4:4 streams (High 4:4:4 Predictive profile, CAVLC and CABAC, 4x4 transform): Cb and Cr are decoded like luma and converted to the NV12 chroma by the mean of 2 x 2 samples. The output was checked against FFmpeg (bit-identical luma and chroma) with thermal camera recordings (CAVLC, intra 16x16, P slices; CABAC, intra 4x4, B pyramid, weighted prediction, deblocking).
- The scaling matrices of 4:4:4 parameter sets (12 lists) are parsed; the cropping of 4:4:4 streams is in single samples (a frame of odd visible size gets one more decoded column or row).
- Not supported (no output, as before): 4:4:4 with separate colour planes or with the 8x8 transform, lossless coding.
1.1.4 17.11.2026 - Build without warnings with GCC 9 (Jetson Nano, Ubuntu 18.04): variables and parameters that only one variant of a template uses are marked [[maybe_unused]].
1.1.5 21.11.2026 - CMake: hardening flags are checked with -Werror, the build with Clang 15 for AArch64 has no warnings.

Library files

The repository structure is organized as follows:

CMakeLists.txt ---------------- Main CMake build configuration.
README.md --------------------- Documentation and usage guide.
static ------------------------ Images of the documentation.
src --------------------------- Library source code.
    CMakeLists.txt ------------ CMake script for VDecoderH264 library (SIMD checks, per-file instruction-set flags).
    VDecoderH264.h ------------ Public library interface (PIMPL).
    VDecoderH264.cpp ---------- Public library implementation wrapper.
    VDecoderH264Version.h ----- Version definition header.
    VDecoderH264Version.h.in -- Template for CMake version generation.
    impl ---------------------- Internal decoder implementation files.
        VDecoderH264Impl.h ---- Internal PIMPL class declaration.
        VDecoderH264Impl.cpp -- PIMPL class implementation & frame buffer management.
        H264Compat.h ---------- Compiler intrinsics, bit operations and SIMD vector types (SSE4.1 / AVX2, portable C++).
        H264Engine.h ---------- Decoding engine interface: decoded pictures and motion vector grid.
        H264Engine.cpp -------- Decoder core: bitstream, parameter sets, DPB, reconstruction order, threads; portable kernels.
        H264EngineInternal.h -- Internal data structures (parameter sets, pictures, macroblock data, kernel table).
        H264Pipeline.h -------- Progress counters shared by the parsing thread and the worker threads.
        H264Pipeline.cpp ------ Progress counter implementation (spinning, then blocking wait).
        H264PixelKernels.inl -- Pixel kernels: prediction, transforms, deblocking (compiled once per SIMD level).
        H264Slice.inl --------- Slice data: macroblock layer, CABAC / CAVLC decoding, motion vector prediction.
        x86 ------------------- x86 SIMD levels.
            H264SimdLevels.h -- Levels built into the library, kernel sets of the levels.
            H264SimdLevels.cpp - Choice of the level for the running CPU (CPUID, XGETBV), no instruction-set flags.
            H264PixelSse41.cpp - Pixel kernels compiled for SSE4.1.
            H264PixelAvx2.cpp -- Pixel kernels compiled for AVX2.
example ----------------------- Standalone sample application (uses the SimpleUI library).
    H264Parser.h -------------- Standalone H.264 elementary stream parser header.
    H264Parser.cpp ------------ Standalone H.264 elementary stream parser implementation.
    CMakeLists.txt ------------ Example build configuration.
    main.cpp ------------------ Example demonstrating video decoding and MV extraction.

VDecoderH264 class description

VDecoderH264 class declaration

The VDecoderH264 class is declared in VDecoderH264.h:

namespace rapidpixel
{
class VDecoderH264 : public VCodec
{
public:

    /// Class constructor.
    VDecoderH264();

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

    /// A decoder can not be copied or moved.
    VDecoderH264(const VDecoderH264&) = delete;
    VDecoderH264(VDecoderH264&&) = delete;
    VDecoderH264& operator=(const VDecoderH264&) = delete;
    VDecoderH264& operator=(VDecoderH264&&) = delete;

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

    /// Decode H.264 data to an NV12 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 codec command.
    bool executeCommand(VCodecCommand id) override;

    /// Get motion vectors of the last frame returned by transcode(...).
    const std::vector<std::vector<float>>& getMotionVector();
};
}

The class is not thread-safe: an object must not be used from several threads at the same time without external synchronization. Different objects are independent.

getVersion method

The getVersion() method returns a string with the current version of the library:

static std::string getVersion();

Example usage:

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

Terminal output:

VDecoderH264 version: 1.1.5

transcode method

The transcode(…) method decodes H.264 Annex B data into an uncompressed NV12 video frame.

bool transcode(Frame& src, Frame& dst) override;
Parameter Type Description
src Frame& Source data. src.fourcc must be Fourcc::H264, src.data points to src.size bytes of complete NAL units of an Annex B byte stream (one or more NAL units with start codes, or one NAL unit without start code). A NAL unit must not be split between calls. src.size = 0 marks the end of the stream (src.data may be nullptr then).
dst Frame& Result frame. On success the decoder sets dst.width and dst.height (visible size after cropping), dst.fourcc = Fourcc::NV12, dst.size = width * height * 3 / 2, dst.frameId and dst.sourceId = 0. If dst.data is not nullptr and dst.size is at least the NV12 size, the frame is written into the existing buffer (dst.data must be valid for dst.size bytes); otherwise dst gets new memory. In the modes CUSTOM_1 = 1.0f and 2.0f, dst.size is 0 and no pixel data is written.

Returns: true if dst received a frame; false if no frame is ready yet (for example after parameter sets only, or when no frame is left at the end of the stream), if src is invalid (other fourcc, negative size, nullptr data with size > 0), if the data is not supported or corrupted, or if memory could not be allocated (the rest of the data of the call is dropped then). If false is returned, dst is not changed.

At EOF, repeatedly pass a source frame with fourcc = Fourcc::H264 and size = 0 until transcode(...) returns false. This returns all queued and delayed pictures, including B-frames. No input data pointer is required for this call. dst.frameId is the decoded picture identifier in decoding order; it is not copied from the current input packet. The decoder copies NAL data internally, so the input buffer requires no prefix or suffix padding.

If one call carries several pictures, the first one is returned and the others wait in a queue for the following calls. The memory of the waiting pictures is limited to 1 GiB: when a call produces more, the oldest waiting pictures are dropped (this happens only if the caller passes much more data than it reads frames, for example a damaged stream that expands to many large pictures).

4:4:4 streams (chroma_format_idc 3, the colour components in one picture): Cb and Cr are decoded at full resolution like luma, the NV12 chroma sample is the rounded mean of 2 x 2 decoded samples. A 4:4:4 frame whose visible size is odd gets one more decoded column or row (NV12 needs an even size).

Not supported (no frames): sequences with interlaced coding (frame_mbs_only_flag 0), 4:2:2 or monochrome sampling, 4:4:4 with separate colour planes or with the 8x8 transform (transform_8x8_mode_flag 1), a bit depth above 8 or lossless coding, and pictures with slice groups or redundant picture counts. SP / SI slices and data partitions (NAL unit types 2 to 4) are not decoded. The macroblocks of missing, corrupted or not decoded slices are copied from the most recent reference picture (mid-gray if there is none). The largest picture is 139264 macroblocks (for example 8192 x 4352 pixels), at most 1055 macroblocks in each direction.

getMotionVector method

The getMotionVector() method retrieves the spatial motion vectors for the most recently decoded video frame.

const std::vector<std::vector<float>>& getMotionVector();

Returns: A two-dimensional vector where each element is a 4-component vector [x, y, dx, dy]:

  • x: Horizontal pixel coordinate of the visible top-left corner of the 16x16 macroblock after SPS cropping.
  • y: Vertical pixel coordinate of the visible top-left corner of the 16x16 macroblock after SPS cropping.
  • dx: Horizontal motion displacement in pixels (average of the 16 4x4-block motion vectors of the macroblock, list 0, or list 1 for macroblocks predicted from list 1 only).
  • dy: Vertical motion displacement in pixels (same averaging).

The method returns one element per macroblock intersecting the visible picture, in raster order (for example 8160 elements for 1920x1080). A crop through a macroblock includes its visible portion; its position is clipped to the visible image and its displacement still averages the complete macroblock. For intra macroblocks (and all macroblocks of I / IDR frames) dx = dy = 0. The vector is empty before the first frame and after RESET. The returned reference points to an internal buffer of the decoder: it stays valid for the lifetime of the decoder, its content is changed by transcode(...) and RESET.

Example:

rapidpixel::VDecoderH264 decoder;
// ... frames are decoded with decoder.transcode(...)
const std::vector<std::vector<float>>& mvs = decoder.getMotionVector();
for (const std::vector<float>& mv : mvs)
{
    const float x = mv[0];
    const float y = mv[1];
    const float dx = mv[2];
    const float dy = mv[3];
    // Process or visualize motion vector
    std::cout << x << " " << y << " " << dx << " " << dy << std::endl;
}

setParam method

The setParam(…) method configures decoder parameters.

bool setParam(VCodecParam id, float value) override;
Parameter Type Description
id VCodecParam Parameter identifier from the VCodecParam enum.
value float Value to assign to the parameter. NaN, infinity, values other than the ones listed below and values of unsupported parameters are rejected.

Supported parameters:

  • VCodecParam::LOG_LEVEL: integer value with a magnitude below 1e9 (default 0.0f), stored and returned by getParam(...). The decoder writes no log.
  • VCodecParam::TYPE: integer value with a magnitude below 1e9 (default 0.0f), stored and returned by getParam(...). The decoder is always a software decoder.
  • VCodecParam::CUSTOM_1: Decoding mode (default 0.0f):
    • 0.0f - full video decoding to NV12 + motion vectors.
    • 1.0f - motion vectors only: the frame is fully decoded, but NV12 frame buffer copy is skipped (dst gets width, height, fourcc = NV12 and size = 0).
    • 2.0f - motion vectors from parsing only: no pixel reconstruction and no deblocking, dst is set as in mode 1.0f. Motion vectors and the sequence of returned frames are identical to modes 0.0f and 1.0f.
    • Switching between 0.0f and 1.0f is possible at any time (bit-exact). Mode 2.0f does not reconstruct pixels, so after switching from 2.0f back to 0.0f the pictures are correct only from the next IDR picture (motion vectors are always correct).
  • VCodecParam::CUSTOM_2: Number of decoding threads (default 1.0f):
    • 1.0f - single-threaded decoding (default): everything is decoded in the thread which calls transcode(...), no worker threads are created.
    • 0.0f - automatic: up to 4 threads depending on the number of logical processors.
    • N >= 2 (integer) - parsing thread plus N - 1 worker threads (at most 5 threads: larger values use 5).
    • The output is bit-identical for every value. The value can be changed at any time: the number of threads changes at the start of the next picture. If a thread can not be created, the decoder uses fewer threads.
  • VCodecParam::CUSTOM_3: Color range control for output NV12 frame (default 1.0f):
    • 1.0f: Automatic (default). If bitstream signals or infers Limited Range and frame luminance data analysis confirms limited dynamic range [16..235], automatically expands luma [16..235] and chroma [16..240] to Full Range [0..255] during NV12 assembly. Full-range frames are preserved without clipping or alteration.
    • 0.0f: Disabled / pass-through: pass-through raw decoded samples without range expansion.
    • 2.0f: Forced expansion: always expand Limited Range to Full Range regardless of bitstream headers or pixel statistics.

Returns: true if the parameter was set, false otherwise (the parameter keeps its value).

getParam method

The getParam(…) method queries parameter values from the decoder.

float getParam(VCodecParam id) override;

Returns: Value of the specified parameter, or -1.0f if unsupported.

executeCommand method

The executeCommand(…) method sends control commands to the decoder.

bool executeCommand(VCodecCommand id) override;

Supported commands:

  • VCodecCommand::RESET: drops all pictures (also the frames waiting for output) and parameter sets; the decoder waits for a new stream. The parameters set with setParam(...) keep their values.

Returns: true if the command was executed; false for other commands, or if the memory for the new decoding state could not be allocated (the decoder is not changed then).

Build and connect to your project

Build stand alone

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

<work folder>
    VDecoderH264
    Frame
    VCodec
    SimpleUI

Typical commands to build the library and the example:

cd VDecoderH264
mkdir build
cd build
cmake ..
make

On Windows use cmake --build . --config Release instead of make. If VDecoderH264 is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame and ../VCodec (in this order) before the library itself, and the folder ../SimpleUI before the example. If a folder does not exist CMake stops with an error. The repository has no test application.

CMake options

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

Option Default Description
${PARENT}_VDECODERH264 ON Build the library.
${PARENT}_VDECODERH264_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 VDecoderH264 as a sub-repository.
CMAKE_BUILD_TYPE Release (if not specified) Build type.
VDECODERH264_ENABLE_SIMD ON Build the SSE4.1 and AVX2 kernels of x86 CPUs (OFF: portable C++ kernels only, see SIMD acceleration and portability).

Connect to your project

The library does not add its dependencies when it is included in another CMake project: the project adds them. To connect the VDecoderH264 library to your CMake project as source code, create folder 3rdparty in your repository and copy the folders of the libraries Frame, VCodec and VDecoderH264 there (for example from the folder modules of the RapidPixel SDK). For example, if your repository has the structure:

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

The new structure of your repository:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    Frame
    VCodec
    VDecoderH264

Create the CMakeLists.txt file in the 3rdparty folder. It adds the libraries in dependency order: Frame, VCodec, then VDecoderH264. The file 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_VDECODERH264                    ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VDECODERH264)
    SET(${PARENT}_VDECODERH264                          ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VDECODERH264_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_VDECODERH264)
    add_subdirectory(VDecoderH264)
endif()

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 VDecoderH264 library in your src/CMakeLists.txt file:

target_link_libraries(${PROJECT_NAME} VDecoderH264)

Include the public header in your code:

#include "VDecoderH264.h"

If the project does not add the Frame and VCodec libraries, the compilation of the library stops with an error such as VCodec.h: No such file or directory.

SIMD acceleration and portability

The pixel kernels of the decoder (inter prediction, inverse transforms, intra prediction, deblocking filter) are written once (src/impl/H264PixelKernels.inl) on a small vector type and compiled for several instruction-set levels. The level is chosen once per process, when the first decoder is created:

CPU Kernels used How the level is chosen
x86 / x86-64 AVX2 -> SSE4.1 -> portable C++ CPUID (SSSE3 and SSE4.1 for the SSE4.1 level). AVX2 also needs an operating system that saves the YMM registers (OSXSAVE and XGETBV).
ARM64 / AArch64 and any other CPU portable C++ No intrinsics are compiled.

Everything else (bitstream parsing, CABAC / CAVLC, parameter sets, DPB, threads, NV12 output) is compiled without instruction-set flags. A binary built with any compiler therefore starts and decodes on every CPU of its architecture: checked with emulated Haswell (AVX2), Nehalem (SSE4.2), Penryn (SSE4.1) and Conroe (SSSE3, portable kernels) CPUs. The decoded output is bit-identical for every level.

Instruction-set flags are applied per source file, never globally:

Source files Flags
src/impl/x86/H264PixelSse41.cpp -msse4.1 (GCC / Clang). MSVC needs no flag.
src/impl/x86/H264PixelAvx2.cpp -mavx2 (GCC / Clang), /arch:AVX2 (MSVC).
All other files, including the CPU detection (src/impl/x86/H264SimdLevels.cpp) and the portable kernels No instruction-set flags (no -march=native, no global -mavx2 or /arch:AVX2).

The kernel code of each level is in its own namespace (portable, sse41, avx2), so that the linker never replaces a function of a lower level by a copy compiled with AVX2 or SSE4.1 code generation. CMake checks with try_compile that the compiler can build the x86 kernels. If it cannot (old compiler, unusual toolchain, universal macOS binary), the affected levels are left out, a message is printed during configuration and the next lower level is used. Options:

Option / macro Effect
-DVDECODERH264_ENABLE_SIMD=OFF Builds the portable kernels only (defines VDECODERH264_NO_SIMD).
VDECODERH264_NO_SSE41, VDECODERH264_NO_AVX2 Leave out the SSE4.1 and AVX2 kernels (VDECODERH264_NO_SSE41) or only the AVX2 kernels. CMake defines them automatically when a check fails.

CMake adds these macros as private definitions of the VDecoderH264 target. Without CMake, compile all src/**/*.cpp files and the src/*.cpp files of the Frame and VCodec libraries as C++17 (with the src folders of Frame and VCodec as include paths), add the flags of the table to the two kernel files (or define the macros above) and link the system thread library (-pthread).

The decoder needs a little-endian CPU, a 32-bit int and an arithmetic right shift of negative integers: the compilation stops with an error otherwise (checks in src/impl/H264Compat.h). The library and the example are built and the decoder is tested with GCC 12 and 13 and Clang 15 and 18 on Linux x86-64, GCC 13 and Clang 18 for Linux AArch64 (run under emulation) and MSVC 14.51 (Visual Studio 2026) on Windows x86-64.

Simple example

The example application (example/main.cpp) opens an H.264 elementary stream file, decodes the frames to NV12, extracts the motion vectors and shows the luma of the frames with the motion vectors using SimpleUI:

#include <cmath>
#include <cstring>
#include <exception>
#include <iostream>
#include <string>
#include <vector>
#include "VDecoderH264.h"
#include "H264Parser.h"
#include "SimpleUi.h"



namespace
{
/// Limit of float values which can be converted to int. 2^31 is exactly
/// representable as float, so (-LIMIT <= value < LIMIT) is the exact range
/// of int.
constexpr float INT_RANGE_LIMIT{2147483648.0f};

/// Smallest motion of a drawn motion vector, pixels.
constexpr float MIN_DRAWN_MOTION{0.5f};

/// Time to wait for a key after a frame is shown, ms.
constexpr int KEY_WAIT_MS{30};

/// Key code of the Escape key.
constexpr int ESCAPE_KEY{27};



/// Convert a float to int. A conversion of NaN or of a value outside of the
/// int range is undefined behavior, so such values are rejected.
bool toInt(float value, int& result)
{
    if (!(value >= -INT_RANGE_LIMIT && value < INT_RANGE_LIMIT))
    {
        return false;
    }
    result = static_cast<int>(value);
    return true;
}



/// Decode the file and show the frames with their motion vectors until the
/// end of the file, the Escape key or the window is closed.
int run(const std::string& videoPath)
{
    // Open H.264 elementary stream file.
    rapidpixel::H264Parser parser;
    if (!parser.open(videoPath))
    {
        std::cerr << "Failed to open video file: " << videoPath << std::endl;
        return 1;
    }

    // Initialize decoder and UI window.
    rapidpixel::VDecoderH264 decoder;
    rapidpixel::SimpleUiWindow window("VDecoderH264 - Motion Vectors");
    window.show();

    // Input H264 frame.
    rapidpixel::Frame h264Frame(640, 480, rapidpixel::Fourcc::H264);
    // Decoded NV12 frame.
    rapidpixel::Frame nv12Frame(640, 480, rapidpixel::Fourcc::NV12);
    // Converted YUV frame.
    rapidpixel::Frame yuvFrame(640, 480, rapidpixel::Fourcc::YUV24);

    // Decode and display video frames.
    while (window.isOpen())
    {
        // At the end of the file (or after an error) the delayed frames are
        // taken with source frames of size 0.
        if (!parser.getFrame(h264Frame))
        {
            h264Frame.size = 0;
        }
        // Decode H.264 frame to NV12 format.
        if (!decoder.transcode(h264Frame, nv12Frame))
        {
            if (h264Frame.size == 0)
            {
                break;
            }
            continue;
        }

        // Convert NV12 frame to YUV format with only Y channel.
        if (nv12Frame.width != yuvFrame.width || nv12Frame.height != yuvFrame.height)
        {
            yuvFrame = rapidpixel::Frame(nv12Frame.width, nv12Frame.height,
                                         rapidpixel::Fourcc::YUV24);
        }
        if (yuvFrame.data == nullptr || nv12Frame.size < yuvFrame.size / 3)
        {
            std::cerr << "Unexpected frame size" << std::endl;
            return 1;
        }
        std::memset(yuvFrame.data, 128, static_cast<size_t>(yuvFrame.size));
        for (int i = 0; i < yuvFrame.size; i += 3)
        {
            yuvFrame.data[i] = nv12Frame.data[i / 3];
        }

        // Overlay motion vectors on the frame.
        for (const std::vector<float>& mv : decoder.getMotionVector())
        {
            if (mv.size() < 4 ||
                (std::abs(mv[2]) <= MIN_DRAWN_MOTION && std::abs(mv[3]) <= MIN_DRAWN_MOTION))
            {
                continue;
            }
            int x1{0};
            int y1{0};
            int x2{0};
            int y2{0};
            if (toInt(mv[0], x1) && toInt(mv[1], y1) && toInt(mv[0] + mv[2], x2) &&
                toInt(mv[1] + mv[3], y2))
            {
                rapidpixel::SimpleUiDraw::drawLine(yuvFrame, x1, y1, x2, y2, {0, 255, 0}, 1);
            }
        }

        // Render frame and process UI events (ESC to exit).
        window.render(yuvFrame);
        if (window.getKey(KEY_WAIT_MS) == ESCAPE_KEY)
        {
            break;
        }
    }
    return 0;
}

}



// Entry point.
int main(int argc, char* argv[])
{
    // Print library version.
    std::cout << "VDecoderH264 v" << rapidpixel::VDecoderH264::getVersion() << std::endl;

    // Get input H.264 file path.
    std::string videoPath;
    if (argc > 1)
    {
        videoPath = argv[1];
    }
    else
    {
        std::cout << "Enter path to video file (*.h264): ";
        std::getline(std::cin, videoPath);
    }
    // Quotes around a path (added by drag and drop on a console) are removed.
    if (!videoPath.empty() && (videoPath.front() == '"' || videoPath.front() == '\''))
    {
        videoPath.erase(0, 1);
    }
    if (!videoPath.empty() && (videoPath.back() == '"' || videoPath.back() == '\''))
    {
        videoPath.pop_back();
    }
    if (videoPath.empty())
    {
        videoPath = "test.h264";
    }

    try
    {
        return run(videoPath);
    }
    catch (const std::exception& e)
    {
        // memory allocation, window or drawing errors
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
}

Table of contents