vencoderjpeg_web_logo

VEncoderJPEG C++ library

v1.0.3

Table of contents

Overview

The VEncoderJPEG C++ library provides a standalone software JPEG image and Motion-JPEG (MJPEG) video encoder for Windows, Linux and embedded platforms. The VEncoderJPEG class inherits the interface and data structures of the VCodec interface library and does not need a hardware encoder. The library depends on the VCodec library (codec interface) and on the Frame library (video frame class) used by VCodec; their repositories are not part of this repository (see Build and connect to your project). It also links the thread library of the system (CMake Threads::Threads, -pthread on Linux). The library uses the C++17 standard. Key features:

  • Baseline JPEG (ITU-T T.81, SOF0) with JFIF 1.02 header: 8-bit samples, standard Annex K Huffman tables, Annex K quantization tables scaled by the quality parameter with the scaling of RFC 2435, Appendix A (quality 100 gives steps of 1).
  • Input pixel formats: NV12, NV21, YU12 (I420), YV12, YUYV, UYVY, RGB24, BGR24, YUV24 and GRAY - every raw format of the Frame class.
  • Chroma subsampling: 4:2:0, 4:2:2, 4:4:4 and grayscale, selected automatically from the source format or set explicitly. Chroma is averaged or repeated when the source chroma resolution differs from the encoded one.
  • Multi-threading with identical output: a frame is split into bands of MCU rows that are transformed and Huffman-coded in parallel and then joined at bit level. The stream is byte-identical for any number of threads and contains no restart markers, so it can be decoded by any JPEG decoder.
  • Performance: 1920x1080 NV12 camera frame (quality 80) in 2.7 ms on one core, 0.75 ms with automatic threads (see Quality and performance). SSE2, SSSE3 and AVX2 kernels selected at run time from the CPU, so one binary runs on every x86-64 CPU; portable C++ kernels on other platforms; all kernels produce identical streams (see Portability).
  • Input validation: invalid frames and parameters are rejected without memory access outside the source data; the output never exceeds the buffer size the Frame class allocates for compressed data; the methods throw no exceptions, memory or thread shortage is reported by the return value (see Security).
  • No sensitive data left behind: internal buffers holding frame data are overwritten with zeros by the RESET command and by the destructor.

VEncoderJPEG 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.0.1 07.10.2026 SSE2, SSSE3 and AVX2 kernels selected at run time: the default build runs on every x86-64 CPU (the default build of 1.0.0 needed AVX2). Compiler warning and exploit mitigation options for all targets. Internal code reorganization. The encoded streams are unchanged.
1.0.2 15.10.2026 VCodec sub-repository removed: the VCodec and Frame libraries are added from the folders next to the repository or by the top-level project. Test application with self-checking tests (encoding and decoding of all pixel formats, invalid frames, parameters, threads); it writes no files. The example checks the results of all calls. Documentation updated. The encoded streams are unchanged.
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.
README.md ----------------------- Documentation.
src ----------------------------- Folder with library source code.
    CMakeLists.txt -------------- CMake file of the library.
    VEncoderJPEG.h -------------- Main library header file (PIMPL).
    VEncoderJPEG.cpp ------------ Public class implementation.
    VEncoderJPEGVersion.h ------- Header file with library version.
    VEncoderJPEGVersion.h.in ---- File for CMake to generate version header.
    impl ------------------------ Internal implementation (namespace rapidpixel::jpegenc, VEncoderJPEGImpl in rapidpixel).
        VEncoderJPEGImpl.h/.cpp - Parameters, validation, destination frame management.
        FrameEncoder.h/.cpp ----- Encoder core: bands of MCU rows, threads, stream assembly.
        CodingSetup.h/.cpp ------ Geometry, tables and stream header kept between frames.
        SimdLevel.h/.cpp -------- Run-time selection of the kernel level (CPUID, XGETBV).
        BandCoder.h ------------- Interface of the kernel levels (bands, working memory).
        LevelConfig.h ----------- Instruction sets and namespace of the kernel level.
        LevelKernels.h ---------- Functions shared by the kernel sources of a level.
        BandCoder.cpp ----------- Kernel source: transform and coding of a band.
        StripFetch.cpp ---------- Kernel source: source formats to plane strips.
        ColorKernels.cpp -------- Kernel source: RGB to YCbCr conversion (JFIF).
        SpectrumKernels.h/.cpp -- Kernel source: forward DCT and quantization.
        TileCoder.h ------------- Kernel code: Huffman coding of quantized tiles.
        BitPacker.h ------------- Kernel code: bit accumulation of the Huffman coder.
        SourceAdapter.h/.cpp ---- Source pixel formats, conversion plan, range test.
        PictureLayout.h --------- Picture geometry (planes, MCU, tile order).
        BitSplicer.h/.cpp ------- Joining of bit sequences and 0xFF byte stuffing.
        StreamHeader.h/.cpp ----- JPEG marker segments (SOI, APP0, DQT, SOF0, DHT, SOS, EOI).
        QuantSteps.h/.cpp ------- Standard quantization tables, quality scaling.
        PrefixCodes.h/.cpp ------ Standard Huffman tables, canonical codes.
        WipedBuffer.h/.cpp ------ Byte buffer cleared before it is freed.
        WorkerPool.h/.cpp ------- Thread pool.
        BitOps.h ---------------- Portable bit and memory operations.
test ---------------------------- Folder for test application.
    CMakeLists.txt -------------- CMake file for test application.
    main.cpp -------------------- Source C++ file of test application.
example ------------------------- Folder for simple example.
    CMakeLists.txt -------------- CMake file of example.
    main.cpp -------------------- Source C++ file of example.
benchmark ----------------------- Folder for benchmark application.
    CMakeLists.txt -------------- CMake file of benchmark.
    main.cpp -------------------- Source C++ file of benchmark.
static -------------------------- Folder with static files (logo).

VEncoderJPEG class description

VEncoderJPEG class declaration

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

namespace rapidpixel
{
class VEncoderJPEG : public VCodec
{
public:

    /// Class constructor.
    VEncoderJPEG();

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

    /// Copy constructor (deleted).
    VEncoderJPEG(const VEncoderJPEG&) = delete;

    /// Move constructor (deleted).
    VEncoderJPEG(VEncoderJPEG&&) = delete;

    /// Copy assignment operator (deleted).
    VEncoderJPEG& operator=(const VEncoderJPEG&) = delete;

    /// Move assignment operator (deleted).
    VEncoderJPEG& operator=(VEncoderJPEG&&) = delete;

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

    /// Encode raw frame to JPEG.
    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: calls from different threads are serialized by an internal mutex. To encode several streams in parallel create one encoder object per stream. The encoder owns worker threads and buffers, so objects can be neither copied nor moved; use std::unique_ptr to pass an encoder around. The constructor throws std::bad_alloc if the memory of the encoder can’t be allocated; the other methods do not throw exceptions. The destructor stops the threads and overwrites the internal buffers (data of the last frame) with zeros before releasing them.

getVersion method

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

static std::string getVersion();

This method can be used without a VEncoderJPEG class instance:

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

Console output:

VEncoderJPEG class version: 1.0.3

transcode method

The transcode(…) method encodes a raw video frame (Frame class) into a JPEG image. Every frame is encoded independently, so a sequence of frames forms a Motion-JPEG stream. Method declaration:

bool transcode(Frame& src, Frame& dst) override;
Parameter Value
src Source raw frame. Supported pixel formats (field fourcc): NV12, NV21, YU12, YV12, YUYV, UYVY, RGB24, BGR24, YUV24 and GRAY. Width and height: 1 - 65535 pixels and width * height * 4 not larger than INT_MAX; YUYV and UYVY need an even width, NV12, NV21, YU12 and YV12 need an even width and height. The field data must not be nullptr and the field size must be at least the size of the pixel format (for example width * height * 3 / 2 for NV12). The source frame is checked before any sample is read; the encoder reads only the first size bytes of the data, which must be readable (the method can’t check it).
dst Result frame, another object than src. The encoder always produces Fourcc::JPEG data, so the frame does not need to be prepared. If dst has no data, its format is not Fourcc::JPEG or its width or height differ from the source, the frame is reallocated as Frame(src.width, src.height, Fourcc::JPEG). Otherwise its memory must hold width * height * 4 bytes, as the Frame class allocates for JPEG frames. After encoding dst.size holds the size of the JPEG image; frameId and sourceId are copied from the source.

Returns: TRUE if the frame was encoded or FALSE if not (unsupported format, invalid size or data size, src and dst being the same object, image too small for the JPEG headers or stream too large, not enough memory). If FALSE is returned dst is not changed, except when its reallocation failed: dst has no data then. The method does not throw exceptions.

The Frame class allocates width * height * 4 bytes for compressed formats and copies of frames rely on that size, so the encoded image never exceeds it:

  • images smaller than about 13x13 pixels (10x10 pixels for grayscale) are refused, because the JPEG headers alone (607 bytes for colour and 324 bytes for grayscale images) and the shortest data do not fit;
  • a frame whose stream would exceed the limit is encoded again with reduced quality (a message is printed when logging is enabled). This happens for small images at high quality, where the headers take most of the limit (for example 16x16 pixels with fine texture or noise at quality 100), and for extreme noise at quality above about 95 with 4:4:4 subsampling. A 1920x1080 camera image at quality 100 needs 22 % of the limit with 4:2:0 subsampling and 39 % with 4:4:4 subsampling;
  • images of up to about 16x16 pixels with extreme noise may not fit even with quality 1: such frames are refused.

setParam method

The setParam(…) method sets encoder parameters. Method declaration:

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

Returns: TRUE if the parameter was set or FALSE if the parameter is not supported or the value is invalid. The value is rounded to the nearest integer (halves away from zero); a value whose rounded result is outside of the valid range, NaN and infinity are refused and leave the parameter unchanged.

The VCodec.h file of the VCodec library defines IDs of parameters (VCodecParam enum) and commands (VCodecCommand enum). New values are applied from the next frame.

Table 2 - Encoder parameters.

Parameter Access Description
LOG_LEVEL read / write Logging mode: 0 - disabled (default), 1 - console (messages to stderr), 2 - file (accepted, the library has no file output), 3 - console and file (console only). Messages describe refused frames and parameters.
QUALITY read / write JPEG quality 1 - 100, default 80. The value scales the Annex K quantization tables as described in RFC 2435, Appendix A; quality 100 gives steps of 1. 0 is accepted and treated as 1; values outside 0 - 100 are refused.
CUSTOM_1 read / write Chroma subsampling:
0 - automatic (default): 4:2:0 for NV12, NV21, YU12, YV12, RGB24, BGR24 and YUV24, 4:2:2 for YUYV and UYVY, grayscale for GRAY.
1 - 4:2:0.
2 - 4:2:2.
3 - 4:4:4.
4 - grayscale (luma only).
Chroma of higher resolution than encoded is averaged, chroma of lower resolution is repeated; a GRAY source encoded with colour gets neutral chroma.
CUSTOM_2 read / write Number of encoding threads:
1 - single thread (default).
0 - automatic: number of logical processors, at most 16.
N = 2 - 64 - N threads.
Small frames use fewer threads than configured (at least 300 MCUs per thread). The encoded stream does not depend on this parameter. If the system cannot create all threads, setParam(…) returns FALSE and the encoder continues with the threads that were started (their number is returned by getParam(…)).
CUSTOM_3 read / write Numeric range of YUV and GRAY sources (RGB sources are always full range):
0 - pass-through (default): samples are encoded as they are.
1 - automatic: frames that look like limited range video (no luma levels below 14 or above 238, luma reaching the limited range black or white level) are expanded to full range. Low-contrast full range content (fog, haze) is left unchanged.
2 - expansion of limited range: luma [16..235] and chroma [16..240] to [0..255].
JFIF images are full range: use 1 or 2 for sources in limited range (typical for video capture and decoders) to get correct contrast in image viewers.
TYPE read / write Not supported.
BITRATE_KBPS, MIN_BITRATE_KBPS, MAX_BITRATE_KBPS, BITRATE_MODE, FPS, GOP, H264_PROFILE read / write Not supported (JPEG has no rate control).

Example:

rapidpixel::VEncoderJPEG encoder{};
// Quality 90, 4:4:4 subsampling, automatic number of threads.
if (!encoder.setParam(rapidpixel::VCodecParam::QUALITY, 90) ||
    !encoder.setParam(rapidpixel::VCodecParam::CUSTOM_1, 3) ||
    !encoder.setParam(rapidpixel::VCodecParam::CUSTOM_2, 0))
{
    std::cout << "Parameter not set" << std::endl;
}

getParam method

The getParam(…) method returns encoder parameter values. Method declaration:

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

Returns: parameter value or -1 if the parameter is not supported. QUALITY returns the applied value (1 - 100), CUSTOM_2 returns the value as set (0 for automatic) or the number of running threads if not all threads could be started.

executeCommand method

The executeCommand(…) method executes encoder commands. Method declaration:

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

Table 3 - Encoder commands.

Command Description
RESET Overwrites internal buffers (data of the last frame) with zeros, releases them and clears the cached state. Parameters are kept; the next frame is encoded normally.
MAKE_KEY_FRAME Accepted (returns TRUE) and has no effect: every JPEG frame is independently decodable.

Returns: TRUE if the command was executed or FALSE if the command is not supported.

Output stream format

Every encoded frame is a complete JFIF file:

Segment Content
SOI Start of image.
APP0 JFIF 1.02, aspect ratio 1:1, no thumbnail.
DQT Luma table 0 and (for colour images) chroma table 1, 8-bit, zigzag order.
SOF0 Baseline DCT, 8-bit precision, components 1 (Y), 2 (Cb), 3 (Cr) with sampling factors 2x2/1x1/1x1 (4:2:0), 2x1/1x1/1x1 (4:2:2) or 1x1 (4:4:4 and grayscale).
DHT Standard Annex K.3 tables: DC/AC 0 for luma, DC/AC 1 for chroma.
SOS One interleaved scan with all components.
data Entropy-coded data without restart markers.
EOI End of image.

The standard Huffman tables keep the streams compatible with MJPEG consumers that assume them (for example RTP/JPEG, RFC 2435).

Security

Interfaces. The library is a component linked into the application. It has no network, file or inter-process interfaces, reads no environment variables or configuration files, loads no code at run time and needs no privileges. Its only inputs are the frames and parameters passed through the VCodec interface; its only outputs are the encoded frame and optional log messages on stderr (LOG_LEVEL 1 or 3, disabled by default). Messages contain frame sizes and parameter values, never frame data.

Input validation. Every frame is checked before any sample is read: pixel format, width and height (1 - 65535, even where the format requires it, width * height * 4 within the int range of the Frame class), data pointer and data size. Parameter values are range-checked (NaN and infinity are refused); a refused value leaves the configuration unchanged. The encoder relies on the Frame contract: src.data points to at least src.size readable bytes, and a dst frame of the source size and Fourcc::JPEG format owns width * height * 4 bytes, as allocated by the Frame class.

Memory safety. Buffer sizes are computed with overflow checks, and the stream is never larger than width * height * 4 bytes. The value ranges that the Huffman tables and the 16-bit and 32-bit vector arithmetic rely on are proven at compile time from the transform arithmetic (static_assert). Byte pointers are never reinterpreted as vector pointers.

Error handling. The methods throw no exceptions (only the constructor reports a failed allocation of the encoder object with std::bad_alloc). A failed memory allocation or thread creation makes transcode(…) or setParam(…) return FALSE; the encoder stays usable and keeps a consistent configuration.

Data handling. Frame data is processed in memory only; nothing is stored or transmitted. Internal buffers keep data of the last frame until the next frame is encoded. The RESET command and the destructor overwrite these buffers with zeros before releasing them. The destination frame and the source frame belong to the application.

Cryptography. The library contains no cryptographic algorithms, random number generators, keys or other security parameters. It is therefore outside the scope of FIPS 140-3 and does not interact with the cryptographic boundary of validated modules used in the same product. JPEG streams are not protected against disclosure or modification: apply the protection of the transport or storage where needed.

Components. The library consists of its own source code and uses the following libraries, which are separate repositories (see Build and connect to your project); VCodec::getVersion() and Frame::getVersion() report the versions at run time:

Component Version Location
VCodec 2.2.3 (commit 3a311ac) ../VCodec (stand alone build) or added by the top-level project
Frame 5.1.1 (commit d1b3acd) ../Frame (stand alone build) or added by the top-level project

The library was built and tested with the versions above. Normative data: ITU-T T.81 (Annex K tables), JFIF 1.02, RFC 2435 (quality scaling).

Build hardening. The CMake project compiles every target of the repository (library, test application, example, benchmark) with warning and exploit mitigation options:

  • GCC and Clang: -Wall -Wextra -Wpedantic and further warnings, -fstack-protector-strong, -D_FORTIFY_SOURCE=2 (optimized builds), -fstack-clash-protection and -fcf-protection=full (x86) or -mbranch-protection=standard (ARM) where the compiler supports them; executables and shared libraries are linked with -z relro -z now -z noexecstack (Linux).
  • MSVC: /W4 /permissive- /sdl /GS /guard:cf; executables and shared libraries are linked with /DYNAMICBASE /NXCOMPAT /guard:cf.

The library is compiled in standard C++17 mode (no compiler extensions). Instruction set options are given only to the kernel sources of the vector levels (see Portability), never to the whole library.

Build and connect to your project

Build stand alone

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

<work folder>
    VEncoderJPEG
    Frame
    VCodec

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

cd VEncoderJPEG
mkdir build
cd build
cmake ..
make

On Windows use cmake --build . --config Release instead of make. If VEncoderJPEG 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, the CMake configuration fails with an error. Executables are generated in build/bin (build/bin/Release for Visual Studio): VEncoderJPEGTest, VEncoderJPEGExample and VEncoderJPEGBenchmark. The build needs a C++17 compiler and CMake 3.13 or newer (see Portability).

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

Option Default Description
${PARENT}_VENCODERJPEG ON Build the library.
${PARENT}_VENCODERJPEG_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_VENCODERJPEG_EXAMPLE ON (stand alone), OFF (included in other project) Build the example.
${PARENT}_VENCODERJPEG_BENCHMARK ON (stand alone), OFF (included in other project) Build the benchmark application.
${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 VEncoderJPEG as a sub-repository.
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.
VENCODERJPEG_SIMD ON Compile the vector kernels. x86: SSE2 base level and the SSSE3 and AVX2 levels, selected at run time (see Portability). OFF builds the portable C++ kernels only (private compile definition VENCODERJPEG_NO_SIMD).
VENCODERJPEG_AVX2 ON Compile the AVX2 level on x86. OFF leaves it out, for example for compilers without AVX2 support; the binary then uses at most the SSSE3 level (private compile definition VENCODERJPEG_NO_AVX2).

The encoded streams are identical for all options. CMake checks that the compiler can build each kernel level and prints the result, for example VEncoderJPEG: kernel levels: base, SSSE3 ON, AVX2 ON; a level that can’t be built is left out (private compile definitions VENCODERJPEG_NO_SSSE3 and VENCODERJPEG_NO_AVX2).

Connect to your project

If you want to connect the VEncoderJPEG library to your CMake project as source code, you can do the following. The VEncoderJPEG library does not add its dependencies when it is included in another CMake project: your project must add the Frame and VCodec 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 and VEncoderJPEG 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_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()

################################################################################
## 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_VENCODERJPEG)
    add_subdirectory(VEncoderJPEG)
endif()

The 3rdparty/CMakeLists.txt file adds the Frame, VCodec and VEncoderJPEG folders to your project (the dependencies first, then the library) and excludes the test application, the example and the benchmark from compilation (they are also excluded by default when VEncoderJPEG is included in another project). The structure of your repository will be:

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

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

target_link_libraries(${PROJECT_NAME} VEncoderJPEG)

If your project does not add the Frame and VCodec libraries, the compilation fails because their header files are not found (for example, GCC reports “VCodec.h: No such file or directory”).

Done! Include the header in your code:

#include "VEncoderJPEG.h"

Portability

The library uses standard C++17 without compiler extensions and the threads of the C++ standard library; it does not use other operating system interfaces. The encoded streams do not depend on the number of threads, the kernel level or the build options.

The kernels (source conversion, colour conversion, DCT and quantization, Huffman coding) exist in several levels that produce identical streams:

Level Instruction sets Used on
AVX2 AVX2, FMA, BMI1, BMI2, LZCNT, POPCNT Intel Haswell / AMD Excavator and newer, with an operating system that saves the AVX registers.
SSSE3 SSSE3 x86 CPUs without the AVX2 set (Intel Core 2 and newer, AMD Bobcat / Bulldozer and newer).
SSE2 SSE2 Other x86-64 CPUs (base level, part of every x86-64 CPU).
C++ - ARM and other platforms, 32-bit x86 builds without SSE2 code generation on CPUs without SSSE3, and builds with VENCODERJPEG_SIMD=OFF (auto-vectorized by the compiler).

The base level is compiled with the options of the library; on x86 the kernel sources are compiled once more for the SSSE3 and the AVX2 level, each with the instruction set options of that level only (GCC and Clang: -mssse3, -mavx2 -mbmi -mbmi2 -mlzcnt -mpopcnt; MSVC: /arch:AVX2 for the AVX2 level). When the first encoder is created, the library reads the CPU features (CPUID, XGETBV) and uses the fastest level the CPU and the operating system support; nothing else is compiled with instruction set options, so the library runs on every CPU of the target architecture. Universal macOS binaries (several CMAKE_OSX_ARCHITECTURES) use the base level. The CMake options VENCODERJPEG_SIMD and VENCODERJPEG_AVX2 switch the levels off (see CMake options).

The library, the test application, the example and the benchmark were built without warnings, and the test application was run, with GCC 9, 12 and 13 and Clang 10, 15 and 18 (Linux x86-64), GCC 13 and Clang 18 (Linux aarch64, run with QEMU), GCC 13 (Linux 32-bit x86 and 32-bit ARM, ARM run with QEMU) and MSVC 19.51 (Visual Studio 2026, Windows x86-64 and 32-bit x86), using CMake 3.13, 3.16, 3.28 and 4.3. All these builds produce identical streams. Only little-endian hosts were tested. The bit manipulation built-in functions of GCC, Clang and MSVC are used, so other compilers are not supported.

Simple example

This example (example/main.cpp) generates frames in NV12 pixel format, encodes them and saves the first frame as example.jpg. The application returns 0 if all frames were encoded. Source code:

#include <cstdint>
#include <fstream>
#include <iostream>
#include <memory>
#include "VEncoderJPEG.h"



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

    // Create codec object and set params.
    std::unique_ptr<rapidpixel::VCodec> encoder{std::make_unique<rapidpixel::VEncoderJPEG>()};
    if (!encoder->setParam(rapidpixel::VCodecParam::QUALITY, 80))
    {
        std::cout << "Can't set quality" << std::endl;
        return -1;
    }
    // Automatic number of threads. If the system can't start all threads, the
    // encoder works with the threads that were started.
    if (!encoder->setParam(rapidpixel::VCodecParam::CUSTOM_2, 0))
    {
        std::cout << "Not all encoding threads started" << std::endl;
    }

    // Image size.
    const int width{640};
    const int height{480};
    // Source frame.
    rapidpixel::Frame srcFrame{width, height, rapidpixel::Fourcc::NV12};
    // Result frame JPEG.
    rapidpixel::Frame dstFrame{width, height, rapidpixel::Fourcc::JPEG};

    // Main loop.
    int failedFrames{0};
    for (int n = 0; n < 100; ++n)
    {
        // Fill NV12 frame: moving luma gradient and constant colour plane.
        uint8_t* luma{srcFrame.data};
        uint8_t* chroma{srcFrame.data + width * height};
        for (int y = 0; y < height; ++y)
        {
            for (int x = 0; x < width; ++x)
            {
                luma[y * width + x] = static_cast<uint8_t>(x + y + 4 * n);
            }
        }
        for (int y = 0; y < height / 2; ++y)
        {
            for (int x = 0; x < width / 2; ++x)
            {
                chroma[y * width + 2 * x] = static_cast<uint8_t>(64 + x / 4);
                chroma[y * width + 2 * x + 1] = static_cast<uint8_t>(192 - y / 4);
            }
        }
        srcFrame.frameId = n;

        // Encode data.
        if (!encoder->transcode(srcFrame, dstFrame))
        {
            std::cout << "Can't encode frame" << std::endl;
            ++failedFrames;
            continue;
        }

        // Show info.
        const int ratio{static_cast<int>(100.0f * static_cast<float>(dstFrame.size) /
                                         static_cast<float>(srcFrame.size))};
        std::cout << "[" << dstFrame.frameId << "] Size " << dstFrame.size <<
        " bytes, " << ratio << " % of the source size" << std::endl;

        // Save first frame as a JPEG file.
        if (n == 0)
        {
            std::ofstream file{"example.jpg", std::ios::binary};
            file.write(reinterpret_cast<const char*>(dstFrame.data), dstFrame.size);
            if (!file)
            {
                std::cout << "Can't write example.jpg" << std::endl;
                return -1;
            }
        }
    }

    return (failedFrames == 0) ? 0 : -1;
}

Test application

The test application (test/main.cpp, executable VEncoderJPEGTest) checks the library and prints the result of every test. It needs no parameters and writes no files. The tests encode synthetic pictures in all pixel formats, subsampling modes and several sizes and decode the streams with a simple baseline decoder of the test application, which checks the structure of the stream and compares the decoded planes with the source (PSNR). Further tests check that the stream does not depend on the number of threads, that invalid frames and data sizes are refused without changing the destination frame, the parameter values, the stream size limit, the range modes, the RESET command, 3000 random frames and concurrent calls from several threads. The application returns 0 if all tests passed. To run the application on Linux:

cd <application folder>
./VEncoderJPEGTest

Console output:

====================================
VEncoderJPEG v1.0.3 test
====================================

Version:
Version 1.0.3
OK

Default parameters, unsupported parameters and commands:
OK

Parameter values:
OK

Encode and decode: all formats, subsampling modes and sizes:
900 frames encoded and decoded
OK

...

Concurrent calls:
OK

ALL TESTS PASSED

Benchmark

The benchmark application (benchmark/main.cpp, executable VEncoderJPEGBenchmark) measures the encoding time for frame sizes 640x480, 1280x720 and 1920x1080 at quality 80 and 100; all other parameters keep their defaults (NV12 source, automatic subsampling - 4:2:0, one thread). The source is a synthetic scene (colour gradients, fine texture and a moving object) rendered in NV12. No files are written. For every test the application prints its stages (source preparation, encoder creation, warm-up, encoding with progress, short result) and at the end a markdown table with the frame size, quality, number of measured frames and the average, minimum and maximum time of the transcode() call. To run:

cd <application folder>
./VEncoderJPEGBenchmark            # 200 measured frames per test (+10 warm-up frames)
./VEncoderJPEGBenchmark 1000       # custom number of measured frames (1 - 1000000)
taskset -c 0 ./VEncoderJPEGBenchmark   # Linux: pin to one core for stable results

Output example (12th Gen Intel Core i5-12500H, WSL2, pinned to one core):

====================================
VEncoderJPEG v1.0.3 benchmark
====================================

Settings:
  Source: synthetic scene (gradients, texture, moving object), NV12
  Qualities: 80, 100
  Subsampling (CUSTOM_1): 0 (auto: 4:2:0 for NV12)
  Threads (CUSTOM_2): 1
  Range mode (CUSTOM_3): 0
  Frames per test: 200 (+ 10 warm-up frames)
  Logical processors: 16

[1/6] 640x480, quality 80
      Preparing source frames (NV12, 640x480)... done
      Creating encoder (quality 80, other params default)... done
      Warm-up: 10 frames... done (first frame 0.311 ms)
      Encoding: 200 frames... 25% 50% 75% 100% done
      Result: avg 0.253 ms, min 0.232 ms, max 0.637 ms
...
Results (encoding time per frame, transcode() call only):
Size Quality Frames Avg, ms Min, ms Max, ms
640x480 80 200 0.253 0.232 0.637
640x480 100 200 0.577 0.507 1.413
1280x720 80 200 0.726 0.686 1.027
1280x720 100 200 1.661 1.513 2.551
1920x1080 80 200 1.716 1.515 2.463
1920x1080 100 200 3.611 3.307 5.179

The synthetic scene is easier to compress than camera images (see Quality and performance for measurements on a real camera frame). On hybrid CPUs, laptops and virtual machines single frames may take much longer because of thread migration and power management, which shows in the maximum; pin the benchmark to one core for repeatable results.

Testing

The test application, the example and the benchmark use the public interface only and are built with the same warning and hardening options as the library. The test application checks the structure of every stream it produces and decodes it (see Test application). Encoded streams can also be checked with any JPEG decoder, for example the image written by the example:

ffmpeg -v error -xerror -i example.jpg -f null -

Builds with AddressSanitizer and UndefinedBehaviorSanitizer (GCC or Clang on Linux):

cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer" ..
cmake --build . -j
./bin/VEncoderJPEGTest

For data races use -fsanitize=thread instead (the test application encodes with several threads and calls the methods of one encoder from several threads). On WSL2 and some other kernels the sanitizer runtimes need address space randomization switched off: setarch $(uname -m) -R ./bin/VEncoderJPEGTest.

The kernel levels below the one of the build machine are exercised with CPU emulation, for example qemu-x86_64 -cpu Nehalem ./bin/VEncoderJPEGTest (SSSE3 level) or -cpu qemu64 (SSE2 level), or with the build options VENCODERJPEG_AVX2=OFF and VENCODERJPEG_SIMD=OFF. All levels produce identical streams.

Quality and performance

Measurements: 12th Gen Intel Core i5-12500H, Ubuntu 24.04 (WSL2), GCC 13.3, default build (AVX2 kernel level). Test image: real 1920x1080 camera image.

Table 5 - NV12 source (YCbCr 4:2:0). PSNR of the decoded luma plane against the source luma plane.

Quality Size, bytes PSNR Y, dB
30 85797 35.262
50 140975 36.602
75 250071 38.501
90 487662 41.514
95 803547 44.463
100 1809274 58.874

Table 6 - RGB24 source (colour conversion and chroma downsampling included). PSNR of decoded RGB against the source.

Subsampling Quality Size, bytes PSNR, dB
4:2:0 50 141030 31.076
4:2:0 75 250074 32.089
4:2:0 90 487627 33.905
4:2:2 90 589737 35.417
4:4:4 90 757682 36.990
4:4:4 100 3266798 50.774

Table 7 - Encoding time, ms per frame (4:2:0; best of 5 series of 10 frames).

Frame size Source, quality 1 thread 4 threads Auto threads
1920x1080 NV12, 80 2.7 0.97 0.75
1920x1080 BGR24, 80 3.6 1.2 0.93
1920x1080 NV12, 95 5.0 1.8 1.35
1280x720 NV12, 80 1.2 0.42 0.42
1280x720 BGR24, 80 1.6 0.56 0.47
1280x720 NV12, 95 2.0 0.83 0.73
640x512 NV12, 80 0.35 0.16 0.15
640x512 BGR24, 80 0.47 0.18 0.19
640x512 NV12, 95 0.59 0.25 0.25

Table of contents