
VSourceLibCamera C++ library
v2.2.5
Table of contents
- Overview
- Versions
- Library files
- VSourceLibCamera class description
- VSourceLibCamera class declaration
- getVersion method
- openVSource method
- initVSource method
- isVSourceOpen method
- closeVSource method
- getFrame method
- setParam method
- getParam method
- getParams method
- executeCommand method
- decodeAndExecuteCommand method
- encodeSetParamCommand method of VSource interface class
- encodeCommand method of VSource interface class
- decodeCommand method of VSource interface class
- Data structures
- VSourceParams class description
- Build and connect to your project
- Simple example
- Test application
Overview
VSourceLibCamera C++ library provides video capture and video source control functions based on Libcamera API. The library inherits its interface from the VSource interface class. VSource.h file contains data structures: VSourceParams class (contains video source params and provides methods for serialization/deserialization of params), VSourceCommand enum (describes video source action commands) and VSourceParam enum (describes video source params). VSourceLibCamera depends on: Libcamera API (system library, found by pkg-config), VSource interface class (provides interface for video sources, depends on the Frame and ConfigReader libraries) and the Logger library (provides methods to write logs). The repository does not contain the source code of the dependencies (see Build and connect to your project). If the camera doesn’t support the requested pixel format or resolution, libcamera chooses the most appropriate supported ones and the library delivers the frames in the pixel format and size which the camera accepted. The library supports C++17 standard (it is compiled as C++20 if the headers of the installed libcamera require C++20) and Linux only.
VSourceLibCamera 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 | 12.11.2023 | First version |
| 1.1.0 | 16.11.2023 | - Memory allocation mechanism rebuilt. |
| 1.2.0 | 21.11.2023 | - Code cleaned up. - Changed initialization string format. - Changed initialization procedure. |
| 1.3.0 | 14.12.2023 | - Added FPS control. - Mistakes in description fixed. |
| 2.0.0 | 15.09.2023 | - Changed interface to VSource interface. - Added pixel format control. - Test application rebuilt. - Added examples. - Documentation updated. |
| 2.0.1 | 15.09.2023 | - Fixed re-init. - Stop camera manager before configuration. - Exclude v4l2 style (/dev/video0) source name. |
| 2.1.0 | 27.12.2023 | - Region of interest support added. |
| 2.1.1 | 09.01.2024 | - Documentation updated. |
| 2.1.2 | 25.04.2024 | - Documentation updated. - Submodules updated. |
| 2.1.3 | 20.05.2024 | - Documentation updated. - Submodules updated. |
| 2.2.0 | 10.07.2024 | - CMake updated. - Submodules updated. - Repository structure updated. |
| 2.2.1 | 12.08.2024 | - Camera initialization bug solved for newer versions of Libcamera API. |
| 2.2.2 | 03.04.2025 | - Logger submodule update. |
| 2.2.3 | 28.03.2026 | - Fixed compilation error on x86 platform. - Fixed mistakes in documentation. |
| 2.2.4 | 12.10.2026 | - Submodules updated. |
| 2.2.5 | 22.10.2026 | - Sub-repositories removed: the dependencies are cloned next to the repository or added by the parent project. - Several objects can be used in one process (they share the camera manager of libcamera), opening of the same camera from several threads is serialized. - Fixed channel order of RGB24 and BGR24 frames and the layout of YUV24 frames. - Fixed handling of the frame buffer layout: line stride, plane offsets, planes in separate buffers, payload size; failed and truncated frames are dropped. - Frames have the pixel format and size which the camera accepted. - Fixed heap buffer overflows of the region of interest (odd sizes, chroma planes of YU12 and YV12). - JPEG frames have the size of the payload. - Fixed undefined behaviour for NaN, infinite and out of range values of setParam(…), decodeAndExecuteCommand(…) and of the frame rate. - decodeAndExecuteCommand(…) rejects null data, messages of a wrong size and unknown IDs. - Strict check of the init string and of the params of initVSource(…), width or height 0 keeps the default frame size of the camera. - Fixed data races; waiting for a frame does not block the other methods, closeVSource() ends the waiting. - Fixed queueing of capture requests while the camera is stopped. - Fixed frame ID and cycle time of the first frame. - The frame rate is requested only from cameras with the frame duration control (a warning is written to the log otherwise). - The last frame is released when the video source is closed. - Support of libcamera versions which require C++20 (std::span in the headers): the library is compiled as C++20 then. - Compiler warnings and exploit mitigation flags added to CMake files. - Example and test application fixed. - Removed OpenCV from the test application: frames are shown by the SimpleUI library, JPEG frames are decoded by the VDecoderJPEG library. - Documentation updated. |
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.
src ------------------------------- Folder with library source code.
Impl -------------------------- Folder with video source implementation files.
VSourceLibCameraImpl.h ---- Header file of the implementation class.
VSourceLibCameraImpl.cpp -- C++ implementation file.
CMakeLists.txt ---------------- CMake file of the library.
VSourceLibCamera.h ------------ Main library header file.
VSourceLibCameraVersion.h ----- Header file with library version.
VSourceLibCameraVersion.h.in -- File for CMake to generate version header.
VSourceLibCamera.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.
static ---------------------------- Folder with images for documentation.
VSourceLibCamera class description
VSourceLibCamera class declaration
VSourceLibCamera class is declared in VSourceLibCamera.h file. Class declaration:
namespace rapidpixel
{
/// Video source implementation class.
class VSourceLibCameraImpl;
/// Video source class based on libcamera API.
class VSourceLibCamera : public VSource
{
public:
/// Class constructor.
VSourceLibCamera();
/// Class destructor. Closes the video source.
~VSourceLibCamera() override;
/// The class owns a camera: it can't be copied or moved.
VSourceLibCamera(const VSourceLibCamera&) = delete;
VSourceLibCamera(VSourceLibCamera&&) = delete;
VSourceLibCamera& operator= (const VSourceLibCamera&) = delete;
VSourceLibCamera& operator= (VSourceLibCamera&&) = 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;
};
}
All public methods are thread-safe. Waiting for a frame in getFrame(…) does not block the other methods, closeVSource() ends the waiting. Several objects can be used in one process: they share the camera manager of libcamera (libcamera allows one camera manager per process), the first object creates it and the last destroyed object stops it. A camera can be opened by one object at a time.
getVersion method
The getVersion() method returns the string of the current version of VSourceLibCamera class. Method declaration:
static std::string getVersion();
The method can be used without VSourceLibCamera class instance:
std::cout << "VSourceLibCamera class version: " <<
rapidpixel::VSourceLibCamera::getVersion() << std::endl;
Console output:
VSourceLibCamera class version: 2.2.5
openVSource method
The openVSource(…) method opens the video source (an open video source is closed first). The init string sets the camera number, frame size, fps and pixel format, the other video source params (VSourceParams class) keep their values. Instead of the openVSource(…) method, the user can call initVSource(…) method. Method declaration:
bool openVSource(std::string& initString) override;
| Parameter | Value |
|---|---|
| initString | Initialization string. Valid formats: [camera number];[width];[height];[fps];[fourcc] or [camera number];[width];[height];[fps] or [camera number];[width];[height] Initialization string parameters: [camera number] - Index of the camera in the list of cameras of Libcamera API: 0, 1 etc. [width] - Video frame width, integer 0 - 16384. Video frame height must be set as well. The library requests this frame width from the camera. If width or height is 0 the default frame size of the camera is used. [height] - Video frame height, integer 0 - 16384. Video frame width must be set as well. The library requests this frame height from the camera. If width or height is 0 the default frame size of the camera is used. [fps] - FPS, number 0 or 0.001 - 10000 (for example 30 or 29.97). The library requests this frame rate from the camera (frame duration limits). A camera without the frame duration control keeps its frame rate (for example USB cameras of the uvcvideo pipeline handler of libcamera), the library writes a warning to the log then. If set to 0 the frame rate is not requested (default of the camera). If fps is not set the library requests 30. [fourcc] - Pixel format. Valid values: BGR24, RGB24, GRAY, YUV24, YUYV, UYVY, NV12, NV21, YV12, YU12, JPEG. If fourcc is not set the library requests NV12. If the camera doesn’t support the requested pixel format or frame size, libcamera chooses the most appropriate supported ones: the frames have the pixel format and size which the camera accepted. Spaces around the numbers are allowed, empty parts between ‘;’ are skipped. Any other character in a number makes the string invalid. |
Returns: TRUE if the video source is open or FALSE if not (invalid init string, no camera with this number, camera used by another object or process, configuration not supported). If the init string is valid, the camera number (source), width, height, fps and pixel format (if set) are stored in the params also if the camera can’t be opened; after the video source is open the params contain the frame size and the pixel format which the camera accepted (see getParams(…)).
initVSource method
The initVSource(…) method is designed to initialize video source by a set of parameters. Instead of the initVSource(…) method, the user can call openVSource(…). Method declaration:
bool initVSource(VSourceParams& params) override;
| Parameter | Value |
|---|---|
| params | VSourceParams class object. The source field must contain the camera number of Libcamera API (“0”, “1” etc., the default value “/dev/video0” is not valid). The fields fourcc, width, height and fps are checked as the parts of the init string of openVSource(…) (fourcc is required). logLevel must be 0 - 3, other values disable logging (logLevel 0 is stored). The region of interest fields are used by getFrame(…), the other fields are stored without check. |
Returns: TRUE if the video source is open or FALSE if not. The params are stored also if they are not valid or the camera can’t be opened (isOpen is FALSE then).
isVSourceOpen method
The isVSourceOpen() method returns video source initialization status. Initialization status is also included in VSourceParams class. Method declaration:
bool isVSourceOpen() override;
Returns: TRUE if the video source is open (initialized) or FALSE if not.
closeVSource method
The closeVSource() method closes the video source: the camera is stopped and released. A getFrame(…) call which waits for a frame returns FALSE. Method declaration:
void closeVSource() override;
getFrame method
The getFrame(…) method copies the last captured video frame. Every captured frame is delivered once: if the camera captures frames faster than the method is called, older frames are skipped. Waiting for a frame does not block the other methods. Method declaration:
bool getFrame(Frame& frame, int32_t timeoutMsec = 0) override;
| Parameter | Value |
|---|---|
| frame | Output Frame class object. Pixel format can be set in initVSource(…) or openVSource(…) methods, but if the specified pixel format is not supported by the camera, the library returns Frame object with the pixel format which the camera accepted. The frame has the frame size of the video source or the size of the region of interest (see VSourceParam enum). frameId field is the number of the captured frame since the video source was opened (starting with 1), size field is the data size (for JPEG the size of the payload of the frame). The memory of the frame is reused if the frame has the size, the pixel format and (for uncompressed formats) the data size which Frame(width, height, fourcc) allocates, otherwise the frame is reallocated. The memory of a reused JPEG frame must have the size which Frame(width, height, fourcc) allocates (width * height * 4 bytes). The frame is not changed if the method returns FALSE. |
| timeoutMsec | Timeout to wait new frame data, milliseconds: - timeoutMsec == -1 (any negative value) - Method will wait until a new frame arrives or the video source is closed. - timeoutMsec == 0 - Method will only check if a new frame exists. - timeoutMsec > 0 - Method will wait for a new frame for the specified time. |
Returns: TRUE if a new frame is copied or FALSE if not (video source not open, no new frame, video source closed while waiting, memory can’t be allocated).
setParam method
The setParam(…) method is designed to set a new video source parameter value. Supported params: LOG_LEVEL, ROI_X, ROI_Y, ROI_WIDTH and ROI_HEIGHT (valid values see in VSourceParam enum description). The fraction of a value is truncated, NaN, infinite and out of range values are rejected. Method declaration:
bool setParam(VSourceParam id, float value) override;
| Parameter | Description |
|---|---|
| id | Video source parameter ID according to VSourceParam enum. |
| value | Video source parameter value. |
Returns: TRUE if the parameter was set or FALSE if not.
getParam method
The getParam(…) method returns video source parameter value. Method declaration:
float getParam(VSourceParam id) override;
| Parameter | Description |
|---|---|
| id | Video source parameter ID according to VSourceParam enum. |
Returns: parameter value or -1 if the parameter is not supported (GAIN_MODE, GAIN, EXPOSURE_MODE, EXPOSURE, FOCUS_MODE, FOCUS_POS and unknown IDs).
getParams method
The getParams(…) method returns video source params (VSourceParams class object). After the video source is open the params contain the frame size and the pixel format which the camera accepted. Method declaration:
void getParams(VSourceParams& params) override;
| Parameter | Description |
|---|---|
| params | Reference to object of VSourceParams class. |
executeCommand method
The executeCommand(…) method executes a video source action command. Method declaration:
bool executeCommand(VSourceCommand id) override;
| Parameter | Description |
|---|---|
| id | Video source action command ID according to VSourceCommand enum. |
Returns: FALSE. No command is supported by VSourceLibCamera library.
decodeAndExecuteCommand method
The decodeAndExecuteCommand(…) method decodes and executes a command on the video source side. The method will decode commands encoded by encodeCommand(…) and encodeSetParamCommand(…) methods of VSource interface class. If the command is decoded, the method will call setParam(…) or executeCommand(…) methods. decodeAndExecuteCommand(…) is thread-safe (as all public methods). 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. nullptr is rejected. |
| size | Size of command. Must be 11 bytes for SET_PARAM and 7 bytes for COMMAND, other sizes are rejected. |
Returns: TRUE if command decoded (SET_PARAM or COMMAND) and executed or FALSE if not. Commands with unknown parameter or command IDs are rejected.
encodeSetParamCommand method of VSource interface class
The encodeSetParamCommand(…) is a static method of VSource interface class designed to encode a command to change any parameter in a 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(…) method encodes 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 is used on the 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 = 10.0f;
// Encode command.
rapidpixel::VSource::encodeSetParamCommand(
data, size, rapidpixel::VSourceParam::EXPOSURE, outValue);
encodeCommand method of VSource interface class
The encodeCommand(…) is a static method of VSource interface class designed to encode a command for a 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. |
| 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 is used on the 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(…) is a static method of VSource interface class designed to decode a command on the video source side (edge device). The method will decode commands encoded by encodeCommand(…) and encodeSetParamCommand(…) methods of VSource interface class. 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. Must be exactly 7 bytes for COMMAND and exactly 11 bytes for SET_PARAM 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 of decoding COMMAND, 1 - in case of decoding SET_PARAM command or -1 in case of 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 action commands description.
| Command | Description |
|---|---|
| RESTART | Not supported by VSourceLibCamera 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,
/// [read/write] Region of interest upper left corner x coordinate.
ROI_X,
/// [read/write] Region of interest upper left corner y coordinate.
ROI_Y,
/// [read/write] Region of interest width.
ROI_WIDTH,
/// [read/write] 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.
| 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 only | Video frames width, pixels: the width requested by openVSource(…) or initVSource(…), after the video source is open the width which the camera accepted. Can’t be set by setParam(…). |
| HEIGHT | read only | Video frames height, pixels: the height requested by openVSource(…) or initVSource(…), after the video source is open the height which the camera accepted. Can’t be set by setParam(…). |
| GAIN_MODE | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns -1. |
| GAIN | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns -1. |
| EXPOSURE_MODE | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns -1. |
| EXPOSURE | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns -1. |
| FOCUS_MODE | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns -1. |
| FOCUS_POS | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns -1. |
| CYCLE_TIME_MKS | read only | Video capture cycle time, microseconds. The library sets this value automatically: time interval between the two last frames delivered by getFrame(…) (for the first frame after the video source is opened: time since opening). |
| FPS | read only | FPS requested by openVSource(…) or initVSource(…) (0 - default of the camera). A camera without the frame duration control keeps its frame rate. Can’t be set by setParam(…). |
| IS_OPEN | read only | Open flag. 0 - not open, 1 - open. |
| ROI_X | read / write | Region of interest top-left corner horizontal coordinate: 0 - frame width - 1. |
| ROI_Y | read / write | Region of interest top-left corner vertical coordinate: 0 - frame height - 1. |
| ROI_WIDTH | read / write | Region of interest width, pixels: 0 - 16384 (0 - no region of interest). |
| ROI_HEIGHT | read / write | Region of interest height, pixels: 0 - 16384 (0 - no region of interest). |
| CUSTOM_1 | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns the value set by initVSource(…). |
| CUSTOM_2 | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns the value set by initVSource(…). |
| CUSTOM_3 | read / write | Not supported. setParam(…) returns FALSE, getParam(…) returns the value set by initVSource(…). |
Note: The region of interest is used if ROI_WIDTH and ROI_HEIGHT are not 0 and the top-left corner is inside of the frame. It is cut to the frame. For NV12, NV21, YU12 and YV12 the coordinates and the size are rounded down to even values (at least 2), for YUYV and UYVY the horizontal coordinate and the width. After a frame is delivered the ROI params contain the values which were used. The region of interest is not applied to JPEG frames. The ROI params are read when getFrame(…) is called.
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 provides a structure to write/read params from JSON files (JSON_READABLE macro, see ConfigReader class description) and provides 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. 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.0f};
/// Open flag. false - not open, true - open.
bool isOpen{false};
/// Region of interest upper left corner x coordinate.
int roiX{0};
/// Region of interest upper left corner y coordinate.
int roiY{0};
/// Region of interest width.
int roiWidth{0};
/// Region of interest height.
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)
/// Default constructor.
VSourceParams() = default;
/// Copy constructor.
VSourceParams(const VSourceParams& src) = default;
/// Move constructor.
VSourceParams(VSourceParams&& src) = default;
/// Copy assignment operator.
VSourceParams& operator= (const VSourceParams& src) = default;
/// Move assignment operator.
VSourceParams& operator= (VSourceParams&& src) = default;
/// 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 | Camera number of Libcamera API: “0”, “1” etc. The default value “/dev/video0” is not a camera number: the field must be set before initVSource(…). |
| fourcc | string | Pixel format. Valid values: BGR24, RGB24, GRAY, YUV24, YUYV, UYVY, NV12, NV21, YV12, YU12, JPEG. Value tells the video source class which pixel format is preferable for the output video frame: if the camera doesn’t support it, libcamera chooses the most appropriate supported one. After the video source is open the field contains the pixel format of the frames. |
| width | int | Video frame width, 0 - 16384. Video frame height must be set as well. The library requests this frame width from the camera. If width or height is 0 the default frame size of the camera is used. After the video source is open the field contains the frame width which the camera accepted. |
| height | int | Video frame height, 0 - 16384. Video frame width must be set as well. The library requests this frame height from the camera. If width or height is 0 the default frame size of the camera is used. After the video source is open the field contains the frame height which the camera accepted. |
| gainMode | int | Not supported. Stored without check. |
| gain | int | Not supported. Stored without check. |
| exposureMode | int | Not supported. Stored without check. |
| exposure | int | Not supported. Stored without check. |
| focusMode | int | Not supported. Stored without check. |
| focusPos | int | Not supported. Stored without check. |
| cycleTimeMks | int | Video capture cycle time, microseconds. The library sets this value automatically (see CYCLE_TIME_MKS in Table 3). |
| fps | float | FPS: 0 (default of the camera) or 0.001 - 10000. A camera without the frame duration control keeps its frame rate. Can’t be changed by setParam(…). |
| isOpen | bool | Open flag. false - not open, true - open. |
| roiX | int | Region of interest top-left corner horizontal coordinate (see ROI_X in Table 3). |
| roiY | int | Region of interest top-left corner vertical coordinate (see ROI_Y in Table 3). |
| roiWidth | int | Region of interest width, pixels (see ROI_WIDTH in Table 3). |
| roiHeight | int | Region of interest height, pixels (see ROI_HEIGHT in Table 3). |
| custom1 | float | Not supported. Stored without check. |
| custom2 | float | Not supported. Stored without check. |
| custom3 | float | Not supported. Stored without check. |
Note: VSourceParams class fields listed in Table 4 reflect params set/get by methods setParam(…) and getParam(…).
Encode 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 is necessary in case when you need to send video source params via communication channels. The method doesn’t encode fields: source and fourcc. The method provides options to exclude particular parameters from serialization. To do this, the method inserts a binary mask (3 bytes) where each bit represents a particular parameter and the 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 (all params encoded). |
| bufferSize | Data buffer size. If the buffer size is smaller than required, the params that don’t fit in the buffer are not encoded. Must be at least 7 bytes. |
| 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, they can pass a pointer to the mask. If the user wants to exclude a particular parameter from serialization, they should set the corresponding flag in the VSourceParamsMask structure. |
Returns: TRUE if params encoded or FALSE if not (no buffer or buffer smaller than 7 bytes).
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 params.
rapidpixel::VSourceParams in;
in.source = "alsfghljb";
in.logLevel = 0;
// Encode data.
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size))
{
std::cout << "Can't encode params" << std::endl;
return false;
}
std::cout << "Encoded data size: " << size << " bytes" << std::endl;
Example with parameters mask:
// Prepare params.
rapidpixel::VSourceParams in;
in.source = "alsfghljb";
in.logLevel = 0;
// Prepare params mask.
rapidpixel::VSourceParamsMask mask;
mask.logLevel = false; // Exclude logLevel. Others by default.
// Encode data.
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size, &mask))
{
std::cout << "Can't encode params" << std::endl;
return false;
}
std::cout << "Encoded data size: " << size << " bytes" << std::endl;
Decode 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 is necessary in case when you need to receive video source params via communication channels. The method doesn’t decode fields: source and fourcc (they are cleared). The method automatically recognizes which parameters were serialized by the encode(…) method. Method declaration:
bool decode(uint8_t* data, int dataSize);
| Parameter | Value |
|---|---|
| data | Pointer to encoded data buffer. |
| dataSize | Size of data. Must be not smaller than the size of the data written by the encode(…) method. |
Returns: TRUE if data decoded (deserialized) or FALSE if not (the params are not changed then).
Example:
// Encode data.
rapidpixel::VSourceParams in;
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size))
{
std::cout << "Can't encode params" << std::endl;
return false;
}
std::cout << "Encoded data size: " << size << " bytes" << std::endl;
// Decode data.
rapidpixel::VSourceParams out;
if (!out.decode(data, size))
{
std::cout << "Can't decode data" << std::endl;
return false;
}
Read params from JSON file and write to JSON file
VSource library depends on ConfigReader library which provides methods 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.
rapidpixel::VSourceParams in;
rapidpixel::ConfigReader inConfig;
inConfig.set(in, "vSourceParams");
if (!inConfig.writeToFile("TestVSourceParams.json"))
{
std::cout << "Can't write config file" << std::endl;
return false;
}
// Read params from file.
rapidpixel::ConfigReader outConfig;
if (!outConfig.readFromFile("TestVSourceParams.json"))
{
std::cout << "Can't open config file" << std::endl;
return false;
}
rapidpixel::VSourceParams out;
if (!outConfig.get(out, "vSourceParams"))
{
std::cout << "Can't read params" << std::endl;
return false;
}
TestVSourceParams.json will look like:
{
"vSourceParams": {
"logLevel": 0,
"source": "/dev/video0",
"fourcc": "YUYV",
"width": 1920,
"height": 1080,
"gainMode": 1,
"exposureMode": 1,
"focusMode": 1,
"fps": 0.0,
"roiX": 0,
"roiY": 0,
"roiWidth": 0,
"roiHeight": 0,
"custom1": 0.0,
"custom2": 0.0,
"custom3": 0.0
}
}
Build and connect to your project
If the Libcamera API is not installed, you have to install it by commands:
sudo apt-get install meson python3-pip libyaml-dev python3-yaml python3-ply python3-jinja2 libdrm-dev libjpeg-dev libsdl2-dev
git clone https://git.libcamera.org/libcamera/libcamera.git
cd libcamera
meson setup build
sudo ninja -C build install
Build stand alone
The repository does not contain sub-repositories. The libraries VSourceLibCamera depends on (Frame, ConfigReader, VSource, Logger) and the libraries the test application uses (SimpleUI, VCodec, VDecoderJPEG) must be cloned into the same folder as VSourceLibCamera. The folder structure must be:
<work folder>
VSourceLibCamera
Frame
ConfigReader
VSource
Logger
SimpleUI
VCodec
VDecoderJPEG
The libcamera library must be installed (see above, CMake finds it by pkg-config). Newer versions of libcamera use C++20 in their headers: CMake checks the headers and compiles the library as C++20 then (the compiler must support C++20). The header of the library doesn’t include the headers of libcamera, so applications which use the library can be compiled as C++17. Typical commands to build the library, the test application and the example (use the URLs of the repositories provided to you):
git clone <VSourceLibCamera repository URL>
git clone <Frame repository URL>
git clone <ConfigReader repository URL>
git clone <VSource repository URL>
git clone <Logger repository URL>
git clone <SimpleUI repository URL>
git clone <VCodec repository URL>
git clone <VDecoderJPEG repository URL>
cd VSourceLibCamera
mkdir build
cd build
cmake ..
make
If VSourceLibCamera is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame, ../ConfigReader, ../VSource and ../Logger (in this order) before the library itself and the folders ../SimpleUI, ../VCodec and ../VDecoderJPEG before the test application. If a folder does not exist CMake stops with an error. To build the library and the example without the test application (SimpleUI, VCodec and VDecoderJPEG are not needed then) use cmake .. -D_SUBMODULE_CACHE_OVERWRITE=OFF -D_VSOURCE_LIBCAMERA_TEST=OFF instead of cmake ... The library requires Linux: on other systems CMake stops with an error.
CMake options
Table 5 - CMake options of the repository. In the options below ${PARENT} is the prefix defined by the top-level project (empty if VSourceLibCamera is the top-level project).
| Option | Default | Description |
|---|---|---|
| ${PARENT}_VSOURCE_LIBCAMERA | ON | Build the library. |
| ${PARENT}_VSOURCE_LIBCAMERA_TEST | ON (stand alone), OFF (included in other project) | Build the test application. |
| ${PARENT}_VSOURCE_LIBCAMERA_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 VSourceLibCamera as a sub-repository. |
| CMAKE_BUILD_TYPE | Release (if not specified) | Build type. |
Connect to your project
If you want to connect the VSourceLibCamera library to your CMake project as source code, you can do the following. 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 VSourceLibCamera folder and the folders of the libraries it depends on (Frame, ConfigReader, VSource, Logger) there, or add these repositories as sub-repositories. The new structure of your repository:
CMakeLists.txt
src
CMakeLists.txt
yourLib.h
yourLib.cpp
3rdparty
Frame
ConfigReader
VSource
Logger
VSourceLibCamera
Create a CMakeLists.txt file in the 3rdparty folder. VSourceLibCamera does not add its dependencies when it is included in another project: the file adds them in dependency order (Frame, ConfigReader, VSource, Logger) and then the library. The test application and the example of VSourceLibCamera are not built when it is included in another project. 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_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_LOGGER ON CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_LOGGER)
SET(${PARENT}_LOGGER ON CACHE BOOL "" FORCE)
SET(${PARENT}_LOGGER_EXAMPLE OFF CACHE BOOL "" FORCE)
endif()
SET(${PARENT}_SUBMODULE_VSOURCE_LIBCAMERA ON CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_VSOURCE_LIBCAMERA)
SET(${PARENT}_VSOURCE_LIBCAMERA ON CACHE BOOL "" FORCE)
SET(${PARENT}_VSOURCE_LIBCAMERA_TEST OFF CACHE BOOL "" FORCE)
SET(${PARENT}_VSOURCE_LIBCAMERA_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_LOGGER)
add_subdirectory(Logger)
endif()
if (${PARENT}_SUBMODULE_VSOURCE_LIBCAMERA)
add_subdirectory(VSourceLibCamera)
endif()
Next, you need to include the folder 3rdparty in the main CMakeLists.txt file of your repository. Add the following string at the end of your main CMakeLists.txt:
add_subdirectory(3rdparty)
Next, you have to include the VSourceLibCamera library in your src/CMakeLists.txt file:
target_link_libraries(${PROJECT_NAME} VSourceLibCamera)
If the dependencies are not added by your project, the build stops with a compiler error (for example VSource.h: No such file or directory). Done!
Simple example
Example shows how to initialize video source with the generic VSource interface and how to capture video in a loop. Also, the example shows how to get a parameter value (video capture cycle time). The example stops if no frame arrives 10 times in a row (timeout 1 second each). Example:
#include <iostream>
#include <memory>
#include <string>
#include "VSourceLibCamera.h"
namespace
{
/// Number of frame waiting timeouts in a row after which the example stops
/// (the camera does not deliver frames).
constexpr int MAX_TIMEOUTS{10};
/// Frame waiting timeout, milliseconds.
constexpr int FRAME_TIMEOUT_MSEC{1000};
}
int main()
{
// Init video source through the generic VSource interface.
std::unique_ptr<rapidpixel::VSource> source =
std::make_unique<rapidpixel::VSourceLibCamera>();
std::string initString = "0;1280;720;30;NV12";
if (!source->openVSource(initString))
{
std::cout << "Can't open video source" << std::endl;
return -1;
}
// Main loop. It stops if no frame arrives MAX_TIMEOUTS times in a row.
rapidpixel::Frame frame;
int timeouts = 0;
while (timeouts < MAX_TIMEOUTS)
{
// Wait new frame 1 sec.
if (!source->getFrame(frame, FRAME_TIMEOUT_MSEC))
{
++timeouts;
continue;
}
timeouts = 0;
std::cout << "New frame " << frame.frameId << " (" << frame.width <<
"x" << frame.height << ") cycle time : " << static_cast<long long>(
source->getParam(rapidpixel::VSourceParam::CYCLE_TIME_MKS)) <<
" mksec" << std::endl;
}
std::cout << "No frames from video source" << std::endl;
return -1;
}
Test application
The VSourceLibCamera/test folder contains a test application for VSourceLibCamera class.
The test application will allow the user to test functionality of VSourceLibCamera class. The application asks for the camera index, frame size, fps, pixel format and region of interest, captures frames, prints the average frame rate of the last 90 frames and can display the frames. The frames are shown in a window with the frame ID, frame size, pixel format, cycle time and the average frame rate: JPEG frames are decoded by the VDecoderJPEG library, frames of the other YUV formats and GRAY frames are converted to YUV24. It stops if ESC is pressed in the window, the window is closed or no frame arrives 10 times in a row.
The application uses the SimpleUI library to show video. On Linux the video window requires the libx11-dev and libxext-dev packages. If they are not installed when the project is configured by CMake, SimpleUI is built with the headless stub window backend and the video is not shown. If the window can’t be created (for example, there is no display), the application ends with an error. To install the packages:
sudo apt install libx11-dev libxext-dev
Test application output will be like:
=================================================
VSourceLibCamera v2.2.5 test
=================================================
Enter camera index : 0
Enter width (0 - default 1280) : 1920
Enter height (0 - default 720) : 1080
Enter fps (0 - default 30) : 60
Enter pixel format (NV12, NV21, YU12, YV12, YUYV, UYVY, RGB24, BGR24, YUV24, GRAY, JPEG; 0 - NV12) : YUYV
Enter ROI x coordinate : 0
Enter ROI y coordinate : 0
Enter ROI width (0 for no roi) : 0
Enter ROI height (0 for no roi) : 0
Do you want to display frames (y/n) ? : n
[2:32:04.620978989] [22679] INFO Camera camera_manager.cpp:313 libcamera v0.3.0+65-6ddd79b5
[2:32:04.633756508] [22816] INFO RPI pisp.cpp:695 libpisp version v1.0.6 b567f0455680 17-06-2024 (10:20:00)
[2:32:04.650743601] [22816] INFO RPI pisp.cpp:1154 Registered camera /base/axi/pcie@120000/rp1/i2c@88000/imx708@1a to CFE device /dev/media0 and ISP device /dev/media1 using PiSP variant BCM2712_C0
[2:32:04.651222163] [22679] WARN V4L2 v4l2_pixelformat.cpp:344 Unsupported V4L2 pixel format RPBP
[2:32:04.658343349] [22679] INFO Camera camera.cpp:1183 configuring streams: (0) 1920x1080-YUYV
[2:32:04.658598093] [22816] INFO RPI pisp.cpp:1450 Sensor: /base/axi/pcie@120000/rp1/i2c@88000/imx708@1a - Selected sensor format: 2304x1296-SBGGR10_1X10 - Selected CFE format: 2304x1296-PC1B
FPS : 4
FPS : 33
FPS : 39
FPS : 45
FPS : 47
FPS : 48
FPS : 49
FPS : 51
FPS : 50
FPS : 54
FPS : 54
FPS : 54
FPS : 54
FPS : 54
FPS : 54
FPS : 55
FPS : 55
FPS : 55
FPS : 55
FPS : 55
FPS : 55