vsourceuniversal_web_logo

VSourceUniversal C++ library

v1.1.0

Table of contents

Overview

VSourceUniversal C++ library captures video from every video source that the RapidPixel SDK supports through one VSource interface: video files, network streams, V4L2 devices, cameras of libcamera and cameras, files and streams of Windows Media Foundation. The user gives only the source string (the init string of openVSource(…) or the field source of VSourceParams), the library selects the video source library that can open the source and creates it inside:

Video source library Sources Platform
VSourceFile Video files: MP4, MOV, M4V, 3GP, AVI, Matroska (MKV), WebM, raw H.264, H.265 and Motion JPEG streams (codecs H.264, H.265, Motion JPEG, MPEG-4 Part 2, uncompressed BGR24). Linux, Windows
VSourceStream Network streams: RTSP, RTSPS, SDP-less RTP and SRTP, MPEG-TS over UDP (codecs H.264, H.265, JPEG), KLV and ONVIF® metadata. Linux, Windows
VSourceV4L2 V4L2 video devices (USB cameras, capture cards, MIPI cameras with a V4L2 driver): raw formats, MJPEG, H.264, H.265. Linux
VSourceLibCamera Cameras of libcamera (Raspberry Pi cameras, other cameras with a libcamera pipeline handler, USB cameras). Linux
VSourceWmf Cameras, video files and HTTP / RTSP streams of Windows Media Foundation. Windows

Key features:

  • One source string for every source. The init strings of the video source libraries are accepted as they are: "video.mp4", "rtsp://192.168.1.67:8554/live -tcp", "/dev/video0;1280;720;30;MJPEG", "0;1280;720;30;NV12", "Integrated Webcam;1280;720". The RTSP stream of an ONVIF® camera is found by the library itself: "onvif://admin:secret@192.168.1.100" (HTTP) or "onvifs://admin:secret@192.168.1.100 -fingerprint ..." (HTTPS). A prefix with the name of a library selects the library explicitly ("VSourceWmf:rtsp://..."). See Video source selection.
  • Automatic build configuration. The CMake project checks the platform and the dependencies (the folders of the libraries, libcamera, the V4L2 header of the kernel, the Media Foundation libraries of the Windows SDK) and builds only the video source libraries that can work on the target system. See Automatic selection of the libraries.
  • Same output for every source. The pixel format of the frames is chosen by the caller (the fourcc of the frame given to getFrame(…)), as with VSourceFile and VSourceStream: the encoded frames of a source as they are or the frames decoded and converted to any uncompressed format of the Frame library. The frames of a camera that delivers MJPEG, H.264 or H.265 are decoded by the library itself.
  • Custom codec. A codec that implements the VCodec interface (for example a hardware decoder) can replace the built-in software decoders for every source: setCodec(…).
  • Region of interest for every source. The region of interest is cut by the library itself, also for the sources whose libraries do not support it.
  • Status and telemetry. isVSourceConnected() tells whether the source delivers video right now (network streams reconnect by themselves), getTelemetry(…) returns the telemetry of the last frame: frame ID, key frame flag, timestamps, lost frames, packet loss and the KLV / ONVIF® metadata of network streams. getLibrary() tells which library is used.
  • Thread safety. All methods can be called from any thread, closeVSource() interrupts a waiting getFrame(…) and the initialization of a network stream.
  • No Logger dependency. The library writes its own log (console and / or file VSourceUniversal.log) like VSourceWmf; the video source libraries write their own logs.
  • Standard C++17, Linux and Windows.

VSourceUniversal 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 19.11.2026 - First version.
1.0.1 21.11.2026 - CMake: hardening flags are checked with -Werror, the build with Clang 15 for AArch64 has no warnings.
1.1.0 23.11.2026 - ONVIF® devices: source strings onvif:// (requests over HTTP) and onvifs:// (requests over HTTPS, the certificate of the device verified by the CA paths, -cafile or a pinned -fingerprint, or not verified with -noverify): onvif[s]://[user[:password]@]IPv4[:port][/profileToken] [options]. The RTSP stream of the device is found by the requests GetSystemDateAndTime, GetCapabilities, GetProfiles and GetStreamUri (WS-UsernameToken with the clock of the device) and opened by VSourceStream; the profile is chosen by its token, by its number (-profile N) or is the first profile with video. What the build does not have (WS-UsernameToken, TLS) fails the initialization before any request. See ONVIF® devices.
- The copies of the source string made for the video source library are wiped after the initialization (they can hold a password).
- CMake: CryptoProvider (added with VSourceStream) is linked for WS-UsernameToken, ws2_32 on Windows.

Library files

The library is supplied only by source code as a CMake project. The libraries that VSourceUniversal uses (Frame, ConfigReader, VSource, VCodec, VDecoderH264, VDecoderH265, VDecoderJPEG, FormatConverter, the video source libraries and their dependencies) and SimpleUI (used by the test application and the example to display video) are separate repositories: they are not part of this repository (see Build and connect to your project). The repository structure is shown below:

CMakeLists.txt ------------------- Main CMake file of the library (selects the video source libraries).
src ------------------------------ Folder with library source code.
    CMakeLists.txt --------------- CMake file of the library.
    VSourceUniversal.h ----------- Main library header file.
    VSourceUniversalVersion.h ---- Header file with library version.
    VSourceUniversalVersion.h.in - Service CMake file to generate version header.
    VSourceUniversal.cpp --------- C++ implementation wrapper.
    Impl ------------------------- Folder with internal implementation.
        VSourceUniversalImpl.h --- Header file of the implementation class.
        VSourceUniversalImpl.cpp - Implementation: life cycle, frames, params, telemetry.
        SourceLibrary.h ---------- Header file of the selection of the video source libraries.
        SourceLibrary.cpp -------- Parsing of the source string, creation of the libraries.
        FrameProcessor.h --------- Header file of the frame processing.
        FrameProcessor.cpp ------- Decoding, region of interest, pixel formats.
        OnvifClient.h ------------ Header file of the ONVIF client.
        OnvifClient.cpp ---------- ONVIF client: SOAP requests over HTTP/1.1 or HTTPS (GetSystemDateAndTime, GetCapabilities, GetProfiles, GetStreamUri), WS-UsernameToken.
        OnvifSource.h ------------ Header file of the source strings onvif:// and onvifs://.
        OnvifSource.cpp ---------- Source strings onvif:// and onvifs://: parsing, choice of the profile, URL of the RTSP stream.
        OnvifXml.h --------------- Header file of the XML reader of the answers of ONVIF devices.
        OnvifXml.cpp ------------- XML reader: elements by local names, references, CDATA, no DTD, limits.
test ----------------------------- Folder for test application files.
    CMakeLists.txt --------------- CMake file for test application.
    main.cpp --------------------- Source C++ file of test application (automatic tests, check of a source, interactive mode).
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.

Video source selection

Source string

The source string is the initString of openVSource(…) or the field source of VSourceParams given to initVSource(…). It can have up to 32768 bytes and must not have zero characters. The library finds the video source library by the form of the string (Table 2) and gives the string to the library: the formats of the init strings of the video source libraries are accepted as they are. The letter case of URL schemes and prefixes is ignored.

Table 2 - Selection of the video source library by the source string.

Source string Library Examples
rtsp://..., rtsps://..., rtp://..., udp://..., srtp://... VSourceStream: the source string of VSourceStream, a URL and options separated by spaces. Windows without VSourceStream: rtsp:// and rtp:// URLs are opened by VSourceWmf. rtsp://192.168.1.67:8554/live
rtsp://admin:secret@192.168.1.67/live -tcp
rtp://0.0.0.0:5004
udp://239.1.1.1:5600 -iface 192.168.1.10
onvif://..., onvifs://... VSourceStream with the RTSP stream of an ONVIF® device: onvif[s]://[user[:password]@]IPv4[:port][/profileToken] [options]; the requests to the device are HTTP (onvif) or HTTPS (onvifs), see ONVIF® devices. onvif://admin:secret@192.168.1.100
onvif://admin:secret@192.168.1.100/Profile_2 -tcp
onvif://admin:secret@192.168.1.100:8000 -profile 2
onvifs://admin:secret@192.168.1.100 -fingerprint 01:23:...:EF
http://..., https://..., custom://... VSourceWmf (Windows only): url or url;fourcc. http://192.168.1.70:7031/video
http://192.168.1.70/video.mp4
/dev/... VSourceV4L2 (Linux only): device;width;height;fps;fourcc (width, height, fps and fourcc are optional). /dev/video0
/dev/video0;1280;720;30;MJPEG
/dev/v4l/by-id/usb-...-video-index0;640;480
Camera number 0 - 999: number;width;height;fps;fourcc (width, height, fps and fourcc are optional). Linux: VSourceLibCamera (camera of libcamera with this index; "0" alone is opened with the default frame size of the camera). If libcamera is not available or can’t open the camera: VSourceV4L2 with the device /dev/video<number> and the other parts of the string.
Windows: VSourceWmf (camera with this index; the fps is not used, the fourcc is the requested pixel format of Media Foundation).
0
0;1280;720
0;1280;720;30;NV12
1;0;0;0;MJPEG
Any other string VSourceFile: video file (path or path;width;height;fps, the extra parts are not used). Windows: a file that VSourceFile can’t open (for example *.wmv, *.flv) is opened by VSourceWmf; a string that is not a file (no such file and no extension of a video file) is a camera name of VSourceWmf (name or name;width;height;fps;fourcc). video.mp4
/home/user/video.h264
D:\video\record.wmv
Integrated Webcam;1280;720

A source that a library can’t open is given to the next library of the row, if there is one (Linux camera number: VSourceLibCamera, then VSourceV4L2; Windows file: VSourceFile, then VSourceWmf). getLibrary() returns the library that opened the source (or the last library that was tried). The libraries that are not built (see Automatic selection of the libraries) are skipped.

Explicit selection of a library

A prefix with the name of a library selects the library explicitly: VSourceFile:, VSourceStream:, VSourceV4L2:, VSourceLibCamera: or VSourceWmf: (any letter case). The rest of the string is given to the library as it is, with two exceptions: a camera number after VSourceV4L2: is the device /dev/video<number> (VSourceV4L2:0;640;480 - /dev/video0;640;480) and a camera number without the frame size after VSourceLibCamera: gets the default frame size of the camera. If the library is not built, the initialization fails. Examples:

"VSourceWmf:rtsp://192.168.1.67/live"   // Network stream opened by Media Foundation.
"VSourceWmf:C:/video/video.mp4"         // Video file decoded by Media Foundation.
"VSourceV4L2:0;1280;720;30;YUYV"        // V4L2 device /dev/video0.
"VSourceLibCamera:0;1920;1080;30;NV12"  // Camera 0 of libcamera.
"VSourceFile:123"                       // File with the name "123" (not camera 123).
"VSourceStream:onvif://192.168.1.100"    // ONVIF device (as "onvif://192.168.1.100").
"VSourceStream:onvifs://192.168.1.100"   // ONVIF device over HTTPS (as "onvifs://192.168.1.100").

ONVIF® devices

The source strings onvif:// and onvifs:// open the RTSP stream of an ONVIF® device (a camera or an encoder that implements the ONVIF® Profile S or T). With onvif:// the requests to the device are HTTP, with onvifs:// HTTPS. VSourceUniversal asks the device for the stream itself and opens it with VSourceStream: getLibrary() returns VSOURCE_STREAM, the telemetry and the KLV / ONVIF® metadata of the stream are those of VSourceStream. Format:

onvif://[user[:password]@]IPv4[:port][/profileToken] [options]
onvifs://[user[:password]@]IPv4[:port][/profileToken] [options]

Table 3 - Parts of the source strings onvif:// and onvifs://.

Part Description
user:password Credentials of the device (an ONVIF® user that can get the media profiles and the stream). The rules of the credentials of an RTSP URL of VSourceStream: percent-decoded (%XX), each at most 128 bytes, the user name without control characters, :, " and \, the password without control characters. /, ?, # and @ must be percent-encoded in them (p@ss - p%40ss); the last @ of the address ends them. Without them no authentication is used. The options -user and -password are refused: the credentials are given only in the URL.
IPv4 IPv4 address of the device (four decimal numbers without leading zeros). Host names and IPv6 are not supported.
onvif / onvifs Scheme (any letter case): onvif - the requests to the device are HTTP, onvifs - HTTPS (TLS 1.2 or 1.3; needs OpenSSL 3, which the CMake project finds as for the RTSPS of VSourceStream). A device that is asked over HTTPS can report an http:// address of its Media service: its path is used over HTTPS.
port TCP port of the ONVIF® service of the device: 80 by default for onvif, 443 for onvifs.
/profileToken Token of the media profile (percent-decoded; a / of the token must be percent-encoded), optional. The tokens of a device are written to the log when it is opened (and printed by VSourceUniversalTest --onvif-profiles).
-profile N Number of the media profile, 1 - 1000: the profile N in the order of the answer of the device (the numbers of the log). Not together with a token. This option is used by VSourceUniversal and is not given to VSourceStream. -profile NAME with a name is the compliance mode of VSourceStream: only ONVIF (or NO) is accepted (the requests of onvif:// are plain HTTP, which the strict modes of VSourceStream forbid; the strict modes are not supported for onvifs:// yet).
-timeout MS Timeout of every request to the device, 100 - 60000 ms (10000 by default); given to VSourceStream too (its init deadline).
-fingerprint FP onvifs: SHA-256 fingerprint of the certificate of the device, 32 hexadecimal pairs separated by : (95 characters) or 64 hexadecimal digits, any letter case. Only the fingerprint is checked (in constant time), not the chain and the name: the way to accept the self-signed certificate of a camera securely. The fingerprint is printed, for example, by openssl s_client -connect 192.168.1.100:443 </dev/null \| openssl x509 -noout -fingerprint -sha256.
-cafile PATH onvifs: PEM CA bundle that verifies the certificate chain of the device (instead of the default CA paths of OpenSSL). The certificate must name the IPv4 address of the device in subjectAltName.
-noverify onvifs: the certificate of the device is not verified: the device is not authenticated (a warning is written to the log). Not together with -fingerprint or -cafile. Without -fingerprint, -cafile and -noverify the certificate is verified by the default CA paths of OpenSSL, which refuse the self-signed certificate of a camera (the error says so).
Other options Given to VSourceStream with the URL of the stream (-tcp, -reconnect 3000, -nometadata, …). -fingerprint, -cafile and -noverify are given to VSourceStream only if the stream is rtsps:// (VSourceStream refuses them for rtsp://); with onvif:// they are used only for such a stream.

The initialization (openVSource(…), initVSource(…), RESTART) checks what the build needs (WS-UsernameToken if the source string has credentials: CryptoProvider with SHA-1; TLS for onvifs://: OpenSSL 3) - without it the initialization fails before any request - and sends these requests to the device, each on its own HTTP/1.1 connection (TLS for onvifs://; the TLS context is made before the connection, so a TLS setting error such as a missing CA file is found without a request):

  1. GetSystemDateAndTime (device service /onvif/device_service, no authentication): the clock of the device. The Created time of WS-UsernameToken is the time of this clock, so a device whose clock differs from the clock of the computer accepts the token. If the device answers with an error, the clock of the computer is used; if it does not answer, the initialization fails at once.
  2. GetCapabilities with the category Media: the address of the Media service. The request is sent without authentication and, if the device refuses it, with the credentials. The path of the address is used with the IPv4 address of the source string (a device behind NAT reports its own address). If the request fails, the device service is used.
  3. GetProfiles (Media service ver10, WS-UsernameToken): the media profiles.
  4. The choice of the profile: the profile with the token of the URL, the profile number N of -profile N, or the first profile with video that is not MPEG-4 (H.264, H.265, JPEG or an unknown encoding; the encoding of Media ver10 is only a hint: VSourceStream finds the codec of the stream from its SDP). An unknown token or number fails the initialization, the error names the profiles of the device.
  5. GetStreamUri of the profile (RTP-Unicast over RTSP): the URI of the stream. The host of the URI is replaced by the IPv4 address of the source string, its port and path are kept. The credentials of the source string are written percent-encoded into the URL.
  6. VSourceStream opens the URL with the options of the source string.

Example (the values are examples): the profiles of a camera with two sensors and the source strings of its streams:

ONVIF profiles: 1: Profile_1 "Sensor 1" H264 1920x1080; 2: Profile_2 "Sensor 2" H264 1920x1080.

onvif://admin:secret@192.168.1.100                   -> Profile_1 (the first profile with video)
onvif://admin:secret@192.168.1.100/Profile_2         -> Profile_2 (token)
onvif://admin:secret@192.168.1.100 -profile 2 -tcp   -> Profile_2 (number), RTSP over TCP
onvifs://admin:secret@192.168.1.100 -fingerprint 01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF
                                                     -> Profile_1, the requests over HTTPS (pinned certificate)

Notes:

  • RESTART asks the device again: a device can give a URI that is valid only for a time (tt:Timeout) or until its reboot. The automatic reconnection of VSourceStream uses the URL of the initialization.
  • closeVSource() and a new initialization stop the requests to the device within some tens of milliseconds.
  • The password is never sent: WS-UsernameToken carries its SHA-1 digest. With onvif:// the requests (the profiles, the URI of the stream) can be read on the network, onvifs:// protects them. HTTP Digest authentication of the requests, Media2 (devices that implement only Profile T without Media ver10), the strict compliance modes, host names and IPv6 are not supported yet.
  • WS-UsernameToken needs CryptoProvider (SHA-1 and random numbers), which is added with VSourceStream. CryptoProvider is initialized in its standard mode if nothing has initialized it (the mode of VSourceStream in its compliance mode ONVIF®), or in the FIPS mode if the operating system requires it.
  • The log has the steps: the clock of the device, the Media service, the profiles, the chosen profile and the URL of the stream with the credentials and the query hidden.
  • The log of onvifs:// names the check of the certificate (-noverify is written as an error: the device is not authenticated).
  • getParams(…) returns the source string onvif:// or onvifs:// as it was given.

Video source libraries

The video source libraries keep their own behaviour, VSourceUniversal only selects and controls them. Their documentation describes the details: frame delivery (VSourceFile delivers every frame of a file at the frame rate of the file, VSourceStream delivers the frames in arrival order from a buffer, VSourceV4L2 delivers the newest frame of a camera, VSourceLibCamera every captured frame once, VSourceWmf the last frame), automatic reconnection (VSourceStream, VSourceWmf, VSourceV4L2), the options of the source strings and the supported parameters (see VSourceParam enum). The blocking time of openVSource(…) is the time of the library: VSourceStream waits for the session (default timeout 10 seconds, option -timeout) and for the first frame (at most 3 seconds), VSourceV4L2 waits for the first frame of the camera (up to 60 seconds), VSourceWmf returns at once and connects in its capture thread.

Capture behaviour

Output frames

The fourcc of the Frame object given to getFrame(…) chooses the output, as with VSourceFile and VSourceStream (Table 4). A default-constructed Frame has the fourcc YUV24: set the fourcc before every call.

Table 4 - Output of getFrame(…) by the fourcc of the frame.

Frame::fourcc set by the caller Delivered frame
H264, HEVC or JPEG The frames of the source as they are, whichever of the three is asked for: the encoded frames of a file, a stream or a camera (H.264 / H.265 Annex-B access units, complete JPEG images) or the uncompressed frames of a camera (or of an uncompressed AVI file). Frame::fourcc tells the format. The region of interest is not applied.
RGB24, BGR24, YUYV, UYVY, GRAY, YUV24, NV12, NV21, YU12, YV12 The frames decoded if needed (see Decoding and custom codec), cut to the region of interest and converted to the requested format with FormatConverter. A frame that the converter refuses (for example of odd width or height) is delivered in its own format (Frame::fourcc tells which).
Any other value Nothing: getFrame(…) returns FALSE at once (logged at most once per second).

The memory of the frame is reused when it has the size and the format of the delivered frame. Frame::frameId is the frame ID of the video source library, Frame::sourceId is not changed. A change of the requested format between encoded and decoded frames makes VSourceFile and VSourceStream continue at the next key frame (see their documentation): request one format for a source.

Decoding and custom codec

The encoded frames are decoded by:

  • VSourceFile and VSourceStream: their own built-in decoders (VDecoderH264, VDecoderH265, VDecoderJPEG; 2 decoding threads, automatic colour range).
  • VSourceV4L2 and VSourceLibCamera (cameras that deliver MJPEG, H.264 or H.265): the built-in decoders of VSourceUniversal - VDecoderJPEG, VDecoderH264 and VDecoderH265 with the same settings. The H.265 decoder gets the NAL units of a frame one by one (as in VSourceStream).
  • VSourceWmf: Media Foundation (the frames are always uncompressed).

A custom codec set by setCodec(…) (an object that implements the VCodec interface, for example a hardware decoder of VCodecUniversal, VCodecNv, VCodecLibva, VCodecV4L2 or VCodecWmf) replaces the built-in decoders:

  • network streams: the codec is given to VSourceStream::setCodec(…) and is called on the decode thread of VSourceStream;
  • video files: VSourceUniversal asks VSourceFile for the encoded frames of the file and calls the codec in the thread of getFrame(…);
  • cameras: the encoded frames of the camera are given to the codec in the thread of getFrame(…).

The codec gets the encoded frame as src of VCodec::transcode(…) (H.264 / H.265 Annex-B access units with the parameter sets in front of the key frames, complete JPEG images; src.data is followed by 64 zero bytes that src.size does not count) and dst with the fourcc NV12. Its output may be any uncompressed format of the Frame library: it is converted to the requested one. The codec gets VCodecCommand::RESET before the first frame of every new source and after a change of the codec. It is never called concurrently. A frame that the codec gives no picture for (the codec needs more frames or can’t decode the frame) is skipped: getFrame(…) reads the next frame while its timeout is not over.

Region of interest

The region of interest (ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT) is applied by VSourceUniversal to the uncompressed output frames of every source (it is not given to the video source libraries). The region is used if its width and height are not 0 and its top-left corner is inside of the frame. It is cut to the frame, the coordinates and the size are rounded down to even values (at least 2 x 2 pixels must stay). A region that can’t be applied to a frame (its top-left corner is outside of the frame, less than 2 x 2 pixels of it are inside of the frame, a 4:2:0 frame of odd width or height, a YUYV or UYVY frame of odd width) is not used for that frame: the whole frame is delivered. The frames of a camera and the pictures of the decoders of VSourceUniversal are cut before the conversion, the frames decoded by VSourceFile and VSourceStream after it. The region of interest is not applied to the frames delivered as they are (compressed fourcc).

Connection status and telemetry

isVSourceOpen() is the open status of the library. isVSourceConnected() tells whether the source delivers video right now: for network streams it is VSourceStream::isVSourceConnected() (FALSE from the moment the connection is lost until media arrives again, while isVSourceOpen() stays TRUE during the automatic reconnection), for the other sources it is the open status (VSourceWmf: a source is open when it delivers frames).

getTelemetry(…) returns the telemetry of the frame that the last successful getFrame(…) returned (Table 5).

Table 5 - Telemetry by the video source library.

Field VSourceStream Other libraries
frameId Frame ID of the stream. Frame::frameId of the frame.
keyFrame Key frame flag of the encoded frame (also for a decoded frame). TRUE for an uncompressed frame, a JPEG frame, an H.264 IDR picture and an H.265 IRAP picture.
timestamp RTP timestamp (MPEG-TS: PTS), 90 kHz. Time when the library returned the frame, 90 kHz of the monotonic clock.
captureTimeUsec Capture time on the sender’s clock (precision time stamp SEI, RTP header extension, RTCP sender report), -1 if unknown. VSourceV4L2: the time of the timestamp of the driver (receive time minus CUSTOM_1). Others: -1.
receiveTimeUsec Receive time of the last packet of the frame. Time when the library returned the frame.
lostFrames Frames lost before the frame. VSourceV4L2: CUSTOM_3. VSourceLibCamera and VSourceWmf: the gaps of the frame IDs. VSourceFile: 0.
lostPackets, packetLossPercent Packet loss of the stream. 0.
metadata KLV, ONVIF® and SEI user data bound to the frame. Empty.

Thread safety

All public methods are thread safe. openVSource(…), initVSource(…), closeVSource() and RESTART are serialized: one runs at a time. A closeVSource() or a new initialization stops the initialization of a network stream that runs in another thread (VSourceStream and the requests to an ONVIF® device stop within some tens of milliseconds, the initialization returns FALSE) and a waiting getFrame(…) (the video source libraries end the wait; for a video file the wait ends after at most one frame interval of the playback, 1 / FPS, because VSourceFile waits for the playback time of a frame inside its getFrame(…), also with the timeout 0). The initialization of the other libraries is not stopped: closeVSource() and a new initialization wait for it (VSourceV4L2 waits up to 60 s for the first frame of a camera). getFrame(…) calls of several threads are served one after another. While an initialization runs, getFrame(…) returns FALSE. The object of a video source library that is replaced by a new initialization is destroyed when the last call that uses it returns. getParams(…), getParam(…), setParam(…), isVSourceOpen(), isVSourceConnected(), getTelemetry(…) and getLibrary() never wait for a waiting getFrame(…). setCodec(…) waits for a decoding in progress. The object must not be destroyed while another thread calls its methods.

Logging

LOG_LEVEL (0 - disable, 1 - file, 2 - console, 3 - file and console) is applied to VSourceUniversal and to the video source library. VSourceUniversal writes the selection of the libraries, the requests to an ONVIF® device (see ONVIF® devices), the initialization results and the errors of getFrame(…) (at most one per second) to the console and / or to the file VSourceUniversal.log in the current directory. The file is opened for each record and is not given to child processes; nothing is written to a file that is larger than 16 MB. On Linux a new log file can be read and written only by its owner, and only a regular file of the user with one link is written (a symbolic link, a FIFO or a device with the name of the log is not used). The user info of a URL (user:password@, up to the last @ of the URL), the query of a URL (after ?) and the values of the options -user, -password and -srtpkey are not written to the log; the bytes that are not printable ASCII characters are replaced by ? and a message is cut after 1024 characters. The video source libraries write their own logs (for example VSourceStream.log, VSourceWmf.log; VSourceV4L2 and VSourceLibCamera use the Logger library).

VSourceUniversal class description

VSourceUniversal class declaration

VSourceUniversal class is declared in VSourceUniversal.h file. The class owns the video source library: it is not copyable and not movable.

namespace rapidpixel
{
/// Universal video source.
class VSourceUniversal : public VSource
{
public:

    /// Class constructor.
    VSourceUniversal();

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

    /// Copy and move operations are deleted.
    VSourceUniversal(const VSourceUniversal&) = delete;
    VSourceUniversal(VSourceUniversal&&) = delete;
    VSourceUniversal& operator= (const VSourceUniversal&) = delete;
    VSourceUniversal& operator= (VSourceUniversal&&) = 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;

    /// Get connection status.
    bool isVSourceConnected();

    /// Get the telemetry of the last frame.
    bool getTelemetry(VSourceUniversalTelemetry& telemetry);

    /// Set a custom video codec.
    void setCodec(VCodec* codec);

    /// Get the video source library.
    VSourceUniversalLibrary getLibrary();

    /// Check if a video source library is built.
    static bool isLibraryAvailable(VSourceUniversalLibrary library);
};
}

getVersion method

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

static std::string getVersion();

Method can be used without VSourceUniversal class instance:

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

Console output:

VSourceUniversal version: 1.0.1

openVSource method

The openVSource(…) method opens the video source by the init string. The video source that is open is closed first. The init string selects the video source library (see Video source selection), the library is created and its openVSource(…) method gets the init string (without the prefix of a library). LOG_LEVEL and the region of interest keep their values. A valid init string is kept for RESTART and getParams(…), also if the library can’t open the source. Instead of openVSource(…) the user can call initVSource(…). Method declaration:

bool openVSource(std::string& initString) override;
Parameter Value
initString Init string, up to 32768 bytes without zero characters (see Source string). Examples: "video.mp4", "rtsp://192.168.1.67:8554/live -tcp", "/dev/video0;1280;720;30;YUYV", "0;1280;720", "VSourceWmf:Integrated Webcam". The string is not changed.

Returns: TRUE if the video source is open (VSourceWmf: the init string is valid and its capture thread runs, the source is connected in the thread) or FALSE if not (empty or too long string, a zero character in the string, unknown URL scheme, the library is not available, the library can’t open the source, the initialization was stopped by closeVSource() or another initialization).

initVSource method

The initVSource(…) method initializes the video source by a VSourceParams object. The video source that is open is closed first. The field source selects the video source library (see Video source selection; the parts of the string are not split, a camera number is only the number), the library is created and its initVSource(…) method gets the params (the field source without the prefix of a library, the region of interest fields 0). Valid params are kept for RESTART and getParams(…), also if the library can’t open the source. Method declaration:

bool initVSource(VSourceParams& params) override;
Parameter Value
params VSourceParams object. Fields checked by VSourceUniversal: source (up to 32768 bytes without zero characters), logLevel (0 - 3), roiX, roiY, roiWidth, roiHeight (0 - 16384, applied by VSourceUniversal). The other fields are used by the video source library: fourcc, width, height, fps (requested format of a camera, playback FPS of a file), gain, gainMode, exposure, exposureMode, focusPos, focusMode (camera controls), custom2 (buffer depth of VSourceStream), see the documentation of the libraries. On success the fields width, height, fps, fourcc and isOpen are updated with the values of the library, source is not changed. If FALSE is returned the params are not changed.

Returns: TRUE if the video source is initialized or FALSE if not (a field checked by VSourceUniversal is not valid, the reasons of openVSource(…)).

isVSourceOpen method

The isVSourceOpen() method returns the open status of the video source library (also included in VSourceParams). Method declaration:

bool isVSourceOpen() override;

Returns: TRUE if the video source is open or FALSE if not (no source, closed, the initialization failed; VSourceWmf: the source is not connected yet).

closeVSource method

The closeVSource() method closes the video source. A waiting getFrame(…) returns FALSE, an initialization of a network stream that runs in another thread is stopped. The video source library object is kept until the next initialization: getLibrary() and getParams(…) still describe it. Method declaration:

void closeVSource() override;

getFrame method

The getFrame(…) method returns a new video frame. Method declaration:

bool getFrame(Frame& frame, int32_t timeoutMsec = 0) override;
Parameter Value
frame Output video frame (see Frame class description). Its fourcc chooses the output (see Output frames): H264, HEVC or JPEG - the frames of the source as they are; RGB24, BGR24, YUYV, UYVY, GRAY, YUV24, NV12, NV21, YU12, YV12 - the frames converted to this format; another value - FALSE at once. On success fourcc is the format of the delivered frame, frameId is the frame ID of the video source library, sourceId is not changed. If FALSE is returned the content of the frame must not be used.
timeoutMsec Timeout to wait new frame data, milliseconds:
- timeoutMsec < 0 (for example -1) - waits until a new frame arrives or the video source is closed.
- timeoutMsec == 0 - only checks if a new frame exists.
- timeoutMsec > 0 - waits for a new frame the specified time.

Returns: TRUE if a new frame was copied or FALSE if not (no new frame in time, no source, the source is closed or being initialized, unsupported fourcc, the decoder gives no picture, the uncompressed frames of the source have less data than their width and height need).

setParam method

The setParam(…) method sets a video source param. LOG_LEVEL is applied to VSourceUniversal and to the video source library, the region of interest params are applied by VSourceUniversal, the other params are given to the video source library (see VSourceParam enum). Method declaration:

bool setParam(VSourceParam id, float value) override;
Parameter Description
id Parameter ID according to VSourceParam enum.
value Parameter value. NaN and infinity are rejected. LOG_LEVEL: 0 - 3, ROI params: 0 - 16384 (the fraction is dropped). The values of the other params are checked by the library.

Returns: TRUE if the parameter was set or FALSE if not (not valid value, read only or not supported param, no video source library for the params of the library).

getParam method

The getParam(…) method returns a video source param value. Method declaration:

float getParam(VSourceParam id) override;
Parameter Description
id Parameter ID according to VSourceParam enum.

Returns: parameter value or -1 if the param is not supported or not available. Without a video source library WIDTH, HEIGHT and FPS are 0.

getParams method

The getParams(…) method returns the video source params: the params of the video source library with the fields source (the source string of the last valid openVSource(…) or initVSource(…) call, with the prefix of a library; empty after a call with a string or params that are not valid), logLevel, roiX, roiY, roiWidth, roiHeight, cycleTimeMks and isOpen of VSourceUniversal. The field fourcc is the format of the last frame returned by getFrame(…) (before the first frame: the fourcc of the library). Method declaration:

void getParams(VSourceParams& params) override;
Parameter Description
params VSourceParams object. It is not changed if memory is not available.

executeCommand method

The executeCommand(…) method executes a video source command. Method declaration:

bool executeCommand(VSourceCommand id) override;
Parameter Description
id Command ID according to VSourceCommand enum. RESTART opens the video source again (a new object of the video source library) with the init string or the params of the last openVSource(…) or initVSource(…) call, also after closeVSource(). After a call with a string or params that are not valid there is nothing to repeat.

Returns: TRUE if the command was executed or FALSE if not (unknown command, no valid initialization to repeat, the source can’t be opened).

decodeAndExecuteCommand method

The decodeAndExecuteCommand(…) method decodes and executes a command encoded by encodeSetParamCommand(…) or encodeCommand(…) and calls setParam(…) or executeCommand(…). The method can be called from any thread. Method declaration:

bool decodeAndExecuteCommand(uint8_t* data, int size) override;
Parameter Description
data Pointer to command data. nullptr is rejected.
size Size of command: exactly 11 bytes for SET_PARAM, exactly 7 bytes for COMMAND.

Returns: TRUE if the command was decoded and executed or FALSE if not.

isVSourceConnected method

The isVSourceConnected() method returns the connection status: TRUE while the video source delivers video (see Connection status and telemetry). Method declaration:

bool isVSourceConnected();

Returns: network streams - VSourceStream::isVSourceConnected(): TRUE while the source is open, its session is established and a media packet arrived within the last 2 seconds, FALSE while the connection is lost or being re-established; other sources - the open status of the library. FALSE without a source and after closeVSource(). Example:

rapidpixel::VSourceUniversal source;
std::string initString = "rtsp://192.168.1.67:8554/live -tcp";
if (source.openVSource(initString))
{
    bool connected = source.isVSourceConnected();
    rapidpixel::Frame frame;
    for (int i = 0; i < 1000; ++i)
    {
        if (source.isVSourceConnected() != connected)
        {
            connected = !connected;
            std::cout << (connected ? "Connection restored" : "Connection lost, reconnecting...") << std::endl;
        }
        frame.fourcc = rapidpixel::Fourcc::BGR24;
        if (source.getFrame(frame, 100))
        {
            // Process the frame.
        }
    }
}

getTelemetry method

The getTelemetry(…) method returns the telemetry of the frame that the last successful getFrame(…) call returned (see Connection status and telemetry and VSourceUniversalTelemetry structure). The next successful getFrame(…) of any thread replaces it: call the method from the thread that called getFrame(…), right after it. Method declaration:

bool getTelemetry(VSourceUniversalTelemetry& telemetry);
Parameter Description
telemetry Output VSourceUniversalTelemetry structure. It is reset to its defaults if the method returns FALSE. Pass the same structure to every call: its buffers are reused.

Returns: TRUE if a frame was delivered since the last initialization and the telemetry describes it or FALSE if not (before the first frame, after closeVSource() or a failed initialization). Example:

rapidpixel::VSourceUniversal source;
std::string initString = "rtsp://192.168.1.67:8554/live";
rapidpixel::Frame frame;
frame.fourcc = rapidpixel::Fourcc::NV12;
rapidpixel::VSourceUniversalTelemetry telemetry;
if (source.openVSource(initString) && source.getFrame(frame, 1000) &&
    source.getTelemetry(telemetry))
{
    std::cout << "Frame " << telemetry.frameId << (telemetry.keyFrame ? " key" : "") <<
    " lost before " << telemetry.lostFrames << ", " << telemetry.metadata.size() <<
    " metadata units" << std::endl;
    for (const rapidpixel::VSourceUniversalMetadata& unit : telemetry.metadata)
    {
        if (unit.type == rapidpixel::VSourceUniversalDataType::KLV && unit.exact && unit.valid)
        {
            // unit.data holds a checked KLV unit that describes exactly this frame.
        }
    }
}

setCodec method

The setCodec(…) method sets a custom video codec that decodes the encoded frames when getFrame(…) is asked for an uncompressed fourcc (see Decoding and custom codec). The method can be called at any time, also before the initialization: the codec is used for every next source. It waits for a decoding in progress, so the previous codec is not used after it returns. Method declaration:

void setCodec(VCodec* codec);
Parameter Value
codec Pointer to an object of a class that implements the VCodec interface or nullptr to use the built-in decoders of the libraries (the default). The codec must stay valid until setCodec(nullptr) returns or the VSourceUniversal object is destroyed. It must not throw exceptions and must not call the methods of the VSourceUniversal object.

Example with a hardware decoder of the VCodecUniversal library:

rapidpixel::VCodecUniversal decoder;
rapidpixel::VSourceUniversal source;
source.setCodec(&decoder);
std::string initString = "rtsp://192.168.1.67:8554/live";
rapidpixel::Frame frame;
frame.fourcc = rapidpixel::Fourcc::BGR24;
// The frame is decoded by VCodecUniversal and converted to BGR24.
if (source.openVSource(initString) && source.getFrame(frame, 1000))
{
    std::cout << "Frame " << frame.width << "x" << frame.height << std::endl;
}

getLibrary method

The getLibrary() method returns the video source library that was selected by the last openVSource(…) or initVSource(…) call: the library that opened the source or, if no library could open it, the last library that was tried. Method declaration:

VSourceUniversalLibrary getLibrary();

Returns: VSourceUniversalLibrary value, NONE before the first initialization and if the source string is not valid or no library for it is built.

isLibraryAvailable method

The isLibraryAvailable(…) static method tells if a video source library is built with VSourceUniversal (see Automatic selection of the libraries). Method declaration:

static bool isLibraryAvailable(VSourceUniversalLibrary library);
Parameter Value
library VSourceUniversalLibrary value.

Returns: TRUE if the library is built and can be used or FALSE if not (also for NONE).

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). VSourceUniversal.h defines the VSourceUniversalLibrary enum, the VSourceUniversalTelemetry and VSourceUniversalMetadata structures and the VSourceUniversalDataType enum.

VSourceCommand enum

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

Table 6 - Video source commands.

Command Description
RESTART Opens the video source again with the init string or the params of the last initialization (see executeCommand(…)). 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 7 - Video source params in VSourceUniversal. “Library” means that the param is given to the video source library in use: its support and range are the ones of the library (see the documentation of the library).

Parameter Access Description
LOG_LEVEL read / write Logging mode: 0 - Disable, 1 - File, 2 - Console, 3 - Both. Applied to VSourceUniversal (file VSourceUniversal.log) and to the video source library (see Logging).
WIDTH library Width of the frames of the source (not of the region of interest). VSourceV4L2: can be set (the device is restarted). Other libraries: read only. 0 without a library.
HEIGHT library Height of the frames of the source. VSourceV4L2: can be set (the device is restarted). Other libraries: read only. 0 without a library.
GAIN_MODE library Gain mode of a camera: VSourceV4L2, VSourceWmf (cameras). Others: not supported.
GAIN library Gain of a camera: VSourceV4L2, VSourceWmf (cameras). Others: not supported.
EXPOSURE_MODE library Exposure mode of a camera: VSourceV4L2, VSourceWmf (cameras). Others: not supported.
EXPOSURE library Exposure of a camera: VSourceV4L2, VSourceWmf (cameras). Others: not supported.
FOCUS_MODE library Focus mode of a camera: VSourceV4L2, VSourceWmf (cameras). Others: not supported.
FOCUS_POS library Focus position of a camera: VSourceV4L2, VSourceWmf (cameras). Others: not supported.
CYCLE_TIME_MKS read only Interval between the two last frames returned by getFrame(…), microseconds (for the first frame: since the initialization). 0 after closeVSource().
FPS library Frame rate. VSourceFile: playback FPS of the file (0.01 - 1000, can be set). VSourceV4L2: can be set (the device is restarted). VSourceStream, VSourceLibCamera, VSourceWmf: read only. 0 without a library.
IS_OPEN read only Open flag: 1 - open, 0 - not open (isVSourceOpen()).
ROI_X read / write Region of interest top-left corner horizontal coordinate, 0 - 16384 (see Region of interest).
ROI_Y read / write Region of interest top-left corner vertical coordinate, 0 - 16384.
ROI_WIDTH read / write Region of interest width, 0 - 16384 (0 - no region of interest).
ROI_HEIGHT read / write Region of interest height, 0 - 16384 (0 - no region of interest).
CUSTOM_1 library VSourceV4L2 and VSourceStream: age of the last frame of the library, microseconds (read only). Others: see the library.
CUSTOM_2 library VSourceV4L2: number of capture buffers 1 - 32 (applied at the next initialization). VSourceStream: output buffer depth 1 - 512. Others: see the library.
CUSTOM_3 library VSourceV4L2 and VSourceStream: number of frames lost before the last frame of the library (read only). Others: see the library.

VSourceUniversalLibrary enum

The enum is declared in VSourceUniversal.h file:

enum class VSourceUniversalLibrary
{
    /// No library: no video source was initialized or the source string is
    /// not valid.
    NONE = 0,
    /// VSourceFile: video files. Linux and Windows.
    VSOURCE_FILE = 1,
    /// VSourceStream: network video streams. Linux and Windows.
    VSOURCE_STREAM = 2,
    /// VSourceV4L2: V4L2 video devices. Linux only.
    VSOURCE_V4L2 = 3,
    /// VSourceLibCamera: cameras of libcamera. Linux only.
    VSOURCE_LIBCAMERA = 4,
    /// VSourceWmf: cameras, video files and streams of Windows Media
    /// Foundation. Windows only.
    VSOURCE_WMF = 5
};

VSourceUniversalTelemetry structure

The structure is declared in VSourceUniversal.h file. The fields have the meaning of the fields of VSourceStreamTelemetry of the VSourceStream library (see Table 5 in Connection status and telemetry for the other libraries):

struct VSourceUniversalTelemetry
{
    /// Frame::frameId of the frame.
    int frameId{0};
    /// TRUE if the frame can be used without the previous frames.
    bool keyFrame{false};
    /// Media timestamp of the frame, 90 kHz.
    uint32_t timestamp{0};
    /// Capture time of the frame, UNIX epoch microseconds, -1 if unknown.
    int64_t captureTimeUsec{-1};
    /// Time when the frame was received, UNIX epoch microseconds.
    int64_t receiveTimeUsec{0};
    /// Number of frames lost before this frame.
    int lostFrames{0};
    /// Media packets lost since the initialization (network streams only).
    uint64_t lostPackets{0};
    /// Share of the media packets lost over the last 10 s, percent.
    float packetLossPercent{0.0f};
    /// Metadata units bound to the frame (network streams only).
    std::vector<VSourceUniversalMetadata> metadata;
};

VSourceUniversalMetadata structure

The structure is declared in VSourceUniversal.h file. It is one metadata unit of a network stream (see VSourceStreamMetadata of the VSourceStream library):

struct VSourceUniversalMetadata
{
    /// Data type: KLV, ONVIF or UNKNOWN.
    VSourceUniversalDataType type{VSourceUniversalDataType::NONE};
    /// Metadata stream index 0..3.
    int stream{0};
    /// TRUE if the unit describes exactly this frame.
    bool exact{true};
    /// TRUE if the unit passed the structure checks.
    bool valid{true};
    /// Unit bytes: one KLV unit, one XML document or one SEI payload.
    std::vector<uint8_t> data;
};

VSourceUniversalDataType enum

The enum is declared in VSourceUniversal.h file, its values are the values of VSourceStreamDataType:

enum class VSourceUniversalDataType
{
    /// No metadata (a default-constructed unit).
    NONE = 0,
    /// KLV (SMPTE 336M; Local Set and others).
    KLV = 1,
    /// ONVIF metadata stream XML document.
    ONVIF = 2,
    /// H.264 / H.265 SEI user_data_unregistered payloads (option -seidata).
    UNKNOWN = 3
};

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, VSourceUniversal and the video source libraries validate 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 (as in 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;
}

The field source of a configuration file selects the video source as the init string does, for example "source": "rtsp://192.168.1.67:8554/live -tcp" or "source": "0" with "width": 1280, "height": 720 and "fourcc": "NV12".

Build and connect to your project

Prerequisites

  • Operating system: Linux or Windows 10 / 11.
  • Compiler: C++17 compiler: GCC or Clang on Linux, Microsoft Visual C++ on Windows (the compilers that the library is built and tested with are listed in Portability). VSourceLibCamera is compiled as C++20 if the headers of the installed libcamera need it.
  • Build system: CMake 3.13 or newer (with CMake 3.19 or newer the list of the libraries in use is printed at the end of the configuration).
  • Libraries (source code): the libraries are not part of the repository, their folders must be next to the folder of VSourceUniversal (Table 8).
  • System libraries (optional): libcamera for VSourceLibCamera (found by pkg-config, for example sudo apt install libcamera-dev), the V4L2 header linux/videodev2.h of the kernel for VSourceV4L2 (package linux-libc-dev), OpenSSL 3.0 or newer for the TLS of VSourceStream (rtsps://) and for onvifs:// (for example sudo apt install libssl-dev), the Windows SDK with the Media Foundation libraries mfplat.lib, mf.lib, mfreadwrite.lib, mfuuid.lib for VSourceWmf.
  • SimpleUI: required only for the test application and the example (display of video). On Linux SimpleUI displays video with X11 (libx11-dev, libxext-dev), without them it uses a stub window.

Table 8 - Libraries next to VSourceUniversal.

Library Needed for Required
Frame, ConfigReader, VSource, VCodec Interface, frames, params. Yes
VDecoderH264, VDecoderH265, VDecoderJPEG Decoding of the encoded frames of cameras (and of VSourceFile, VSourceStream). Yes
FormatConverter Pixel format conversion. Yes
VSourceFile Video files. Optional
VSourceStream, CryptoProvider Network streams. Optional
VSourceV4L2, Logger V4L2 devices (Linux). Optional
VSourceLibCamera, Logger Cameras of libcamera (Linux). Optional
VSourceWmf Media Foundation (Windows). Optional
SimpleUI Test application and example. Only for them

Build stand alone

The repository does not contain sub-repositories. Copy the folders of the libraries (Table 8) next to the folder of VSourceUniversal, for example from the folder modules of the RapidPixel SDK. The folder structure:

<work folder>
    VSourceUniversal
    Frame
    ConfigReader
    VSource
    VCodec
    VDecoderH264
    VDecoderH265
    VDecoderJPEG
    FormatConverter
    VSourceFile
    VSourceStream
    CryptoProvider
    VSourceV4L2
    VSourceLibCamera
    Logger
    VSourceWmf
    SimpleUI

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

cd VSourceUniversal
mkdir build
cd build
cmake ..
make

On Windows:

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

If VSourceUniversal is the top-level CMake project, the main CMakeLists.txt file selects the video source libraries (see below) and adds the folders of the libraries in order of their mutual dependencies (Frame, ConfigReader, VSource, VCodec, VDecoderH264, VDecoderH265, VDecoderJPEG, FormatConverter, CryptoProvider, Logger, VSourceFile, VSourceStream, VSourceV4L2, VSourceLibCamera, VSourceWmf) before the library itself, and the folder ../SimpleUI when the test application or the example is built. If a folder of a required library does not exist CMake stops with an error. The binaries of the test application and of the example are in the folder build/bin (Windows: build/bin/Release). To build without the test application and the example use cmake .. -D_SUBMODULE_CACHE_OVERWRITE=OFF -D_VSOURCEUNIVERSAL_TEST=OFF -D_VSOURCEUNIVERSAL_EXAMPLE=OFF (SimpleUI is not needed then).

Automatic selection of the libraries

The main CMakeLists.txt file (stand alone build) checks for every video source library whether it can be built on the target system and prints the result:

Library Built if
VSourceFile The folder ../VSourceFile exists.
VSourceStream Linux or Windows, the folders ../VSourceStream and ../CryptoProvider exist.
VSourceV4L2 Linux, the folders ../VSourceV4L2 and ../Logger exist, the header linux/videodev2.h is found.
VSourceLibCamera Linux, the folders ../VSourceLibCamera and ../Logger exist, libcamera is found by pkg-config and a test program that uses it compiles and links (pkg-config of a cross build can find the libcamera of the build machine: set PKG_CONFIG_LIBDIR or PKG_CONFIG_SYSROOT_DIR for the target).
VSourceWmf Windows, the folder ../VSourceWmf exists, the Media Foundation libraries of the Windows SDK are found.

A library can be switched off by its option VSOURCEUNIVERSAL_USE_<LIBRARY> (see CMake options). Example of the output of CMake on Linux without libcamera:

-- VSourceUniversal: VSourceFile - built
-- VSourceUniversal: VSourceStream - built
-- VSourceUniversal: VSourceV4L2 - built
-- VSourceUniversal: VSourceLibCamera - not built: libcamera not found (pkg-config libcamera)
-- VSourceUniversal: VSourceWmf - not built: Windows only
...
-- VSourceUniversal: video source libraries in use: VSourceFile, VSourceStream, VSourceV4L2

The file src/CMakeLists.txt links every video source library whose target exists in the project (Linux: VSourceFile, VSourceStream, VSourceV4L2, VSourceLibCamera; Windows: VSourceFile, VSourceStream, VSourceWmf) and enables its code by the macro VSOURCEUNIVERSAL_<LIBRARY> (for example VSOURCEUNIVERSAL_VSOURCELIBCAMERA). The targets are looked up when the build files are generated, so a top-level project can add the video source libraries before or after VSourceUniversal. isLibraryAvailable(…) tells the application which libraries are built.

CMake options

Table 9 - CMake options of the repository. In the options below ${PARENT} is the prefix defined by the top-level project (empty if VSourceUniversal is the top-level project).

Option Default Description
${PARENT}_VSOURCEUNIVERSAL ON Build the library.
${PARENT}_VSOURCEUNIVERSAL_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_VSOURCEUNIVERSAL_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 VSourceUniversal as a sub-repository.
VSOURCEUNIVERSAL_USE_VSOURCEFILE ON Use VSourceFile if it is available.
VSOURCEUNIVERSAL_USE_VSOURCESTREAM ON Use VSourceStream if it is available.
VSOURCEUNIVERSAL_USE_VSOURCEV4L2 ON Use VSourceV4L2 if it is available (Linux).
VSOURCEUNIVERSAL_USE_VSOURCELIBCAMERA ON Use VSourceLibCamera if it is available (Linux).
VSOURCEUNIVERSAL_USE_VSOURCEWMF ON Use VSourceWmf if it is available (Windows).
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 there the folders of the libraries of Table 8 that your project needs (for example from the folder modules of the RapidPixel SDK). When VSourceUniversal is included in another project it does not add its dependencies and does not check the system: your project adds the libraries in dependency order and only the video source libraries that can be built on the target system (VSourceUniversal uses every video source library whose target exists). Example with all libraries (folder structure):

<your project>
    CMakeLists.txt
    3rdparty
        CMakeLists.txt
        Frame
        ConfigReader
        VSource
        VCodec
        VDecoderH264
        VDecoderH265
        VDecoderJPEG
        FormatConverter
        CryptoProvider
        Logger
        VSourceFile
        VSourceStream
        VSourceV4L2
        VSourceLibCamera
        VSourceWmf
        VSourceUniversal

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}_VSOURCEUNIVERSAL                      ON  CACHE BOOL "" FORCE)
SET(${PARENT}_VSOURCEUNIVERSAL_TEST                 OFF CACHE BOOL "" FORCE)
SET(${PARENT}_VSOURCEUNIVERSAL_EXAMPLE              OFF CACHE BOOL "" FORCE)

################################################################################
## INCLUDING SUBDIRECTORIES
## Adding subdirectories according to the 3rd-party configuration
################################################################################
# Libraries that VSourceUniversal always needs.
foreach(LIBRARY Frame ConfigReader VSource VCodec VDecoderH264 VDecoderH265
                VDecoderJPEG FormatConverter)
    add_subdirectory(${LIBRARY})
endforeach()

# Video source libraries of the platform (VSourceUniversal uses the ones that
# are added).
add_subdirectory(CryptoProvider)
add_subdirectory(VSourceFile)
add_subdirectory(VSourceStream)
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
    add_subdirectory(Logger)
    add_subdirectory(VSourceV4L2)
    find_package(PkgConfig QUIET)
    if (PkgConfig_FOUND)
        pkg_check_modules(LIBCAMERA_CHECK QUIET libcamera)
    endif()
    if (LIBCAMERA_CHECK_FOUND)
        add_subdirectory(VSourceLibCamera)
    endif()
elseif (WIN32)
    add_subdirectory(VSourceWmf)
endif()

add_subdirectory(VSourceUniversal)

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} VSourceUniversal)

The header of the library includes only VSource.h and VCodec.h: the headers of the video source libraries are not needed by your project. If your project does not add a required library (Table 8), the build stops with an error such as VSource.h: No such file or directory.

Test application

The test application (VSourceUniversalTest) has five modes:

  • Automatic tests (no arguments): version, available libraries, invalid source strings and params, selection of the libraries by the source string (video files, network streams, V4L2 devices, camera numbers, Media Foundation cameras, prefixes), all output pixel formats of a video file (pixel-exact check of BGR24), region of interest (rounding, cutting, all formats, params of initVSource), Motion JPEG file with the built-in decoders and with a custom codec (calls, RESET, zero padding of the input, frame order), telemetry and status, params, commands (RESTART, encoded commands), log file (no passwords and keys, no control characters, access mode), interruption of a waiting getFrame(…) and of an initialization of a network stream by closeVSource(), calls of all methods from several threads at the same time (also a change of the custom codec), destruction of an open source, the internal ONVIF® client (conversion of the dates of devices, the XML reader with refused documents and limits, GetSystemDateAndTime with a test HTTP server on 127.0.0.1: the request, answers of a real device, chunked and close-delimited answers, HTTP errors, SOAP faults, invalid answers, the timeout, the stop from another thread, a refused connection; the WS-UsernameToken password digest of the example of the ONVIF® Application Programmer’s Guide and the rules of the credentials; GetCapabilities: the address of the Media service behind NAT, on another port, with https, invalid addresses, a second request with the credentials after a refusal; GetProfiles: the profiles of the answer, the token of every request checked again from its nonce and Created time of the clock of the device, a new nonce per request, the user name in XML, refused requests; GetStreamUri: the request with the stream setup and the token, the flags of the URI, rtsps, invalid tokens, invalid URIs (the URI, which can hold credentials, is not written to the error), nested SOAP fault subcodes; HTTPS with a test server and certificates made by the test (with OpenSSL): a pinned fingerprint in both forms, refused certificates (another fingerprint, the default CA paths, another CA, another IP address) without a request, -cafile, -noverify, a missing CA file, GetProfiles over TLS, TLS to a server without TLS, a stop in the TLS handshake; the source strings onvif:// and onvifs:// with invalid syntax (refused before any request), its parsing, the URL of the RTSP stream and the choice of the profile; open of onvif:// with a test device and a test RTSP server: the requests, the profile number and the token, the URL given to VSourceStream (the host of the source string), RESTART that asks the device again, a device that does not answer, a close during the requests, onvifs:// with a pinned fingerprint and an http address of the Media service, the log of VSourceUniversal and VSourceStream without the password). The test files and the log files are made by the test application in the temporary folder (their names have the process ID) and removed after the test. Without VSourceFile the tests that need video files are skipped.
  • Time of an ONVIF® device: VSourceUniversalTest --onvif-time <IPv4>[:port] [timeout ms] sends GetSystemDateAndTime to the device (port 80 and timeout 5000 ms by default) and prints the UTC time of the device, its clock mode (NTP or manual), the difference to the system clock and the time of the request.
  • Profiles of an ONVIF® device: VSourceUniversalTest --onvif-profiles <IPv4>[:port] <user> <password> [timeout ms] sends GetSystemDateAndTime, GetCapabilities (the address of the Media service) and GetProfiles with WS-UsernameToken and prints the media profiles (token, name, encoding, resolution, frame rate, bitrate, video source, metadata) with the RTSP URI of each profile (GetStreamUri; the credentials of a URI are shown as ***). Empty user and password - no authentication. The password is visible in the process list of the system: use the mode only on a computer of the tester.
  • Check of a source: VSourceUniversalTest --check <init string> [frames] [--codec] [--bgr24] opens the source, reads frames (the pixel format changes from frame to frame: BGR24, NV12, YUYV, GRAY, H264; --bgr24 - only BGR24), prints the library, the frames, the telemetry and the params. --codec sets a custom codec (software decoders behind the VCodec interface) to check the custom codec path.
  • Interactive mode: VSourceUniversalTest --interactive <init string> displays the frames of the source with SimpleUI (ESC - exit, R - RESTART, C - close / open).

The test application prints one block per test and returns 0 if all automatic tests pass.

Portability

The library uses the C++17 standard and has no code for a particular processor, instruction set or byte order: the frames are copied byte by byte and the pixel formats are converted by FormatConverter, which selects its SIMD kernels when it runs. The video source libraries of a platform are selected by CMake (see Automatic selection of the libraries). Version 1.0.0 was built (no compiler warnings with the warning options of the CMake files) and its test application was run with GCC 12 and 13 and Clang 15 and 18 on Linux x86-64, with the GCC 13 and Clang 18 cross compilers for Linux AArch64 (the test application under QEMU) and with Visual Studio 2022 on Windows x86-64. The frames of a set of test video files and the results of the frame processing of the library were identical with GCC 12 and 13, Clang 15 and 18, GCC 13 for AArch64 and Visual Studio 2022.

Simple example

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

int main(int argc, char** argv)
{
    // Open video source: a video file, a stream URL or a camera. The library
    // is selected by the init string.
    rapidpixel::VSourceUniversal source;
    std::string initString = (argc > 1) ? argv[1] : "0;640;480";
    if (!source.openVSource(initString))
    {
        // The init string is not printed: it can hold a password.
        std::cout << "ERROR: can't open video source" << std::endl;
        return -1;
    }

    // Create the window to display the video.
    rapidpixel::SimpleUiWindow window("VSourceUniversal Video Display");
    window.show();

    rapidpixel::Frame frame;
    rapidpixel::VSourceUniversalTelemetry telemetry;
    int noFrameCount = 0;
    while (window.isOpen() && noFrameCount < 10)
    {
        // Wait up to 1000 ms for new frame in BGR24 format: the frames of
        // every source are decoded and converted by the library.
        frame.fourcc = rapidpixel::Fourcc::BGR24;
        if (!source.getFrame(frame, 1000))
        {
            ++noFrameCount;
            continue;
        }
        noFrameCount = 0;
        const int lostFrames =
                source.getTelemetry(telemetry) ? telemetry.lostFrames : 0;

        // 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) + " | Lost: " +
                std::to_string(lostFrames) + " | Connected: " +
                std::to_string(source.isVSourceConnected()),
                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