
VDecoderH265 C++ library
v1.1.2
Table of contents
- Overview
- Versions
- Library files
- VDecoderH265 class description
- Build and connect to your project
- SIMD acceleration and portability
- Simple example
Overview
The VDecoderH265 C++ library provides a standalone software H.265 (HEVC) video decoder for Linux, Windows, and embedded platforms. Key features:
- No third-party decoding libraries: Contains complete, self-contained implementations of HEVC NAL parsing (SPS, PPS, slice headers; the VPS is not needed for decoding and is skipped), Exp-Golomb bitstream reading, CABAC entropy decoding, inverse quantization, 4x4 / 8x8 / 16x16 / 32x32 DCT and DST transforms, Intra prediction (Planar, DC, and 33 directional Angular modes), Inter motion compensation (fractional 7/8-tap luma and 4-tap chroma sub-pel interpolation and bi-prediction), DPB (Decoded Picture Buffer) management, Sample Adaptive Offset (SAO), and an adaptive in-loop deblocking filter. No third-party media frameworks or OS-specific decoding services are required: the library depends only on the VCodec interface library and the Frame library used by it.
- Pure C++ source code: Built from C++17 source code with SIMD intrinsics (AVX2, SSE4.1 on x86 / x86-64, NEON on ARM) and a portable scalar implementation of every routine. Uses no precompiled third-party libraries and no runtime dynamic loading (
.dll,.so,LoadLibrary,dlopen). - Runs on every CPU of the target architecture: the SIMD kernels are compiled for their instruction set function by function and selected at run time (AVX2 -> SSE4.1 -> scalar on x86, NEON on ARM64 and on 32-bit ARM if the compiler generates NEON code, scalar on every other architecture), so a binary never requires an instruction set the CPU does not have. See SIMD acceleration and portability.
- Cross-platform: Windows x86 and x86-64 (MSVC, MinGW-w64), Linux x86 / x86-64 (GCC, Clang), Linux ARM64 / AArch64 (GCC, Clang, NEON) and Linux 32-bit ARM (GCC, Clang, with or without NEON). Any other platform with a C++17 compiler and
std::threadis built with the scalar code path. The decoded output is bit-identical on all platforms and SIMD levels and, for streams without errors, for all thread counts (see setParam method). - Supported streams: 8-bit 4:2:0 Main profile streams: CABAC entropy decoding, I, P and B slices, weighted prediction, 4x4 to 32x32 transform hierarchy (including transform skip and explicit scaling lists), PCM and lossless (
cu_transquant_bypass) coding units, multiple and dependent slices, tiles, WPP entry points, all IRAP types (IDR, CRA, BLA, RASL / RADL handling) and the output order process (pic_output_flag,no_output_of_prior_pics_flag, DPB bumping). The range extension tools of 8-bit 4:2:0 streams (implicit and explicit RDPCM, transform skip rotation and context, persistent Rice adaptation, CABAC bypass alignment, disabled intra smoothing) are decoded too. Each coded picture is returned as one frame: the fields of a field coded stream are returned one by one. Not supported: bit depth above 8, 4:2:2 / 4:4:4 / monochrome, extended precision processing (such streams are rejected with an error, never decoded wrongly), multilayer / 3D extensions (only the base layer,nuh_layer_id = 0, is decoded). - Verified against the conformance suites: all 136 8-bit 4:2:0 streams of the JCT-VC
HEVC_v1conformance suite and the 8-bit 4:2:0 streams of theRExtsuite (GENERAL_8b_420_RExt_Sony_1,WPP_HIGH_TP_444_8BIT_RExt_Apple_2,WPP_AND_TILE_HIGH_TP_444_8BIT_RExt_Apple_2,WPP_AND_TILE_AND_CABAC_BYPASS_ALIGN_1_HIGH_TP_444_14BIT_RExt_Apple_2) decode bit-exactly (MD5 of the output equals the official MD5 shipped with each stream) in single- and multi-threaded mode on every platform on which the decoder was run (see SIMD acceleration and portability). The remaining 11 streams of theHEVC_v1suite use more than 8 bits, the otherRExtstreams use other bit depths, other chroma formats or extended precision processing: they are rejected. - Motion Vector Extraction: Provides spatial motion vector extraction through
getMotionVector(), returning[x, y, dx, dy]for one sample per 16x16 display-grid cell, with conformance-window cropping accounted for. - 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.
- 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. - Single-threaded by default, optional multi-threading: By default (
CUSTOM_2 = 1.0f) the decoder works single-threaded, without background threads. Optionally (CUSTOM_2 = 0.0ffor automatic, orN >= 2) worker threads decode the CTB rows of WPP slices or the tiles of a slice in parallel and run the in-loop filters (deblocking, SAO) in parallel; the output of a stream without errors stays bit-identical. - Standard VCodec Interface: Inherits from the
rapidpixel::VCodecinterface (VCodec library), so the decoder can be used wherever the SDK expects aVCodec. - C++17 Architecture: Uses the PIMPL pattern: the public header contains no internal decoder structures. The VDecoderH265 class depends on the VCodec class (video codec interface), which depends on the Frame class (video frame structure). The example application uses SimpleUI for window display and drawing vector overlays, and a lightweight H.265 elementary stream parser (
H265Parser). The library uses the C++17 standard.
VDecoderH265 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 | 30.09.2026 | - First version. |
| 1.1.0 | 25.10.2026 | - Deep rework of the code. |
| 1.1.1 | 17.11.2026 | - Build without warnings with GCC 9 (Jetson Nano, Ubuntu 18.04): the bytes of the stream are shifted as unsigned values. |
| 1.1.2 | 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.
src ----------------------------- Library source code.
CMakeLists.txt -------------- CMake script for VDecoderH265 library.
VDecoderH265.h -------------- Public library interface (PIMPL).
VDecoderH265.cpp ------------ Public library implementation wrapper.
VDecoderH265Version.h ------- Version definition header.
VDecoderH265Version.h.in ---- Template for CMake version generation.
impl ------------------------ Internal decoder implementation files.
VDecoderH265Impl.h ------ Internal PIMPL class declaration.
VDecoderH265Impl.cpp ---- PIMPL class implementation, NV12 packing, and motion vector extraction.
CoreTypes.h ------------- Shared HEVC constants, enumerations, and math utilities.
BitWalker.h / .cpp ------ On-the-fly RBSP emulation-prevention unescaping bit reader and Exp-Golomb parser.
PacketSplitter.h / .cpp - Annex B start-code scanner and NAL unit header parser.
ParamCatalog.h / .cpp --- VPS, SPS, PPS, scaling list, short-term RPS, and tile/CTB scan table registry.
ArithEngine.h / .cpp ---- Context-Adaptive Binary Arithmetic Coding (CABAC) engine and probability models.
SurfaceStore.h / .cpp --- Decoded picture surfaces, block metadata grids, and Decoded Picture Buffer (DPB).
ParallelPool.h / .cpp --- Multi-threaded worker pool and Wavefront Parallel Processing (WPP) synchronization.
TransformCore.h / .cpp -- Scan order tables, inverse quantization, and 4x4..32x32 inverse DST-VII / DCT-II.
IntraSynth.h / .cpp ----- Intra prediction (Planar, DC, 33 Angular modes, and MPM derivation).
InterPredictor.h / .cpp - Spatial/temporal motion vector prediction (Merge/AMVP) and fractional MC.
SimdKernels.h / .cpp ---- Runtime-dispatched x86 (SSE4.1/AVX2) and ARM (NEON) SIMD kernels.
LoopFilters.h / .cpp ---- In-loop adaptive deblocking filter and Sample Adaptive Offset (SAO) filter.
SliceDirector.h / .cpp -- Slice segment header parser, CTU quadtree/RQT syntax decoder, and frame pipeline.
example ------------------------- Example application.
CMakeLists.txt -------------- Example build configuration.
H265Parser.h ---------------- H.265 / HEVC elementary stream file parser header.
H265Parser.cpp -------------- H.265 / HEVC elementary stream file parser implementation.
main.cpp -------------------- Example demonstrating video decoding and MV extraction.
VDecoderH265 class description
VDecoderH265 class declaration
The VDecoderH265 class is declared in VDecoderH265.h:
namespace rapidpixel
{
class VDecoderH265 : public VCodec
{
public:
/// Class constructor.
VDecoderH265();
/// Class destructor.
~VDecoderH265() override;
/// The decoder is not copyable and not movable.
VDecoderH265(const VDecoderH265&) = delete;
VDecoderH265(VDecoderH265&&) = delete;
VDecoderH265& operator=(const VDecoderH265&) = delete;
VDecoderH265& operator=(VDecoderH265&&) = delete;
/// Get library version.
static std::string getVersion();
/// Decode H.265 access unit, get the next decoded frame in NV12 format.
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 decoded frame.
const std::vector<std::vector<float>>& getMotionVector();
};
}
All methods can be called from several threads: they are serialized by a mutex (a call waits while another thread decodes). The reference returned by getMotionVector() must not be used while another thread calls transcode(…) or executeCommand(…). If there is not enough memory for the decoder, the constructor does not throw: every method then reports a failure (false, -1.0f or an empty motion vector list).
getVersion method
The getVersion() method returns a string with the current version of the library:
static std::string getVersion();
Example usage:
std::cout << "VDecoderH265 version: " << rapidpixel::VDecoderH265::getVersion() << std::endl;
Terminal output:
VDecoderH265 version: 1.1.2
transcode method
The transcode(…) method decodes an incoming H.265 Annex B access unit and returns the next decoded frame in output order as an uncompressed NV12 video frame.
bool transcode(Frame& src, Frame& dst) override;
| Parameter | Type | Description |
|---|---|---|
src | Frame& | Source compressed video frame. Field src.fourcc must be Fourcc::HEVC (other values, for example Fourcc::H264, are rejected). Submit one complete Annex B access unit per call, with src.data and src.size describing its bytes; the data must stay valid during the call. src.frameId is returned with the decoded frame of this access unit. A NAL unit may have at most 16 MiB and the queued input at most 64 MiB (each NAL unit counts 128 bytes more than its size): data beyond these limits is dropped. If a frame is returned, src.width and src.height are set to the size of the frame. Unsupported chroma formats and bit depths are rejected. |
dst | Frame& | Destination uncompressed video frame. If a frame is returned, the decoder writes the NV12 pixel data to dst.data and sets dst.width, dst.height (size of the conformance window), dst.size = width * height * 3 / 2 (0 in the motion vectors only mode, see setParam method), dst.fourcc = Fourcc::NV12 and dst.frameId (frameId of the access unit of the frame). The memory of dst is reused if dst.size is large enough (dst.size must not exceed the memory of dst.data), otherwise new memory is allocated. |
Returns: true if a frame was decoded and written to dst; false if no frame is ready yet (for example the access unit contains only parameter sets, or the frame is held back in the DPB for reordering), if the input is invalid (src.fourcc other than Fourcc::HEVC, src.size < 0, src.data = nullptr with src.size > 0), if the stream is not supported or if there is not enough memory. dst is not changed if the method returns false.
At EOF, repeatedly call transcode() with an empty HEVC frame (src.size = 0) until it returns false to retrieve delayed B-frames. Empty input marks the end of the stream, not an access-unit boundary. Execute RESET before feeding a new stream. Output dst.frameId identifies the source access unit that produced the displayed frame, including after reordering.
rapidpixel::VDecoderH265 decoder;
rapidpixel::Frame dst;
rapidpixel::Frame eof;
eof.fourcc = rapidpixel::Fourcc::HEVC;
while (decoder.transcode(eof, dst))
{
std::cout << "Frame " << dst.frameId << ": " << dst.width << "x" << dst.height << std::endl;
}
getMotionVector method
The getMotionVector() method retrieves the spatial motion vectors of the last frame returned by transcode(…).
const std::vector<std::vector<float>>& getMotionVector();
Returns: A reference to a two-dimensional vector where each element is a 4-component vector [x, y, dx, dy] of one 16x16 cell of the frame. The reference stays valid until the next transcode(...) or executeCommand(...) call or the destruction of the decoder: copy the vector if you need it longer. Before the first decoded frame (and after RESET) the vector is empty.
x: Horizontal pixel coordinate of the top-left corner of the cell.y: Vertical pixel coordinate of the top-left corner of the cell.dx: Horizontal motion displacement in pixels.dy: Vertical motion displacement in pixels.
Intra-coded cells have zero displacement dx=0, dy=0. For predicted cells, the decoder samples the center of each 16x16 cell, clamped to the visible picture at partial edges. It returns L0 when available, otherwise L1. This is a display-grid summary, not all coded sub-partitions or both bi-prediction vectors. Coordinates are relative to the cropped, displayed picture.
Example:
rapidpixel::VDecoderH265 decoder;
const std::vector<std::vector<float>>& vectors = decoder.getMotionVector();
for (const std::vector<float>& mv : vectors)
{
std::cout << "Cell " << mv[0] << "," << mv[1] << " motion " << mv[2] << "," << mv[3] << 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. |
Supported parameters:
VCodecParam::LOG_LEVEL: Stored and returned bygetParam(...); it has no effect (the decoder writes no log).VCodecParam::TYPE: Stored and returned bygetParam(...); it has no effect (the library has one decoder type).VCodecParam::CUSTOM_1: Decoding mode (default0.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 (dstgetswidth,height,fourcc = NV12,frameIdandsize = 0;dst.datais not changed).
VCodecParam::CUSTOM_2: Number of decoding threads (default1.0f):1.0f- single-threaded decoding (default): everything is decoded in the thread which callstranscode(...), no worker threads are created.0.0f- automatic: worker thread pool depending on hardware concurrency (at most 16 workers).N >= 2- worker pool ofNthreads, capped at 32 workers.getParam(CUSTOM_2)reports the actual applied count.- The output of a stream without errors is bit-identical for every value. After an error in the data of a slice segment with WPP rows or tiles, the single-threaded decoder skips the rest of the segment, while worker threads continue with the next row or tile: the frames can differ between
1.0fand the other values (the result is the same for every run and for every number of worker threads).
VCodecParam::CUSTOM_3: Color range control for output NV12 frame (default1.0f):1.0f: Automatic (default). If the stream does not signal full range (video_full_range_flagof the VUI is 0 or absent) and the luma samples of the frame look like limited range video (a coarse grid of samples covers at least 8 code values and fewer than one sample in 500 is below 14 or above 238), luma [16..235] and chroma [16..240] are expanded to full range [0..255] during NV12 assembly. The check is made for every frame; other frames are copied without 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 for another parameter ID, an invalid value or if the worker threads can not be started (the previous thread count stays then).
Values must be finite integers representable as int (NaN, infinity and fractions are rejected). CUSTOM_1 accepts only 0/1, CUSTOM_2 accepts nonnegative counts (0 selects automatic), and CUSTOM_3 accepts only 0/1/2.
getParam method
The getParam(…) method queries parameter values from the decoder.
float getParam(VCodecParam id) override;
Returns: Value of the specified parameter (for VCodecParam::CUSTOM_2 the number of threads in use), or -1.0f for another parameter ID.
executeCommand method
The executeCommand(…) method sends control commands to the decoder.
bool executeCommand(VCodecCommand id) override;
Supported commands:
VCodecCommand::RESET: Drops all decoded frames (the Decoded Picture Buffer), the pending input and the motion vectors. The SPS and PPS received before are kept.
Returns: true if the command was executed; false for another command.
Build and connect to your project
The library needs CMake 3.13 or newer and a C++17 compiler with std::thread support (tested with GCC 12 and 13, Clang 15 and 18 and MinGW-w64 GCC 13). The default build type is Release.
Build stand alone
The repository does not contain sub-repositories. The libraries VDecoderH265 depends on (Frame, VCodec) must be placed in the same folder as VDecoderH265: copy their folders, for example from the folder modules of the RapidPixel SDK. The example also needs the folder of the SimpleUI library. The folder structure must be:
<work folder>
VDecoderH265
Frame
VCodec
SimpleUI
Typical commands to build the library and the example:
cd VDecoderH265
mkdir build
cd build
cmake ..
make
On Windows use cmake --build . --config Release instead of make. If VDecoderH265 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, the CMake configuration fails with an error. To build the library without the example (the folder ../SimpleUI is not needed then), run cmake .. -D_SUBMODULE_CACHE_OVERWRITE=OFF -D_VDECODERH265_EXAMPLE=OFF instead of cmake .. (see CMake options).
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 VDecoderH265 is the top-level project).
| Option | Default | Description |
|---|---|---|
| ${PARENT}_VDECODERH265 | ON | Build the library. |
| ${PARENT}_VDECODERH265_EXAMPLE | ON (stand alone), OFF (included in other project) | Build the example (it needs the SimpleUI library). |
| ${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 VDecoderH265 as a sub-repository. |
| CMAKE_BUILD_TYPE | Release (if not specified) | Build type. |
| VDECODERH265_ENABLE_SIMD | ON | Build the SIMD kernels (see SIMD acceleration and portability). OFF builds the portable scalar code only. |
Connect to your project
If you want to connect the VDecoderH265 library to your CMake project as source code, you can do the following. The VDecoderH265 library does not add its dependencies when it is included in another CMake project: your project must add the Frame and VCodec libraries (in this order) before VDecoderH265. For example, if your repository has the 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 and VDecoderH265 there (for example from the folder modules of the RapidPixel SDK). Create a CMakeLists.txt file in the 3rdparty folder. The CMakeLists.txt 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_VDECODERH265 ON CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VDECODERH265)
SET(${PARENT}_VDECODERH265 ON CACHE BOOL "" FORCE)
SET(${PARENT}_VDECODERH265_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_VDECODERH265)
add_subdirectory(VDecoderH265)
endif()
The 3rdparty/CMakeLists.txt file adds the Frame, VCodec and VDecoderH265 folders to your project (the dependencies first, then the library; the example of VDecoderH265 is not built). The structure of your repository will be:
CMakeLists.txt
src
CMakeLists.txt
yourLib.h
yourLib.cpp
3rdparty
CMakeLists.txt
Frame
VCodec
VDecoderH265
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 VDecoderH265 library in your src/CMakeLists.txt file:
target_link_libraries(${PROJECT_NAME} VDecoderH265)
Include the public header in your code:
#include "VDecoderH265.h"
If your project does not add the Frame and VCodec libraries, the compilation of the VDecoderH265 library fails because the VCodec.h header file is not found (for example, GCC reports “VCodec.h: No such file or directory”).
SIMD acceleration and portability
The decoder is plain C++17 with a complete scalar implementation of every DSP routine. SIMD kernels are optional accelerators which are selected at run time, when the decoder is created (the CPU is checked once per process):
| CPU | Kernels used | How the level is chosen |
|---|---|---|
| x86 / x86-64 | AVX2 -> SSE4.1 -> scalar | GCC and Clang: the CPU model of the compiler runtime (__builtin_cpu_supports). MSVC: CPUID and XGETBV. The SSE4.1 kernels need SSSE3 and SSE4.1. The AVX2 kernels need AVX2 and OS support for the YMM registers. |
| ARM64 / AArch64 | NEON | Always available on AArch64. |
| 32-bit ARM | NEON or scalar | NEON if the compiler generates NEON code (__ARM_NEON is defined, for example with -mfpu=neon). |
| Any other CPU | scalar | No intrinsics are compiled. |
A binary built on a machine with AVX2 therefore also starts and decodes on a CPU with only SSE4.1 or even only SSE2 (checked with emulated Haswell, Sandy Bridge, Nehalem, Penryn, Conroe and Opteron G1 CPUs), and the decoded output is bit-identical for every level.
All kernels are in src/impl/SimdKernels.cpp. GCC and Clang compile the SSE4.1 and AVX2 kernels as functions with the target attribute (target("sse4.1,ssse3"), target("avx2")); MSVC compiles the intrinsics without options. No source file gets instruction-set flags (no -march=native, no global -mavx2 or /arch:AVX2), so the rest of the library keeps the baseline instruction set of the target.
CMake checks with check_cxx_source_compiles that the compiler can build the CPU detection and SSE4.1 and AVX2 intrinsics in functions with target attributes. If it cannot (for example an old compiler or an unusual toolchain), the x86 kernels are left out, a message is printed during configuration, and the scalar code is used. A universal macOS binary (more than one architecture in CMAKE_OSX_ARCHITECTURES) gets no SSE4.1 and AVX2 kernels (the NEON kernels of its ARM64 part are still built). Options:
| Option / macro | Effect |
|---|---|
-DVDECODERH265_ENABLE_SIMD=OFF | Builds the portable scalar decoder only (defines VDECODERH265_NO_SIMD). |
VDECODERH265_NO_SSE41, VDECODERH265_NO_AVX2 | Leave out the x86 kernel sets. CMake defines them automatically when the compiler probe fails. |
CMake sets these macros as private compile definitions of the VDecoderH265 target: they do not change the public header and the code that uses the library. Without CMake, compile all src/**/*.cpp files and the .cpp files of the VCodec and Frame libraries as C++17 with the src folders of the three libraries in the include path (no instruction-set flags are needed; define the macros above to leave out kernel sets) and link the system thread library (-pthread) and, on targets where std::atomic of 8-bit values needs it (for example RISC-V), the atomic library (-latomic; CMake checks this and links it automatically).
The decoder does not depend on the byte order of the CPU. It was built and run on Linux x86-64 (GCC 12 and 13, Clang 15 and 18), Linux x86 32-bit (GCC 13), Linux AArch64 (GCC 13, Clang 18), Linux 32-bit ARM (GCC 13 with and without NEON, Clang 18 with NEON), Linux s390x (big-endian, GCC 13) and Windows x86-64 (MinGW-w64 GCC 13); the 32-bit Windows build (MinGW-w64 GCC 13) was compiled. The ARM and s390x builds were run in the QEMU emulator, the Windows build in Wine.
Simple example
The example application (example/main.cpp) demonstrates opening an H.265 video file, decoding frames to NV12, draining the frames delayed by reordering at the end of the stream, extracting motion vectors, and rendering them using SimpleUI:
#include <cmath>
#include <cstdint>
#include <cstring>
#include <exception>
#include <iostream>
#include <string>
#include <vector>
#include "H265Parser.h"
#include "SimpleUi.h"
#include "VDecoderH265.h"
namespace
{
/// Key code of ESC (SimpleUiWindow::getKey()).
constexpr int KEY_ESC = 27;
/// Time to wait for a key after each frame, milliseconds.
constexpr int FRAME_DELAY_MS = 30;
/// Motion vectors shorter than this in both directions are not drawn, pixels.
constexpr float MIN_DRAWN_MOTION = 0.5f;
/// Neutral value of the U and V samples of a YUV24 frame (gray image).
constexpr uint8_t NEUTRAL_CHROMA = 128;
/// 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;
/// Remove spaces, tabs, line breaks and a pair of quotes around the path
/// (a path pasted into the console is often quoted).
std::string cleanPath(std::string path)
{
const char* const blanks = " \t\r\n";
const size_t first = path.find_first_not_of(blanks);
if (first == std::string::npos)
{
return std::string();
}
path = path.substr(first, path.find_last_not_of(blanks) - first + 1);
if (path.size() >= 2 && (path.front() == '"' || path.front() == '\'') &&
path.back() == path.front())
{
path = path.substr(1, path.size() - 2);
}
return path;
}
/// Convert float value 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;
}
/// Draw the luma plane of the decoded frame as a gray YUV24 image with the
/// motion vectors of the decoder on top. A frame without luma samples (motion
/// vectors only mode, size 0) gives a gray image with the vectors only.
/// Returns FALSE if the frame has no size.
bool drawFrame(rapidpixel::VDecoderH265& decoder, const rapidpixel::Frame& nv12Frame,
rapidpixel::Frame& yuvFrame)
{
if (nv12Frame.width != yuvFrame.width || nv12Frame.height != yuvFrame.height)
{
yuvFrame = rapidpixel::Frame(nv12Frame.width, nv12Frame.height, rapidpixel::Fourcc::YUV24);
}
if (yuvFrame.data == nullptr)
{
return false;
}
std::memset(yuvFrame.data, NEUTRAL_CHROMA, static_cast<size_t>(yuvFrame.size));
const int64_t lumaSize = static_cast<int64_t>(nv12Frame.width) * nv12Frame.height;
if (nv12Frame.data != nullptr && nv12Frame.size >= lumaSize)
{
for (int64_t i = 0; i < lumaSize; ++i)
{
yuvFrame.data[3 * i] = nv12Frame.data[i];
}
}
// Overlay of the motion vectors [x, y, dx, dy]: start point and end point.
const rapidpixel::Color green{0, 255, 0, 255};
for (const std::vector<float>& mv : decoder.getMotionVector())
{
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
if (mv.size() < 4 ||
(std::fabs(mv[2]) <= MIN_DRAWN_MOTION && std::fabs(mv[3]) <= MIN_DRAWN_MOTION) ||
!toInt(mv[0], x1) || !toInt(mv[1], y1) || !toInt(mv[0] + mv[2], x2) ||
!toInt(mv[1] + mv[3], y2))
{
continue;
}
rapidpixel::SimpleUiDraw::drawLine(yuvFrame, x1, y1, x2, y2, green, 1);
}
return true;
}
}
// Entry point.
int main(int argc, char* argv[])
{
try
{
// Print library version.
std::cout << "VDecoderH265 v" << rapidpixel::VDecoderH265::getVersion() << std::endl;
// Get the path of the H.265 file from the command line or the console.
std::string videoPath;
if (argc > 1)
{
videoPath = argv[1];
}
else
{
std::cout << "Enter path to video file (*.h265): ";
std::getline(std::cin, videoPath);
}
videoPath = cleanPath(videoPath);
if (videoPath.empty())
{
std::cerr << "No video file" << std::endl;
return -1;
}
// Open H.265 elementary stream file.
rapidpixel::H265Parser parser;
if (!parser.open(videoPath))
{
std::cerr << "Failed to open video file: " << videoPath << std::endl;
return -1;
}
// Initialize decoder and UI window.
rapidpixel::VDecoderH265 decoder;
rapidpixel::SimpleUiWindow window("VDecoderH265 - Motion Vectors");
window.show();
// Input H.265 frame (access unit), decoded NV12 frame and the frame to
// render.
rapidpixel::Frame h265Frame;
rapidpixel::Frame nv12Frame;
rapidpixel::Frame yuvFrame;
// Decode and display video frames until the end of the file or ESC.
int decodedFrames = 0;
bool running = true;
while (running && window.isOpen() && parser.getFrame(h265Frame))
{
// The decoder returns FALSE while it needs more data (pictures are
// held back for reordering) or for damaged data: the next access
// unit is decoded then.
if (decoder.transcode(h265Frame, nv12Frame))
{
++decodedFrames;
if (drawFrame(decoder, nv12Frame, yuvFrame))
{
window.render(yuvFrame);
}
running = window.getKey(FRAME_DELAY_MS) != KEY_ESC;
}
}
if (parser.failed())
{
std::cerr << "Failed to read the video file" << std::endl;
}
// End of stream: an empty HEVC frame returns the pictures held back
// for reordering, one per call.
rapidpixel::Frame eofFrame;
eofFrame.fourcc = rapidpixel::Fourcc::HEVC;
while (running && window.isOpen() && decoder.transcode(eofFrame, nv12Frame))
{
++decodedFrames;
if (drawFrame(decoder, nv12Frame, yuvFrame))
{
window.render(yuvFrame);
}
running = window.getKey(FRAME_DELAY_MS) != KEY_ESC;
}
std::cout << decodedFrames << " frames decoded" << std::endl;
return decodedFrames > 0 ? 0 : -1;
}
catch (const std::exception& e)
{
// The window can not be created, a frame can not be rendered or there
// is not enough memory.
std::cerr << "Error: " << e.what() << std::endl;
return -1;
}
}