vsourceopencv_web_logo

VSourceOpenCv C++ library

v2.0.4

Table of contents

Overview

VSourceOpenCv C++ library provides video capture and video source control function based on OpenCV library (version >=4.5). It provides simple interface for video capture from video files (*.mp4, *.avi, *.mov, *.wmv, *.flv, *.swf, *.f4v and *.webm), video streams (rtp, rtsp, http) and UVC (Universal Video Class) compatible devices (e.g. web cameras) or other devices supported by OpenCV. The library supports automatic reconnection to the video source in case of connection loss. The library also plays video files continuously (starts over when playback ends). The library supports BGR24 output video frame pixel format and H264, HEVC, JPEG for video streams (configurable by user). The library inherits interface from open source VSource interface class. VSource.h file contains data structures VSourceParams class (contains video source params and provides methods for serialization/deserialization params), VSourceCommand enum (describes video source action commands), VSourceParam enum (describes video source params) and includes VSourceOpenCv class declaration. VSourceOpenCv depends on: OpenCV (version >=4.5, linked, Apache 2.0 license), VSource interface class (provides interface for video sources, source code included, Apache 2.0 license) and open source Logger library (provides method to write logs, source code included, Apache 2.0 license). The library supports C++17 standard.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 11.07.2023 First version.
1.0.1 13.11.2023 - VSource class updated.
- Logger class updated.
1.0.2 13.11.2023 - CMake structure updated.
1.0.3 15.12.2023 - Auto reconnection issue fixed.
1.1.0 27.12.2023 - Region of interest support added.
1.1.1 09.01.2024 - Documentation updated.
2.0.0 22.03.2024 - VSource class updated.
- Code reorganized.
- Added support of compressed video output.
- Documentation updated.
2.0.1 15.04.2024 - binary_semaphore replaced by conditional_variable.
2.0.2 20.05.2024 - Submodules updated.
- Documentation updated.
2.0.3 07.07.2024 - CMake updated.
- Submodules updated.
2.0.4 23.07.2024 - Files structure changed.

Library files

The library is supplied only by source code. The user is given 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.
3rdparty ----------------------- Folder with third-party libraries.
    CMakeLists.txt ------------- CMake file to include third-party libraries.
    Logger --------------------- Folder with Logger library source code.
    VSource -------------------- Folder with VSource library source code.
src ---------------------------- Folder with library source code.
    CMakeLists.txt ------------- CMake file of the library.
    VSourceOpenCv.h ------------ Main library header file.
    VSourceOpenCvVersion.h ----- Header file with library version.
    VSourceOpenCvVersion.h.in -- Service CMake file to generate version header.
    VSourceOpenCv.cpp ---------- C++ implementation file.
    Impl ----------------------- Folder with video source implementation.
        VSourceOpenCvImpl.h ---- Header file of video source implementation.
        VSourceOpenCvImpl.cpp -- C++ implementation file.
test --------------------------- Folder for test application files.
    CMakeLists.txt ------------- CMake file for test application.
    main.cpp ------------------- Source C++ file of test application.
example ------------------------ Folder for example application.
    CMakeLists.txt ------------- CMake file for example application.
    main.cpp ------------------- Source C++ file of example application.

VSourceOpenCv class description

VSourceOpenCv class declaration

VSourceOpenCv interface class declared in VSourceOpenCv.h file. Class declaration:

namespace cr
{
namespace video
{
/// Video source class based on OpenCV.
class VSourceOpenCv : public VSource
{
public:

    /// Class constructor.
    VSourceOpenCv();

    /// Class destructor.
    ~VSourceOpenCv();

    /// 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 VSourceOpenCv class. Method declaration:

static std::string getVersion();

Method can be used without VSourceOpenCv class instance:

cout << "VSourceOpenCv version: " << VSourceOpenCv::getVersion() << endl;

Console output:

VSourceOpenCv version: 2.0.3

openVSource method

The openVSource(…) method initializes video source. Video source params (VSourceParams class) will be initialized by default. Instead of openVSource(…) method user can call initVSource(…) method. This method doesn’t open video source directly. This method checks initialization string and runs internal video capture thread which will open video source. Method declaration:

bool openVSource(std::string& initString) override;
Parameter Value
initString Initialization string. The library can open video files (*.mp4, *.avi, *.mov, *.wmv, *.flv, *.swf, *.f4v and *.webm), video streams (rtp, rtsp, http) and UVC (Universal Video Class) compatible devices (e.g. web cameras) or other devices supported by OpenCV. Valid formats:
“camera num” - camera number (e.g. “0”, “1”, “2” etc.).
“camera num;width;height” - camera number and resolution (e.g. “0;640;480”).
“device name” - device name (e.g. “/dev/video0”).
“device name;width;height” - device name and resolution (e.g. “/dev/video0;640;480”).
“file path” - video file path (e.g. “video.mp4”).
“file path;fps” - video file path and fps (e.g. “video.mp4;30”).
“stream url” - video stream url (e.g. “rtsp://192.168.1.70:7031/unicast”).
“stream url;fourcc” - video stream url and compressed frame fourcc code (e.g. “rtsp://192.168.1.70:7031/unicast;H264”, “…;HEVC”, “…;JPEG”).

Returns: TRUE if the video initialized (or already initialized) or FALSE if not.

initVSource method

The initVSource(…) method initializes video source by set of parameters. Instead of initVSource(…) method user can call openVSource(…). This method doesn’t open video source directly. This method checks initialization parameters and runs internal video capture thread which will open video source. Method declaration:

bool initVSource(VSourceParams& params) override;
Parameter Value
params VSourceParams class. Field source of VSourceParams class is video source initialization string. Valid formats:
“camera num” - camera number (e.g. “0”, “1”, “2” etc.).
“device name” - device name (e.g. “/dev/video0”).
“file path” - video file path (e.g. “video.mp4”).
“stream url” - video stream url (e.g. “rtsp://192.168.1.70:7031/unicast”).
The video source will set parameters according to params class. The library uses only parameters:
VSourceParams->source - video source initialization string (file name, device, stream etc.).
VSourceParams->fps - FPS applied only for video files. For other sources the library will calculate real FPS.
VSourceParams->fourcc - output video frame format. By default BGR24. If a user opens a video stream and wants to receive compressed data (without decoding with OpenCV), he must specify the correct stream format: H264, HEVC or JPEG (The format must match the actual stream format).
VSourceParams->width - frame width. Will be applied only for devices (source: “device num” or “device name”). If width >= 0 the library will set it to device.
VSourceParams->height - frame height. Will be applied only for devices (source: “device num” or “device name”). If height >= 0 the library will set it to device.
VSourceParams->roiX - top-left horizontal ROI coordinate. Will be applied only for BGR24 output frames.
VSourceParams->roiY - top-left vertical ROI coordinate. Will be applied only for BGR24 output frames.
VSourceParams->roiWidth - ROI width. Will be applied only for BGR24 output frames.
VSourceParams->roiHeight - ROI height. Will be applied only for BGR24 output frames.

Returns: TRUE if the video source initialized or FALSE if not.

isVSourceOpen method

The isVSourceOpen() method returns video source initialization status. Initialization status also included in VSourceParams class. Initialization shows if the library receives video. If no input video method will return FALSE and internal video capture thread will start process of reconnection to video source. Method declaration:

bool isVSourceOpen() override;

Returns: TRUE if the video source open (there is input video) or FALSE if not.

closeVSource method

The closeVSource() method closes video source. Method stops internal video capture thread. Method declaration:

void closeVSource() override;

getFrame method

The getFrame(…) method returns video frame. Video source supports auto re-initialization in case connection loss. In case capturing video from video file the method start playback again after end of file. Method declaration:

bool getFrame(Frame& frame, int32_t timeoutMsec = 0) override;
Parameter Value
frame Output video frame (see Frame class description). Generally output frame has BGR24 format but if user receives stream and set output format to H264, HEVC or JPEG.
timeoutMsec Timeout to wait new frame data, milliseconds:
- timeoutMs == -1 - Method will wait endlessly until new data arrive.
- timeoutMs == 0 - Method will only check if new data exist.
- timeoutMs > 0 - Method will wait new data specified time.

Returns: TRUE if new frame exists and copied or FALSE if not (wait timeout expired or video source not initialized).

setParam method

The setParam(…) method set new video source parameters value. Method will set parameters to video device. Method can be used only after video source initialization. Method declaration:

bool setParam(VSourceParam id, float value) override;
Parameter Description
id Video source parameter ID according to VSourceParam enum. This method supports only parameters:
VSourceParam::LOG_LEVEL
VSourceParam::ROI_X
VSourceParam::ROI_Y
VSourceParam::ROI_WIDTH
VSourceParam::ROI_HEIGHT
VSourceParam::FOCUS_MODE - the library will call OpenCV function set(cv::CAP_PROP_AUTOFOCUS, value).
VSourceParam::FOCUS_POS - the library will call OpenCV function set(cv::CAP_PROP_FOCUS, value).
VSourceParam::GAIN - the library will call OpenCV function set(cv::CAP_PROP_GAIN, value).
VSourceParam::EXPOSURE_MODE - the library will call OpenCV function set(cv::CAP_PROP_AUTO_EXPOSURE, value).
VSourceParam::EXPOSURE - the library will call OpenCV function set(cv::CAP_PROP_EXPOSURE, value).
value Video source parameter value. Depends on parameter ID.

Returns: TRUE if the parameter was set or FALSE if not (not valid value or not supported).

getParam method

The getParam(…) method returns video source parameter value. Method will request parameters from device. Method can be used only after video source initialization. Method declaration:

float getParam(VSourceParam id) override;
Parameter Description
id Video source parameter ID according to VSourceParam enum. This method supports only parameters:
VSourceParam::LOG_LEVEL
VSourceParam::ROI_X
VSourceParam::ROI_Y
VSourceParam::ROI_WIDTH
VSourceParam::ROI_HEIGHT
VSourceParam::FOCUS_MODE - the library will call OpenCV function get(cv::CAP_PROP_AUTOFOCUS).
VSourceParam::FOCUS_POS - the library will call OpenCV function get(cv::CAP_PROP_FOCUS).
VSourceParam::GAIN - the library will call OpenCV function get(cv::CAP_PROP_GAIN).
VSourceParam::EXPOSURE_MODE - the library will call OpenCV function get(cv::CAP_PROP_AUTO_EXPOSURE).
VSourceParam::EXPOSURE - the library will call OpenCV function get(cv::CAP_PROP_EXPOSURE).
VSourceParam::CYCLE_TIME_MKS
VSourceParam::WIDTH
VSourceParam::HEIGHT
VSourceParam::FPS
VSourceParam::IS_OPEN

Returns: parameter value or -1 of the parameter not supported.

getParams method

The getParams(…) method returns all video source parameters. Method declaration:

void getParams(VSourceParams& params) override;
Parameter Description
params VSourceParams class object. For not supported parameter the library will set value -1.

executeCommand method

The executeCommand(…) method executes video source command. Not supported by the library. Method declaration:

bool executeCommand(VSourceCommand id) override;
Parameter Description
id Video source action command ID according to VSourceCommand enum.

Returns: FALSE in any case.

decodeAndExecuteCommand method

The decodeAndExecuteCommand(…) method decodes and executes command on video source side. Method will decode commands which encoded by encodeCommand(…) and encodeSetParamCommand(…) methods of VSource interface class. If command decoded the method will call setParam(…) or executeCommand(…) methods. decodeAndExecuteCommand(…) is thread-safe. This means that the method can be safely called from any thread. Method declaration:

bool decodeAndExecuteCommand(uint8_t* data, int size) override;
Parameter Description
data Pointer to input command.
size Size of command. Must be 11 bytes for SET_PARAM and 7 bytes for COMMAND.

Returns: TRUE if command decoded (SET_PARAM or COMMAND) and executed or FALSE if not.

encodeSetParamCommand method of VSource interface class

The encodeSetParamCommand(…) static method designed to encode command to change any parameter for 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.
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;
// Random parameter value.
float outValue = (float)(rand() % 20);
// Encode command.
VSurce::encodeSetParamCommand(data, size, VSourceParam::EXPOSURE, outValue);

encodeCommand method of VSource interface class

The encodeCommand(…) static method designed to encode command for 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.
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[11];
// Size of encoded data.
int size = 0;
// Encode command.
VSource::encodeCommand(data, size, 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.
size Size of command. Should be 11 bytes for SET_PARAM and 7 bytes for COMMAND.
paramId Parameter ID according to VSourceParam enum. After decoding SET_PARAM command the method will return parameter ID.
commandId Command ID according to VSourceCommand enum. After decoding COMMAND the method will return command ID.
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.

Data structures

VSource.h file of VSource interface class defines IDs for parameters (VSourceParam enum) and IDs for action commands (VSourceCommand enum).

VSourceCommand enum

Enum declaration:

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

Table 2 - Video source commands description.

Command Description
RESTART Not supported be the library.

VSourceParam enum

Enum declaration:

enum class VSourceParam
{
    /// [read/write] Logging mode. Values: 0 - Disable, 1 - Only file,
    /// 2 - Only terminal, 3 - File and terminal.
    LOG_LEVEL = 1,
    /// [read/write] Frame width. User can set frame width before initialization
    /// or after. Some video source classes may set width automatically.
    WIDTH,
    /// [read/write] Frame height. User can set frame height before
    /// initialization or after. Some video source classes may set height
    /// automatically.
    HEIGHT,
    /// [read/write] Gain mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual control, 1 - Auto.
    GAIN_MODE,
    /// [read/write] Gain value. Value: 0(min for particular video source class)
    /// - 65535(max for particular video source class).
    GAIN,
    /// [read/write] Exposure mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual control, 1 - Auto.
    EXPOSURE_MODE,
    /// [read/write] Exposure value. Value: 0(min for particular video source
    /// class) - 65535(max for particular video source class).
    EXPOSURE,
    /// [read/write] Focus mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual control, 1 - Auto.
    FOCUS_MODE,
    /// [read/write] Focus position. Value: 0(full near) - 65535(full far).
    FOCUS_POS,
    /// [read only] Video capture cycle time. **VSource** class sets this value
    /// automatically. This parameter means time interval between two captured
    /// video frame.
    CYCLE_TIME_MKS,
    /// [read/write] FPS. User can set frame FPS before initialization or after.
    /// Some video source classes may set FPS automatically.
    FPS,
    /// [read only] Open flag. 0 - not open, 1 - open.
    IS_OPEN,
    /// Region of interest upper left corner x coordinate.
    ROI_X,
    /// Region of interest upper left corner y coordinate.
    ROI_Y,
    /// Region of interest width.
    ROI_WIDTH,
    /// Region of interest height.
    ROI_HEIGHT,
    /// [read/write] Custom parameter. Depends on implementation.
    CUSTOM_1,
    /// [read/write] Custom parameter. Depends on implementation.
    CUSTOM_2,
    /// [read/write] Custom parameter. Depends on implementation.
    CUSTOM_3
};

Table 3 - Video source params description. Some params are not supported in VSourceOpenCv implementation.

Parameter Access Description
LOG_LEVEL read / write Logging mode. Specifies the log output mode. Values:
0 - Disable,
1 - Only file,
2 - Only terminal (console),
3 - File and terminal.
WIDTH read / write Not supported to set. Read only. Frame size control available only for video devices during initialization. The library will set automatically actual video resolution.
HEIGHT read / write Not supported to set. Read only. Frame size control available only for video devices during initialization. The library will set automatically actual video resolution.
GAIN_MODE read / write Not supported. Will have value -1.
GAIN read / write Gain value. Value depends on OpenCV version and video device. Every time when user call getParam(…) the library takes actual values from video source device.
EXPOSURE_MODE read / write Exposure mode. Value depends on OpenCV version and video device. Every time when user call getParam(…) the library takes actual values from video source device.
EXPOSURE read / write Exposure value. Value depends on OpenCV version and video device. Every time when user call getParam(…) the library takes actual values from video source device.
FOCUS_MODE read / write Focus mode. Value depends on OpenCV version and video device. Every time when user call getParam(…) the library takes actual values from video source device.
FOCUS_POS read / write Focus position. Value depends on OpenCV version and video device. Every time when user call getParam(…) the library takes actual values from video source device.
CYCLE_TIME_MKS read only Video capture cycle time, microseconds. VSourceOpenCv class sets this value automatically depending on input FPS. This parameter means time interval between two captured video frame.
FPS read / write Not supported to set. Read only. FPS control available only for video files during initialization. The library will set automatically actual FPS.
IS_OPEN read only Open flag. 0 - not open, 1 - open (video receiving).
ROI_X read / write Region of interest top-left corner horizontal coordinate.
ROI_Y read / write Region of interest top-left corner vertical coordinate.
ROI_WIDTH read / write Region of interest width, pixels.
ROI_HEIGHT read / write Region of interest height, pixels.
CUSTOM_1 read / write Not supported. Will have value -1.
CUSTOM_2 read / write Not supported. Will have value -1.
CUSTOM_3 read / write Not supported. Will have value -1.

VSourceParams class description

VSourceParams class declaration

VSourceParams class used for video source initialization (initVSource(…) method) or to get all actual params (getParams(…) method). Also VSourceParams provide structure to write/read params from JSON files (JSON_READABLE macro, see ConfigReader class description) and provide methods to encode and decode params. Class declaration:

class VSourceParams
{
public:
    /// Logging mode. Values: 0 - Disable, 1 - Only file,
    /// 2 - Only terminal, 3 - File and terminal.
    int logLevel{0};
    /// Video source: file, video stream, video device, camera num, etc.
    std::string source{"/dev/video0"};
    /// FOURCC: RGB24, BGR24, YUYV, UYVY, GRAY, YUV24, NV12, NV21, YU12, YV12.
    /// Value says to video source class which pixel format preferable for
    /// output video frame. Particular video source class can ignore this params
    /// during initialization. Parameters should be set before initialization.
    std::string fourcc{"YUYV"};
    /// Frame width. User can set frame width before initialization
    /// or after. Some video source classes may set width automatically.
    int width{1920};
    /// Frame height. User can set frame height before
    /// initialization or after. Some video source classes may set height
    /// automatically.
    int height{1080};
    /// Gain mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual control, 1 - Auto.
    int gainMode{1};
    /// Gain value. Value: 0(min for particular video source class)
    /// - 65535(max for particular video source class).
    int gain{0};
    /// Exposure mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual control, 1 - Auto.
    int exposureMode{1};
    /// Exposure value. Value: 0(min for particular video source
    /// class) - 65535(max for particular video source class).
    int exposure{1};
    /// Focus mode. Focus mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual control, 1 - Auto.
    int focusMode{1};
    /// Focus position. Value: 0(full near) - 65535(full far).
    int focusPos{0};
    /// Video capture cycle time. **VSource** class sets this value
    /// automatically. This parameter means time interval between two captured
    /// video frame.
    int cycleTimeMks{0};
    /// FPS. User can set frame FPS before initialization or after.
    /// Some video source classes may set FPS automatically.
    float fps{0};
    /// Open flag. 0 - not open, 1 - open.
    bool isOpen{false};
    /// Region of intrest upper left corner x coordinate.
    int roiX{0};
    /// Region of intrest upper left corner y coordinate.
    int roiY{0};
    /// Region of intrest width.
    int roiWidth{0};
    /// Region of intrest heigth.
    int roiHeight{0};
    /// Custom parameter. Depends on implementation.
    float custom1{0.0f};
    /// Custom parameter. Depends on implementation.
    float custom2{0.0f};
    /// Custom parameter. Depends on implementation.
    float custom3{0.0f};

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

    /// Copy operator.
    VSourceParams& operator= (const VSourceParams& src);

    /// Encode (serialize) params.
    bool encode(uint8_t* data, int bufferSize, int& size,
                VSourceParamsMask* mask = nullptr);

    /// Decode (deserialize) params.
    bool decode(uint8_t* data, int dataSize);
};

Table 4 - VSourceParams class fields description.

Field type Description
logLevel int Logging mode. Specifies the log output mode. Values:
0 - Disable,
1 - Only file,
2 - Only terminal (console),
3 - File and terminal.
source string Video source initialization string. Valid formats:
“camera num” - camera number (e.g. “0”, “1”, “2” etc.).
“device name” - device name (e.g. “/dev/video0”).
“file path” - video file path (e.g. “video.mp4”).
“stream url” - video stream url (e.g. “rtsp://192.168.1.70:7031/unicast”).
fourcc string Pixel format. Generally output frame has Fourcc::BGR24 format but if user receives stream and set output format to Fourcc::H264. Fourcc::HEVC or Fourcc::JPEG the output format will be set respectively.
width int Video frame width. Frame size control available only for video devices during initialization. The library will set automatically actual video resolution.
height int Video frame height. Frame size control available only for video devices during initialization. The library will set automatically actual video resolution.
gainMode int Not supported. Will have value -1.
gain int Gain value. Value depends on OpenCV version and video device. Every time when user call getParams(…) the library takes actual values from video source device.
exposureMode int Exposure mode. Value depends on OpenCV version and video device. Every time when user call getParams(…) the library takes actual values from video source device.
exposure int Exposure value. Value depends on OpenCV version and video device. Every time when user call getParams(…) the library takes actual values from video source device.
focusMode int Focus mode. Value depends on OpenCV version and video device. Every time when user call getParams(…) the library takes actual values from video source device.
focusPos int Focus position. Value depends on OpenCV version and video device. Every time when user call getParams(…) the library takes actual values from video source device.
cycleTimeMks int Video capture cycle time, microseconds. VSourceOpenCv class sets this value automatically depending on input FPS value. This parameter means time interval between two captured video frame.
fps float FPS. Can’t be changes after initialization.
isOpen bool Open flag. false - not open, true - open.
roiX int Region of interest top-left corner horizontal coordinate.
roiY int Region of interest top-left corner vertical coordinate.
roiWidth int Region of interest width, pixels.
roiHeight int Region of interest height, pixels.
custom1 float Not supported. Will have value -1.
custom2 float Not supported. Will have value -1.
custom3 float Not supported. Will have value -1.

None: VSourceParams class fields listed in Table 4 reflects params set/get by methods setParam(…) and getParam(…).

Serialize video source params

VSourceParams class provides method encode(…) to serialize video source params (fields of VSourceParams class, see Table 4). Serialization of video source params necessary in case when you need to send video source params via communication channels. Method doesn’t encode fields: initString and fourcc. Method provides options to exclude particular parameters from serialization. To do this method inserts binary mask (2 bytes) where each bit represents particular parameter and decode(…) method recognizes it. Method declaration:

bool encode(uint8_t* data, int bufferSize, int& size, VSourceParamsMask* mask = nullptr);
Parameter Value
data Pointer to data buffer.
size Size of encoded data. 79 bytes by default.
bufferSize Data buffer size. If buffer size smaller than required, buffer will be filled with fewer parameters.
mask Parameters mask - pointer to VSourceParamsMask structure. VSourceParamsMask (declared in VSource.h file) determines flags for each field (parameter) declared in VSourceParams class. If the user wants to exclude any parameters from serialization, he can put a pointer to the mask. If the user wants to exclude a particular parameter from serialization, he should set the corresponding flag in the VSourceParamsMask structure.

VSourceParamsMask structure declaration:

struct VSourceParamsMask
{
    bool logLevel{true};
    bool width{true};
    bool height{true};
    bool gainMode{true};
    bool gain{true};
    bool exposureMode{true};
    bool exposure{true};
    bool focusMode{true};
    bool focusPos{true};
    bool cycleTimeMks{true};
    bool fps{true};
    bool isOpen{true};
    bool roiX{true};
    bool roiY{true};
    bool roiWidth{true};
    bool roiHeight{true};
    bool custom1{true};
    bool custom2{true};
    bool custom3{true};
};

Example without parameters mask:

// Prepare random params.
VSourceParams in;
in.initString = "any string";
in.logLevel = 0;

// Encode data.
uint8_t data[1024];
int size = 0;
in.encode(data, 1024, size);
cout << "Encoded data size: " << size << " bytes" << endl;

Example without parameters mask:

// Prepare random params.
VSourceParams in;
in.initString = "any string";
in.logLevel = 0;

// Prepare params mask.
VSourceParamsMask mask;
mask.logLevel = false; // Exclude logLevel. Others by default.

// Encode data.
uint8_t data[1024];
int size = 0;
in.encode(data, 1024, size, &mask);
cout << "Encoded data size: " << size << " bytes" << endl;

Deserialize video source params

VSourceParams class provides method decode(…) to deserialize video source params (fields of VSourceParams class, see Table 4). Deserialization of video source params necessary in case when you need to receive video source params via communication channels. Method doesn’t decode fields: initString and fourcc. Method automatically recognizes which parameters were serialized by encode(…) method. Method declaration:

bool decode(uint8_t* data, int dataSize);
Parameter Value
data Pointer to encode data buffer. Data size should be at least 62 bytes.
dataSize Size of data.

Returns: TRUE if data decoded (deserialized) or FALSE if not.

Example:

// Encode data.
VSourceParams in;
uint8_t data[1024];
int size = 0;
in.encode(data, 1024, size);

cout << "Encoded data size: " << size << " bytes" << endl;

// Decode data.
VSourceParams out;
if (!out.decode(data, size))
    cout << "Can't decode data" << endl;

Read params from JSON file and write to JSON file

VSource library depends on ConfigReader library which provides method to read params from JSON file and to write params to JSON file. Example of writing and reading params to JSON file:

// Write params to file.
VSurceParams in;
cr::utils::ConfigReader inConfig;
inConfig.set(in, "vSourceParams");
inConfig.writeToFile("TestVSourceParams.json");

// Read params from file.
cr::utils::ConfigReader outConfig;
if(!outConfig.readFromFile("TestVSourceParams.json"))
{
    cout << "Can't open config file" << endl;
    return false;
}

TestVSourceParams.json will look like:

{
    "vSourceParams": {
        "custom1": 150.0,
        "custom2": 252.0,
        "custom3": 30.0,
        "exposureMode": 226,
        "focusMode": 89,
        "fourcc": "skdfjhvk",
        "fps": 206.0,
        "gainMode": 180,
        "height": 61,
        "logLevel": 17,
        "roiHeight": 249,
        "roiWidth": 167,
        "roiX": 39,
        "roiY": 223,
        "source": "alsfghljb",
        "width": 35
    }
}

Build and connect to your project

Typical commands to build VSourceOpenCv library (OpenCV should be installed in your system):

cd VSourceOpenCv
mkdir build
cd build
cmake ..
make

If you want connect VSourceOpenCv library to your CMake project as source code you can make follow. For example, if your repository has structure:

CMakeLists.txt
src
    CMakeList.txt
    yourLib.h
    yourLib.cpp

Create folder 3rdparty in your repository and copy repository folder VSourceOpenCv to 3rdparty folder. New structure of your repository:

CMakeLists.txt
src
    CMakeList.txt
    yourLib.h
    yourLib.cpp
3rdparty
    VSourceOpenCv

Create CMakeLists.txt file in 3rdparty folder. CMakeLists.txt 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_VSOURCE                         ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VSOURCE)
    SET(${PARENT}_VSOURCE_OPENCV                        ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_VSOURCE_OPENCV_TEST                   OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_VSOURCE_OPENCV_EXAMPLE                OFF CACHE BOOL "" FORCE)
endif()

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

File 3rdparty/CMakeLists.txt adds folder VSourceOpenCv to your project and excludes test application and example from compiling (by default test application and example excluded from compiling if VSourceOpenCv included as sub-repository). Your repository new structure will be:

CMakeLists.txt
src
    CMakeList.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    VSourceOpenCv

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

add_subdirectory(3rdparty)

Next you have to include VSourceOpenCv library in your src/CMakeLists.txt file:

target_link_libraries(${PROJECT_NAME} VSourceOpenCv)

Done!

Simple example

Example shows how to initialize video source with generic VSource interface and how to capture video in loop. Also example show how to get video source parameters. Example:

#include <iostream>
#include "VSourceOpenCv.h"

int main(void)
{
    // Open video source.
    cr::video::VSource* source = new cr::video::VSourceOpenCv();
    std::string initString = "0;640;480";
    if (!source->openVSource(initString))
        return -1;

    cr::video::Frame frame;
    while (true)
    {
        // Wait new frame 1000 msec.
        if (!source->getFrame(frame, 1000))
            continue;

        // Get current params.
        cr::video::VSourceParams params;
        source->getParams(params);

        // Display cycle time.
        cv::Mat openCvFrame(frame.height, frame.width, CV_8UC3, frame.data);
        cv::putText(openCvFrame, "Frame ID " + std::to_string(frame.frameId) +
        " Cycle time " + std::to_string(params.cycleTimeMks / 1000) + " msec.",
        cv::Point(5, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 1);

        // Show frame with OpenCV.
        cv::imshow("VIDEO", openCvFrame);
        if (cv::waitKey(1) == 27)
            break;
    }

    return 1;
}