vcodecnv_web_logo

VCodecNv C++ library

v1.0.1

Table of contents

Overview

The VCodecNv C++ library provides video encoding and decoding for H264, HEVC (H265) and JPEG codecs on Windows and Linux. H264 and HEVC frames are encoded by the hardware encoder of the GPU (NVENC) and decoded by the hardware decoder of the GPU (NVDEC) through the API of the Video Codec SDK. NVENC does not encode JPEG: JPEG frames are encoded by the software encoder VEncoderJPEG. JPEG frames are decoded by NVDEC if the GPU decodes the image, otherwise by the software decoder VDecoderJPEG. The VCodecNv class inherits its interface and data structures from the VCodec library and uses the Logger library, which provides functions for printing logs. The library is written using the C++17 standard and is supplied as source code only. The library is a CMake project.

The platform is detected automatically: the CMake files and the source code select the Windows or the Linux implementation, the GPU and its capabilities are checked at run time. The library is not linked with the libraries of the GPU driver: the CUDA driver library (nvcuda.dll / libcuda.so.1), the NVENC library (nvEncodeAPI64.dll / libnvidia-encode.so.1) and the NVDEC library (nvcuvid.dll / libnvcuvid.so.1) are loaded when the first frame is processed. A program that uses the library also starts on a computer without the GPU driver: H264 and HEVC frames are not processed there (transcode(…) returns FALSE), JPEG frames are processed by the software codecs. To build the library, the headers of the Video Codec SDK are needed (the CUDA Toolkit is not needed): CMake finds them without settings and stops with an error if they are not found (see Build and connect to your project).

Operation of the encoder and the decoder:

  • The encoder works in the synchronous mode of NVENC with the low latency tuning of the presets, without B-frames and without look-ahead: every transcode(…) call returns the coded frame of its source frame (no frame delay). The H264 and HEVC streams declare that the pictures are not reordered (H264: VUI with bitstream_restriction_flag = 1 and max_num_reorder_frames = 0): a decoder does not have to hold pictures back for reordering.
  • The key frames are set by the library: the first frame, every GOP-th frame and the frame after the command MAKE_KEY_FRAME are IDR pictures with the parameter sets (H264: SPS and PPS, HEVC: VPS, SPS and PPS). A new GOP size is used at once.
  • The decoder works without display delay: a stream without B-frames gives the picture of every coded frame in the same transcode(…) call. A stream with B-frames gives the pictures in display order with the reorder delay of the stream.

The codecs are created again automatically when needed: the encoder when the frame size, the codec, the H264 profile, the preset or the GPU changes; the decoder follows a change of the picture size or of the format of the stream by itself (it changes the size of the NVDEC decoder or creates it again). The bitrate, the frame rate and the GOP size are changed without a new encoder, the bitrate mode too if the GPU supports it.

Encoding time on RTX 4050 Laptop GPU, Windows 11 (msec per frame, NV12 input, test pattern, 3000 kbps, 30 fps, preset P4; JPEG: software encoder, 1 thread, quality 80):

codec / resolution 1920x1080 1280x720 640x480
H264 ~3.7 msec ~2.0 msec ~1.2 msec
HEVC ~4.3 msec ~2.4 msec ~1.3 msec
JPEG ~1.3 msec ~0.6 msec ~0.2 msec

Decoding time on RTX 4050 Laptop GPU, Windows 11 (msec per frame, NV12 output, test data files; JPEG: NVDEC):

codec / resolution 1920x1080 1280x720 640x480
H264 ~3.4 msec ~2.0 msec ~0.9 msec
HEVC ~2.7 msec ~1.7 msec ~0.7 msec
JPEG ~2.5 msec ~1.6 msec ~0.8 msec

The times include the copy of the pictures between the system memory and the GPU. The first frame of a codec object takes longer: the GPU context, the encoder or the decoder are created (about 60 msec; the first object of a program also loads the GPU driver, about 1.5 sec).

VCodecNv 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 08.11.2026 First version.
1.0.1 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.
example --------------------- Folder with simple example of VCodecNv usage.
    CMakeLists.txt ---------- CMake file for example application.
    main.cpp ---------------- Source code file of example application.
static ---------------------- Folder with static project resources.
    vcodecnv_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.
    data -------------------- Pre-generated bitstreams for decoder tests.
        test_*.h264 --------- H264 test streams (1920x1080, 1280x720, 640x480; 176x144 with B-frames).
        test_*.hevc --------- HEVC test streams (1920x1080, 1280x720, 640x480; 176x144 lossless: 8-bit and 10-bit 4:2:0 and 4:4:4).
        test_*.jpeg --------- JPEG test streams (1920x1080, 1280x720, 640x480).
src ------------------------- Folder with source code of the library.
    CMakeLists.txt ---------- CMake file of the library.
    VCodecNv.cpp ------------ C++ implementation file.
    VCodecNv.h -------------- Header file which includes VCodecNv class declaration.
    VCodecNvVersion.h ------- Header file which includes version of the library.
    VCodecNvVersion.h.in ---- CMake service file to generate version file.
    impl -------------------- Internal implementation details.
        cuda ---------------- Folder with the declarations of the CUDA driver API.
            cuda.h ---------- Types of the CUDA driver API used by the library and by the NVDEC headers.
        NvApi.cpp ----------- Loading of the CUDA, NVENC and NVDEC libraries.
        NvApi.h ------------- Declaration of the loaded functions, GPU context.
        NvDecoder.cpp ------- NVDEC decoder implementation.
        NvDecoder.h --------- NVDEC decoder declaration.
        NvEncoder.cpp ------- NVENC encoder implementation.
        NvEncoder.h --------- NVENC encoder declaration.
        VCodecNvImpl.cpp ---- Internal implementation (parameters, codecs).
        VCodecNvImpl.h ------ Internal implementation declaration.

VCodecNv class description

VCodecNv class declaration

The VCodecNv class is declared in the VCodecNv.h file. Class declaration:

namespace rapidpixel
{
class VCodecNv : public VCodec
{
public:

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

    /// Class constructor.
    VCodecNv();

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

    /// The object can not be copied or moved.
    VCodecNv(const VCodecNv& src) = delete;
    VCodecNv(VCodecNv&& src) = delete;
    VCodecNv& operator=(const VCodecNv& src) = delete;
    VCodecNv& operator=(VCodecNv&& src) = delete;

    /// Encode or decode a 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;
};
}

All methods are thread-safe: the calls of one object are serialized by a mutex, a call waits while another thread is in transcode(…). Different objects can be used by different threads at the same time. The constructor allocates no GPU resource: the encoder or the decoder is created by the first transcode(…) call. The destructor releases the encoder, the decoder and the GPU context.

getVersion method

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

static std::string getVersion();

The method can be used without a VCodecNv class instance:

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

Console output:

VCodecNv class version: 1.0.1

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, the library encodes; if src is compressed and dst is NV12, the library decodes. The video codec processes frames one at a time. Switching between encoding and decoding releases the encoder or the decoder of the other direction. 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, even width and height in the range 2 - 8192, size equal to width * height * 3 / 2 and data pointing to that many bytes. The GPU limits the size further (H264 encoding: up to 4096 x 4096 on the tested GPU, HEVC up to 8192 x 8192; JPEG encoding needs at least about 16 x 16 pixels). For decoding: must have compressed format H264, HEVC or JPEG, data pointing to one complete coded frame and size (> 0) set to its length: an access unit of the Annex-B byte stream (start codes) for H264 and HEVC, one image for JPEG. The library can not check that data points to size bytes.
dst Result video frame (see Frame class description). For encoding: must have compressed format JPEG, H264, or HEVC. If its width or height differs from the source frame, its size is 0 or it has no data, the frame is allocated again (width * height * 4 bytes); otherwise data must point to at least width * height * 4 bytes. For decoding: must have raw pixel format NV12. The frame gets the picture with the size of the stream, rounded up to even numbers (the display area of the stream; an odd size is extended by one column or row); it is allocated again if its size or pixel format differs. frameId and sourceId are copied from the source frame of the returned picture.

Returns: TRUE if the frame was processed or FALSE if not: invalid pixel formats or frame fields, no GPU driver or no GPU (H264, HEVC), a frame size or a stream format that the GPU does not support (for example H264 4:2:2 streams; HEVC decoding needs at least 144 x 144 pixels on the tested GPU), a damaged coded frame, not enough memory. If FALSE is returned the content of dst is not defined. When decoding, a call can return TRUE with dst.size 0: a stream with B-frames gives its pictures in display order, the first pictures come after the frames that the stream reorders (the last pictures of such a stream stay in the decoder until the next frames or RESET). A damaged frame that NVDEC conceals gives a picture, a frame that it can not decode gives no picture; decoding continues with the next key frame. For damaged JPEG images the result (TRUE or FALSE) can differ between runs with the same data: it depends on the hardware decoder.

Encoding details: every call returns the coded frame of its source frame; the frame is a key frame (IDR picture with the parameter sets) for the first frame of an encoder, every GOP-th frame and the frame after the command MAKE_KEY_FRAME. The encoder is created again (the next frame is a key frame) when the frame size, the codec, the H264 profile, the preset (CUSTOM_2) or the GPU (CUSTOM_1) changes, and when the GPU can not change the bitrate or the bitrate mode of a running encoder.

Decoding details: the decoder supports the formats that NVDEC of the GPU supports. Pictures of formats other than 8-bit 4:2:0 are converted to NV12: high bit depth to 8 bits (rounding), 4:4:4 chroma to 4:2:0 (average of 2 x 2 samples), monochrome to gray chroma (128); the GPU converts them itself if it can. A change of the picture size of the stream (a new sequence header) is handled by the decoder: the next pictures have the new size. JPEG images are decoded by NVDEC if the GPU decodes their format and size (the tested GPU: 4:0:0, 4:2:0, 4:2:2 and 4:4:4 images of at least 64 x 64 pixels), otherwise by the software decoder VDecoderJPEG (see the parameter TYPE). Both decoders give the samples of the image without range conversion.

setParam method

The setParam(…) method is designed to set new video codec parameter values. Integer parameters truncate the value (FPS keeps fractions). The values are used by the next transcode(…) call. 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: not supported parameter ID (a value outside of the VCodecParam enum), NaN, infinity or a value out of the range of Table 2. If FALSE is returned the parameter is not changed. The only exception is CUSTOM_3: if the threads of the software JPEG codecs can not be created, FALSE is returned, the value is stored and the codecs keep their threads.

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.

Parameter Access Description
LOG_LEVEL read / write Logging mode. Values:
0 - Disable.
1 - Only terminal (console).
2 - Only file.
3 - File and terminal.
Default: 1. The file is written by the Logger library only if its log folder and file name are set (Logger::setSaveLogParams(…)). An error that is repeated by every frame (for example no GPU) is printed once, the number of repetitions is printed with the next other error. The software JPEG codecs get the same value.
BITRATE_KBPS read / write Bitrate in kbps. Range: 1 - 1,000,000 kbps. Default: 5000 kbps. For H264 and HEVC encoding. Constant bitrate mode: the bitrate of the stream (NVENC inserts no filler data: a simple picture can give fewer bits). Variable bitrate mode: the average bitrate (not lower than MIN_BITRATE_KBPS). A change is applied to the running encoder (no new encoder, no key frame) if the GPU supports it, otherwise the encoder is created again.
MIN_BITRATE_KBPS read / write Minimum bitrate in kbps for the variable bitrate mode. Range: 0 - 1,000,000 kbps. Default: 0 (no minimum). NVENC has no minimum bitrate control: if BITRATE_KBPS is lower than this value, the encoder uses this value as average bitrate. The encoder can still give fewer bits for a simple picture. Not used in the constant bitrate mode.
MAX_BITRATE_KBPS read / write Maximum (peak) bitrate in kbps for the variable bitrate mode. Range: 0 - 1,000,000 kbps. Default: 0. A value lower than the average bitrate (and 0) gives a peak equal to the average bitrate. Not used in the constant bitrate mode.
BITRATE_MODE read / write Bitrate mode for H264 and HEVC encoding: 0 - constant bitrate (default), 1 - variable bitrate. A change is applied to the running encoder if the GPU supports it, otherwise the encoder is created again (the tested GPU creates it again).
QUALITY read / write JPEG quality. Range: 0 - 100 (0 is stored as 1, the lowest quality; 100 is the highest quality). Default: 80. For JPEG encoding, used from the next frame.
FPS read / write Frame rate. Range: 1 - 1000 fps, fractions are allowed (29.97 is given to the encoder as 2997 / 100). Default: 30 fps. For H264 and HEVC encoding: the rate control divides the bitrate among the frames by this value, and the stream carries it in its timing information. A change is applied to the running encoder.
GOP read / write GOP size (period of key frames). Range: 1 - 10,000. Default: 30. For H264 and HEVC encoding. Value 1 means each output frame is a key frame, 20 means every 20th frame is a key frame, etc. The key frames are set by the library: a new value is used at once (no new encoder) and counts from the last key frame.
H264_PROFILE read / write H264 profile for H264 encoding:
0 - Baseline (default).
1 - Main.
2 - High.
A change creates a new encoder on the next H264 frame. HEVC frames are always encoded with the Main profile.
TYPE read / write Decoder of JPEG frames:
0 - NVDEC if the GPU decodes the image, the software decoder VDecoderJPEG otherwise (default).
1 - The software decoder VDecoderJPEG only.
H264 and HEVC frames are always encoded and decoded by the GPU, JPEG frames are always encoded by the software encoder VEncoderJPEG.
CUSTOM_1 read / write Index of the GPU (CUDA device). Range: 0 - 63. Default: 0. A change creates the encoder or the decoder again on the next frame. A GPU that does not exist gives FALSE for H264 and HEVC frames; JPEG frames are processed by the software codecs then.
CUSTOM_2 read / write Preset of NVENC: 1 (P1, fastest) - 7 (P7, best quality). Default: 4. The presets are used with the low latency tuning. A change creates a new encoder on the next frame.
CUSTOM_3 read / write Number of threads of the software JPEG codecs (VEncoderJPEG, VDecoderJPEG): 0 - automatic, 1 - 32 threads. Default: 1. Applied at once.

Note on parameter change behavior. Parameters BITRATE_KBPS, MIN_BITRATE_KBPS, MAX_BITRATE_KBPS and FPS are applied to the running encoder by the reconfiguration function of NVENC: the stream continues without a key frame. GOP is applied by the library without NVENC. BITRATE_MODE is applied in the same way if the GPU supports it. H264_PROFILE, CUSTOM_1 and CUSTOM_2 need a new encoder, which the next transcode(…) call creates (the frame is a key frame and takes longer). QUALITY and CUSTOM_3 are applied to the software JPEG codecs at once.

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 (the value that was set) or -1 if the ID is not supported (a value outside of the VCodecParam enum).

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 executed or FALSE if the ID is not supported (a value outside of the VCodecCommand enum).

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.

Command Description
RESET Release the encoder, the decoder (with the pictures that it holds), the software JPEG codecs and the GPU context. The parameters are kept. The next frame creates the codec again: an encoded stream starts with a key frame, a decoder waits for the next key frame of the stream.
MAKE_KEY_FRAME The next encoded H264 or HEVC frame is a key frame (IDR picture with the parameter sets). The command is accepted at any time (every JPEG frame and the first frame of an encoder are key frames).

Build and connect to your project

The library is built on Windows (x64) with Visual Studio 2022 and CMake 3.21 or newer (the first CMake version with the generator of Visual Studio 2022) and on Linux with GCC or Clang and CMake 3.13 or newer. On Linux install the build tools:

sudo apt-get -y install build-essential cmake git

The library needs the headers of the Video Codec SDK 12.0 or newer: nvEncodeAPI.h of the NVENC API, nvcuvid.h and cuviddec.h of the NVDEC API. The CUDA Toolkit is not needed: the types of the CUDA driver API that the library and the NVDEC headers use are declared in the file src/impl/cuda/cuda.h of the library (cuviddec.h includes it as <cuda.h>: its folder is the first folder of the include path of the library, so it is used also when the folder of the SDK headers contains the cuda.h of a CUDA Toolkit). No library is linked: the libraries of the GPU driver are loaded at run time. The src/CMakeLists.txt file searches the headers of the Video Codec SDK without settings in the folders Video_Codec_SDK* and Video_Codec_Interface* next to the VCodecNv folder (of several such folders, the folder with the greatest name first) and then in the default search folders of CMake: the system include folders (Linux: for example /usr/local/include) and on Windows also the folders include next to the folders bin of the PATH (for example the include folder of an installed CUDA Toolkit). The first folder that has nvEncodeAPI.h is used.

The configuration stops with an error if a header of the Video Codec SDK is not found or if the NVENC API version of nvEncodeAPI.h is older than 12.0. This also applies when VCodecNv is included in another CMake project: the configuration of that project stops, a VCodecNv library without the headers of the NVENC and NVDEC API is not built. CMake prints the found headers, for example:

-- Video Codec SDK headers: <work folder>/Video_Codec_Interface_13.1.24/Interface (NVENC API 13.1)

To run the encoder and the decoder, the computer needs a GPU with NVENC and NVDEC and a GPU driver that supports the NVENC API version of the headers the library was built with. The minimum driver version of a Video Codec SDK version is given in the Read Me of the SDK (Video Codec SDK 13.1: driver 610 or newer). With an older driver H264 and HEVC encoding fails and the library logs the NVENC API versions of the driver and of the headers: update the driver or build the library with the headers of an older Video Codec SDK. The library was tested with the interface headers of the Video Codec SDK 13.1, CMake 3.27 (Windows) and 3.28 (Linux) and the GPU driver 610.60.

Installation on Windows:

  • GPU driver: the driver installs the CUDA, NVENC and NVDEC libraries (nvcuda.dll, nvEncodeAPI64.dll and nvcuvid.dll) into the system folder C:\Windows\System32. The library loads them only from this folder.
  • Video Codec SDK: download the archive of the SDK or of its interface package (headers only) and unpack it next to the VCodecNv folder, or copy the three headers of its Interface folder into a folder include next to a folder bin of the PATH, for example %CUDA_PATH%\include of an installed CUDA Toolkit (administrator rights needed).

Installation on Linux:

  • GPU driver: the library needs the libraries libcuda.so.1, libnvidia-encode.so.1 and libnvcuvid.so.1 of the driver. On Ubuntu the packages nvidia-driver-<version> and nvidia-driver-<version>-server install them. The headless packages (nvidia-headless-<version>, nvidia-headless-<version>-server) do not: install the packages libnvidia-encode-<version> and libnvidia-decode-<version> too (with the suffix -server for the server driver).
  • Video Codec SDK: unpack the archive next to the VCodecNv folder, or copy the three headers of its Interface folder into /usr/local/include (root rights needed).
  • WSL 2: the GPU driver of Windows provides the driver libraries (folder /usr/lib/wsl/lib): do not install a GPU driver in WSL.

Build stand alone

The repository does not contain sub-repositories. The libraries VCodecNv depends on (Frame, VCodec, Logger, VDecoderJPEG, VEncoderJPEG) must be placed in the same folder as VCodecNv: copy their folders, for example from the folder modules of the RapidPixel SDK. The Video Codec SDK (or its interface headers package) can be unpacked into the same folder too: CMake finds it there. The folder structure must be:

<work folder>
    VCodecNv
    Frame
    VCodec
    Logger
    VDecoderJPEG
    VEncoderJPEG
    Video_Codec_Interface_13.1.24 (on Linux not needed if the headers are in a system include folder)

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

cd VCodecNv
mkdir build
cd build
cmake ..
make

On Windows use cmake .. -G "Visual Studio 17 2022" -A x64 and cmake --build . --config Release instead of make. If VCodecNv is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame, ../VCodec, ../Logger, ../VDecoderJPEG and ../VEncoderJPEG (in this order) before the library itself. If a folder does not exist CMake stops with an error. The test application and the example are built into the build/bin folder (on Windows 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 VCodecNv is the top-level project).

Option Default Description
${PARENT}_VCODEC_NV ON Build the library.
${PARENT}_VCODEC_NV_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_VCODEC_NV_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 VCodecNv as a sub-repository. To switch off the test application or the example of a stand alone build, set it to OFF too, for example: cmake -D_SUBMODULE_CACHE_OVERWRITE=OFF -D_VCODEC_NV_EXAMPLE=OFF ..
VIDEO_CODEC_SDK_INCLUDE_DIR found by CMake Folder of the headers of the Video Codec SDK (cache variable). Not needed: CMake finds the headers (see above). It can be set to use the headers of another folder.
CMAKE_BUILD_TYPE Release (if not specified) Build type.
BUILD_SHARED_LIBS OFF (not defined) Standard CMake variable: ON builds the libraries as dynamic libraries.

Connect to your project

If you want to connect the VCodecNv library to your CMake project as source code, you can do the following. The VCodecNv library does not add its dependencies when it is included in another CMake project: your project must add the Frame, VCodec, Logger, VDecoderJPEG and VEncoderJPEG libraries. 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, Logger, VDecoderJPEG, VEncoderJPEG and VCodecNv 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_LOGGER                          ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_LOGGER)
    SET(${PARENT}_LOGGER                                ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_LOGGER_EXAMPLE                        OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VDECODERJPEG                    ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VDECODERJPEG)
    SET(${PARENT}_VDECODERJPEG                          ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VDECODERJPEG_EXAMPLE                  OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VENCODERJPEG                    ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VENCODERJPEG)
    SET(${PARENT}_VENCODERJPEG                          ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VENCODERJPEG_TEST                     OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VENCODERJPEG_EXAMPLE                  OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VENCODERJPEG_BENCHMARK                OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VCODEC_NV                       ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VCODEC_NV)
    SET(${PARENT}_VCODEC_NV                             ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VCODEC_NV_TEST                        OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VCODEC_NV_EXAMPLE                     OFF CACHE BOOL "" FORCE)
endif()

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

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

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

if (${PARENT}_SUBMODULE_VDECODERJPEG)
    add_subdirectory(VDecoderJPEG)
endif()

if (${PARENT}_SUBMODULE_VENCODERJPEG)
    add_subdirectory(VEncoderJPEG)
endif()

if (${PARENT}_SUBMODULE_VCODEC_NV)
    add_subdirectory(VCodecNv)
endif()

The 3rdparty/CMakeLists.txt file adds the Frame, VCodec, Logger, VDecoderJPEG, VEncoderJPEG and VCodecNv folders to your project (the dependencies first, then the library) and excludes the test applications, examples and benchmarks. The structure of your repository will be:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    Frame
    VCodec
    Logger
    VDecoderJPEG
    VEncoderJPEG
    VCodecNv

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

target_link_libraries(${PROJECT_NAME} VCodecNv)

The headers of the Video Codec SDK are found by the src/CMakeLists.txt file of VCodecNv as described above: nothing has to be set when you configure your project (the Video Codec SDK can be unpacked into the 3rdparty folder, next to VCodecNv). If they are not found, the configuration of your project stops with the error of VCodecNv. Linking VCodecNv also links its dependencies: VCodec and Logger (and through VCodec the Frame library), VDecoderJPEG, VEncoderJPEG, the thread library (CMake target Threads::Threads) and on Linux the dl library (${CMAKE_DL_LIBS}). A program that is linked without CMake must link them too (on Linux for example -pthread -ldl). The headers of the Video Codec SDK and src/impl/cuda/cuda.h are used only to build the library: the public header VCodecNv.h does not include them, a project that includes VCodecNv.h does not see them.

The dependencies can be added before or after VCodecNv. If your project does not add the Frame, VCodec, Logger, VDecoderJPEG and VEncoderJPEG libraries, the compilation of VCodecNv stops with an error about a header of a missing library, for example Logger.h: No such file or directory.

Simple example

The example generates 60 video frames 1280x720 (NV12) with moving color stripes, encodes every frame to H264 with one codec object and decodes it back to NV12 with a second codec object. If a frame can not be encoded or decoded (for example without a GPU), the example stops with an error message:

#include <cstdint>
#include <iostream>
#include "VCodecNv.h"

int main()
{
    std::cout << "VCodecNv version: " << rapidpixel::VCodecNv::getVersion() << std::endl;

    // Encoder: H264, 2500 kbps, 30 fps, a key frame every 30 frames.
    rapidpixel::VCodecNv encoder;
    encoder.setParam(rapidpixel::VCodecParam::BITRATE_KBPS, 2500);
    encoder.setParam(rapidpixel::VCodecParam::FPS, 30);
    encoder.setParam(rapidpixel::VCodecParam::GOP, 30);

    // Decoder: a second codec object (an object either encodes or decodes).
    rapidpixel::VCodecNv decoder;

    // Source frame (NV12), encoded frame (H264) and decoded frame (NV12).
    rapidpixel::Frame sourceFrame(1280, 720, rapidpixel::Fourcc::NV12);
    rapidpixel::Frame encodedFrame(1280, 720, rapidpixel::Fourcc::H264);
    rapidpixel::Frame decodedFrame(1280, 720, rapidpixel::Fourcc::NV12);

    for (int n = 0; n < 60; ++n)
    {
        // Generate the picture: color stripes that move by 4 pixels every frame.
        for (int i = 0; i < sourceFrame.size; ++i)
        {
            sourceFrame.data[i] = static_cast<uint8_t>(i + n * 4);
        }

        // Encode the picture to H264.
        if (!encoder.transcode(sourceFrame, encodedFrame))
        {
            std::cout << "Can't encode frame " << n << std::endl;
            return -1;
        }

        // Decode the H264 frame back to a picture.
        if (!decoder.transcode(encodedFrame, decodedFrame))
        {
            std::cout << "Can't decode frame " << n << std::endl;
            return -1;
        }

        std::cout << "Frame " << n << ": encoded " << encodedFrame.size << " bytes, decoded " << decodedFrame.width << "x" << decodedFrame.height << std::endl;
    }

    return 0;
}

Console output:

VCodecNv version: 1.0.1
Frame 0: encoded 5231 bytes, decoded 1280x720
Frame 1: encoded 5399 bytes, decoded 1280x720
Frame 2: encoded 871 bytes, decoded 1280x720
...
Frame 29: encoded 839 bytes, decoded 1280x720
Frame 30: encoded 8319 bytes, decoded 1280x720
...
Frame 59: encoded 991 bytes, decoded 1280x720

Frames 0 and 30 are key frames (GOP 30). The sizes of the encoded frames depend on the GPU and its driver.

Test application

The test application (VCodecNv/test/main.cpp) for the VCodecNv C++ library runs all tests without user input and returns 0 if all tests passed. It checks the version, the default, valid and invalid parameters, the commands and invalid frames (these tests need no GPU), then encodes a test pattern with all 3 codecs (H264, HEVC, JPEG) in 3 resolutions (1920x1080, 1280x720, 640x480, 100 frames each, every frame must give its coded frame), decodes the test data files of the test/data folder (every frame must give its picture in the same call), encodes moving pictures and decodes them again (the luma and the chroma PSNR must be at least 30 dB), checks the positions of the key frames (GOP, MAKE_KEY_FRAME, a GOP change), the rate changes without a new encoder (the size of the coded frames must follow the bitrate and the frame rate) and the H264 profiles, encodes and decodes streams whose picture size changes, decodes HEVC streams of other formats (10-bit and 4:4:4: the pictures must be equal to the 8-bit 4:2:0 stream of the same pictures) and an H264 stream with B-frames, decodes JPEG images of all chroma formats, of an odd size and of a size that NVDEC does not decode with both JPEG decoders, decodes damaged copies of the test data, calls the parameter methods from several threads while a frame is encoded, runs several objects in parallel threads, creates and destroys 40 codec objects (a GPU limits the number of its encoder sessions), selects a GPU that does not exist and switches one object between the codecs and the directions. H264 and HEVC tests are reported as N/S if the computer has no GPU with NVENC and NVDEC (or no GPU driver); with the option –require-gpu this is a test failure. The application writes no files. To run the application on Linux:

cd build
./bin/VCodecNvTest --require-gpu

On Windows run build\bin\Release\VCodecNvTest.exe –require-gpu. Output of the application on Windows 11 with RTX 4050 Laptop GPU:

=================================================
VCodecNv v1.0.1 test
=================================================

GPU: H264 encoding and decoding works

Version:
  VCodecNv version: 1.0.1
OK (0.0 s)

Default parameters:
OK (0.0 s)

...

Rate change:
  H264: 9025 bytes/frame (2000 kbps, 30 fps), 27504 (6000 kbps), 74925 (6000 kbps, 10 fps), 88116 (variable bitrate, new encoder)
  HEVC: 8559 bytes/frame (2000 kbps, 30 fps), 23938 (6000 kbps), 74319 (6000 kbps, 10 fps), 48825 (variable bitrate, new encoder)
OK (0.8 s)

...

Stream formats:
  8-bit 4:2:0: 16 pictures
  10-bit 4:2:0: 4 pictures equal to 8-bit 4:2:0
  8-bit 4:4:4: 4 pictures equal to 8-bit 4:2:0
  10-bit 4:4:4: 4 pictures equal to 8-bit 4:2:0
  H264 with B-frames: 14 pictures, 2 calls without picture, min PSNR 45.3 dB
OK (0.3 s)

...

Summary:
  Codec Res        | Encode             | Decode
  H264  1920x1080  |   3.66 ms 100/100  |   3.38 ms 100/100
  H264  1280x720   |   2.04 ms 100/100  |   1.99 ms 100/100
  H264  640x480    |   1.23 ms 100/100  |   0.85 ms 100/100
  HEVC  1920x1080  |   4.33 ms 100/100  |   2.73 ms 100/100
  HEVC  1280x720   |   2.44 ms 100/100  |   1.72 ms 100/100
  HEVC  640x480    |   1.28 ms 100/100  |   0.74 ms 100/100
  JPEG  1920x1080  |   1.25 ms 100/100  |   2.52 ms 100/100
  JPEG  1280x720   |   0.58 ms 100/100  |   1.55 ms 100/100
  JPEG  640x480    |   0.18 ms 100/100  |   0.84 ms 100/100

All tests passed

The summary shows the mean processing time of a frame and the number of frames with output.

Portability

The library is built for Windows and Linux (on other systems the configuration stops with an error); the operating system is detected by CMake and by the compiler. It was built without warnings by Visual Studio 2022 (MSVC 19.36) and by GCC 12 and 13 and Clang 15 and 18 for x86-64 (Release and Debug), and by GCC 13 and Clang 18 for aarch64 (cross compilation; the tests that need no GPU were run under emulation). A cross compilation needs no files of the target processor besides its compiler and C++ library: the headers of the Video Codec SDK do not depend on the processor and are searched on the host too. The types of src/impl/cuda/cuda.h have the sizes, values and layout of the CUDA driver API of 64-bit systems (checked for x86-64 with MSVC, GCC and Clang and for aarch64 with GCC). The encoder and the decoder were tested on Windows 11 and on Linux (Ubuntu 24.04 under WSL 2) with the same GPU: the coded frames and the decoded pictures are the same on both systems. The library loads the CUDA, NVENC and NVDEC libraries of the GPU driver at run time (Windows: from the system folder only; Linux: through the search path of the dynamic linker) and needs a driver that supports the NVENC API version of the Video Codec SDK headers it was built with. The test data files of the test/data folder store the frame count and the frame sizes as 32-bit little-endian numbers; the test application reads them byte by byte, independent of the byte order of the processor.


Table of contents