 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 "fmp4Writer.h"
#include <cerrno>
#include <cstring>
#include <ctime>
#include <sys/stat.h>
#include "../codecs/h264/h264.h"
namespace mtx {
namespace {
// Box building: a box is written with a placeholder size that is patched when it ends
class BoxWriter{ public: Bytes buf;
void u8(uint32_t v) { buf.push_back((uint8_t) v); } void u16(uint32_t v) { u8(v >> 8); u8(v); } void u24(uint32_t v) { u8(v >> 16); u16(v); } void u32(uint32_t v) { u16(v >> 16); u16(v); } void u64(uint64_t v) { u32((uint32_t) (v >> 32)); u32((uint32_t) v); } void bytes(const Bytes & b) { buf.insert(buf.end(), b.begin(), b.end()); } void str(const char * s, size_t n) { buf.insert(buf.end(), (const uint8_t *) s, (const uint8_t *) s + n); } void zeros(size_t n) { buf.insert(buf.end(), n, 0); }
size_t begin(const char * type) { size_t tPos = buf.size(); u32(0); str(type, 4); return tPos; } size_t beginFull(const char * type, uint8_t version, uint32_t flags) { size_t tPos = begin(type); u8(version); u24(flags); return tPos; } void end(size_t pos) { uint32_t s = (uint32_t) (buf.size() - pos); buf[pos] = (uint8_t) (s >> 24); buf[pos + 1] = (uint8_t) (s >> 16); buf[pos + 2] = (uint8_t) (s >> 8); buf[pos + 3] = (uint8_t) s; } void patch32(size_t pos, uint32_t v) { buf[pos] = (uint8_t) (v >> 24); buf[pos + 1] = (uint8_t) (v >> 16); buf[pos + 2] = (uint8_t) (v >> 8); buf[pos + 3] = (uint8_t) v; } void matrix() { static const uint32_t m[9] = {0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000}; for (uint32_t v : m) { u32(v); } }};
const uint32_t TIMESCALE = 90000;const uint32_t TRACK_ID = 1;
Bytes buildInit(const Bytes & sps, const Bytes & pps, int width, int height){ BoxWriter w; size_t b = w.begin("ftyp"); w.str("iso6", 4); w.u32(1); w.str("iso6", 4); w.str("iso5", 4); w.str("mp41", 4); w.str("avc1", 4); w.end(b);
size_t moov = w.begin("moov"); { size_t mvhd = w.beginFull("mvhd", 0, 0); w.u32(0); // creation
w.u32(0); // modification
w.u32(1000); w.u32(0); // duration: unknown (fragmented)
w.u32(0x00010000); // rate
w.u16(0x0100); // volume
w.zeros(10); w.matrix(); w.zeros(24); w.u32(TRACK_ID + 1); w.end(mvhd);
size_t trak = w.begin("trak"); { size_t tkhd = w.beginFull("tkhd", 0, 3); w.u32(0); w.u32(0); w.u32(TRACK_ID); w.u32(0); w.u32(0); // duration
w.zeros(8); w.u16(0); // layer
w.u16(0); // alternate group
w.u16(0); // volume
w.u16(0); w.matrix(); w.u32((uint32_t) width << 16); w.u32((uint32_t) height << 16); w.end(tkhd);
size_t mdia = w.begin("mdia"); { size_t mdhd = w.beginFull("mdhd", 0, 0); w.u32(0); w.u32(0); w.u32(TIMESCALE); w.u32(0); w.u16(0x55c4); // "und"
w.u16(0); w.end(mdhd);
size_t hdlr = w.beginFull("hdlr", 0, 0); w.u32(0); w.str("vide", 4); w.zeros(12); w.str("VideoHandler", 13); w.end(hdlr);
size_t minf = w.begin("minf"); { size_t vmhd = w.beginFull("vmhd", 0, 1); w.zeros(8); w.end(vmhd);
size_t dinf = w.begin("dinf"); size_t dref = w.beginFull("dref", 0, 0); w.u32(1); size_t url = w.beginFull("url ", 0, 1); w.end(url); w.end(dref); w.end(dinf);
size_t stbl = w.begin("stbl"); { size_t stsd = w.beginFull("stsd", 0, 0); w.u32(1); size_t avc1 = w.begin("avc1"); w.zeros(6); w.u16(1); // data reference index
w.zeros(16); w.u16((uint32_t) width); w.u16((uint32_t) height); w.u32(0x00480000); // 72 dpi
w.u32(0x00480000); w.u32(0); w.u16(1); // frame count
w.zeros(32); // compressor name
w.u16(0x0018); // depth
w.u16(0xffff); // pre_defined = -1
size_t avcC = w.begin("avcC"); w.bytes(h264::buildAvcC(sps, pps)); w.end(avcC); w.end(avc1); w.end(stsd);
size_t stts = w.beginFull("stts", 0, 0); w.u32(0); w.end(stts); size_t stsc = w.beginFull("stsc", 0, 0); w.u32(0); w.end(stsc); size_t stsz = w.beginFull("stsz", 0, 0); w.u32(0); w.u32(0); w.end(stsz); size_t stco = w.beginFull("stco", 0, 0); w.u32(0); w.end(stco); } w.end(stbl); } w.end(minf); } w.end(mdia); } w.end(trak);
size_t mvex = w.begin("mvex"); size_t trex = w.beginFull("trex", 0, 0); w.u32(TRACK_ID); w.u32(1); // default sample description
w.u32(0); w.u32(0); w.u32(0); w.end(trex); w.end(mvex); } w.end(moov); return w.buf;}
} // namespace
bool mkdirAll(const std::string & dir){ if (dir.empty()) { return true; } std::string tCur; size_t tPos = 0; while (tPos != std::string::npos) { tPos = dir.find('/', tPos + 1); tCur = dir.substr(0, tPos); if (tCur.empty()) { continue; } if (mkdir(tCur.c_str(), 0755) != 0 && errno != EEXIST) { return false; } } return true;}
std::string expandRecordPath(const std::string & pattern, const std::string & pathName, int64_t timeUs){ time_t tSec = (time_t) (timeUs / 1000000); struct tm tTm; localtime_r(&tSec, &tTm); std::string tOut; char tB[32]; for (size_t i = 0; i < pattern.size(); i++) { if (pattern[i] != '%' || i + 1 >= pattern.size()) { tOut.push_back(pattern[i]); continue; } if (pattern.compare(i, 5, "%path") == 0) { tOut += pathName; i += 4; continue; } char c = pattern[++i]; switch (c) { case 'Y': snprintf(tB, sizeof(tB), "%04d", tTm.tm_year + 1900); break; case 'm': snprintf(tB, sizeof(tB), "%02d", tTm.tm_mon + 1); break; case 'd': snprintf(tB, sizeof(tB), "%02d", tTm.tm_mday); break; case 'H': snprintf(tB, sizeof(tB), "%02d", tTm.tm_hour); break; case 'M': snprintf(tB, sizeof(tB), "%02d", tTm.tm_min); break; case 'S': snprintf(tB, sizeof(tB), "%02d", tTm.tm_sec); break; case 'f': snprintf(tB, sizeof(tB), "%06d", (int) (timeUs % 1000000)); break; case 's': snprintf(tB, sizeof(tB), "%lld", (long long) tSec); break; default: snprintf(tB, sizeof(tB), "%%%c", c); break; } tOut += tB; } return tOut + ".mp4";}
bool Fmp4Writer::open(const std::string & file, const Bytes & sps, const Bytes & pps, int width, int height, std::string & err){ close(); size_t tSlash = file.rfind('/'); if (tSlash != std::string::npos && ! mkdirAll(file.substr(0, tSlash))) { err = "cannot create the directory of " + file + ": " + strerror(errno); return false; } m_pFile = fopen(file.c_str(), "wb"); if (m_pFile == nullptr) { err = "cannot create " + file + ": " + strerror(errno); return false; } m_sFile = file; m_nSequence = 0; m_vPending.clear(); Bytes tInit = buildInit(sps, pps, width, height); if (fwrite(tInit.data(), 1, tInit.size(), m_pFile) != tInit.size() || fflush(m_pFile) != 0) { err = "write error on " + file + ": " + strerror(errno); fclose(m_pFile); m_pFile = nullptr; return false; } return true;}
void Fmp4Writer::addSample(int64_t dts, const UnitPtr & unit){ Sample s; s.dts = dts; s.idr = unit->idr; s.data = h264::toAvcc(unit->nalus); m_vPending.push_back(std::move(s));}
int64_t Fmp4Writer::pendingSpan() const{ if (m_vPending.size() < 2) { return 0; } return m_vPending.back().dts - m_vPending.front().dts;}
bool Fmp4Writer::flushFragment(int64_t nextDts, bool final, std::string & err){ if (m_pFile == nullptr || m_vPending.empty()) { return true; } // The duration of the last sample is nextDts - its dts (the recorder flushes before adding the next
// unit); on the final flush of a segment it is the previous duration.
size_t tCount = m_vPending.size();
BoxWriter w; size_t moof = w.begin("moof"); size_t mfhd = w.beginFull("mfhd", 0, 0); w.u32(++m_nSequence); w.end(mfhd); size_t traf = w.begin("traf"); size_t tfhd = w.beginFull("tfhd", 0, 0x020000); // default-base-is-moof
w.u32(TRACK_ID); w.end(tfhd); size_t tfdt = w.beginFull("tfdt", 1, 0); w.u64((uint64_t) (m_vPending.front().dts < 0 ? 0 : m_vPending.front().dts)); w.end(tfdt); size_t trun = w.beginFull("trun", 0, 0x000001 | 0x000100 | 0x000200 | 0x000400); w.u32((uint32_t) tCount); size_t tDataOffsetPos = w.buf.size(); w.u32(0); size_t tMdatSize = 0; for (size_t i = 0; i < tCount; i++) { int64_t tDur; if (i + 1 < m_vPending.size()) { tDur = m_vPending[i + 1].dts - m_vPending[i].dts; } else { tDur = final ? m_nLastDuration : nextDts - m_vPending[i].dts; } if (tDur <= 0 || tDur > 10 * (int64_t) TIMESCALE) { tDur = m_nLastDuration; // timestamp jump or B-frames: keep the timeline going
} m_nLastDuration = tDur; w.u32((uint32_t) tDur); w.u32((uint32_t) m_vPending[i].data.size()); w.u32(m_vPending[i].idr ? 0x02000000 : 0x01010000); tMdatSize += m_vPending[i].data.size(); } w.end(trun); w.end(traf); w.end(moof); w.patch32(tDataOffsetPos, (uint32_t) (w.buf.size() + 8)); // from the start of moof to the mdat payload
w.u32((uint32_t) (tMdatSize + 8)); w.str("mdat", 4); bool tOk = fwrite(w.buf.data(), 1, w.buf.size(), m_pFile) == w.buf.size(); for (size_t i = 0; i < tCount && tOk; i++) { tOk = fwrite(m_vPending[i].data.data(), 1, m_vPending[i].data.size(), m_pFile) == m_vPending[i].data.size(); } tOk = tOk && fflush(m_pFile) == 0; m_vPending.erase(m_vPending.begin(), m_vPending.begin() + tCount); if (! tOk) { err = "write error on " + m_sFile + ": " + strerror(errno); return false; } return true;}
void Fmp4Writer::close(){ if (m_pFile != nullptr) { std::string tErr; flushFragment(0, true, tErr); fclose(m_pFile); m_pFile = nullptr; } m_vPending.clear();}
} // namespace mtx
|