vcodecwmf_web_logo

VCodecWmf C++ library

v1.0.3

Table of contents

Overview

The VCodecWmf C++ library provides hardware-accelerated and software video encoding and decoding for H264, HEVC (H.265), and JPEG formats based on Microsoft Media Foundation (WMF) and Windows Imaging Component (WIC) for Windows (Windows 11 and later). The VCodecWmf class implements the VCodec interface and adheres to the RapidPixel Coding Standards.

The library automatically enumerates and prioritizes the best available backend at runtime:

  1. Hardware acceleration priority: NVIDIA GPU (NVENC/NVDEC) -> Intel GPU (Quick Sync) -> AMD GPU (AMF) -> Software fallback (Microsoft MFT / WIC). The order is chosen by the vendor of the GPU, not by the type of the GPU (dedicated or integrated).
  2. Low-latency real-time streaming: Disables B-frames (CODECAPI_AVEncMPVDefaultBPictureCount = 0), enables low-latency pipeline (CODECAPI_AVEncCommonLowLatency = TRUE), supports dynamic GOP and CBR/VBR rate control.
  3. JPEG processing: Uses Windows Imaging Component (WIC) without external dependencies. The NV12 <-> BGR24 conversion is made by the library on the CPU.
  4. C++ standard: Strictly written in C++17, compiling cleanly under warning level /W4.

Encoding time of VCodecWmf on Windows 11 (Intel Core i7-13700H, NVIDIA GeForce RTX 4050 Laptop GPU, NV12 input, 30 fps, 3000 kbps, CBR):

codec / resolution 1920x1080 1280x720 640x480
H264 ~4.17 msec ~1.99 msec ~1.07 msec
HEVC ~4.71 msec ~2.35 msec ~1.22 msec
JPEG ~6.30 msec ~3.02 msec ~0.96 msec

Decoding time of VCodecWmf on Windows 11 (Intel Core i7-13700H, NVIDIA GeForce RTX 4050 Laptop GPU, NV12 output):

codec / resolution 1920x1080 1280x720 640x480
H264 ~8.53 msec ~8.12 msec ~7.56 msec
HEVC ~8.53 msec ~7.41 msec ~7.37 msec
JPEG ~5.43 msec ~2.40 msec ~0.84 msec

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

Performance comparison: VCodecWmf vs FFmpeg

The following table compares the performance (average frame latency and throughput) of VCodecWmf directly against FFmpeg 6.0 (hardware accelerated with NVENC/CUVID) on the same machine and identical test datasets (100 frames):

Codec Resolution VCodecWmf Encode FFmpeg NVENC Encode VCodecWmf Decode FFmpeg CUVID Decode
H264 1920x1080 4.17 ms (~240 fps) 20.37 ms (~49 fps) 8.53 ms (~117 fps) 2.82 ms (~354 fps)
H264 1280x720 1.99 ms (~502 fps) 3.00 ms (~333 fps) 8.12 ms (~123 fps) 2.08 ms (~480 fps)
H264 640x480 1.07 ms (~935 fps) 2.06 ms (~484 fps) 7.56 ms (~132 fps) 1.47 ms (~682 fps)
HEVC 1920x1080 4.71 ms (~212 fps) 4.83 ms (~207 fps) 8.53 ms (~117 fps) 2.44 ms (~410 fps)
HEVC 1280x720 2.35 ms (~425 fps) 3.00 ms (~333 fps) 7.41 ms (~135 fps) 1.90 ms (~525 fps)
HEVC 640x480 1.22 ms (~820 fps) 2.00 ms (~501 fps) 7.37 ms (~136 fps) 1.51 ms (~664 fps)
JPEG 1920x1080 6.30 ms (~159 fps) 3.60 ms (~278 fps) 5.43 ms (~184 fps) 0.69 ms (~1445 fps)
JPEG 1280x720 3.02 ms (~331 fps) 1.84 ms (~542 fps) 2.40 ms (~417 fps) 0.67 ms (~1498 fps)
JPEG 640x480 0.96 ms (~1042 fps) 1.01 ms (~987 fps) 0.84 ms (~1190 fps) 0.51 ms (~1954 fps)

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 28.09.2026 - Initial release of Microsoft Media Foundation (WMF) and Windows Imaging Component (WIC) codec library for Windows 11 and later.
1.0.1 16.10.2026 - Sub-repositories are removed: the dependencies (Frame, VCodec) are expected next to the library folder when it is built stand alone.
- H264 encoding no longer waits forever for an encoder that reports an output format change (the call hangs on some GPUs): the wait for an encoder is limited to 5 seconds, the output format change is handled.
- Decoding of H264 and HEVC streams of 1920x1080 reads the chroma plane from the right place (decoders align the height of the buffer to 1088 rows).
- The size of the decoded picture is read from the decoder; the frame gets the size of the picture.
- Frame sizes are checked (positive, even, up to 8192 pixels, up to 8192 x 4320 pixels), also the size read from a JPEG header; the data size of a source frame is checked; the size of a packet is checked against the buffer of the destination frame.
- Parameter values are checked: NaN, infinity and values outside of the range are rejected (before they were converted without a check). Ranges: see Table 2.
- H264_PROFILE default value is 1 (Main), as the encoder uses.
- executeCommand(MAKE_KEY_FRAME) returns TRUE.
- JPEG encoding and decoding use streams over the memory of the frames: a stream created by the system leaked about 12 KB for every frame (more than 500 MB in 20,000 frames). A damaged JPEG could corrupt the heap (the process stopped with a heap corruption error).
- Every encoder and decoder is shut down when it is not used any more: a codec object that encoded or decoded video left a thread, about 15 handles and about 25 MB of memory behind when it was destroyed.
- Memory shortage in transcode(…) is reported as FALSE.
- COM is kept initialized for the process: the library works in threads that did not initialize COM.
- Hardening: compiler and linker security options, standard C++ only (no compiler extensions). The default warning level of CMake (/W3) is removed from the compiler options of the library, the example and the test application (warning D9025 with the Ninja and NMake generators).
- Tests: API with invalid arguments, damaged streams, threads, life cycle of the codec, end of the process; the test application works in a folder whose path has non-ASCII characters.
1.0.2 14.11.2026 - The test data files (H264, HEVC and JPEG) are removed from the repository: the user supplies them (see Test data). The test application skips the checks that need a missing file.
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 (enforces Windows platform).
example --------------------- Folder with simple example of VCodecWmf usage.
    CMakeLists.txt ---------- CMake file for example application.
    main.cpp ---------------- Source code file of example application.
static ---------------------- Folder with static project resources.
    vcodecwmf_web_logo.png -- Web logo used in README.
test ------------------------ Folder with codec test application.
    CMakeLists.txt ---------- CMake file for codec test application.
    main.cpp ---------------- Source code file of codec test application.
src ------------------------- Folder with source code of the library.
    CMakeLists.txt ---------- CMake file of the library.
    VCodecWmf.cpp ----------- C++ implementation file of the public class.
    VCodecWmf.h ------------- Header file which includes VCodecWmf class declaration.
    VCodecWmfVersion.h ------ Header file which includes version of the library.
    VCodecWmfVersion.h.in --- CMake service file to generate version file.
    impl -------------------- Internal WMF and WIC implementation details.
        WmfContext.cpp ------ Direct3D 11 device and DXGI GPU adapter management.
        WmfContext.h -------- Direct3D 11 device manager declaration.
        WmfEncoder.cpp ------ Hardware-accelerated and software MFT video encoder.
        WmfEncoder.h -------- MFT video encoder declaration.
        WmfDecoder.cpp ------ Hardware-accelerated and software MFT video decoder.
        WmfDecoder.h -------- MFT video decoder declaration.
        WicJpegCodec.cpp ---- WIC JPEG encoder and decoder with NV12 conversion.
        WicJpegCodec.h ------ WIC JPEG codec declaration.
        VCodecWmfImpl.cpp --- Internal backend implementation and routing.
        VCodecWmfImpl.h ----- Internal backend declaration.

VCodecWmf class description

VCodecWmf class declaration

The VCodecWmf class is declared in the VCodecWmf.h file. The methods are thread-safe: calls from several threads are serialized. A frame that is passed to a method must not be accessed by another thread until the method returns. The constructor throws std::bad_alloc if memory is not available. The copy and the move operations of the class are deleted. Class declaration:

class VCodecWmf : public VCodec
{
public:

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

    /// Class constructor.
    VCodecWmf();

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

    /// Copy and move operations are deleted.
    VCodecWmf(const VCodecWmf&) = delete;
    VCodecWmf(VCodecWmf&&) = delete;
    VCodecWmf& operator=(const VCodecWmf&) = delete;
    VCodecWmf& operator=(VCodecWmf&&) = delete;

    /// Transcode (encode or decode) 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;

private:

    /// Implementation of the codec.
    std::unique_ptr<VCodecWmfImpl> m_impl{nullptr};
};

getVersion method

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

static std::string getVersion();

The method can be used without a VCodecWmf class instance:

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

Console output:

VCodecWmf class version: 1.0.3

transcode method

The transcode(…) method is intended to encode and decode video frames (Frame class). The direction (encode or decode) is determined by the fourcc fields of the src and dst frames: if src is NV12 and dst is a compressed format (H264, HEVC, JPEG), the library encodes; if src is compressed and dst is NV12, the library decodes. Other combinations of the pixel formats are rejected. The video codec processes frames one at a time. Method declaration:

bool transcode(Frame& src, Frame& dst);
Parameter Value
src Source video frame (see Frame class description). For encoding: must have raw pixel format NV12, data must be not nullptr, width and height must be positive and even and not larger than 8192, the frame must not have more than 8192 x 4320 pixels and size must be not less than width * height * 3 / 2. For decoding: must have compressed format H264, HEVC, or JPEG, data must be not nullptr and size must be the actual bitstream length (positive). The width and height of an H264 or HEVC frame are passed to the decoder (1920x1080 if they are not positive) and must meet the limits of encoding. The size of a JPEG image is read from the data and must meet the limits of encoding.
dst Result video frame (see Frame class description). For encoding: must have compressed format H264, HEVC, or JPEG. For decoding: must have raw pixel format NV12. A frame with a size that differs from the size of the result is reallocated: for encoding the size of the result is the size of src, for decoding it is the size of the decoded picture. A frame that is not reallocated must have a buffer of the size that the Frame constructor allocates for its size and pixel format.

Returns: TRUE if the frame was encoded/decoded successfully or FALSE if not (invalid frame or pixel formats, error of the encoder or decoder, memory is not available). If TRUE is returned and dst.size is 0, the encoder or the decoder accepted the frame and needs more data: the result comes with a next frame. The content of dst is not defined if FALSE is returned. The library cannot check that a non-nullptr data pointer is valid for size bytes: the pointer must be valid. The call waits for a hardware encoder not longer than 5 seconds. After an error of an encoder or a decoder it is created again by the next call. H264 and HEVC decoding uses the graphics driver when the computer has a suitable GPU: a damaged or crafted stream can make the driver block inside the decoder, and then the call does not return (it was observed with the Microsoft H264 decoder on an Intel GPU: the call did not return for more than 60 seconds and used no CPU time). The library cannot interrupt the call, so an application that decodes streams from an untrusted source should decode them in a separate process.

setParam method

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

bool setParam(VCodecParam id, float value);
Parameter Description
id Video codec parameter ID according to VCodecParam enum.
value Video codec parameter value.

Returns: TRUE if the parameter was set or FALSE if not. An unknown ID, NaN, infinity and a value outside of the range of the parameter (see Table 2) are rejected: the parameter is not changed. The fractional part of a value is cut off. TYPE and CUSTOM_1 - CUSTOM_3 have no range: any value (also NaN and infinity) is accepted and stored as it is.

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 parameter descriptions for VCodecWmf.

Parameter Access Description
LOG_LEVEL read / write Log level: 0 - Disable, 1 - Console, 2 - File, 3 - Console and file (as in the VCodec.h file). Range: 0 - 3. Default: 0. The library does not write a log: the value is only stored.
BITRATE_KBPS read / write Target bitrate in kbps. Range: 1 - 100,000 kbps. Default: 3000 kbps. For H264/HEVC encoding. Applied on-the-fly via ICodecAPI.
MIN_BITRATE_KBPS read / write Minimum bitrate in kbps. Always 0 (WMF hardware/software encoders do not impose a minimum bitrate floor; getParam always returns 0.0f). setParam accepts values from 0 to 100,000 and does not change the value.
MAX_BITRATE_KBPS read / write Maximum peak bitrate in kbps for variable bitrate mode (BITRATE_MODE = 1). Range: 1 - 100,000 kbps. Default: 5000 kbps. Dynamically applied via CODECAPI_AVEncCommonMaxBitRate.
BITRATE_MODE read / write Bitrate mode: 0 - Constant Bitrate (CBR), 1 - Variable Bitrate (Peak-constrained VBR). Default: 0. Dynamically applied via CODECAPI_AVEncCommonRateControlMode. Other values (also 0.5) are rejected.
QUALITY read / write JPEG encoding quality. Range: 1 - 100 (1 = lowest, 100 = highest). Default: 80.
FPS read / write Frame rate. Range: 1 - 240 fps. Default: 30 fps. Used for rate control (the encoder is initialized with the value) and for the timestamps of the frames.
GOP read / write GOP size (keyframe interval in frames). Range: 0 - 1000 (0 - the encoder default). Default: 30.
H264_PROFILE read / write H264 profile for H264 encoding: 0 - Baseline, 1 - Main, 2 - High. Default: 1. The profile is used when the encoder is initialized (the first frame, a change of the frame size or of the codec, RESET command).
TYPE read / write Not used. The value is only stored: setParam accepts any value, getParam returns the last value set (default 0). It does not select the backend and does not report the backend in use: the encoder, decoder and GPU adapter are always selected automatically (see Overview).
CUSTOM_1 read / write Custom parameter 1. The value is only stored (default 0).
CUSTOM_2 read / write Custom parameter 2. The value is only stored (default 0).
CUSTOM_3 read / write Custom parameter 3. The value is only stored (default 0).

getParam method

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

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

Returns: Parameter value or -1 if the parameter is not supported.

executeCommand method

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

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

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

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 command descriptions for VCodecWmf.

Command Description
RESET Resets encoder and decoder state: they are created again by the next frame.
MAKE_KEY_FRAME Forces the next encoded frame to be an IDR keyframe via CODECAPI_AVEncVideoForceKeyFrame. It has no effect on the decoder and on the JPEG codec.

Build and connect to your project

Prerequisites and System Requirements

The library is designed for Windows 11 and later (x64 architecture).

  1. Operating System: Windows 11 (64-bit).
  2. Build Tools:
    • Microsoft Visual C++ (MSVC 19.51 of Visual Studio 2026 Build Tools was used to build and test the library) with the “Desktop development with C++” workload installed.
    • CMake version 3.13 or higher.
    • Windows 11 SDK (included with Visual Studio). All required system libraries are part of the standard Windows SDK:
      • Media Foundation (mfplat.lib, mfuuid.lib)
      • Direct3D 11 & DXGI (d3d11.lib, dxgi.lib)
      • Windows Imaging Component (windowscodecs.lib)
      • Shell & COM (shlwapi.lib, ole32.lib, oleaut32.lib)
  3. GPU Drivers:
    • For NVIDIA GPU hardware encoding/decoding: latest NVIDIA Game Ready or Studio drivers supporting NVENC/NVDEC.
    • For Intel integrated GPUs: latest Intel Graphics drivers with Quick Sync Video support.
    • For AMD GPUs: latest AMD Radeon Software drivers with AMF support.
  4. HEVC Codec Note:
    • Windows 11 includes native hardware HEVC MFT transforms when compatible GPU drivers are installed.
    • If software HEVC decoding is required on systems without hardware HEVC blocks, install the “HEVC Video Extensions” package from the Microsoft Store.

Build stand alone

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

<work folder>
    VCodecWmf
    Frame
    VCodec

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

cd VCodecWmf
cmake -B build -S .
cmake --build build --config Release

If VCodecWmf is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame and ../VCodec (in this order) before the library itself. If a folder does not exist CMake stops with an error. The compiled library is located in build/src/Release/VCodecWmf.lib, and the example and test executables in build/bin/Release/.

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 VCodecWmf is the top-level project).

Option Default Description
${PARENT}_VCODECWMF ON Build the library.
${PARENT}_VCODECWMF_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_VCODECWMF_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 VCodecWmf as a sub-repository.
CMAKE_BUILD_TYPE Release (if not specified) Build type.

Connect to your project

If you want to connect the VCodecWmf library to your CMake project as source code, you can follow these steps. VCodecWmf does not add its dependencies (Frame and VCodec) when it is included in another project: your project must add them before it links the library. 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 and VCodecWmf there (for example from the folder modules of the RapidPixel SDK). The new structure of your repository:

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

Create a CMakeLists.txt file in the 3rdparty folder. The CMakeLists.txt should contain (the libraries are added in the order of their dependencies: Frame, VCodec, VCodecWmf):

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_VCODECWMF                       ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VCODECWMF)
    SET(${PARENT}_VCODECWMF                             ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VCODECWMF_TEST                        OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VCODECWMF_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_VCODECWMF)
    add_subdirectory(VCodecWmf)
endif()

The file 3rdparty/CMakeLists.txt adds the folders Frame, VCodec and VCodecWmf to your project and will exclude test applications and examples from compiling. Your repository’s new structure will be:

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

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

add_subdirectory(3rdparty)

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

target_link_libraries(${PROJECT_NAME} VCodecWmf)

Done! If a project does not add Frame and VCodec, its build stops with the error Cannot open include file: 'VCodec.h': No such file or directory.

Portability

The library works only on Windows (the main CMakeLists.txt stops with an error on other systems): it uses Media Foundation, Direct3D 11, DXGI and Windows Imaging Component. It was built and tested for x64 with MSVC 19.51 (Visual Studio 2026 Build Tools); other compilers and Windows on ARM were not tested. The library has no CPU specific code: there are no SIMD intrinsics and no CPU specific compiler options. The conversion between NV12 and BGR24 for JPEG is made by plain C++ code; the operating system components choose their own CPU and GPU code at run time. The library does not serialize integers or floats: the frame data is passed as raw bytes, and the code does not depend on the byte order of the CPU.

Simple example

The example application generates gray frames with a moving white rectangle, encodes them to HEVC using VCodecWmf, and writes compressed data to a binary file “out.hevc”. Every call that can fail is checked:

#include <cstdint>
#include <cstring>
#include <fstream>
#include <iostream>
#include "VCodecWmf.h"



namespace
{
/// Width of the frames, pixels. The size must be even.
constexpr int FRAME_WIDTH{1280};
/// Height of the frames, pixels. The size must be even.
constexpr int FRAME_HEIGHT{720};
/// Number of frames to encode.
constexpr int FRAMES_NUMBER{200};
/// Value of the Y plane of the background (gray).
constexpr uint8_t BACKGROUND_LEVEL{128};
/// Value of the Y plane of the moving object (white).
constexpr uint8_t OBJECT_LEVEL{255};
/// Width and height of the moving object, pixels.
constexpr int OBJECT_SIZE{128};
/// Minimum distance between the moving object and the border of the frame,
/// pixels.
constexpr int OBJECT_MARGIN{5};
/// Name of the output file.
constexpr const char* OUTPUT_FILE_NAME{"out.hevc"};
}



int main()
{
    // Create codec and set params. Every call that can fail is checked.
    rapidpixel::VCodecWmf codec;
    if (!codec.setParam(rapidpixel::VCodecParam::BITRATE_KBPS, 7500.0f) ||
        !codec.setParam(rapidpixel::VCodecParam::GOP, 30.0f) ||
        !codec.setParam(rapidpixel::VCodecParam::FPS, 30.0f))
    {
        std::cout << "Cannot set codec parameters" << std::endl;
        return 1;
    }

    // Create NV12 frame and output HEVC frame. The frame has no data if its
    // size is not valid or memory is not available.
    rapidpixel::Frame frameNv12(FRAME_WIDTH, FRAME_HEIGHT,
                                rapidpixel::Fourcc::NV12);
    rapidpixel::Frame frameHEVC(FRAME_WIDTH, FRAME_HEIGHT,
                                rapidpixel::Fourcc::HEVC);
    if (frameNv12.data == nullptr || frameHEVC.data == nullptr)
    {
        std::cout << "Cannot create frames" << std::endl;
        return 1;
    }

    // Neutral chroma: the picture is gray with a white object.
    std::memset(frameNv12.data + FRAME_WIDTH * FRAME_HEIGHT, BACKGROUND_LEVEL,
                static_cast<size_t>(FRAME_WIDTH) * FRAME_HEIGHT / 2);

    // Create output file.
    std::ofstream outputFile(OUTPUT_FILE_NAME, std::ios::binary);
    if (!outputFile)
    {
        std::cout << "Cannot create file " << OUTPUT_FILE_NAME << std::endl;
        return 1;
    }

    // Params for moving object.
    int directionX = 1;
    int directionY = 1;
    int objectX = FRAME_WIDTH / 4;
    int objectY = FRAME_HEIGHT / 2;

    // Encode and record frames.
    int packetsNumber = 0;
    for (int n = 0; n < FRAMES_NUMBER; ++n)
    {
        // Draw moving object on the Y plane.
        std::memset(frameNv12.data, BACKGROUND_LEVEL,
                    static_cast<size_t>(FRAME_WIDTH) * FRAME_HEIGHT);
        for (int y = objectY; y < objectY + OBJECT_SIZE && y < FRAME_HEIGHT;
             ++y)
        {
            for (int x = objectX; x < objectX + OBJECT_SIZE &&
                 x < FRAME_WIDTH; ++x)
            {
                frameNv12.data[y * FRAME_WIDTH + x] = OBJECT_LEVEL;
            }
        }
        objectX += directionX;
        objectY += directionY;
        if (objectX >= FRAME_WIDTH - OBJECT_SIZE - OBJECT_MARGIN ||
            objectX <= OBJECT_SIZE + OBJECT_MARGIN)
        {
            directionX = -directionX;
        }
        if (objectY >= FRAME_HEIGHT - OBJECT_SIZE - OBJECT_MARGIN ||
            objectY <= OBJECT_SIZE + OBJECT_MARGIN)
        {
            directionY = -directionY;
        }

        // Encode.
        if (!codec.transcode(frameNv12, frameHEVC))
        {
            std::cout << "Cannot encode frame" << std::endl;
            continue;
        }

        // Write to file. The encoder can need more frames before it produces
        // a packet: the size of the frame is 0 then.
        if (frameHEVC.size > 0)
        {
            outputFile.write(reinterpret_cast<const char*>(frameHEVC.data),
                             frameHEVC.size);
            if (!outputFile)
            {
                std::cout << "Cannot write file " << OUTPUT_FILE_NAME
                          << std::endl;
                return 1;
            }
            ++packetsNumber;
        }
    }

    outputFile.close();
    std::cout << "Packets written: " << packetsNumber << std::endl;

    return packetsNumber > 0 ? 0 : 1;
}

Test application

The test application (test/main.cpp) for the VCodecWmf C++ library has four modes: Manual encoder test, Auto test (the time of encoding and decoding for all codecs and resolutions), Parameter & API tests (default values and ranges of the parameters, commands, pixel formats, invalid frames, invalid and damaged streams, a JPEG that declares a huge image) and Encoding & decoding tests (JPEG round trip, decoding of the test streams, layout of the decoded picture, encoding with H264 and HEVC, VBR and CBR switching, changes of the resolution and of the format, creation and destruction of many codecs (handles and threads), use from several threads, end of a process that used a codec). The mode is selected in the menu or with a command line argument: --manual (or 1), --auto (or 2), --param (or 3), --codec or --all (the Parameter & API tests, the Encoding & decoding tests and the Auto test). The argument --exit-check is used by the test of the end of the process (the application starts itself with it). The application returns 0 if all checks passed, 1 if a check failed and 2 if the argument is unknown. The tests write no files: the application checks that the run directory is not changed. The Manual encoder test writes the file with the encoded frames. The checks that need a test data file that is missing are skipped: the application prints SKIPPED with the name of the file and its folder, the skipped checks do not fail the run (see Test data). To run the application:

cd build\bin\Release
.\VCodecWmfTest.exe

After starting, you will see the mode selection menu:

========================================
  VCodecWmf v1.0.3 test
========================================

========================================
              SET MODE
========================================
  1 - Manual encoder
  2 - Auto test
  3 - Parameter & API tests
  4 - Encoding & decoding tests
  0 - Exit
>

Manual encoder mode

Allows to select a codec (H264, HEVC, or JPEG), use default parameters or enter custom ones (resolution, frame count, bitrate/GOP/FPS for H264/HEVC and profile for H264, or quality for JPEG), and encode a test video pattern. The test pattern consists of 8 colored vertical bars with a scrolling brightness wave and a white square bouncing diagonally. Encoded output is saved to out.h264, out.hevc, or out.jpeg. For JPEG, only the last encoded frame is kept in the file.

=== MANUAL ENCODER TEST ===
Codec (0-H264, 1-HEVC, 2-JPEG): 0

Defaults:
  Resolution: 1920x1080
  Frames: 100
  Bitrate: 3000 kbps
  FPS: 30
  GOP: 30
  Profile: Baseline

Use defaults? (1-yes, 0-no): 1

Output: out.h264
  Frame 100/100  size=5765  time=4.15 ms

========================================
           SUMMARY
========================================
Encoded: 100/100
Avg: 4.17 ms/frame
File: out.h264

Auto test mode

Runs encoding and decoding tests for all 3 codecs (H264, HEVC, JPEG) across 3 resolutions (1920x1080, 1280x720, 640x480) with 100 frames each. Decoding uses the test data files of the folder test/data (see Test data): a missing file is shown as NO DATA. After all tests complete, a summary table is displayed:

========================================
           AUTO TEST
========================================

=== ENCODING ===
  H264 1920x1080 ... 4.17 ms (100/100)
  H264 1280x720 ... 1.99 ms (100/100)
  H264 640x480 ... 1.07 ms (100/100)
  HEVC 1920x1080 ... 4.71 ms (100/100)
  HEVC 1280x720 ... 2.35 ms (100/100)
  HEVC 640x480 ... 1.22 ms (100/100)
  JPEG 1920x1080 ... 6.30 ms (100/100)
  JPEG 1280x720 ... 3.02 ms (100/100)
  JPEG 640x480 ... 0.96 ms (100/100)

=== DECODING ===
  H264 1920x1080 ... 8.53 ms (100/100)
  H264 1280x720 ... 8.12 ms (100/100)
  H264 640x480 ... 7.56 ms (100/100)
  HEVC 1920x1080 ... 8.53 ms (100/100)
  HEVC 1280x720 ... 7.41 ms (100/100)
  HEVC 640x480 ... 7.37 ms (100/100)
  JPEG 1920x1080 ... 5.43 ms (100/100)
  JPEG 1280x720 ... 2.40 ms (100/100)
  JPEG 640x480 ... 0.84 ms (100/100)

========================================
           SUMMARY
========================================

  Codec Res        | Encode             | Decode            
  ----- ---------- | ------------------ | ------------------
  H264  1920x1080  |   4.17 ms 100/100  |   8.53 ms 100/100 
  H264  1280x720   |   1.99 ms 100/100  |   8.12 ms 100/100 
  H264  640x480    |   1.07 ms 100/100  |   7.56 ms 100/100 
  ----- -----------+--------------------+-------------------
  HEVC  1920x1080  |   4.71 ms 100/100  |   8.53 ms 100/100 
  HEVC  1280x720   |   2.35 ms 100/100  |   7.41 ms 100/100 
  HEVC  640x480    |   1.22 ms 100/100  |   7.37 ms 100/100 
  ----- -----------+--------------------+-------------------
  JPEG  1920x1080  |   6.30 ms 100/100  |   5.43 ms 100/100 
  JPEG  1280x720   |   3.02 ms 100/100  |   2.40 ms 100/100 
  JPEG  640x480    |   0.96 ms 100/100  |   0.84 ms 100/100 

Test data

The test data files are not in the repository: to run the checks that need them, create the folder test/data and put the files of Table 5 in it. Without a file the checks that need it are skipped (SKIPPED with the name of the file and its folder), the summary line gives the number of skipped parts of the tests (Checks: ..., skipped: ..., result: ...) and the Auto test shows NO DATA.

Table 5 - Test data files supplied by the user.

File Content Tests that use the file
test_1920x1080.h264, test_1280x720.h264, test_640x480.h264 H264, Constrained Baseline profile, 4:2:0, 100 frames. Frames 0 and 60 are IDR pictures with SPS and PPS, the other frames are P-frames (no B-frames). The colors do not change from row to row at the top of the picture (vertical color bars). Decoding of the test streams, Layout of the decoded picture (the chroma rows 7 and 8 of frame 50), Auto test. test_640x480.h264 also: Decoding of invalid frames, Corruption campaign.
test_1920x1080.hevc, test_1280x720.hevc, test_640x480.hevc HEVC, Main profile, 4:2:0, 100 frames. Frames 0, 30, 60 and 90 are IDR pictures with VPS, SPS and PPS, the other frames are P-frames (no B-frames). The colors do not change from row to row at the top of the picture (vertical color bars). Decoding of the test streams, Layout of the decoded picture (the chroma rows 7 and 8 of frame 50), Auto test. test_640x480.hevc also: Decoding of invalid frames, Corruption campaign.
test_1920x1080.jpeg, test_1280x720.jpeg, test_640x480.jpeg JPEG, 100 frames: baseline JPEG images, 4:2:0. Decoding of the test streams, Auto test. test_640x480.jpeg also: Decoding of invalid frames, Hostile JPEG (the frame header of the first image), Corruption campaign.

A test data file has the number of frames (32-bit number), then for every frame its size in bytes (32-bit number) and its data: one access unit of an Annex B byte stream (NAL units with start codes) or one JPEG image. The numbers are little-endian. The size of the pictures is the size in the file name.

The files can be made from the test pattern of FFmpeg with the encoders libx264, libx265 and mjpeg and with Python 3. Save the script below as pack.py in the build folder. It writes the frames of a stream (the packets that FFprobe finds in it) to a test data file and creates the folder of the file:

import os
import struct
import subprocess
import sys

# Test data file: number of frames, then the size and the data of every frame
# (32-bit little-endian numbers). A frame is a packet of the stream (FFprobe).
stream, result = sys.argv[1], sys.argv[2]
data = open(stream, 'rb').read()
sizes = [int(size) for size in subprocess.run(
    ['ffprobe', '-v', 'error', '-show_entries', 'packet=size', '-of', 'csv=p=0',
     stream], capture_output=True, check=True, text=True).stdout.split()]
if sum(sizes) != len(data):
    sys.exit('The packets do not cover the stream')
os.makedirs(os.path.dirname(os.path.abspath(result)), exist_ok=True)
with open(result, 'wb') as file:
    file.write(struct.pack('<I', len(sizes)))
    position = 0
    for size in sizes:
        file.write(struct.pack('<I', size) + data[position:position + size])
        position += size

Then run the commands below in the build folder (checked with FFmpeg 6.1):

ffmpeg -y -f lavfi -i testsrc=size=1920x1080:rate=30 -frames:v 100 -pix_fmt yuv420p -c:v libx264 -profile:v baseline -g 60 -sc_threshold 0 stream.264
python pack.py stream.264 ..\test\data\test_1920x1080.h264
ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30 -frames:v 100 -pix_fmt yuv420p -c:v libx264 -profile:v baseline -g 60 -sc_threshold 0 stream.264
python pack.py stream.264 ..\test\data\test_1280x720.h264
ffmpeg -y -f lavfi -i testsrc=size=640x480:rate=30 -frames:v 100 -pix_fmt yuv420p -c:v libx264 -profile:v baseline -g 60 -sc_threshold 0 stream.264
python pack.py stream.264 ..\test\data\test_640x480.h264
ffmpeg -y -f lavfi -i testsrc=size=1920x1080:rate=30 -frames:v 100 -pix_fmt yuv420p -c:v libx265 -g 30 -bf 0 -x265-params open-gop=0:scenecut=0 stream.265
python pack.py stream.265 ..\test\data\test_1920x1080.hevc
ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30 -frames:v 100 -pix_fmt yuv420p -c:v libx265 -g 30 -bf 0 -x265-params open-gop=0:scenecut=0 stream.265
python pack.py stream.265 ..\test\data\test_1280x720.hevc
ffmpeg -y -f lavfi -i testsrc=size=640x480:rate=30 -frames:v 100 -pix_fmt yuv420p -c:v libx265 -g 30 -bf 0 -x265-params open-gop=0:scenecut=0 stream.265
python pack.py stream.265 ..\test\data\test_640x480.hevc
ffmpeg -y -f lavfi -i testsrc=size=1920x1080:rate=30 -frames:v 100 -pix_fmt yuvj420p -c:v mjpeg -q:v 2 stream.mjpeg
python pack.py stream.mjpeg ..\test\data\test_1920x1080.jpeg
ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30 -frames:v 100 -pix_fmt yuvj420p -c:v mjpeg -q:v 2 stream.mjpeg
python pack.py stream.mjpeg ..\test\data\test_1280x720.jpeg
ffmpeg -y -f lavfi -i testsrc=size=640x480:rate=30 -frames:v 100 -pix_fmt yuvj420p -c:v mjpeg -q:v 2 stream.mjpeg
python pack.py stream.mjpeg ..\test\data\test_640x480.jpeg

Table of contents