rtsp_server_web_logo

RtspServerLive555 C++ library

v4.0.0

Table of contents

Overview

The RtspServerLive555 is a C++ library that implements an RTSP server. The library is based on the popular open-source library Live555 (source code not included, just linked). It provides a simple interface according to the VStreamer interface class and can be included in any C++ project. It allows developers to create an RTSP server without the complexity of the Live555 library. Users can set general RTSP server parameters: RTSP server port, IP, stream name, user name, and password. The server works frame-by-frame: users provide video frames. RtspServerLive555 accepts both raw pixel formats and compressed formats like H264, HEVC, or JPEG. If the frame is in a compressed format (H264, HEVC, or JPEG), it bypasses any overlay and resizing processes and is sent directly to clients. However, if the frame is raw, it undergoes a series of processing steps. First, resizing is performed if necessary, followed by the application of any required overlay. Finally, the processed frame is encoded into a compressed format before being transmitted to clients (to use these functions the user must define video codec and video overlay implementations according to VCodec and VOverlay interfaces). The library relies on several dependencies: VCodec (defines video codec interface, source code included, Apache 2.0 license), VOverlay (defines video overlay interface, source code included, Apache 2.0 license), FormatConverterOpenCv (provides methods to convert pixel formats, source code included), ConfigReader (provides methods to work with JSON files, source code included, Apache 2.0 license) and OpenCV (version 4.5 and higher, video scaling functions). It has been specifically tested and verified for functionality on the Linux operating system. It uses the C++17 standard. The RTSP server provided by the library is compatible with all popular RTSP clients: ffmpeg, gstreamer, VLC, Milestone etc.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 20.11.2023 - First version which supports H264 and JPEG codecs.
1.0.1 22.11.2023 - Documentation updated.
1.1.0 04.12.2023 - Getting number of clients feature added.
- Tracing packet loss ratio feature added.
2.0.0 13.12.2023 - Interface is changed.
- Streaming Raw frame support added.
2.0.1 04.01.2024 - Source code typos and styling issues fixed.
- Example applications updated.
- Documentation updated.
2.0.2 15.01.2024 - Bugs fixed.
2.0.3 22.01.2024 - Initialization bugs fixed.
- New parameters added.
3.0.0 16.04.2024 - New VStreamer interface implemented.
- Source code reviewed and simplified.
3.0.1 21.05.2024 - Submodules updated.
- Documentation updated.
3.1.0 05.08.2024 - Moved implementation files.
- CMake structure changed.
3.1.1 03.04.2025 - Multiple submodules update.
3.1.2 27.07.2025 - VSourceFile submodule update.
- Fix compiling warnings.
3.1.3 11.08.2025 - Update connecting live555 dependency.
3.1.4 26.10.2025 - VSourceFile submodule update for test application.
4.0.0 15.11.2025 - VStreamer interface updated.

Library files

The library is supplied as source code only. The user is provided with a set of files in the form of a CMake project (repository). The repository structure is shown below:

CMakeLists.txt ------------------------ Main CMake file of the library.
3rdparty ------------------------------ Folder with third-party libraries.
    CMakeLists.txt -------------------- CMake file to include third-party libraries.
    FormatConverterOpenCv ------------- Folder with FormatConverterOpenCv library source code.
    VStreamer ------------------------- Folder with VStreamer interface library source code.
src ----------------------------------- Folder with library source code.
    CMakeLists.txt -------------------- CMake file of the library.
    RtspServerLive555.cpp ------------- Library main class source file.
    RtspServerLive555.h --------------- Library main class header file.
    RtspServerLive555Version.h -------- Header file with library version.
    RtspServerLive555Version.h.in ----- Service CMake file to generate version header.
    impl
        RtspServerLive555Impl.cpp ----- Library implementation class source file.
        RtspServerLive555Impl.h ------- Library implementation class header file.
        MJPEGVideoSource.cpp ---------- Library side class source file.
        MJPEGVideoSource.h ------------ Library side class header file.
        Source.cpp -------------------- Library side class source file.
        Source.h ---------------------- Library side class header file.
        UnicastServerMediaSubsession.cpp Library side class source file.
        UnicastServerMediaSubsession.h - Library side class header file.
test ---------------------------------- Folder of test application.
    3rdparty -------------------------- Folder with third-party libraries for test application.
        VSourceFile ------------------- Folder with VSourceFile library source code.
    CMakeLists.txt -------------------- CMake file of test application.
    main.cpp -------------------------- Source C++ file of test application.
examples ------------------------------ Folder for examples
    CompressedFrameStreaming ---------- Folder with example for compressed video frames.
        CMakeLists.txt ---------------- CMake file of example.
        main.cpp ---------------------- Source code of example.
    RawFrameStreaming ----------------- Folder with example for RAW video frames.
        CMakeLists.txt ---------------- CMake file of example.
        main.cpp ---------------------- Source code of example.

The test application additionally depends on the VSourceFile library (source code included), which provides methods to read H264 and HEVC files.

RtspServerLive555 class description

RtspServerLive555 class declaration

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

namespace cr
{
namespace video
{
class RtspServerLive555 : public VStreamer
{
public:

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

    /// Class constructor.
    RtspServerLive555();

    /// Class destructor.
    ~RtspServerLive555();

    /// Init video streamer by set of parameters.
    bool initVStreamer(VStreamerParams& params,
                       cr::video::VCodec* codec = nullptr,
                       cr::video::VOverlay* overlay = nullptr) override;

    /// Get init status.
    bool isVStreamerInit() override;

    /// Set video streamer parameter.
    bool setParam(VStreamerParam id, float value) override;

    /// Set video streamer parameter.
    bool setParam(VStreamerParam id, std::string value) override;

    /// Get all video streamer parameters.
    void getParams(VStreamerParams& params) override;

    /// Execute action command.
    bool executeCommand(VStreamerCommand id) override;

    /// Send frame to video streamer.
    bool sendFrame(cr::video::Frame& frame, uint8_t* userData = nullptr, int userDataSize = 0) override;

    /// Close video streamer.
    void closeVStreamer() override;
};
}
}

getVersion method

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

static std::string getVersion();

This method can be used without an RtspServerLive555 class instance:

std::cout << "RtspServerLive555 version: " << RtspServerLive555::getVersion();

Console output:

RtspServerLive555 version: 4.0.0

initVStreamer method

The initVStreamer(…) method initializes the RTSP server. If the server is already initialized, the method will reinitialize the server. If RTSP server parameters are changed, the user does not need to call the initVStreamer(…) method to reinitialize the server. Method declaration:

bool initVStreamer(VStreamerParams& params,
              cr::video::VCodec* codec = nullptr,
              cr::video::VOverlay* overlay = nullptr) override;
Parameter Value
params VStreamerParams object that includes the required initialization parameters.
codec Pointer to a VCodec object for raw frame streaming.
overlay Pointer to a VOverlay object.

Important note: The VCodec implementation must be designed to accept input frames in NV12 format. The RtspServerLive555 library feeds NV12-formatted frames into the codec. If a custom implementation of VCodec does not support NV12 as the input format, the library will not work properly. Similarly, the VOverlay implementation must also be designed to handle input frames in YUV24 format instead of NV12. This requirement is essential for the correct operation of the library.

Returns: TRUE if the initialization is successful or FALSE if not.

isVStreamerInit method

The isVStreamerInit() method returns the video streamer initialization status. Method declaration:

bool isVStreamerInit() override;

Returns: TRUE if the video streamer is initialized or FALSE if not.

setParam (string parameter) method

The setParam(…) method sets a parameter with a string value. Method declaration:

bool setParam(VStreamerParam id, std::string value) override;
Parameter Value
id Parameter ID from the VStreamerParam enum class.
value Parameter value with a string type.

Returns: TRUE if the parameter is set successfully or FALSE if not.

setParam (float parameter) method

The setParam(…) method sets a parameter with a float value. Method declaration:

bool setParam(VStreamerParam id, float value) override;
Parameter Value
id Parameter ID from the VStreamerParam enum class.
value Parameter value with a float type.

Returns: TRUE if the parameter is set successfully or FALSE if not.

getParams method

The getParams(…) method gets the current parameters defined in the form of VStreamerParams. Method declaration:

void getParams(VStreamerParams& params) override;
Parameter Value
params Reference to a VStreamerParams object to store the current parameters.

executeCommand method

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

bool executeCommand(VStreamerCommand id) override;
Parameter Value
id Command ID from the VStreamerCommand enum.

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

sendFrame method

The sendFrame(…) method sends a video frame to the video streamer for streaming. The method copies the frame data to an internal buffer. This method is thread-safe. Method declaration:

bool sendFrame(cr::video::Frame& frame, uint8_t* userData = nullptr, int userDataSize = 0) override;
Parameter Value
frame Frame object. H264, HEVC, and RAW frame formats are supported. In the case of a RAW frame, a VCodec object must be provided to the initVStreamer method. Additionally, in the case of a RAW frame format, scaling will be performed by the server (based on the fit mode) if the provided frame has different dimensions than those defined by VStreamerParams. If the provided frame is not RAW, the video overlay cannot be applied even if the user provides a VOverlay instance to the initVStreamer method.
userData Pointer to user data buffer. Not used in the library.
userDataSize Size of user data buffer in bytes if userData is not null. Not used in the library.

Returns: TRUE if the frame is sent or FALSE if not.

closeVStreamer method

The closeVStreamer() method closes the RTSP server if it is open. Method declaration:

void closeVStreamer() override;

decodeAndExecuteCommand method of VStreamer interface

The decodeAndExecuteCommand(…) method decodes and executes a command encoded by the encodeSetParamCommand(…) and encodeCommand(…) methods of the VStreamer interface class on the video streamer side. It is a virtual method, which means that if the implementation does not define it, the default definition from the VStreamer class will be used. Each implementation of the video streamer must provide thread-safe setParam(…) and executeCommand(…) method calls to make the default definition of decodeAndExecuteCommand(…) thread-safe. This means that the decodeAndExecuteCommand(…) method can be safely called from any thread. Method declaration:

virtual bool decodeAndExecuteCommand(uint8_t* data, int size);
Parameter Description
data Pointer to input command.
size Size of command.

Returns: TRUE if the command is decoded (SET_PARAM or COMMAND) and executed (action command or set param command).

encodeSetParamCommand method of VStreamer interface

The encodeSetParamCommand(…) static method encodes a command to change any parameter in a remote video streamer. To control a video streamer remotely, the developer must design their own protocol and according to it encode the command and deliver it over the communication channel. To simplify this, the VStreamer class contains static methods for encoding control commands. The VStreamer class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). encodeSetParamCommand(…) is designed to encode the SET_PARAM command. The method has two overloads: one for numeric parameters and one for string parameters. Method declaration:

static void encodeSetParamCommand(uint8_t *data, int &size,  VStreamerParam id, float value);

static void encodeSetParamCommand(uint8_t* data, int& size, VStreamerParam id, std::string value);
Parameter Description
data Pointer to data buffer for encoded command. Must have size >= 11 bytes or in case of string parameters must be large enough to hold the string + 12 bytes.
size Size of encoded data. Will be at least 11 bytes.
id Parameter ID according to VStreamerParam enum.
value Numeric video streamer parameter value. Only for non-string parameters. For string parameters (see VStreamerParam enum) this parameter may have any value.
value String parameter value (see VStreamerParam enum).

encodeSetParamCommand(…) is a static method and is used without a VStreamer class instance. This method is used on the client side (control system). Example of command encoding:

// Buffer for encoded data.
uint8_t data[11];
// Size of encoded data.
int size = 0;
// Random parameter value.
float outValue = (float)(rand() % 20);
// Encode command.
VStreamer::encodeSetParamCommand(data, size, VStreamerParam::CUSTOM1, outValue);

encodeCommand method of VStreamer interface

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

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

encodeCommand(…) is a static method and is used without a VStreamer class instance. This method is used on the client side (control system). Example of command encoding:

// Buffer for encoded data.
uint8_t data[11];
// Size of encoded data.
int size = 0;
// Encode command.
VStreamer::encodeCommand(data, size, VStreamerCommand::RESTART);

decodeCommand method of VStreamer interface

The decodeCommand(…) static method decodes a command on the video streamer side (edge device). Method declaration:

static int decodeCommand(uint8_t* data,
                         int size,
                         VStreamerParam& paramId,
                         VStreamerCommand& commandId,
                         float& value,
                         std::string& strValue);
Parameter Description
data Pointer to input command.
size Size of command. Should be minimum 11 bytes for SET_PARAM and 7 bytes for COMMAND.
paramId Parameter ID according to VStreamerParam enum. After decoding a SET_PARAM command the method will return the parameter ID.
commandId Command ID according to VStreamerCommand enum. After decoding a COMMAND the method will return the command ID.
value Numeric video streamer parameter value. Only for non-string parameters. For string parameters (see VStreamerParam enum) this parameter may have any value.
strValue String parameter value (see VStreamerParam enum).

Returns: 0 - in case of decoding COMMAND, 1 - in case of decoding SET_PARAM command or -1 in case of errors.

Data structures

The VStreamer.h file of the VStreamer interface class defines IDs for parameters (VStreamerParam enum) and IDs for commands (VStreamerCommand enum).

VStreamerCommand enum

Enum declaration:

enum class VStreamerCommand
{
    /// Restart.
    RESTART = 1,
    /// Enable. Equal to MODE param.
    ON,
    /// Disable. Equal to MODE param.
    OFF,
    /// Generate key frame command.
    GENERATE_KEYFRAME
};

Table 4 - Video stream action commands description. Some commands may be unsupported by a particular video streamer class.

Command Description
RESTART Restarts the streamer with the last VStreamerParams.
ON Enables the streamer if it is disabled.
OFF Disables the streamer if it is enabled.
GENERATE_KEYFRAME Action command to generate a key frame by the video codec in case of H264/HEVC video encoding. This function is required in some cases. The VCodec implementation provided by the user should support this function.

VStreamerParam enum

Enum declaration:

enum class VStreamerParam
{
    /// Mode: 0 - disabled, 1 - enabled.
    MODE = 1,
    /// Video stream width from 8 to 8192.
    WIDTH,
    /// Video stream height from 8 to 8192.
    HEIGHT,
    /// Streamer IP.
    IP,
    /// RTSP port, integer [0:65535].
    RTSP_PORT,
    /// RTSPS port, integer [0:65535].
    RTSPS_PORT,
    /// RTP port, integer [0:65535].
    RTP_PORT,
    /// WebRTC port, integer [0:65535].
    WEBRTC_PORT,
    /// HLS port, integer [0:65535].
    HLS_PORT,
    /// SRT port, integer [0:65535].
    SRT_PORT,
    /// RTMP port, integer [0:65535].
    RTMP_PORT,
    /// RTMPS port, integer [0:65535].
    RTMPS_PORT,
    /// Metadata port, integer [0:65535].
    METADATA_PORT,
    /// RTSP protocol enable / disable, integer: 0 - disable, 1 - enable.
    RTSP_MODE,
    /// RTP protocol enable / disable, integer: 0 - disable, 1 - enable.
    RTP_MODE,
    /// WebRTC protocol enable / disable, integer: 0 - disable, 1 - enable.
    WEBRTC_MODE,
    /// HLS protocol enable / disable, integer: 0 - disable, 1 - enable.
    HLS_MODE,
    /// SRT protocol enable / disable, integer: 0 - disable, 1 - enable.
    SRT_MODE,
    /// RTMP protocol enable / disable, integer: 0 - disable, 1 - enable.
    RTMP_MODE,
    /// Metadata protocol enable / disable, integer: 0 - disable, 1 - enable.
    METADATA_MODE,
    /// RTSP multicast IP.
    RTSP_MULTICAST_IP,
    /// RTSP multicast port, integer [0:65535].
    RTSP_MULTICAST_PORT,
    /// Streamer user (for RTSP streaming): "" - no user.
    USER,
    /// Streamer password (for RTSP streaming): "" - no password.
    PASSWORD,
    /// Streamer suffix (for RTSP streaming, stream name).
    SUFFIX,
    /// Metadata suffix (stream name).
    METADATA_SUFFIX,
    /// Minimum bitrate for variable bitrate mode, kbps.
    MIN_BITRATE_KBPS,
    /// Maximum bitrate for variable bitrate mode, kbps.
    MAX_BITRATE_KBPS,
    /// Current bitrate, kbps.
    BITRATE_KBPS,
    /// Bitrate mode: 0 - constant bitrate, 1 - variable bitrate.
    BITRATE_MODE,
    /// FPS.
    FPS,
    /// GOP size for H264 and H265 codecs.
    GOP,
    /// H264 profile: 0 - baseline, 1 - main, 2 - high.
    H264_PROFILE,
    /// JPEG quality from 1 to 100% for JPEG codec.
    JPEG_QUALITY,
    /// Codec type: "H264", "HEVC" or "JPEG".
    CODEC,
    /// Scaling mode: 0 - fit, 1 - fill.
    FIT_MODE,
    /// Cycle time, integer μsec (microseconds).
    CYCLE_TIME_USEC,
    /// Overlay mode: 0 - disable, 1 - enable.
    OVERLAY_MODE,
    /// Type of the streamer.
    TYPE,
    /// Custom parameter 1.
    CUSTOM1,
    /// Custom parameter 2.
    CUSTOM2,
    /// Custom parameter 3. 
    CUSTOM3,
    /// Path to openssl key for RTSP.
    RTSP_KEY,
    /// Path to openssl certificate for RTSP.
    RTSP_CERT,
    /// Path to openssl key for WebRTC.
    WEBRTC_KEY,
    /// Path to openssl certificate for WebRTC.
    WEBRTC_CERT,
    /// Path to openssl key for HLS.
    HLS_KEY,
    /// Path to openssl certificate for HLS.
    HLS_CERT,
    /// Path to openssl key for RTMP.
    RTMP_KEY,
    /// Path to openssl certificate for RTMP.
    RTMP_CERT,
    /// RTSP encryption type: "no", "strict", "optional".
    RTSP_ENCRYPTION,
    /// WebRTC encryption type: "no", "yes".
    WEBRTC_ENCRYPTION,
    /// RTMP encryption type: "no", "strict", "optional".
    RTMP_ENCRYPTION,
    /// HLS encryption type: "no", "yes".
    HLS_ENCRYPTION,
    /// Logging mode: 0 - Disable, 1 - Only file, 2 - Only terminal, 3 - File and terminal.
    LOG_LEVEL
};

Table 5 - Video streamer params description.

Parameter Description Support Status
MODE Enables/disables the RTSP server (0 - disabled, 1 - enabled). Supported
WIDTH Frame width. Supported
HEIGHT Frame height. Supported
IP The RTSP server IP address. Supported
RTSP_PORT The RTSP server port. Supported
RTSPS_PORT The RTSPS (RTSP over TLS) server port. Not supported
RTP_PORT The RTP port. Not supported
WEBRTC_PORT The WebRTC port. Not supported
HLS_PORT The HLS (HTTP Live Streaming) port. Not supported
SRT_PORT The SRT (Secure Reliable Transport) port. Not supported
RTMP_PORT The RTMP (Real-Time Messaging Protocol) port. Not supported
RTMPS_PORT The RTMPS (RTMP over TLS) port. Not supported
METADATA_PORT The metadata port. Not supported
RTSP_MODE RTSP protocol enable/disable (0 - disable, 1 - enable). Not supported
RTP_MODE RTP protocol enable/disable (0 - disable, 1 - enable). Not supported
WEBRTC_MODE WebRTC protocol enable/disable (0 - disable, 1 - enable). Not supported
HLS_MODE HLS protocol enable/disable (0 - disable, 1 - enable). Not supported
SRT_MODE SRT protocol enable/disable (0 - disable, 1 - enable). Not supported
RTMP_MODE RTMP protocol enable/disable (0 - disable, 1 - enable). Not supported
METADATA_MODE Metadata protocol enable/disable (0 - disable, 1 - enable). Not supported
RTSP_MULTICAST_IP The RTSP multicast IP address. Not supported
RTSP_MULTICAST_PORT The RTSP multicast port. Not supported
USER Username for authentication of the RTSP stream. Supported
PASSWORD Password for authentication of the RTSP stream. Supported
SUFFIX Stream name for the RTSP stream. Supported
METADATA_SUFFIX Metadata stream name. Not supported
MIN_BITRATE_KBPS Minimum bitrate for variable bitrate encoding for raw input video frames. Not supported
MAX_BITRATE_KBPS Maximum bitrate for variable bitrate encoding for raw input video frames. Not supported
BITRATE_KBPS Bitrate for constant bitrate encoding for raw input video frames. Supported
BITRATE_MODE Enables/disables variable bitrate. Not supported
FPS The streamer FPS and the encoding FPS for raw input video frames. Regardless of the input video frame rate, the streamer provides the specified FPS. If the FPS value is 0, the streamer provides an FPS equal to the input video frame rate. Supported
GOP Codec GOP size for raw input video frames. Supported
H264_PROFILE H264 encoding profile for raw input video frames. Supported
JPEG_QUALITY JPEG encoding quality for raw input video frames. Supported
CODEC Codec type for encoding raw frames (“H264”, “HEVC”, or “JPEG”). Supported
FIT_MODE Scaling mode. Values: 0 - fit, 1 - crop, for raw input video frames. Supported
OVERLAY_MODE Overlay enable/disable for raw input video frames. Values: 0 - disable, 1 - enable. Supported
CYCLE_TIME_USEC Read only. Cycle time, microseconds. Calculated by streamer. Supported
TYPE Type of the streamer. Not supported
CUSTOM1 Custom parameter 1. Not supported
CUSTOM2 Custom parameter 2. Not supported
CUSTOM3 Custom parameter 3. Not supported
RTSP_KEY Path to OpenSSL key file for RTSP encryption. Not supported
RTSP_CERT Path to OpenSSL certificate file for RTSP encryption. Not supported
WEBRTC_KEY Path to OpenSSL key file for WebRTC encryption. Not supported
WEBRTC_CERT Path to OpenSSL certificate file for WebRTC encryption. Not supported
HLS_KEY Path to OpenSSL key file for HLS encryption. Not supported
HLS_CERT Path to OpenSSL certificate file for HLS encryption. Not supported
RTMP_KEY Path to OpenSSL key file for RTMP encryption. Not supported
RTMP_CERT Path to OpenSSL certificate file for RTMP encryption. Not supported
RTSP_ENCRYPTION RTSP encryption type (“no”, “strict”, “optional”). Not supported
WEBRTC_ENCRYPTION WebRTC encryption type (“no”, “yes”). Not supported
RTMP_ENCRYPTION RTMP encryption type (“no”, “strict”, “optional”). Not supported
HLS_ENCRYPTION HLS encryption type (“no”, “yes”). Not supported
LOG_LEVEL Logging mode. Values: 0 - Disable, 1 - Only file, 2 - Only terminal, 3 - File and terminal. Not supported

VStreamerParams class description

VStreamerParams class declaration

The VStreamerParams class is used for video stream initialization (initVStreamer(…) method) or to get all current parameters (getParams(…) method). Additionally, VStreamerParams provides a structure to write/read parameters from JSON files (JSON_READABLE macro, see ConfigReader class description) and provides methods to encode and decode parameters. Class declaration:

class VStreamerParams
{
public:
    /// Streamer mode: false - Off, true - On.
    bool enable{true};
    /// Video stream width from 8 to 8192.
    int width{1280};
    /// Video stream height from 8 to 8192.
    int height{720};
    /// Streamer IP.
    std::string ip{"0.0.0.0"};
    /// RTSP port.
    int rtspPort{8554};
    /// RTSPS port.
    int rtspsPort{8555};
    /// RTP port.
    int rtpPort{5004};
    /// WebRTC port.
    int webRtcPort{7000};
    /// HLS port.
    int hlsPort{8080};
    /// SRT port.
    int srtPort{6000};
    /// RTMP port.
    int rtmpPort{1935};
    /// RTMPS port.
    int rtmpsPort{1936};
    /// Metadata port.
    int metadataPort{9000};
    /// RTSP protocol enable / disable: false - disable, true - enable.
    bool rtspEnable{true};
    /// RTP protocol enable / disable: false - disable, true - enable.
    bool rtpEnable{true};
    /// WebRTC protocol enable / disable: false - disable, true - enable.
    bool webRtcEnable{true};
    /// HLS protocol enable / disable: false - disable, true - enable.
    bool hlsEnable{true};
    /// SRT protocol enable / disable: false - disable, true - enable.
    bool srtEnable{true};
    /// RTMP protocol enable / disable: false - disable, true - enable.
    bool rtmpEnable{true};
    /// Metadata protocol enable / disable: false - disable, true - enable.
    bool metadataEnable{false};
    /// RTSP multicast IP.
    std::string rtspMulticastIp{"224.1.0.1/16"};
    /// RTSP multicast port.
    int rtspMulticastPort{18000};
    /// Streamer user (for RTSP streaming): "" or "no" - no user.
    std::string user{"no"};
    /// Streamer password (for RTSP streaming): "" or "no" - no password.
    std::string password{"no"};
    /// Streamer suffix (for RTSP streaming) (stream name).
    std::string suffix{"live"};
    /// Metadata suffix (stream name).
    std::string metadataSuffix{"metadata"};
    /// Minimum bitrate for variable bitrate mode, kbps.
    int minBitrateKbps{1000};
    /// Maximum bitrate for variable bitrate mode, kbps.
    int maxBitrateKbps{5000};
    /// Current bitrate, kbps.
    int bitrateKbps{3000};
    /// Bitrate mode: 0 - constant bitrate, 1 - variable bitrate.
    int bitrateMode{0};
    /// FPS.
    float fps{30.0f};
    /// GOP size for H264 and H265 codecs.
    int gop{30};
    /// H264 profile: 0 - baseline, 1 - main, 2 - high.
    int h264Profile{0};
    /// JPEG quality from 1 to 100% for JPEG codec.
    int jpegQuality{80};
    /// Codec type: "H264", "HEVC" or "JPEG".
    std::string codec{"H264"};
    /// Scaling mode: 0 - fit, 1 - crop.
    int fitMode{0};
    /// Cycle time, microseconds. Calculated by streamer.
    int cycleTimeUs{0};
    /// Overlay mode: false - off, true - on.
    bool overlayEnable{true};
    /// Type of the streamer.
    int type{0};
    /// Custom parameter 1.
    float custom1{0.0f};
    /// Custom parameter 2.
    float custom2{0.0f};
    /// Custom parameter 3.
    float custom3{0.0f};
    /// Path to openssl key for RTSP: "" or "no" - no key.
    std::string rtspKey{"no"};
    /// Path to openssl certificate for RTSP: "" or "no" - no certificate.
    std::string rtspCert{"no"};
    /// Path to openssl key for WebRTC: "" or "no" - no key.
    std::string webRtcKey{"no"};
    /// Path to openssl certificate for WebRTC: "" or "no" - no certificate.
    std::string webRtcCert{"no"};
    /// Path to openssl key for HLS: "" or "no" - no key.
    std::string hlsKey{"no"};
    /// Path to openssl certificate for HLS: "" or "no" - no certificate.
    std::string hlsCert{"no"};
    /// Path to openssl key for RTMP: "" or "no" - no key.
    std::string rtmpKey{"no"};
    /// Path to openssl certificate for RTMP: "" or "no" - no certificate.
    std::string rtmpCert{"no"};
    /// RTSP encryption type: "" or "no", "strict", "optional".
    std::string rtspEncryption{"no"};
    /// WebRTC encryption type: "" or "no", "yes".
    std::string webRtcEncryption{"no"};
    /// RTMP encryption type: "" or "no", "strict", "optional".
    std::string rtmpEncryption{"no"};
    /// HLS encryption type: "" or "no", "yes".
    std::string hlsEncryption{"no"};
    /// Logging mode: 0 - Disable, 1 - Only file, 2 - Only terminal, 3 - File and terminal.
    int logLevel{0};

    JSON_READABLE(VStreamerParams, enable, width, height, ip, rtspPort, rtspsPort, rtpPort,
                  webRtcPort, hlsPort, srtPort, rtmpPort, rtmpsPort, metadataPort,
                  rtspEnable, rtpEnable, webRtcEnable, hlsEnable, srtEnable,
                  rtmpEnable, metadataEnable, rtspMulticastIp, rtspMulticastPort,
                  user, password, suffix, metadataSuffix, minBitrateKbps,
                  maxBitrateKbps, bitrateKbps, bitrateMode, fps, gop, h264Profile,
                  jpegQuality, codec, fitMode, overlayEnable, type, custom1,
                  custom2, custom3, rtspKey, rtspCert, webRtcKey, webRtcCert,
                  hlsKey, hlsCert, rtmpKey, rtmpCert, rtspEncryption,
                  webRtcEncryption, rtmpEncryption, hlsEncryption, logLevel)

    /// Assignment operator.
    VStreamerParams& operator= (const VStreamerParams& src);

    /// Serialize parameters.
    bool serialize(uint8_t* data, int bufferSize, int& size,
                   VStreamerParamsMask* mask = nullptr);

    /// Deserialize parameters.
    bool deserialize(uint8_t* data, int dataSize);
};

Serialize video streamer params

The VStreamerParams class provides a serialize(…) method to serialize video streamer parameters (fields of the VStreamerParams class). Serialization of video streamer parameters is necessary when you need to send video streamer parameters via communication channels. The method provides options to exclude particular parameters from serialization. To do this, the method inserts a binary mask (5 bytes) where each bit represents a particular parameter and the deserialize(…) method recognizes it. Method declaration:

bool serialize(uint8_t* data, int bufferSize, int& size, VStreamerParamsMask* mask = nullptr);
Parameter Value
data Pointer to data buffer.
bufferSize Data buffer size. If the buffer size is smaller than required, the buffer will be filled with fewer parameters.
size Size of serialized data.
mask Parameters mask - a pointer to the VStreamerParamsMask structure. VStreamerParamsMask (declared in the VStreamer.h file) determines flags for each field (parameter) declared in the VStreamerParams class. If the user wants to exclude any parameters from serialization, they can provide a pointer to the mask. If the user wants to exclude a particular parameter from serialization, they should set the corresponding flag in the VStreamerParamsMask structure.

VStreamerParamsMask structure declaration:

struct VStreamerParamsMask
{
    bool enable{true};
    bool width{true};
    bool height{true};
    bool ip{true};
    bool rtspPort{true};
    bool rtspsPort{true};
    bool rtpPort{true};
    bool webRtcPort{true};
    bool hlsPort{true};
    bool srtPort{true};
    bool rtmpPort{true};
    bool rtmpsPort{true};
    bool metadataPort{true};
    bool rtspEnable{true};
    bool rtpEnable{true};
    bool webRtcEnable{true};
    bool hlsEnable{true};
    bool srtEnable{true};
    bool rtmpEnable{true};
    bool metadataEnable{true};
    bool rtspMulticastIp{true};
    bool rtspMulticastPort{true};
    bool user{true};
    bool password{true};
    bool suffix{true};
    bool metadataSuffix{true};
    bool minBitrateKbps{true};
    bool maxBitrateKbps{true};
    bool bitrateKbps{true};
    bool bitrateMode{true};
    bool fps{true};
    bool gop{true};
    bool h264Profile{true};
    bool jpegQuality{true};
    bool codec{true};
    bool fitMode{true};
    bool cycleTimeUs{true};
    bool overlayEnable{true};
    bool type{true};
    bool custom1{true};
    bool custom2{true};
    bool custom3{true};
    bool rtspKey{true};
    bool rtspCert{true};
    bool webRtcKey{true};
    bool webRtcCert{true};
    bool hlsKey{true};
    bool hlsCert{true};
    bool rtmpKey{true};
    bool rtmpCert{true};
    bool rtspEncryption{true};
    bool webRtcEncryption{true};
    bool rtmpEncryption{true};
    bool hlsEncryption{true};
    bool logLevel{true};
};

Example without parameters mask:

// Prepare random params.
VStreamerParams in;
in.ip = "alsfghljb";
in.rtspPort = 8554;

// Serialize parameters.
uint8_t data[1024];
int size = 0;
in.serialize(data, 1024, size);
cout << "Serialized data size: " << size << " bytes" << endl;

Example with parameters mask:

// Prepare random parameters.
VStreamerParams in;
in.ip = "alsfghljb";
in.rtspPort = 8554;

// Prepare parameters mask.
VStreamerParamsMask mask;
mask.rtspEnable = false; // Exclude RTSP stream. Others by default.

// Serialize parameters.
uint8_t data[1024];
int size = 0;
in.serialize(data, 1024, size, &mask);
cout << "Serialized data size: " << size << " bytes" << endl;

Deserialize video streamer params

The VStreamerParams class provides a deserialize(…) method to deserialize video streamer parameters (fields of the VStreamerParams class). Deserialization of video streamer parameters is necessary when you need to receive video streamer parameters via communication channels. The method automatically recognizes which parameters were serialized by the serialize(…) method. Method declaration:

bool deserialize(uint8_t* data, int dataSize);
Parameter Value
data Pointer to the serialized data buffer.
dataSize Size of data in bytes.

Returns: TRUE if the data is deserialized or FALSE if not.

Example:

// Serialize parameters.
VStreamerParams in;
uint8_t data[1024];
int size = 0;
in.serialize(data, 1024, size);

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

// Deserialize parameters.
VStreamerParams out;
if (!out.deserialize(data, size))
    cout << "Can't deserialize data" << endl;

Read params from JSON file and write to JSON file

The VStreamer library depends on the ConfigReader library which provides methods to read parameters from JSON files and to write parameters to JSON files. Example of writing and reading parameters to/from a JSON file:

// Write params to file.
VStreamerParams in;
cr::utils::ConfigReader inConfig;
inConfig.set(in, "vStreamerParams");
inConfig.writeToFile("TestVStreamerParams.json");

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

TestVStreamerParams.json will look like (random values):

{
    "vStreamerParams": 
    {
        "bitrateKbps": 45157,
        "bitrateMode": 53395,
        "codec": "dkgvmkrnjv",
        "custom1": 16353.0,
        "custom2": 30513.0,
        "custom3": 16213.0,
        "enable": false,
        "fitMode": 14594,
        "fps": 12255.0,
        "gop": 32446,
        "h264Profile": 17051,
        "height": 44304,
        "hlsCert": "24kjcnnv",
        "hlsEnable": false,
        "hlsEncryption": "wieufjpowkf",
        "hlsKey": "wqlovf;qb",
        "hlsPort": 9365,
        "ip": "sfspfo9jbjnbjhklvllks",
        "jpegQuality": 22605,
        "logLevel": 0,
        "maxBitrateKbps": 11267,
        "metadataEnable": false,
        "metadataPort": 35074,
        "metadataSuffix": "z.,nfpowe",
        "minBitrateKbps": 6818,
        "overlayEnable": true,
        "password": "sddgoihw,",
        "rtmpCert": "wfpomv",
        "rtmpEnable": true,
        "rtmpEncryption": "skldfjdf",
        "rtmpKey": "dkkkkjfkjdkjfkj2134",
        "rtmpPort": 55981,
        "rtmpsPort": 1936,
        "rtpEnable": true,
        "rtpPort": 31062,
        "rtspCert": "lkjrkjg",
        "rtspEnable": true,
        "rtspEncryption": "quyen",
        "rtspKey": "dh;skcsf",
        "rtspMulticastIp": "wpofuihifo",
        "rtspMulticastPort": 47135,
        "rtspPort": 42745,
        "rtspsPort": 56847,
        "srtEnable": true,
        "srtPort": 1963,
        "suffix": "pisfhcowmfv",
        "type": 5617,
        "user": "slfljkv",
        "webRtcCert": "erghshiAJ",
        "webRtcEnable": false,
        "webRtcEncryption": "l;uoykh",
        "webRtcKey": "WERUHUHFE",
        "webRtcPort": 50955,
        "width": 48849
    }
}

Examples

The first application shows how to open a video file (compressed video) with the VSourceFile library, capture video, and send it to the RTSP server.

#include <iostream>
#include "RtspServerLive555.h"
#include "VSourceFile.h"

using namespace std;
using namespace cr::rtsp;
using namespace cr::video;

int main()
{
    cout << "RtspServerLive555 v" << RtspServerLive555::getVersion() << endl;
    cout << endl;

    // Initialize RTSP server parameters for encoded frames with default parameters.
    VStreamerParams params;
    params.rtspPort = 7031;
    params.ip = "0.0.0.0";
    params.suffix = "live";
    params.user = ""; // No user name.
    params.password = ""; // No password.
    params.fps = 30;

    // RTSP server.
    RtspServerLive555 server;
    if(!server.initVStreamer(params))
    {
        cout << "Can't init RTSP server" << endl;
        return -1;
    }
    cout << "RTSP init string: rtsp://127.0.0.1:7031/live" << endl;
    
    // Set video source initialization string.
    string initString = "out.264;1280;720;30";

    // Initialize file video source.
    VSourceFile fileSource;
    if(!fileSource.openVSource(initString))
    {
        cout << "Can't open source file" << endl;
        return -1;
    }

    // Main thread.
    Frame sourceFrame;
    while(1)
    {
        // Get new frame from video file.
        if(!fileSource.getFrame(sourceFrame, 1000))
        {
            cout << "Could not get the frame" << endl;
            continue;
        }
        
        // Send frame to RTSP server.
        if(!server.sendFrame(sourceFrame))
        {
            cout << "Cannot send frame to RTSP server" << endl;
        }
        
    }
    return 1;
}

The second application shows how to work with raw video frames. This application includes a custom implementation of a video codec and video overlay.

#include <iostream>
#include <opencv2/opencv.hpp>
#include "RtspServerLive555.h"
#include <FormatConverterOpenCv.h>

using namespace cv;
using namespace std;
using namespace cr::rtsp;
using namespace cr::video;
using namespace std::chrono;

/// Custom video codec class based on OpenCV for JPEG encoding.
class VCodecOpenCv : public VCodec
{
public:

    /// Encode video frame.
    bool transcode(Frame& src, Frame& dst)
    {
        // Check input data.
        if (src.size == 0 || src.width == 0 || src.height == 0)
            return false;

        // Check output frame initialization.
        if (dst.width != src.width || dst.height != src.height)
            dst = Frame(src.width, src.height, Fourcc::JPEG);

        // VCodec implementations work with NV12 input,
        // so RtspServerLive555 also follows the same logic.
        // This means any custom VCodec implementation should accept NV12 input.
        Frame bgrFrame;
        bgrFrame.fourcc = Fourcc::BGR24;
        FormatConverterOpenCv converter;
        converter.convert(src, bgrFrame);

        // Create cv::Mat from the BGR data
        Mat bgrFrameCv(bgrFrame.height, bgrFrame.width, CV_8UC3, bgrFrame.data);

        // Set JPEG quality. Here, 70 is an example quality level.
        vector<int> compression_params;
        compression_params.push_back(IMWRITE_JPEG_QUALITY);
        compression_params.push_back(70); // Quality level here

        // git status the image to JPG format
        vector<uchar> encodedImage;
        imencode(".jpg", bgrFrameCv, encodedImage, compression_params);

        // Copy the data from vector to uint8_t array
        copy(encodedImage.begin(), encodedImage.end(), dst.data);
        dst.size = encodedImage.size();

        return true;
    }

    // Not used.
    bool setParam(VCodecParam id, float value) { return false; }

    // Not used.
    float getParam(VCodecParam id) { return -1.0; }

    // Not used.
    bool executeCommand(VCodecCommand id) { return false; }
};

/// Custom video overlay implementation. Works with YUV pixel formats.
class VOverlayCustom : public VOverlay
{
public:

    /// Overlay the information on the video.
    bool overlay(Frame& frame, void* data = nullptr)
    {
        // Put the text on the frame.
        static int counter = 0;
        Mat yuvImg(frame.height, frame.width, CV_8UC3, frame.data);
        putText(yuvImg, to_string(counter++), Point(60, 60),
                FONT_HERSHEY_SIMPLEX, 2.5, Scalar(76, 84, 255), 2);
        return true;
    }
};

int main(void)
{
    cout << "RtspServerLive555 v" << RtspServerLive555::getVersion() << endl;
    cout << endl;

    // Set initial RTSP server parameters.
    VStreamerParams params;
    params.rtspPort = 7031;
    params.ip = "0.0.0.0"; // For any IP.
    params.suffix = "live";
    params.user = "";       // No user name.
    params.password = "";   // No password.
    params.fps = 30;
    params.codec = "JPEG";
    params.width = 1280;
    params.height = 720;
    params.fitMode = 0;
    params.overlayEnable = true;

    // Create and initialize RTSP server.
    RtspServerLive555 server;
    if(!server.initVStreamer(params, new VCodecOpenCv(), new VOverlayCustom()))
    {
        cout << "Can't init RTSP server" << endl;
        return -1;
    }
    cout << "RTSP init string: rtsp://127.0.0.1:7031/live" << endl;

    // Main loop.
    int sourceFrameWidth = 1280;
    int sourceFrameHeight = 1024;
    Mat sourceFrame(sourceFrameHeight, sourceFrameWidth, CV_8UC3);
    int frameId = 0;
    while(1)
    {
        // Create new artificial frame.
        memset(sourceFrame.data, 60, sourceFrameWidth * sourceFrameHeight * 3);
        putText(sourceFrame, to_string(frameId++), Point(300, 300),
                FONT_HERSHEY_SIMPLEX, 6, Scalar(255, 255, 0), 5);

        // Prepare Frame object from OpenCV.
        Frame bgrFrame;
        bgrFrame.width = sourceFrame.size().width;
        bgrFrame.height = sourceFrame.size().height;
        bgrFrame.size = bgrFrame.width * bgrFrame.height * 3;
        bgrFrame.data = sourceFrame.data;
        bgrFrame.fourcc = Fourcc::BGR24;

        // Send raw frame to RTSP server.
        if(!server.sendFrame(bgrFrame))
        {
            cout << "Cannot send frame to RTSP server" << endl;
            continue;
        }

        // Wait for approx 30 fps.
        this_thread::sleep_for(milliseconds(33));
    }
    return 1;
}

Dependencies

The RtspServerLive555 is a C++ library that uses the Live555 library, which in turn relies on OpenSSL for secure network communication. To effectively utilize the RtspServerLive555 library, it is essential to ensure that both Live555 and OpenSSL are correctly installed and configured on your system. The library also uses the OpenCV library (version 4.5 and higher).

How to install OpenSSL

  • Run the command:

      sudo apt-get install libssl-dev
    

How to install Live555 by using package manager

  • Run the command:

      sudo apt-get install liblivemedia-dev
    

    If you get an error from the package manager, go to the next step and install Live555 from source code.

    Important note: There will be a compilation error if your system has Live555 from both source code installation and package manager installation at the same time. To solve this problem, you should remove one of them. For example:

      sudo apt-get remove liblivemedia-dev
    

How to install Live555 from source code

  • First, you need to download Live555 from the official website.

  • Extract the .tar.gz file.

      tar -xz live.(version).tar.gz
    
  • Run the genMakefiles command with the proper OS name. You can check supported OSes in the live folder by examining the config.OSname files.

      cd live
    
      ./genMakefiles <os-platform>
    

    for example:

      ./genMakefiles linux-64bit
    

    If you are getting a compile error, add -std=C++17 -DNO_STD_LIB flags to the CPLUSPLUS_FLAGS parameter in config.os-platform, for example config.linux-64-bit:

      COMPILE_OPTS =		$(INCLUDES) -fPIC -I/usr/local/include -I. -O2 -DSOCKLEN_T=socklen_t -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64
      C =			c
      C_COMPILER =		cc
      C_FLAGS =		$(COMPILE_OPTS)
      CPP =			cpp
      CPLUSPLUS_COMPILER =	c++
      CPLUSPLUS_FLAGS =	$(COMPILE_OPTS) -Wall -DBSD=1 -Wno-deprecated -std=C++17 -DNO_STD_LIB
      OBJ =			o
      LINK =			c++ -o
      LINK_OPTS =		-L.
      CONSOLE_LINK_OPTS =	$(LINK_OPTS)
      LIBRARY_LINK =		ar cr 
      LIBRARY_LINK_OPTS =	
      LIB_SUFFIX =			a
      LIBS_FOR_CONSOLE_APPLICATION = -lssl -lcrypto
      LIBS_FOR_GUI_APPLICATION =
      EXE =
    
  • Run the make command:
      make
    
  • Install to the system:
      sudo make install
    

How to install OpenCV

  • Run the command:

      sudo apt-get install libopencv-dev
    

Build and connect to your project

Typical commands to build the RtspServerLive555 library:

cd RtspServerLive555
mkdir build
cd build
cmake ..
make

If you want to connect the RtspServerLive555 library to your CMake project as source code, you can follow these steps. For example, if your repository has the following structure:

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

Create a 3rdparty folder in your repository and copy the RtspServerLive555 repository folder there. The new structure of your repository:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    RtspServerLive555

Create a CMakeLists.txt file in the 3rdparty folder. The CMakeLists.txt should contain:

cmake_minimum_required(VERSION 3.13)

################################################################################
## 3RD-PARTY
## dependencies for the project
################################################################################
project(3rdparty LANGUAGES CXX)

################################################################################
## SETTINGS
## basic 3rd-party settings before use
################################################################################
# To inherit the top-level architecture when the project is used as a submodule.
SET(PARENT ${PARENT}_YOUR_PROJECT_3RDPARTY)
# Disable self-overwriting of parameters inside included subdirectories.
SET(${PARENT}_SUBMODULE_CACHE_OVERWRITE OFF CACHE BOOL "" FORCE)

################################################################################
## INCLUDING SUBDIRECTORIES
## Adding subdirectories according to the 3rd-party configuration
################################################################################
add_subdirectory(RtspServerLive555)

The file 3rdparty/CMakeLists.txt adds the RtspServerLive555 folder to your project and excludes the test application from compiling (by default, the test application is excluded from compiling if RtspServerLive555 is included as a sub-repository). The new structure of your repository:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    RtspServerLive555

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

add_subdirectory(3rdparty)

Next, you need to add the following part to the main CMakeLists.txt file of your repository to include the Live555 library properly. This part should be located before add_subdirectory(3rdparty) in the main CMakeLists.txt.

if(EXISTS /usr/include/liveMedia)
    include_directories(/usr/include/BasicUsageEnvironment)
    include_directories(/usr/include/groupsock)
    include_directories(/usr/include/UsageEnvironment)
    include_directories(/usr/include/liveMedia)
    set(live555PackageInstallation 1)
    add_definitions(-Dlive555PackageInstallation=${live555PackageInstallation})
else()
    include_directories(/usr/local/include/BasicUsageEnvironment)
    include_directories(/usr/local/include/groupsock)
    include_directories(/usr/local/include/UsageEnvironment)
    include_directories(/usr/local/include/liveMedia)
endif()

Next, you have to include the RtspServerLive555 library in your src/CMakeLists.txt file:

target_link_libraries(${PROJECT_NAME} RtspServerLive555)

Done!


Table of contents