vsourcewmf_web_logo

VSourceWmf C++ library

v1.0.2

Table of contents

Overview

VSourceWmf C++ library provides video capture and video source control based on Microsoft Media Foundation (WMF) on Windows. It captures video from:

  1. Physical Capture Devices: USB cameras, other cameras with a Media Foundation driver and video capture cards.
  2. Virtual Cameras: Virtual video sources and software capture devices registered in Windows.
  3. Custom Media Sources & Files: Video files (*.mp4, *.avi, *.mov, *.wmv, *.flv, *.swf, *.f4v, *.webm, *.mkv) and network video streams via URL.

Key features:

  • Low latency: The library uses IMFSourceReader with MF_LOW_LATENCY = TRUE and the hardware-accelerated video processing of Media Foundation to keep the capture-to-application latency low.
  • Threading: Each video source instance has one worker thread which captures frames. The library keeps only the last frame, so no frame queue builds up. All methods of the class can be called from any thread.
  • Resolution & FPS Control: For all sources, FPS and resolution can be determined by the source. For USB/hardware cameras, custom resolution can be selected via width and height properties (when both > 0). A video file is played with the FPS of the file or with the FPS that is set by the user.
  • Format Negotiation: The library attempts to set the requested format as a source reader property. If the requested format cannot be set, it delivers an uncompressed format that it supports (BGR24, NV12, YUYV, UYVY, YU12, YV12 or GRAY). A source whose frames cannot be converted to one of these formats is not opened (isVSourceOpen() stays FALSE).
  • Hardware RGB32 / BGR24 & ROI Support: Converts camera streams directly to BGR24 with dynamic Region of Interest (ROI) support.
  • Camera Controls: Direct hardware control of Exposure, Exposure Mode, Gain, Gain Mode, Focus, and Focus Mode via IAMCameraControl and IAMVideoProcAmp interfaces.
  • Auto-Reconnection: Automatically attempts reconnection if a video device or stream connection is interrupted: the capture thread opens the source again every second, and also if the source sends no frames for 15 seconds.
  • Standard Interface: Inherits from the VSource interface class.
  • Standard C++17: C++17 implementation with zero external logger dependency.

VSourceWmf 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 28.09.2026 - First version based on Microsoft Media Foundation (WMF).
1.0.1 16.10.2026 - Git submodules are removed: the libraries Frame, ConfigReader and VSource must be next to the library (see Build and connect to your project).
- The test application and the example display video with the SimpleUI library, which must be next to the library to build them.
- Fixed: RGB24 frames with rows stored bottom-up or with padding were output upside down or skewed; the fps of the init string (file path;fps) and the fps of the params structure were ignored when a video file was played; YU12 and YV12 frames were copied wrong; the buffer of a sample was not checked against the size of the frame (a stream that changes its size or a damaged sample could cause a read outside of the buffer).
- Fixed: closeVSource() was blocked for about a minute while the connection to a network host was pending; concurrent RESTART commands terminated the application; the capture thread and the user threads used the camera controls without a lock; a source that was never opened blocked getFrame(…) with a negative timeout; a sample that could not be read produced an empty or repeated frame; a connected source that stopped sending frames stayed open and was waited for without a limit; resources of the media source and the list of devices were not released; the callback of the connection to a file or a URL was not released at every opening (memory and a handle leaked at every opening and reconnection); the format of the frames stayed the old one after a change of the stream that the library cannot process; a mode of a camera control could write the value 0 to the control if the control could not be read; the other streams of a video file (audio) were collected by the source reader without being taken; the source reader was released while a read was pending (a rare deadlock inside Media Foundation), the reader is flushed first and the release of the objects of Media Foundation is limited to 10 seconds, so closeVSource() and the destructor do not block.
- Security: the init string and the params structure are validated (length, number of parts, numbers, fps, size, ROI, log level, FOURCC); the size of a frame is limited to 16384 x 16384 and 67108864 pixels; NaN, infinity and out-of-range values of setParam(…) are rejected; user name and password of a URL are not written to the log; the source reader works in asynchronous mode, so the stop does not depend on a source that does not answer.
- Behavior changes: an init string with a wrong number of parts, a number that is not whole or an fps outside of 0.01 - 1000 is rejected; the modes (focus, gain, exposure) must be 0 or 1; LOG_LEVEL must be 0 - 3; ROI params must be 0 - 16384; RESTART of a source that was not initialized returns FALSE; getFrame(…) of a source that is not open returns FALSE at once; initVSource(…) rejects invalid params; extensions of video files are compared without regard to letter case; a source whose frames cannot be converted to a supported uncompressed format is not opened; a source is a video file if its path ends with an extension of a video file and a stream if it starts with the scheme of a stream (a camera name that has the text rtp or .mov inside is a camera name); getParam(…) of WIDTH, HEIGHT and FPS returns 0 after closeVSource(); control characters of a source are replaced in the log and nothing is written to a log file that is larger than 16 MB.
1.0.2 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 only by source code as a CMake project. The libraries Frame, ConfigReader and VSource (and SimpleUI, which the test application and the example use to display video) are separate repositories: they are not part of this repository. The repository structure is shown below:

CMakeLists.txt -------------- Main CMake file of the library.
src ------------------------- Folder with library source code.
    CMakeLists.txt ---------- CMake file of the library (verifies Windows & WMF).
    VSourceWmf.h ------------ Main library header file.
    VSourceWmfVersion.h ----- Header file with library version.
    VSourceWmfVersion.h.in -- Service CMake file to generate version header.
    VSourceWmf.cpp ---------- C++ implementation wrapper.
    Impl -------------------- Folder with internal Media Foundation implementation.
        VSourceWmfImpl.h ---- Header file of WMF video source implementation.
        VSourceWmfImpl.cpp -- C++ WMF video capture implementation.
test ------------------------ Folder for test application files.
    CMakeLists.txt ---------- CMake file for test application.
    main.cpp ---------------- Source C++ file of test application (automatic tests, the argument --interactive starts the manual test with SimpleUI display).
example --------------------- Folder for example application.
    CMakeLists.txt ---------- CMake file for example application.
    main.cpp ---------------- Source C++ file of example application.
static ---------------------- Folder with the logo of the library.

VSourceWmf class description

VSourceWmf class declaration

VSourceWmf class is declared in VSourceWmf.h file. The class owns the capture thread: it is not copyable and not movable.

namespace rapidpixel
{
/// Video source class based on Windows Media Foundation (WMF).
class VSourceWmf : public VSource
{
public:

    /// Class constructor.
    VSourceWmf();

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

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

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

    /// Open video source.
    bool openVSource(std::string& initString) override;

    /// Init video source.
    bool initVSource(VSourceParams& params) override;

    /// Get open status.
    bool isVSourceOpen() override;

    /// Close video source.
    void closeVSource() override;

    /// Get new video frame.
    bool getFrame(Frame& frame, int32_t timeoutMsec = 0) override;

    /// Set video source param.
    bool setParam(VSourceParam id, float value) override;

    /// Get video source param value.
    float getParam(VSourceParam id) override;

    /// Get video source params structure.
    void getParams(VSourceParams& params) override;

    /// Execute command.
    bool executeCommand(VSourceCommand id) override;

    /// Decode and execute command.
    bool decodeAndExecuteCommand(uint8_t* data, int size) override;
};
}

getVersion method

The getVersion() static method returns string of current version of VSourceWmf class:

static std::string getVersion();

Method can be used without VSourceWmf class instance:

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

Console output:

VSourceWmf version: 1.0.2

openVSource method

The openVSource(…) method initializes the video source using an initialization string. Video source parameters (VSourceParams class) will be initialized by default. Instead of openVSource(…) method, the user can call initVSource(…). This method checks the initialization string and starts the internal video capture thread. The thread opens the source and opens it again if the connection is lost, so the method returns TRUE also if the source does not exist: use isVSourceOpen() to know if the source is connected. The library does not restrict the source: any file path or URL that Media Foundation can open is opened. If the video source is already open the method does nothing and returns TRUE. Method declarations:

bool openVSource(std::string& initString) override;
Parameter Value
initString Initialization string (up to 32768 bytes). The parts of the string are separated by ;, empty parts are ignored, a string with another number of parts than a format below has is rejected (a file path or URL that has ; can be set by initVSource(…)). The library can open physical capture devices, virtual cameras, video files and network video streams/URLs. A source is a video file if its path ends with *.mp4, *.avi, *.mov, *.wmv, *.flv, *.swf, *.f4v, *.webm or *.mkv (the letter case is ignored; the query and the fragment of a URL are not a part of the path, so a http URL of a video file is a file too). A source is a stream if it starts with rtsp://, rtp://, http://, https:// or custom:// (the letter case is ignored). Other sources are cameras. Valid formats:
- "camera num" - camera index from 0 to 999 (e.g. "0", "1", "2").
- "camera num;width;height" - camera index and resolution, whole numbers from 1 to 16384 (e.g. "0;640;480", "0;1280;720").
- "device name" - part of the friendly device name or of the symbolic link (e.g. "Integrated Webcam").
- "device name;width;height" - device name and resolution.
- "file path" - video file path (e.g. "video.mp4").
- "file path;fps" - video file path and playback FPS from 0.01 to 1000 (e.g. "video.mp4;30", 0 - the FPS of the file). The video is played in a loop.
- "stream url" - video stream/source URL (e.g. "http://192.168.1.70:7031/video").
- "stream url;fourcc" - stream URL and fourcc format code (e.g. "http://...;BGR24", "...;NV12").

Returns: TRUE if the initialization string is valid and the capture thread is running or FALSE if not.

initVSource method

The initVSource(…) method initializes the video source from a VSourceParams structure. The method does what openVSource(…) does, with the fields of the structure instead of the initialization string:

bool initVSource(VSourceParams& params) override;
Parameter Value
params VSourceParams object. Field source is the video source initialization string.
Supported fields:
- source - video source: camera number, device name, video file path or stream URL (up to 32768 bytes). The parts of the string are not split: ; is a part of the source.
- fourcc - requested output video frame format (e.g. "BGR24", "NV12", "YUYV"), up to 16 chars without spaces. A format that the library cannot deliver is replaced by a supported one.
- width - frame width. Applied to hardware/USB devices if both width and height > 0, 0 - 16384.
- height - frame height. Applied to hardware/USB devices if both width and height > 0, 0 - 16384.
- fps - FPS for video files playback: 0 (the FPS of the file) or from 0.01 to 1000.
- roiX, roiY, roiWidth, roiHeight - Region of Interest applied to BGR24 frames, 0 - 16384.
- gain, gainMode - initial gain and gain mode.
- exposure, exposureMode - initial exposure and auto exposure mode.
- focusPos, focusMode - initial focus position and autofocus mode.
- logLevel - logging mode (0 - 3).
A negative value of gain, gainMode, exposure, exposureMode, focusPos or focusMode means that the control is not set. The default values of the structure are not negative: set the controls that must stay unchanged to -1.

Returns: TRUE if the params are valid and the capture thread is running or FALSE if not (the source is unknown or longer than 32768 bytes, logLevel is not 0 - 3, fourcc is longer than 16 chars or has a space, width, height or a ROI field is negative or greater than 16384, or the fps of a video file is not valid). If the video source is already open the method does nothing and returns TRUE.

isVSourceOpen method

The isVSourceOpen() method returns video source open/receiving status:

bool isVSourceOpen() override;

The video source is open from the moment it is connected (the capture thread has created the source reader) until it is lost: no frame for 15 seconds or several reads in a row without a frame, then the capture thread opens the source again.

Returns: TRUE if the video source is open, or FALSE if not (also if the source is not found and the library tries to connect to it).

closeVSource method

The closeVSource() method stops the internal video capture thread, releases all Media Foundation resources, and resets the frame state. A pending connection to a network source is cancelled, the method does not wait for the end of the connection (it waits up to 2 seconds for the answer of the cancel). The wait for the release of the Media Foundation objects is limited to 10 seconds: objects that Media Foundation does not release in time stay with a helper thread:

void closeVSource() override;

getFrame method

The getFrame(…) method retrieves the latest video frame:

bool getFrame(Frame& frame, int32_t timeoutMsec = 0) override;
Parameter Value
frame Output video frame (see Frame class description). Output frame pixel format is Fourcc::BGR24 or raw uncompressed camera format (NV12, YUYV, UYVY, YU12, YV12, GRAY). The frame is not changed if the method returns FALSE.
timeoutMsec Timeout in milliseconds:
- timeoutMsec < 0: waits until a new frame arrives or the video source is closed.
- timeoutMsec == 0: checks if a new frame is immediately available without blocking.
- timeoutMsec > 0: waits up to the specified timeout in milliseconds.

Returns: TRUE if a new frame exists and was copied, or FALSE if timed out, the source is not open or was closed, or the memory for the frame could not be allocated. A frame is returned once. A source that is not open does not block the method.

setParam method

The setParam(…) method updates video source parameters:

bool setParam(VSourceParam id, float value) override;
Parameter Description
id Parameter ID according to VSourceParam enum.
Supported parameters:
- VSourceParam::LOG_LEVEL - logging verbosity (0 - 3).
- VSourceParam::ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT - dynamic Region of Interest cropping (0 - 16384).
- VSourceParam::FOCUS_MODE - camera autofocus (1 - Auto, 0 - Manual) via IAMCameraControl.
- VSourceParam::FOCUS_POS - camera focus position via IAMCameraControl.
- VSourceParam::GAIN_MODE - camera gain mode (1 - Auto, 0 - Manual) via IAMVideoProcAmp.
- VSourceParam::GAIN - camera gain value via IAMVideoProcAmp.
- VSourceParam::EXPOSURE_MODE - camera auto exposure (1 - Auto, 0 - Manual) via IAMCameraControl.
- VSourceParam::EXPOSURE - camera exposure value via IAMCameraControl.
value Value to set. NaN, infinity and a value that is not valid for the parameter are rejected. The camera parameters need an open camera that supports them.

Returns: TRUE if the parameter was set or FALSE if not supported / rejected by hardware / the value is not valid.

getParam method

The getParam(…) method queries a parameter value:

float getParam(VSourceParam id) override;
Parameter Description
id Parameter ID according to VSourceParam enum.
Supported parameters:
- VSourceParam::LOG_LEVEL
- VSourceParam::CYCLE_TIME_MKS - time interval between two captured frames (in microseconds).
- VSourceParam::WIDTH - current width of the frames of the source.
- VSourceParam::HEIGHT - current height of the frames of the source.
- VSourceParam::FPS - calculated real-time capture FPS. The playback FPS of a video file.
- VSourceParam::IS_OPEN - 1.0f if open, 0.0f if not.
- VSourceParam::ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT
- VSourceParam::FOCUS_MODE, FOCUS_POS
- VSourceParam::GAIN_MODE, GAIN
- VSourceParam::EXPOSURE_MODE, EXPOSURE

Returns: Current parameter value, or -1.0f if not supported / unavailable (for example the camera is not open).

getParams method

The getParams(…) method retrieves all current video source parameters:

void getParams(VSourceParams& params) override;
Parameter Description
params VSourceParams object to receive parameters. The camera parameters (gain, gainMode, exposure, exposureMode, focusPos, focusMode) that are not available are -1. custom1, custom2 and custom3 are -1.

executeCommand method

The executeCommand(…) method executes action commands:

bool executeCommand(VSourceCommand id) override;
Parameter Description
id Command ID according to VSourceCommand enum.
- VSourceCommand::RESTART - restarts the video source capture pipeline with the settings of the last openVSource(…) or initVSource(…) call.

Returns: TRUE if the command was executed, or FALSE if not supported or the video source was not initialized.

decodeAndExecuteCommand method

The decodeAndExecuteCommand(…) method decodes and executes remote commands received over a network channel. The method can be safely called from any thread:

bool decodeAndExecuteCommand(uint8_t* data, int size) override;
Parameter Description
data Pointer to command data buffer. Must not be nullptr.
size Buffer size (exactly 11 bytes for SET_PARAM, exactly 7 bytes for COMMAND).

Returns: TRUE if command decoded and executed, or FALSE if invalid (the value of a SET_PARAM command is checked by setParam(…)).

encodeSetParamCommand method of VSource interface class

The encodeSetParamCommand(…) static method designed to encode command to change any parameter in remote video source. To control video source remotely, the developer has to design his own protocol and according to it encode the command and deliver it over the communication channel. To simplify this, the VSource class contains static methods for encoding the control command. The VSource class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). encodeSetParamCommand(…) designed to encode SET_PARAM command. Method declaration:

static void encodeSetParamCommand(uint8_t* data, int& size, VSourceParam id, float value);
Parameter Description
data Pointer to data buffer for encoded command. Must have size >= 11.
size Size of encoded data. Will be 11 bytes (0 if data is nullptr).
id Parameter ID according to VSourceParam enum.
value Parameter value.

encodeSetParamCommand(…) is static and used without VSource class instance. This method used on client side (control system). Command encoding example:

// Buffer for encoded data.
uint8_t data[11];
// Size of encoded data.
int size = 0;
// Parameter value.
float outValue = 5.0f;
// Encode command.
rapidpixel::VSource::encodeSetParamCommand(data, size, rapidpixel::VSourceParam::EXPOSURE, outValue);

encodeCommand method of VSource interface class

The encodeCommand(…) static method designed to encode command to perform action command in remote video source. To control a video source remotely, the developer has to design his own protocol and according to it encode the command and deliver it over the communication channel. To simplify this, the VSource class contains static methods for encoding the control command. The VSource class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). encodeCommand(…) designed to encode COMMAND (action command). Method declaration:

static void encodeCommand(uint8_t* data, int& size, VSourceCommand id);
Parameter Description
data Pointer to data buffer for encoded command. Must have size >= 7 bytes.
size Size of encoded data. Will be 7 bytes (0 if data is nullptr).
id Command ID according to VSourceCommand enum.

encodeCommand(…) is static and used without VSource class instance. This method used on client side (control system). Command encoding example:

// Buffer for encoded data.
uint8_t data[7];
// Size of encoded data.
int size = 0;
// Encode command.
rapidpixel::VSource::encodeCommand(data, size, rapidpixel::VSourceCommand::RESTART);

decodeCommand method of VSource interface class

The decodeCommand(…) static method designed to decode command on video source side (edge device). Method declaration:

static int decodeCommand(uint8_t* data, int size, VSourceParam& paramId, VSourceCommand& commandId, float& value);
Parameter Description
data Pointer to input command. Must not be nullptr.
size Size of command. Must be exactly 11 bytes for SET_PARAM and exactly 7 bytes for COMMAND (other sizes give -1).
paramId Parameter ID according to VSourceParam enum. After decoding SET_PARAM command the method will return parameter ID. An ID that is not a value of the enum gives -1.
commandId Command ID according to VSourceCommand enum. After decoding COMMAND the method will return command ID. An ID that is not a value of the enum gives -1.
value Parameter value (after decoding SET_PARAM command).

Returns: 0 - in case decoding COMMAND, 1 - in case decoding SET_PARAM command or -1 in case errors (the output arguments are not changed).

Data structures

VSource.h defines parameter IDs (VSourceParam enum) and action command IDs (VSourceCommand enum).

VSourceCommand enum

enum class VSourceCommand
{
    /// Restart video source.
    RESTART = 1
};

Table 2 - Video source commands.

Command Description
RESTART Restarts the video capture pipeline. Supported.

VSourceParam enum

enum class VSourceParam
{
    LOG_LEVEL = 1,
    WIDTH,
    HEIGHT,
    GAIN_MODE,
    GAIN,
    EXPOSURE_MODE,
    EXPOSURE,
    FOCUS_MODE,
    FOCUS_POS,
    CYCLE_TIME_MKS,
    FPS,
    IS_OPEN,
    ROI_X,
    ROI_Y,
    ROI_WIDTH,
    ROI_HEIGHT,
    CUSTOM_1,
    CUSTOM_2,
    CUSTOM_3
};

Table 3 - Video source parameters support in VSourceWmf.

Parameter Access Description
LOG_LEVEL read / write Logging mode: 0 - Disable, 1 - File, 2 - Console, 3 - Both. The log file VSourceWmf.log is created in the current directory. The user name and the password of a URL are not written to the log.
WIDTH read only Current width of the frames of the source (0 after closeVSource()). The frames that getFrame(…) returns have the size of the ROI if the ROI is used. Configurable during device initialization via width property.
HEIGHT read only Current height of the frames of the source (0 after closeVSource()). Configurable during device initialization via height property.
GAIN_MODE read / write Gain mode: 0 - Manual, 1 - Auto. Controlled via IAMVideoProcAmp.
GAIN read / write Gain value. Controlled via IAMVideoProcAmp.
EXPOSURE_MODE read / write Exposure mode: 0 - Manual, 1 - Auto. Controlled via IAMCameraControl.
EXPOSURE read / write Exposure value. Controlled via IAMCameraControl.
FOCUS_MODE read / write Focus mode: 0 - Manual, 1 - Auto. Controlled via IAMCameraControl.
FOCUS_POS read / write Focus position. Controlled via IAMCameraControl.
CYCLE_TIME_MKS read only Measured video capture cycle time in microseconds.
FPS read only Real-time measured capture FPS. For video files, the playback FPS (set during init, the FPS of the file by default).
IS_OPEN read only Open flag: 1.0f - open and receiving, 0.0f - closed.
ROI_X read / write Region of interest top-left corner horizontal coordinate (0 - 16384).
ROI_Y read / write Region of interest top-left corner vertical coordinate (0 - 16384).
ROI_WIDTH read / write Region of interest width in pixels (0 - 16384). A ROI that is not inside the frame (or is smaller than 2 x 2 pixels, for example 0) is not used: the frame is not cropped. The ROI is applied to BGR24 frames only.
ROI_HEIGHT read / write Region of interest height in pixels (0 - 16384).
CUSTOM_1 read / write Not supported (setParam(…) returns FALSE, getParam(…) returns -1.0f).
CUSTOM_2 read / write Not supported (setParam(…) returns FALSE, getParam(…) returns -1.0f).
CUSTOM_3 read / write Not supported (setParam(…) returns FALSE, getParam(…) returns -1.0f).

VSourceParams class description

VSourceParams class declaration

VSourceParams class is declared in VSource.h. The values of the fields are transported (encoded, decoded, read from and written to JSON) without a range check: their meaning belongs to the video source implementation, VSourceWmf validates them in initVSource(…). The class is not thread-safe.

class VSourceParams
{
public:
    int logLevel{0};
    std::string source{"/dev/video0"};
    std::string fourcc{"YUYV"};
    int width{1920};
    int height{1080};
    int gainMode{1};
    int gain{0};
    int exposureMode{1};
    int exposure{1};
    int focusMode{1};
    int focusPos{0};
    int cycleTimeMks{0};
    float fps{0.0f};
    bool isOpen{false};
    int roiX{0};
    int roiY{0};
    int roiWidth{0};
    int roiHeight{0};
    float custom1{0.0f};
    float custom2{0.0f};
    float custom3{0.0f};

    JSON_READABLE(VSourceParams, logLevel, source, fourcc, width, height,
                  gainMode, exposureMode, focusMode, fps, roiX, roiY,
                  roiWidth, roiHeight, custom1, custom2, custom3)

    VSourceParams() = default;
    VSourceParams(const VSourceParams& src) = default;
    VSourceParams(VSourceParams&& src) = default;
    VSourceParams& operator= (const VSourceParams& src) = default;
    VSourceParams& operator= (VSourceParams&& src) = default;
    bool encode(uint8_t* data, int bufferSize, int& size, VSourceParamsMask* mask = nullptr);
    bool decode(uint8_t* data, int dataSize);
};

Serialize video source params

Serialize params using encode(…). The method does not encode source and fourcc fields:

rapidpixel::VSourceParams in;
in.width = 640;
in.height = 480;
in.logLevel = 2;

uint8_t data[1024];
int size = 0;
if (!in.encode(data, static_cast<int>(sizeof(data)), size))
{
    std::cout << "Can't encode data" << std::endl;
}

Deserialize video source params

Deserialize params using decode(…). If the method returns FALSE the object is not changed:

// Encoded params (see the previous example).
rapidpixel::VSourceParams in;
uint8_t data[1024];
int size = 0;
if (!in.encode(data, static_cast<int>(sizeof(data)), size))
{
    std::cout << "Can't encode data" << std::endl;
}

// Decode params.
rapidpixel::VSourceParams out;
if (!out.decode(data, size))
{
    std::cout << "Can't decode data" << std::endl;
}

Read params from JSON file and write to JSON file

// Write params to file.
rapidpixel::VSourceParams in;
rapidpixel::ConfigReader inConfig;
if (!inConfig.set(in, "vSourceParams") ||
    !inConfig.writeToFile("TestVSourceParams.json"))
{
    std::cout << "Can't write config file" << std::endl;
}

// Read params from file.
rapidpixel::VSourceParams out;
rapidpixel::ConfigReader outConfig;
if (!outConfig.readFromFile("TestVSourceParams.json") ||
    !outConfig.get(out, "vSourceParams"))
{
    std::cout << "Can't read config file" << std::endl;
}

Build and connect to your project

Prerequisites

  • Operating System: Windows 10 or Windows 11.
  • Compiler: Microsoft Visual C++ (MSVC) with C++17 support. The library is built and tested with Visual Studio 2022 (MSVC 19.36). The code uses std::from_chars for floating point numbers (Visual Studio 2019 16.4 or newer).
  • Build System: CMake 3.13 or newer.
  • Windows SDK: Windows 10/11 SDK (contains Windows Media Foundation libraries: Mfplat.lib, mf.lib, mfreadwrite.lib, mfuuid.lib). The library links these libraries and shlwapi.lib and ole32.lib (PUBLIC: a program that links the library links them too).
  • SimpleUI: Required only for building the test application and the example, which display video with the SimpleUI library (see Build stand alone); the VSourceWmf library itself does not depend on it.

Build stand alone

The repository does not contain sub-repositories. The libraries VSourceWmf depends on (Frame, ConfigReader, VSource) and the library that the test application and the example use to display video (SimpleUI) must be placed in the same folder as VSourceWmf: copy their folders, for example from the folder modules of the RapidPixel SDK. The folder structure must be:

<work folder>
    VSourceWmf
    Frame
    ConfigReader
    VSource
    SimpleUI

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

cd VSourceWmf
mkdir build
cd build
cmake .. -A x64
cmake --build . --config Release

If VSourceWmf is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame, ../ConfigReader and ../VSource (in this order) before the library itself, and the folder ../SimpleUI (after them) when the test application or the example is built. If a folder does not exist CMake stops with an error. The binaries of the test application and of the example are in the folder 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 VSourceWmf is the top-level project).

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

Connect to your project

To use the library in your project, create folder 3rdparty in your repository and copy the folders of the libraries Frame, ConfigReader, VSource and VSourceWmf there (for example from the folder modules of the RapidPixel SDK). The dependencies must be added in dependency order before the library: Frame, ConfigReader, VSource, VSourceWmf. When VSourceWmf is included in another project it does not add its dependencies: they must be added by your project, otherwise the build stops with the error VSource.h: No such file or directory. The library itself does not need SimpleUI: copy the folder of SimpleUI and add it (after Frame) only if your project builds the test application or the example of VSourceWmf (options ${PARENT}_VSOURCEWMF_TEST and ${PARENT}_VSOURCEWMF_EXAMPLE). The folder structure of your project:

<your project>
    CMakeLists.txt
    3rdparty
        CMakeLists.txt
        Frame
        ConfigReader
        VSource
        VSourceWmf

Create the file 3rdparty/CMakeLists.txt:

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_CONFIG_READER                   ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_CONFIG_READER)
    SET(${PARENT}_CONFIG_READER                         ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_CONFIG_READER_EXAMPLES                OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_CONFIG_READER_TESTS                   OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VSOURCE                         ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VSOURCE)
    SET(${PARENT}_VSOURCE                               ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VSOURCE_TEST                          OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VSOURCE_EXAMPLE                       OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_VSOURCEWMF                      ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VSOURCEWMF)
    SET(${PARENT}_VSOURCEWMF                            ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VSOURCEWMF_TEST                       OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VSOURCEWMF_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_CONFIG_READER)
    add_subdirectory(ConfigReader)
endif()

if (${PARENT}_SUBMODULE_VSOURCE)
    add_subdirectory(VSource)
endif()

if (${PARENT}_SUBMODULE_VSOURCEWMF)
    add_subdirectory(VSourceWmf)
endif()

Include the folder 3rdparty in the main CMakeLists.txt of your project and link the library to your target:

add_subdirectory(3rdparty)
target_link_libraries(${PROJECT_NAME} VSourceWmf)

Portability

The library works on Windows only: it uses Windows Media Foundation and the CMake project stops with an error on other systems. The library is built and tested with MSVC 19.36 (Visual Studio 2022) for x86-64 on Windows 11. The frames are copied byte by byte and no data is serialized by the library, so the byte order of the CPU has no effect on the frames. The library has no code for a particular instruction set.

Simple example

#include <iostream>
#include <string>
#include "SimpleUi.h"
#include "VSourceWmf.h"

int main(int argc, char** argv)
{
    // Open video source (e.g. camera 0 at 640x480 resolution). The method
    // starts the capture thread: the source is connected when frames arrive.
    rapidpixel::VSourceWmf source;
    std::string initString = (argc > 1) ? argv[1] : "0;640;480";
    if (!source.openVSource(initString))
    {
        std::cout << "ERROR: wrong init string: " << initString << std::endl;
        return -1;
    }

    // Create the window to display the video. The constructor of the window
    // and the method render(...) throw std::runtime_error on a failure.
    rapidpixel::SimpleUiWindow window("VSourceWmf Video Display");
    window.show();

    rapidpixel::Frame frame;
    int noFrameCount = 0;
    while (window.isOpen() && noFrameCount < 10)
    {
        // Wait up to 1000 ms for new frame.
        if (!source.getFrame(frame, 1000))
        {
            ++noFrameCount;
            continue;
        }
        noFrameCount = 0;

        // The example displays BGR24 frames.
        if (frame.fourcc != rapidpixel::Fourcc::BGR24)
        {
            std::cout << "ERROR: the frame is not BGR24" << std::endl;
            return -1;
        }

        // Retrieve current parameters.
        rapidpixel::VSourceParams params;
        source.getParams(params);

        // Draw the text on the captured frame and display it with SimpleUI.
        rapidpixel::SimpleUiDraw::drawText(frame, 10, 10,
                "Frame ID: " + std::to_string(frame.frameId) + " | Cycle: " +
                std::to_string(params.cycleTimeMks / 1000) + " ms",
                rapidpixel::Color{0, 255, 0, 255}, 16);
        window.render(frame);
        if (window.waitKey(27, 1)) // ESC key to exit
        {
            return 0;
        }
    }

    // The window was closed by the user.
    if (!window.isOpen())
    {
        return 0;
    }

    std::cout << "ERROR: no frames from the video source" << std::endl;
    return -1;
}

Table of contents