 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
1 day ago |
|
#include "webrtcServer.h"
#include <random>
namespace mtx {
namespace {
const char * PLAYER_PAGE = R"HTML(<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>MediaMtx</title><style>html,body{margin:0;height:100%;background:#000}video{width:100%;height:100%;object-fit:contain}#m{position:absolute;top:8px;left:8px;color:#fff;font:14px sans-serif}</style></head><body><video id="v" autoplay muted playsinline></video><div id="m"></div><script>const msg = (t) => { document.getElementById('m').textContent = t; };async function start() { const pc = new RTCPeerConnection(); pc.addTransceiver('video', { direction: 'recvonly' }); pc.ontrack = (e) => { document.getElementById('v').srcObject = e.streams[0] || new MediaStream([e.track]); }; pc.onconnectionstatechange = () => { if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') { msg('reconnecting...'); pc.close(); setTimeout(start, 2000); } else if (pc.connectionState === 'connected') { msg(''); } }; await pc.setLocalDescription(await pc.createOffer()); await new Promise((r) => { if (pc.iceGatheringState === 'complete') r(); else { pc.onicegatheringstatechange = () => { if (pc.iceGatheringState === 'complete') r(); }; setTimeout(r, 2000); } }); const res = await fetch(new URL('whep', window.location.href.replace(/\/?$/, '/')), { method: 'POST', headers: { 'Content-Type': 'application/sdp' }, body: pc.localDescription.sdp }); if (res.status !== 201) { msg('error: ' + res.status + ' ' + await res.text()); pc.close(); setTimeout(start, 2000); return; } await pc.setRemoteDescription({ type: 'answer', sdp: await res.text() });}start();</script></body></html>)HTML";
std::string newSecret(){ static std::mutex s_mutex; static std::random_device s_rd; static std::mt19937_64 s_gen(((uint64_t) s_rd() << 32) ^ s_rd()); std::lock_guard<std::mutex> lock(s_mutex); char tB[40]; snprintf(tB, sizeof(tB), "%016llx%016llx", (unsigned long long) s_gen(), (unsigned long long) s_gen()); return tB;}
std::vector<std::string> splitPath(const std::string & p){ std::vector<std::string> tOut; size_t i = 0; while (i < p.size()) { size_t j = p.find('/', i); if (j == std::string::npos) { j = p.size(); } if (j > i) { tOut.push_back(p.substr(i, j - i)); } i = j + 1; } return tOut;}
} // namespace
WebrtcServer::WebrtcServer(const Conf & global, PathManager * paths) : LogParent("[WebRTC] "), m_global(global), m_pPaths(paths), m_http(this) {}
WebrtcServer::~WebrtcServer(){ stop();}
bool WebrtcServer::start(std::string & err){ rtc::InitLogger(rtc::LogLevel::Warning, [](rtc::LogLevel level, std::string message) { Logger::instance().log(level <= rtc::LogLevel::Error ? LogLevel::Error : (level == rtc::LogLevel::Warning ? LogLevel::Warn : LogLevel::Debug), "[WebRTC] [libdatachannel] %s", message.c_str()); }); if (! m_http.start(m_global.webrtcAddress, [this](const HttpRequest & q, HttpResponse & r) { handle(q, r); }, err)) { return false; } m_bRun = true; m_janitor = std::thread(&WebrtcServer::janitor, this); log(LogLevel::Info, "listener opened on %s (HTTP)", m_global.webrtcAddress.c_str()); return true;}
void WebrtcServer::stop(){ { std::lock_guard<std::mutex> lock(m_stopMutex); if (! m_bRun) { return; } m_bRun = false; } m_stopCond.notify_all(); if (m_janitor.joinable()) { m_janitor.join(); } m_http.stop(); std::map<std::string, std::shared_ptr<WebrtcSession>> tAll; { std::lock_guard<std::mutex> lock(m_mutex); tAll.swap(m_sessions); } for (auto & s : tAll) { s.second->close(); } rtc::Cleanup();}
size_t WebrtcServer::sessionCount() const{ std::lock_guard<std::mutex> lock(m_mutex); return m_sessions.size();}
void WebrtcServer::janitor(){ while (true) { { std::unique_lock<std::mutex> lock(m_stopMutex); m_stopCond.wait_for(lock, std::chrono::seconds(1), [this] { return ! m_bRun; }); if (! m_bRun) { return; } } std::vector<std::shared_ptr<WebrtcSession>> tClose; int64_t tNow = nowMs(); { std::lock_guard<std::mutex> lock(m_mutex); for (auto it = m_sessions.begin(); it != m_sessions.end();) { if (it->second->isClosing() || it->second->connectTimedOut(tNow)) { tClose.push_back(it->second); it = m_sessions.erase(it); } else { ++it; } } } for (auto & s : tClose) { s->close(); } }}
void WebrtcServer::handle(const HttpRequest & req, HttpResponse & res){ res.setHeader("Access-Control-Allow-Origin", m_global.webrtcAllowOrigin); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("Access-Control-Expose-Headers", "ETag, ID, Accept-Patch, Link, Location"); if (req.method == "OPTIONS") { res.status = 204; res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PATCH, DELETE"); res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, If-Match"); return; } std::vector<std::string> tParts = splitPath(req.path); // GET /<path> or /<path>/ -> player page
if (req.method == "GET" && tParts.size() == 1) { if (req.path.back() != '/') { res.status = 301; res.setHeader("Location", req.path + "/"); return; } res.status = 200; res.setHeader("Content-Type", "text/html; charset=utf-8"); res.body = PLAYER_PAGE; return; } if (tParts.size() < 2 || tParts[1] != "whep") { res.status = 404; res.body = "not found"; return; } const std::string & tPathName = tParts[0]; if (tParts.size() == 2) { if (req.method != "POST") { res.status = 405; return; } std::string tType = req.header("content-type"); if (tType.compare(0, 15, "application/sdp") != 0) { res.status = 415; res.body = "invalid Content-Type"; return; } std::shared_ptr<Path> tPath = m_pPaths->find(tPathName); if (! tPath) { res.status = 404; res.body = "path '" + tPathName + "' is not configured"; log(LogLevel::Info, "%s: path '%s' is not configured", req.remoteAddr.c_str(), tPathName.c_str()); return; } std::string tSecret = newSecret(); auto tSession = std::make_shared<WebrtcSession>(tSecret, tPath, m_global, req.remoteAddr); std::string tAnswer, tErr; int tStatus = 500; if (! tSession->create(req.body, tAnswer, tStatus, tErr)) { tSession->log(LogLevel::Info, "closed: %s", tErr.c_str()); tSession->close(); res.status = tStatus; res.body = tErr; return; } { std::lock_guard<std::mutex> lock(m_mutex); m_sessions[tSecret] = tSession; } res.status = 201; res.setHeader("Content-Type", "application/sdp"); res.setHeader("ETag", "*"); res.setHeader("ID", tSecret); res.setHeader("Accept-Patch", "application/trickle-ice-sdpfrag"); res.setHeader("Location", "/" + tPathName + "/whep/" + tSecret); for (const std::string & s : m_global.webrtcICEServers) { res.setHeader("Link", "<" + s + ">; rel=\"ice-server\""); } res.body = tAnswer; return; } // /<path>/whep/<secret>
std::shared_ptr<WebrtcSession> tSession; { std::lock_guard<std::mutex> lock(m_mutex); auto it = m_sessions.find(tParts[2]); if (it != m_sessions.end() && it->second->pathName() == tPathName) { tSession = it->second; } } if (! tSession) { res.status = 404; res.body = "session not found"; return; } if (req.method == "PATCH") { std::string tErr; if (! tSession->addRemoteCandidates(req.body, tErr)) { res.status = 400; res.body = tErr; return; } res.status = 204; } else if (req.method == "DELETE") { { std::lock_guard<std::mutex> lock(m_mutex); m_sessions.erase(tParts[2]); } tSession->log(LogLevel::Info, "deleted by the client"); tSession->close(); res.status = 200; } else { res.status = 405; }}
} // namespace mtx
|