 MediaMtx: C++ replacement for the MediaMTX parts la_mojo uses
New project Projects/MediaMtx, in MediaMTX's module layout (internal/core, conf,
stream, staticsources/rtsp, servers/webrtc, recorder, api, ...):
- RTSP pull of the cameras with live555 (H264, TCP/UDP), reconnect after errors or
when no data arrives for --readTimeout
- WebRTC WHEP on :8889 with libdatachannel, the MediaMTX URLs
(POST /stream_N/whep, PATCH/DELETE /stream_N/whep/<id>), so the dashboard works as is
- recording as fragmented MP4 segments (no transcoding), playable in browsers,
MediaMTX file names; a fragment is flushed every --recordPartDuration
- no mediamtx.yml: command line options + a paths file (SIGHUP reload) + the
v3 paths API (add / patch / replace / delete, written back to the file)
- log lines in the MediaMTX format that kernelHelperMediaMTX parses
Tested with a GStreamer RTSP camera and Chromium (WHEP, recordings), camera
loss / reconnect, API, SIGHUP; ASan + UBSan clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
22 hours ago |
|
#include "conf.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
namespace mtx {
static std::string trim(const std::string & s){ size_t b = s.find_first_not_of(" \t\r\n"); if (b == std::string::npos) { return std::string(); } size_t e = s.find_last_not_of(" \t\r\n"); return s.substr(b, e - b + 1);}
static bool parseBool(const std::string & v, bool & out){ if (v == "yes" || v == "true" || v == "1" || v == "on") { out = true; return true; } if (v == "no" || v == "false" || v == "0" || v == "off") { out = false; return true; } return false;}
bool parseDurationMs(const std::string & s, int64_t & ms){ if (s.empty()) { return false; } char * tEnd = nullptr; double tV = strtod(s.c_str(), &tEnd); if (tEnd == s.c_str() || tV < 0) { return false; } std::string tUnit(tEnd); double tMul; if (tUnit.empty() || tUnit == "s") { tMul = 1000.0; } else if (tUnit == "ms") { tMul = 1.0; } else if (tUnit == "m") { tMul = 60000.0; } else if (tUnit == "h") { tMul = 3600000.0; } else { return false; } ms = (int64_t) (tV * tMul + 0.5); return true;}
bool validPathName(const std::string & name){ if (name.empty() || name.size() > 128) { return false; } for (char c : name) { if (! (isalnum((unsigned char) c) || c == '_' || c == '-' || c == '.' || c == '~')) { return false; } } return name != "." && name != "..";}
bool splitHostPort(const std::string & addr, std::string & host, uint16_t & port){ size_t tColon = addr.rfind(':'); if (tColon == std::string::npos) { return false; } host = addr.substr(0, tColon); int tPort = atoi(addr.c_str() + tColon + 1); if (tPort <= 0 || tPort > 65535) { return false; } port = (uint16_t) tPort; if (host.size() >= 2 && host.front() == '[' && host.back() == ']') { host = host.substr(1, host.size() - 2); } return true;}
std::string hideCredentials(const std::string & url){ size_t tScheme = url.find("://"); if (tScheme == std::string::npos) { return url; } size_t tHostStart = tScheme + 3; size_t tSlash = url.find('/', tHostStart); size_t tAt = url.rfind('@', tSlash == std::string::npos ? url.size() : tSlash); if (tAt == std::string::npos || tAt < tHostStart) { return url; } return url.substr(0, tHostStart) + url.substr(tAt + 1);}
static bool parsePathLine(const std::string & line, PathConf & pc, std::string & err){ std::istringstream tIn(line); std::vector<std::string> tTok; std::string t; while (tIn >> t) { tTok.push_back(t); } if (tTok.size() < 2) { err = "expected: name source [record=yes|no] [transport=tcp|udp]"; return false; } pc = PathConf(); pc.name = tTok[0]; pc.source = tTok[1]; if (! validPathName(pc.name)) { err = "invalid path name '" + pc.name + "'"; return false; } if (pc.source.compare(0, 7, "rtsp://") != 0) { err = "path " + pc.name + ": only rtsp:// sources are supported"; return false; } for (size_t i = 2; i < tTok.size(); i++) { size_t tEq = tTok[i].find('='); if (tEq == std::string::npos) { err = "path " + pc.name + ": bad option '" + tTok[i] + "'"; return false; } std::string k = tTok[i].substr(0, tEq), v = tTok[i].substr(tEq + 1); if (k == "record") { if (! parseBool(v, pc.record)) { err = "path " + pc.name + ": bad record value '" + v + "'"; return false; } } else if (k == "transport" || k == "rtspTransport") { if (v == "tcp") { pc.transport = RtspTransport::Tcp; } else if (v == "udp") { pc.transport = RtspTransport::Udp; } else { err = "path " + pc.name + ": transport must be tcp or udp"; return false; } } else { err = "path " + pc.name + ": unknown option '" + k + "'"; return false; } } return true;}
bool loadPathsFile(const std::string & file, std::vector<PathConf> & out, std::string & err){ std::ifstream tIn(file); if (! tIn) { err = "cannot open paths file " + file; return false; } out.clear(); std::string tLine; int tNo = 0; while (std::getline(tIn, tLine)) { tNo++; size_t tHash = tLine.find('#'); if (tHash != std::string::npos) { tLine = tLine.substr(0, tHash); } tLine = trim(tLine); if (tLine.empty()) { continue; } PathConf tPc; std::string tErr; if (! parsePathLine(tLine, tPc, tErr)) { err = file + ":" + std::to_string(tNo) + ": " + tErr; return false; } for (const PathConf & p : out) { if (p.name == tPc.name) { err = file + ":" + std::to_string(tNo) + ": duplicate path " + tPc.name; return false; } } out.push_back(tPc); } return true;}
bool savePathsFile(const std::string & file, const std::vector<PathConf> & paths, std::string & err){ std::string tTmp = file + ".tmp"; FILE * tF = fopen(tTmp.c_str(), "w"); if (tF == nullptr) { err = "cannot write " + tTmp; return false; } fprintf(tF, "# MediaMtx paths: name source [record=yes|no] [transport=tcp|udp]\n"); for (const PathConf & p : paths) { fprintf(tF, "%s %s record=%s transport=%s\n", p.name.c_str(), p.source.c_str(), p.record ? "yes" : "no", p.transport == RtspTransport::Udp ? "udp" : "tcp"); } if (fclose(tF) != 0 || rename(tTmp.c_str(), file.c_str()) != 0) { err = "cannot write " + file; return false; } return true;}
void Conf::mergeCmdPaths(std::vector<PathConf> & out) const{ // a path given on the command line replaces the one of the paths file
for (const PathConf & p : cmdPaths) { bool tFound = false; for (PathConf & q : out) { if (q.name == p.name) { q = p; tFound = true; } } if (! tFound) { out.push_back(p); } }}
void Conf::printUsage(const char * prog){ fprintf(stderr, "MediaMtx (C++): RTSP camera pull -> WebRTC (WHEP) + fMP4 recording\n" "usage: %s [options]\n" " --paths FILE paths file (name source [record=yes] [transport=tcp|udp]); SIGHUP reloads it\n" " --path NAME=URL[,record][,udp] add a path (repeatable)\n" " --logLevel debug|info|warn|error (info)\n" " --logFile FILE also log to FILE (e.g. mediamtx.log)\n" " --logStdout yes|no (yes)\n" " --readTimeout DUR source without data -> reconnect (10s)\n" " --sourceRetryPause DUR pause before reconnecting a source (5s)\n" " --apiAddress ADDR control API, empty to disable (127.0.0.1:9997)\n" " --webrtcAddress ADDR WHEP HTTP listener (:8889)\n" " --webrtcAllowOrigin ORIGIN CORS Access-Control-Allow-Origin (*)\n" " --webrtcICEServers LIST comma separated, e.g. stun:stun.l.google.com:19302\n" " --webrtcBindAddress IP ICE local address (all)\n" " --webrtcUDPPorts MIN-MAX ICE UDP port range (8189-8289)\n" " --recordPath PATTERN (./recordings/%%path/%%Y-%%m-%%d_%%H-%%M-%%S-%%f), .mp4 is added\n" " --recordSegmentDuration DUR (60s)\n" " --recordPartDuration DUR fragment written to disk every DUR (1s)\n" " DUR: 500ms, 10s, 1m, 1h\n", prog);}
bool Conf::load(int argc, char ** argv, std::string & err){ std::vector<PathConf> tCmdPaths; for (int i = 1; i < argc; i++) { std::string tOpt = argv[i]; std::string tVal; size_t tEq = tOpt.find('='); if (tOpt.compare(0, 2, "--") != 0) { err = "unknown argument " + tOpt; return false; } if (tOpt == "--help" || tOpt == "-h") { err = "help"; return false; } if (tEq != std::string::npos) { tVal = tOpt.substr(tEq + 1); tOpt = tOpt.substr(0, tEq); } else { if (i + 1 >= argc) { err = "missing value for " + tOpt; return false; } tVal = argv[++i]; } bool tOk = true; if (tOpt == "--paths") { pathsFile = tVal; } else if (tOpt == "--path") { // NAME=URL[,record][,udp]
size_t tE = tVal.find('='); if (tE == std::string::npos) { err = "--path expects NAME=URL[,record][,udp]"; return false; } std::string tLine = tVal.substr(0, tE) + " "; std::string tRest = tVal.substr(tE + 1); std::string tUrl = tRest; std::string tFlags; size_t tC = tRest.find(','); if (tC != std::string::npos) { tUrl = tRest.substr(0, tC); tFlags = tRest.substr(tC + 1); } tLine += tUrl; std::istringstream tF(tFlags); std::string tFl; while (std::getline(tF, tFl, ',')) { if (tFl == "record") { tLine += " record=yes"; } else if (tFl == "udp" || tFl == "tcp") { tLine += " transport=" + tFl; } else if (! tFl.empty()) { err = "--path: unknown flag " + tFl; return false; } } PathConf tPc; if (! parsePathLine(tLine, tPc, err)) { return false; } tCmdPaths.push_back(tPc); } else if (tOpt == "--logLevel") { logLevel = parseLogLevel(tVal, &tOk); } else if (tOpt == "--logFile") { logFile = tVal; } else if (tOpt == "--logStdout") { tOk = parseBool(tVal, logStdout); } else if (tOpt == "--readTimeout") { tOk = parseDurationMs(tVal, readTimeoutMs) && readTimeoutMs >= 1000; } else if (tOpt == "--sourceRetryPause") { tOk = parseDurationMs(tVal, sourceRetryPauseMs); } else if (tOpt == "--apiAddress") { apiAddress = tVal; } else if (tOpt == "--webrtcAddress") { webrtcAddress = tVal; } else if (tOpt == "--webrtcAllowOrigin") { webrtcAllowOrigin = tVal; } else if (tOpt == "--webrtcICEServers") { webrtcICEServers.clear(); std::istringstream tS(tVal); std::string tSrv; while (std::getline(tS, tSrv, ',')) { if (! trim(tSrv).empty()) { webrtcICEServers.push_back(trim(tSrv)); } } } else if (tOpt == "--webrtcBindAddress") { webrtcBindAddress = tVal; } else if (tOpt == "--webrtcUDPPorts") { int tMin = 0, tMax = 0; tOk = sscanf(tVal.c_str(), "%d-%d", &tMin, &tMax) == 2 && tMin > 0 && tMax <= 65535 && tMin <= tMax; if (tOk) { webrtcUDPPortMin = (uint16_t) tMin; webrtcUDPPortMax = (uint16_t) tMax; } } else if (tOpt == "--recordPath") { recordPath = tVal; tOk = tVal.find("%path") != std::string::npos; if (! tOk) { err = "--recordPath must contain %path"; return false; } } else if (tOpt == "--recordSegmentDuration") { tOk = parseDurationMs(tVal, recordSegmentDurationMs) && recordSegmentDurationMs >= 1000; } else if (tOpt == "--recordPartDuration") { tOk = parseDurationMs(tVal, recordPartDurationMs) && recordPartDurationMs >= 100; } else { err = "unknown option " + tOpt; return false; } if (! tOk) { err = "bad value '" + tVal + "' for " + tOpt; return false; } } std::string tHost; uint16_t tPort; if (! splitHostPort(webrtcAddress, tHost, tPort)) { err = "bad --webrtcAddress " + webrtcAddress; return false; } if (! apiAddress.empty() && ! splitHostPort(apiAddress, tHost, tPort)) { err = "bad --apiAddress " + apiAddress; return false; } paths.clear(); if (! pathsFile.empty()) { FILE * tF = fopen(pathsFile.c_str(), "r"); if (tF == nullptr) { // a missing file is created by the API on the first change
Logger::instance().log(LogLevel::Warn, "paths file %s does not exist yet", pathsFile.c_str()); } else { fclose(tF); if (! loadPathsFile(pathsFile, paths, err)) { return false; } } } cmdPaths = tCmdPaths; mergeCmdPaths(paths); return true;}
} // namespace mtx
|