Browse Source

Merge remote-tracking branch 'origin/feature/mediamtx-cpp' into feature/embed-video-webrtc

pull/28/head
Claude 5 hours ago
parent
commit
8f1031ffbf
Failed to extract signature
  1. 3
      Projects/MediaMtx/.gitignore
  2. 21
      Projects/MediaMtx/LICENSE.mediamtx
  3. 113
      Projects/MediaMtx/README.md
  4. 322
      Projects/MediaMtx/internal/api/api.cpp
  5. 48
      Projects/MediaMtx/internal/api/api.h
  6. 360
      Projects/MediaMtx/internal/codecs/h264/h264.cpp
  7. 53
      Projects/MediaMtx/internal/codecs/h264/h264.h
  8. 515
      Projects/MediaMtx/internal/conf/conf.cpp
  9. 84
      Projects/MediaMtx/internal/conf/conf.h
  10. 131
      Projects/MediaMtx/internal/core/core.cpp
  11. 39
      Projects/MediaMtx/internal/core/core.h
  12. 119
      Projects/MediaMtx/internal/core/path.cpp
  13. 75
      Projects/MediaMtx/internal/core/path.h
  14. 110
      Projects/MediaMtx/internal/core/pathManager.cpp
  15. 37
      Projects/MediaMtx/internal/core/pathManager.h
  16. 121
      Projects/MediaMtx/internal/logger/logger.cpp
  17. 53
      Projects/MediaMtx/internal/logger/logger.h
  18. 393
      Projects/MediaMtx/internal/protocols/httpp/httpServer.cpp
  19. 74
      Projects/MediaMtx/internal/protocols/httpp/httpServer.h
  20. 415
      Projects/MediaMtx/internal/recorder/fmp4Writer.cpp
  21. 58
      Projects/MediaMtx/internal/recorder/fmp4Writer.h
  22. 120
      Projects/MediaMtx/internal/recorder/recorder.cpp
  23. 42
      Projects/MediaMtx/internal/recorder/recorder.h
  24. 349
      Projects/MediaMtx/internal/servers/webrtc/session.cpp
  25. 74
      Projects/MediaMtx/internal/servers/webrtc/session.h
  26. 285
      Projects/MediaMtx/internal/servers/webrtc/webrtcServer.cpp
  27. 49
      Projects/MediaMtx/internal/servers/webrtc/webrtcServer.h
  28. 543
      Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.cpp
  29. 63
      Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.h
  30. 160
      Projects/MediaMtx/internal/stream/stream.cpp
  31. 98
      Projects/MediaMtx/internal/stream/stream.h
  32. 34
      Projects/MediaMtx/internal/unit/unit.h
  33. 14
      Projects/MediaMtx/main.cpp
  34. 70
      Projects/MediaMtx/makefile
  35. 6
      Projects/MediaMtx/mediamtx.paths.example
  36. 15
      Projects/MediaMtx/mediamtx.service.example

3
Projects/MediaMtx/.gitignore

@ -0,0 +1,3 @@
Debug/
Release/
Asan/

21
Projects/MediaMtx/LICENSE.mediamtx

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 aler9
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

113
Projects/MediaMtx/README.md

@ -0,0 +1,113 @@
# MediaMtx (C++)
A C++ replacement for the parts of [MediaMTX](https://github.com/bluenviron/mediamtx) that la_mojo uses:
* **RTSP pull** of the camera streams (live555), H264 video, TCP or UDP, automatic reconnect
* **WebRTC / WHEP** playback in the browser on port 8889 (libdatachannel) - the same URLs as MediaMTX:
`POST http://<host>:8889/stream_N/whep`, so `mojo_dashboard.js` works unchanged
* **Recording** as fragmented MP4 segments (the camera's H264 as it is, no transcoding) that a browser
plays with `<video src=...>`; same file names as MediaMTX: `recordings/stream_N/2026-12-02_16-58-35-953775.mp4`
* a **control API** with the MediaMTX v3 URLs for paths (`/v3/paths/list`, `/v3/config/paths/add/...`)
Not included (MediaMTX has them): RTSP/RTMP/HLS/SRT servers, publishing, audio, H265, authentication,
playback server, metrics. The source keeps MediaMTX's module layout, so they can be added the same way.
MediaMTX is MIT licensed (see `LICENSE.mediamtx`); this is a rewrite of its design, not a copy of its code.
## Layout
| MediaMtx (C++) | MediaMTX (Go) |
|-----------------------------------------|--------------------------------|
| `main.cpp` | `main.go` |
| `internal/core/core.*` | `internal/core/core.go` |
| `internal/core/pathManager.*`, `path.*` | `internal/core/path_manager.go`, `path.go` |
| `internal/conf/conf.*` | `internal/conf` |
| `internal/logger/logger.*` | `internal/logger` |
| `internal/stream/stream.*` | `internal/stream` |
| `internal/unit/unit.h` | `internal/unit` |
| `internal/staticsources/rtsp/rtspSource.*` | `internal/staticsources/rtsp` |
| `internal/servers/webrtc/*` | `internal/servers/webrtc` |
| `internal/recorder/*` | `internal/recorder` |
| `internal/api/api.*` | `internal/api` |
| `internal/protocols/httpp/httpServer.*` | `internal/protocols/httpp` |
| `internal/codecs/h264/h264.*` | `mediacommon/pkg/codecs/h264` |
Data flow: `RtspSource` -> `Path` -> `Stream` -> readers (`WebrtcSession`, `Recorder`). Every reader has
its own queue and thread (`AsyncReader`): a slow browser or disk never stalls the camera or the others;
an overflowing reader drops units and continues at the next IDR.
## Build
Dependencies:
* live555 - the same as for la_mojo (`pkg-config live555`); old (`char volatile`) and new
(`std::atomic_char`) event loop variables both build
* libdatachannel >= 0.20 (not packaged in Ubuntu 24.04):
```
git clone --branch v0.22.6 https://github.com/paullouisageneau/libdatachannel
cd libdatachannel && git submodule update --init --depth 1 deps/plog deps/libjuice
sudo apt install libsrtp2-dev libusrsctp-dev libssl-dev cmake
cmake -B build -DCMAKE_BUILD_TYPE=Release -DUSE_SYSTEM_SRTP=ON -DUSE_SYSTEM_USRSCTP=ON -DNO_EXAMPLES=ON -DNO_TESTS=ON -DNO_WEBSOCKET=ON
cmake --build build -j8 && sudo cmake --install build && sudo ldconfig
```
* OpenSSL
* JSON: JsonCpp of dr_frucht (`lib/include/json`, `lib/data/json`), compiled in by the makefile
```
make # Release/mediamtx
make CFG=Debug # Debug/mediamtx
```
Other library locations: `make LIVE555_CFLAGS=... LIVE555_LIBS=... DATACHANNEL_CFLAGS=-I... DATACHANNEL_LIBS="-L... -ldatachannel"`
## Run
No `mediamtx.yml`. Global settings are command line options (MediaMTX names), the streams are in a
paths file:
```
# name source options
stream_3 rtsp://user:pass@10.0.0.5:554/stream1 record=yes transport=tcp
stream_4 rtsp://10.0.0.6/live record=no transport=udp
```
```
mediamtx --paths /srv/etc/mediamtx.paths --logFile mediamtx.log \
--recordPath ./recordings/%path/%Y-%m-%d_%H-%M-%S-%f --recordSegmentDuration 60s
```
* `kill -HUP <pid>` reloads the paths file: only added / removed / changed paths restart
* the API changes paths at once and writes the paths file:
```
curl -X POST -d '{"source":"rtsp://10.0.0.5/s1","record":true}' http://127.0.0.1:9997/v3/config/paths/add/stream_3
curl -X PATCH -d '{"record":false}' http://127.0.0.1:9997/v3/config/paths/patch/stream_3
curl -X DELETE http://127.0.0.1:9997/v3/config/paths/delete/stream_3
curl http://127.0.0.1:9997/v3/paths/list
```
* `http://<host>:8889/stream_3/` is a small player page
* `mediamtx --help` lists all options (WebRTC ICE servers, UDP port range, timeouts, ...)
Log lines have the MediaMTX format that `kernelHelperMediaMTX` parses, e.g.
```
2026/12/02 17:00:30 INF [path stream_3] [RTSP source] ready: 1 track (H264)
2026/12/02 17:00:30 INF [path stream_3] stream is available and online, 1 track (H264 640x360)
2026/12/02 17:00:20 ERR [path stream_3] [RTSP source] no data for 10 s
```
## Network
* WebRTC media uses UDP ports 8189-8289 (`--webrtcUDPPorts`); open them like 8889/tcp.
* Behind NAT give a STUN server (`--webrtcICEServers stun:stun.l.google.com:19302`), so the answer
carries the public address.
## Tested
With a GStreamer RTSP test camera (H264 640x360, 25 fps) and Chromium:
* WHEP with the dashboard's code (offer without trickle) and with the player page: video plays;
DELETE ends a session; a closed browser is detected (ICE timeout, ~25 s)
* camera down: `no data for 10 s`, sessions closed, recording closed; camera back: reconnect, recording
continues, the player page reconnects
* recordings: every segment starts with an IDR, exact length (10 s = 250 frames), decodes with ffmpeg
and plays to the end in Chromium, also the segment cut by a shutdown
* API add / patch / delete, paths file written, SIGHUP reload
* AddressSanitizer + UBSan build through all of the above: no reports

322
Projects/MediaMtx/internal/api/api.cpp

@ -0,0 +1,322 @@
#include "api.h"
#include <ctime>
#include <memory>
#include <sstream>
#include <json/json.h> // JsonCpp of dr_frucht (lib/include/json, lib/data/json)
namespace mtx {
namespace {
std::string isoTime(int64_t us)
{
if (us <= 0)
{
return std::string();
}
time_t tSec = (time_t) (us / 1000000);
struct tm tTm;
gmtime_r(&tSec, &tTm);
char tB[40];
strftime(tB, sizeof(tB), "%Y-%m-%dT%H:%M:%SZ", &tTm);
return tB;
}
std::string toText(const Json::Value & v)
{
Json::StreamWriterBuilder tB;
tB["indentation"] = "";
return Json::writeString(tB, v);
}
bool parseJson(const std::string & text, Json::Value & out, std::string & err)
{
Json::CharReaderBuilder tB;
std::unique_ptr<Json::CharReader> tR(tB.newCharReader());
return tR->parse(text.data(), text.data() + text.size(), &out, &err);
}
Json::Value pathConfJson(const PathConf & p)
{
Json::Value j(Json::objectValue);
j["name"] = p.name;
j["source"] = p.source;
j["record"] = p.record;
j["rtspTransport"] = p.transport == RtspTransport::Udp ? "udp" : "tcp";
return j;
}
Json::Value pathInfoJson(const PathInfo & i)
{
Json::Value j(Json::objectValue);
j["name"] = i.name;
j["confName"] = i.name;
j["source"]["type"] = "rtspSource";
j["source"]["id"] = "";
j["ready"] = i.ready;
j["readyTime"] = i.ready ? Json::Value(isoTime(i.readySinceUs)) : Json::Value(Json::nullValue);
j["tracks"] = Json::Value(Json::arrayValue);
if (i.ready)
{
j["tracks"].append("H264");
j["width"] = i.desc.width;
j["height"] = i.desc.height;
}
j["bytesReceived"] = (Json::UInt64) i.bytesReceived;
j["record"] = i.record;
j["readers"] = (Json::UInt64) i.readers;
return j;
}
Json::Value listJson(const Json::Value & items)
{
Json::Value j(Json::objectValue);
j["itemCount"] = items.size();
j["pageCount"] = 1;
j["items"] = items;
return j;
}
void error(HttpResponse & res, int status, const std::string & msg)
{
Json::Value j(Json::objectValue);
j["error"] = msg;
res.status = status;
res.setHeader("Content-Type", "application/json");
res.body = toText(j);
}
void ok(HttpResponse & res, const Json::Value & body)
{
res.status = 200;
res.setHeader("Content-Type", "application/json");
res.body = toText(body);
}
// fields of a path configuration from JSON into pc
bool applyFields(const Json::Value & j, PathConf & pc, std::string & err)
{
if (! j.isObject())
{
err = "body must be a JSON object";
return false;
}
for (const std::string & k : j.getMemberNames())
{
const Json::Value & v = j[k];
if (k == "source" && v.isString())
{
pc.source = v.asString();
}
else if (k == "record" && v.isBool())
{
pc.record = v.asBool();
}
else if (k == "rtspTransport" && v.isString())
{
std::string t = v.asString();
if (t == "tcp" || t == "automatic")
{
pc.transport = RtspTransport::Tcp;
}
else if (t == "udp")
{
pc.transport = RtspTransport::Udp;
}
else
{
err = "rtspTransport must be tcp or udp";
return false;
}
}
else if (k == "name")
{
continue;
}
else
{
err = "unsupported field '" + k + "'";
return false;
}
}
if (pc.source.compare(0, 7, "rtsp://") != 0)
{
err = "source must be an rtsp:// URL";
return false;
}
return true;
}
} // namespace
Api::Api(const Conf & global, PathManager * paths, ApplyFn apply) : LogParent("[API] "), m_global(global), m_pPaths(paths), m_apply(std::move(apply)), m_http(this) {}
Api::~Api()
{
stop();
}
bool Api::start(std::string & err)
{
if (! m_http.start(m_global.apiAddress, [this](const HttpRequest & q, HttpResponse & r) { handle(q, r); }, err))
{
return false;
}
log(LogLevel::Info, "listener opened on %s", m_global.apiAddress.c_str());
return true;
}
void Api::stop()
{
m_http.stop();
}
void Api::handle(const HttpRequest & req, HttpResponse & res)
{
const std::string & p = req.path;
auto starts = [&p](const char * prefix) { return p.compare(0, strlen(prefix), prefix) == 0; };
if (req.method == "GET" && p == "/v3/paths/list")
{
Json::Value tItems(Json::arrayValue);
for (const PathInfo & i : m_pPaths->list())
{
tItems.append(pathInfoJson(i));
}
ok(res, listJson(tItems));
return;
}
if (req.method == "GET" && starts("/v3/paths/get/"))
{
auto tPath = m_pPaths->find(p.substr(strlen("/v3/paths/get/")));
if (! tPath)
{
error(res, 404, "path not found");
return;
}
ok(res, pathInfoJson(tPath->info()));
return;
}
if (req.method == "GET" && p == "/v3/config/paths/list")
{
Json::Value tItems(Json::arrayValue);
for (const PathConf & c : m_pPaths->confs())
{
tItems.append(pathConfJson(c));
}
ok(res, listJson(tItems));
return;
}
if (req.method == "GET" && starts("/v3/config/paths/get/"))
{
auto tPath = m_pPaths->find(p.substr(strlen("/v3/config/paths/get/")));
if (! tPath)
{
error(res, 404, "path not found");
return;
}
ok(res, pathConfJson(tPath->conf()));
return;
}
// changes
std::string tName;
enum { NONE, ADD, PATCH, REPLACE, DEL } tOp = NONE;
if (req.method == "POST" && starts("/v3/config/paths/add/"))
{
tOp = ADD;
tName = p.substr(strlen("/v3/config/paths/add/"));
}
else if (req.method == "PATCH" && starts("/v3/config/paths/patch/"))
{
tOp = PATCH;
tName = p.substr(strlen("/v3/config/paths/patch/"));
}
else if (req.method == "POST" && starts("/v3/config/paths/replace/"))
{
tOp = REPLACE;
tName = p.substr(strlen("/v3/config/paths/replace/"));
}
else if (req.method == "DELETE" && starts("/v3/config/paths/delete/"))
{
tOp = DEL;
tName = p.substr(strlen("/v3/config/paths/delete/"));
}
if (tOp == NONE)
{
error(res, 404, "not found");
return;
}
if (! validPathName(tName))
{
error(res, 400, "invalid path name");
return;
}
std::vector<PathConf> tConfs = m_pPaths->confs();
auto tIt = std::find_if(tConfs.begin(), tConfs.end(), [&tName](const PathConf & c) { return c.name == tName; });
Json::Value tBody(Json::objectValue);
if (tOp != DEL && ! req.body.empty())
{
std::string tParseErr;
if (! parseJson(req.body, tBody, tParseErr))
{
error(res, 400, "invalid JSON: " + tParseErr);
return;
}
}
std::string tErr;
if (tOp == ADD)
{
if (tIt != tConfs.end())
{
error(res, 400, "path already exists");
return;
}
PathConf tPc;
tPc.name = tName;
if (! applyFields(tBody, tPc, tErr))
{
error(res, 400, tErr);
return;
}
tConfs.push_back(tPc);
}
else
{
if (tIt == tConfs.end())
{
error(res, 404, "path not found");
return;
}
if (tOp == DEL)
{
tConfs.erase(tIt);
}
else
{
PathConf tPc;
if (tOp == PATCH)
{
tPc = *tIt;
}
tPc.name = tName;
if (! applyFields(tBody, tPc, tErr))
{
error(res, 400, tErr);
return;
}
*tIt = tPc;
}
}
if (! m_apply(tConfs, tErr))
{
error(res, 500, tErr);
return;
}
res.status = 200;
}
} // namespace mtx

48
Projects/MediaMtx/internal/api/api.h

@ -0,0 +1,48 @@
/*
MediaMtx (C++) - control API (MediaMTX: internal/api, the same v3 URLs for the parts that exist here)
GET /v3/paths/list paths with their state
GET /v3/paths/get/{name}
GET /v3/config/paths/list path configurations
GET /v3/config/paths/get/{name}
POST /v3/config/paths/add/{name} {"source":"rtsp://...","record":true,"rtspTransport":"tcp"}
PATCH /v3/config/paths/patch/{name} the same fields, only those given are changed
POST /v3/config/paths/replace/{name}
DELETE /v3/config/paths/delete/{name}
A change is applied at once (only the changed path restarts) and saved to the paths file.
*/
#pragma once
#include <functional>
#include <string>
#include <vector>
#include "../conf/conf.h"
#include "../core/pathManager.h"
#include "../protocols/httpp/httpServer.h"
namespace mtx {
class Api : public LogParent
{
public:
// applyConfs: replaces the path list (validated), returns false + err on failure
typedef std::function<bool(const std::vector<PathConf> &, std::string &)> ApplyFn;
Api(const Conf & global, PathManager * paths, ApplyFn apply);
~Api();
bool start(std::string & err);
void stop();
private:
void handle(const HttpRequest & req, HttpResponse & res);
Conf m_global;
PathManager * m_pPaths;
ApplyFn m_apply;
HttpServer m_http;
};
} // namespace mtx

360
Projects/MediaMtx/internal/codecs/h264/h264.cpp

@ -0,0 +1,360 @@
#include "h264.h"
#include <cstdio>
#include <cstring>
namespace mtx {
namespace h264 {
namespace {
// Exp-Golomb bit reader over an RBSP (emulation prevention bytes removed)
class BitReader
{
public:
explicit BitReader(const Bytes & d) : m_d(d) {}
bool bit(uint32_t & v)
{
if (m_pos >= m_d.size() * 8)
{
return false;
}
v = (m_d[m_pos >> 3] >> (7 - (m_pos & 7))) & 1;
m_pos++;
return true;
}
bool bits(int n, uint32_t & v)
{
v = 0;
for (int i = 0; i < n; i++)
{
uint32_t b;
if (! bit(b))
{
return false;
}
v = (v << 1) | b;
}
return true;
}
bool ue(uint32_t & v)
{
int tZeros = 0;
uint32_t b = 0;
while (true)
{
if (! bit(b))
{
return false;
}
if (b)
{
break;
}
if (++tZeros > 31)
{
return false;
}
}
uint32_t tRest = 0;
if (! bits(tZeros, tRest))
{
return false;
}
v = ((1u << tZeros) - 1) + tRest;
return true;
}
bool se(int32_t & v)
{
uint32_t u;
if (! ue(u))
{
return false;
}
v = (u & 1) ? (int32_t) ((u + 1) / 2) : -(int32_t) (u / 2);
return true;
}
private:
const Bytes & m_d;
size_t m_pos = 0;
};
Bytes rbsp(const Bytes & nal)
{
Bytes tOut;
tOut.reserve(nal.size());
int tZeros = 0;
for (size_t i = 0; i < nal.size(); i++)
{
if (tZeros >= 2 && nal[i] == 3)
{
tZeros = 0;
continue;
}
tZeros = (nal[i] == 0) ? tZeros + 1 : 0;
tOut.push_back(nal[i]);
}
return tOut;
}
bool skipScalingList(BitReader & r, int size)
{
int32_t tLast = 8, tNext = 8;
for (int j = 0; j < size; j++)
{
if (tNext != 0)
{
int32_t tDelta;
if (! r.se(tDelta))
{
return false;
}
tNext = (tLast + tDelta + 256) % 256;
}
tLast = (tNext == 0) ? tLast : tNext;
}
return true;
}
} // namespace
bool parseSps(const Bytes & sps, SpsInfo & info)
{
if (sps.size() < 4 || naluType(sps) != NALU_SPS)
{
return false;
}
Bytes tR = rbsp(sps);
BitReader r(tR);
uint32_t v, tForbidden;
r.bits(8, tForbidden); // NAL header
uint32_t tProfile, tConstr, tLevel;
if (! r.bits(8, tProfile) || ! r.bits(8, tConstr) || ! r.bits(8, tLevel) || ! r.ue(v))
{
return false;
}
info.profileIdc = (int) tProfile;
info.constraints = (int) tConstr;
info.levelIdc = (int) tLevel;
uint32_t tChroma = 1;
if (tProfile == 100 || tProfile == 110 || tProfile == 122 || tProfile == 244 || tProfile == 44 || tProfile == 83 || tProfile == 86 || tProfile == 118 ||
tProfile == 128 || tProfile == 138 || tProfile == 139 || tProfile == 134 || tProfile == 135)
{
if (! r.ue(tChroma))
{
return false;
}
if (tChroma == 3)
{
r.bit(v); // separate_colour_plane_flag
}
r.ue(v); // bit_depth_luma
r.ue(v); // bit_depth_chroma
r.bit(v); // qpprime_y_zero_transform_bypass
uint32_t tScaling;
if (! r.bit(tScaling))
{
return false;
}
if (tScaling)
{
int tCount = (tChroma != 3) ? 8 : 12;
for (int i = 0; i < tCount; i++)
{
uint32_t tPresent;
if (! r.bit(tPresent))
{
return false;
}
if (tPresent && ! skipScalingList(r, i < 6 ? 16 : 64))
{
return false;
}
}
}
}
r.ue(v); // log2_max_frame_num_minus4
uint32_t tPocType;
if (! r.ue(tPocType))
{
return false;
}
if (tPocType == 0)
{
r.ue(v);
}
else if (tPocType == 1)
{
int32_t s;
r.bit(v);
r.se(s);
r.se(s);
uint32_t tCycle;
if (! r.ue(tCycle) || tCycle > 255)
{
return false;
}
for (uint32_t i = 0; i < tCycle; i++)
{
r.se(s);
}
}
r.ue(v); // max_num_ref_frames
r.bit(v); // gaps_in_frame_num_allowed
uint32_t tWmbs, tHmbs, tFrameMbsOnly;
if (! r.ue(tWmbs) || ! r.ue(tHmbs) || ! r.bit(tFrameMbsOnly))
{
return false;
}
if (! tFrameMbsOnly)
{
r.bit(v); // mb_adaptive_frame_field
}
r.bit(v); // direct_8x8_inference
uint32_t tCrop, cl = 0, cr = 0, ct = 0, cb = 0;
if (! r.bit(tCrop))
{
return false;
}
if (tCrop)
{
r.ue(cl);
r.ue(cr);
r.ue(ct);
r.ue(cb);
}
int tCropX = (tChroma == 0 || tChroma == 3) ? 1 : 2;
int tCropY = ((tChroma == 1) ? 2 : 1) * (2 - (int) tFrameMbsOnly);
info.width = (int) (tWmbs + 1) * 16 - (int) (cl + cr) * tCropX;
info.height = (int) (2 - tFrameMbsOnly) * (int) (tHmbs + 1) * 16 - (int) (ct + cb) * tCropY;
return info.width > 0 && info.height > 0;
}
std::string profileLevelId(const Bytes & sps)
{
if (sps.size() < 4)
{
return "42e01f";
}
char tB[8];
snprintf(tB, sizeof(tB), "%02x%02x%02x", sps[1], sps[2], sps[3]);
return tB;
}
static int b64val(char c)
{
if (c >= 'A' && c <= 'Z')
{
return c - 'A';
}
if (c >= 'a' && c <= 'z')
{
return c - 'a' + 26;
}
if (c >= '0' && c <= '9')
{
return c - '0' + 52;
}
if (c == '+' || c == '-')
{
return 62;
}
if (c == '/' || c == '_')
{
return 63;
}
return -1;
}
std::vector<Bytes> decodeSpropParameterSets(const char * sprop)
{
std::vector<Bytes> tOut;
if (sprop == nullptr)
{
return tOut;
}
Bytes tCur;
uint32_t tAcc = 0;
int tBits = 0;
for (const char * p = sprop;; p++)
{
if (*p == ',' || *p == 0)
{
if (! tCur.empty())
{
tOut.push_back(tCur);
}
tCur.clear();
tAcc = 0;
tBits = 0;
if (*p == 0)
{
break;
}
continue;
}
int v = b64val(*p);
if (v < 0)
{
continue; // '=' padding, spaces
}
tAcc = (tAcc << 6) | (uint32_t) v;
tBits += 6;
if (tBits >= 8)
{
tBits -= 8;
tCur.push_back((uint8_t) ((tAcc >> tBits) & 0xff));
}
}
return tOut;
}
Bytes toAnnexB(const std::vector<Bytes> & nalus)
{
Bytes tOut;
for (const Bytes & n : nalus)
{
static const uint8_t tSc[4] = {0, 0, 0, 1};
tOut.insert(tOut.end(), tSc, tSc + 4);
tOut.insert(tOut.end(), n.begin(), n.end());
}
return tOut;
}
Bytes toAvcc(const std::vector<Bytes> & nalus)
{
Bytes tOut;
for (const Bytes & n : nalus)
{
uint32_t s = (uint32_t) n.size();
tOut.push_back((uint8_t) (s >> 24));
tOut.push_back((uint8_t) (s >> 16));
tOut.push_back((uint8_t) (s >> 8));
tOut.push_back((uint8_t) s);
tOut.insert(tOut.end(), n.begin(), n.end());
}
return tOut;
}
Bytes buildAvcC(const Bytes & sps, const Bytes & pps)
{
Bytes r;
r.push_back(1);
r.push_back(sps.size() > 1 ? sps[1] : 0x42);
r.push_back(sps.size() > 2 ? sps[2] : 0xe0);
r.push_back(sps.size() > 3 ? sps[3] : 0x1f);
r.push_back(0xff); // 4 byte NAL lengths
r.push_back(0xe1); // 1 SPS
r.push_back((uint8_t) (sps.size() >> 8));
r.push_back((uint8_t) sps.size());
r.insert(r.end(), sps.begin(), sps.end());
r.push_back(1); // 1 PPS
r.push_back((uint8_t) (pps.size() >> 8));
r.push_back((uint8_t) pps.size());
r.insert(r.end(), pps.begin(), pps.end());
return r;
}
} // namespace h264
} // namespace mtx

53
Projects/MediaMtx/internal/codecs/h264/h264.h

@ -0,0 +1,53 @@
/*
MediaMtx (C++) - H264 helpers (MediaMTX uses mediacommon/pkg/codecs/h264)
*/
#pragma once
#include <string>
#include <vector>
#include "../../unit/unit.h"
namespace mtx {
namespace h264 {
enum NaluType
{
NALU_NON_IDR = 1,
NALU_IDR = 5,
NALU_SEI = 6,
NALU_SPS = 7,
NALU_PPS = 8,
NALU_AUD = 9,
NALU_STAP_A = 24,
NALU_FU_A = 28
};
inline int naluType(const Bytes & n)
{
return n.empty() ? 0 : (n[0] & 0x1f);
}
struct SpsInfo
{
int width = 0;
int height = 0;
int profileIdc = 0;
int constraints = 0;
int levelIdc = 0;
};
bool parseSps(const Bytes & sps, SpsInfo & info);
// 4d401f style string for SDP profile-level-id and "avc1.4d401f" codec strings
std::string profileLevelId(const Bytes & sps);
// Base64 sprop-parameter-sets ("Z00AH...,aO4...") -> NAL units
std::vector<Bytes> decodeSpropParameterSets(const char * sprop);
// Annex-B byte stream (00 00 00 01 start codes)
Bytes toAnnexB(const std::vector<Bytes> & nalus);
// AVCC: 4 byte big-endian lengths (MP4 samples)
Bytes toAvcc(const std::vector<Bytes> & nalus);
// AVCDecoderConfigurationRecord (avcC box payload)
Bytes buildAvcC(const Bytes & sps, const Bytes & pps);
} // namespace h264
} // namespace mtx

515
Projects/MediaMtx/internal/conf/conf.cpp

@ -0,0 +1,515 @@
#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

84
Projects/MediaMtx/internal/conf/conf.h

@ -0,0 +1,84 @@
/*
MediaMtx (C++) - configuration
No mediamtx.yml: the global settings come from the command line, the paths (streams) from a small
paths file (one line per path, reloaded on SIGHUP) and from the control API.
Paths file:
# name source options
stream_3 rtsp://user:pass@10.0.0.5:554/stream1 record=yes transport=tcp
stream_4 rtsp://10.0.0.6/live record=no
The option names follow MediaMTX (webrtcAddress, recordPath, ...).
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "../logger/logger.h"
namespace mtx {
enum class RtspTransport { Tcp, Udp };
struct PathConf
{
std::string name;
std::string source; // rtsp://...
bool record = false;
RtspTransport transport = RtspTransport::Tcp;
bool operator==(const PathConf & o) const { return name == o.name && source == o.source && record == o.record && transport == o.transport; }
bool operator!=(const PathConf & o) const { return ! (*this == o); }
};
struct Conf
{
// general
LogLevel logLevel = LogLevel::Info;
bool logStdout = true;
std::string logFile; // empty: no file
int64_t readTimeoutMs = 10000; // source: no data for this long -> reconnect
int64_t sourceRetryPauseMs = 5000; // pause before a reconnect
// control API (empty address: disabled)
std::string apiAddress = "127.0.0.1:9997";
// WebRTC (WHEP)
std::string webrtcAddress = ":8889";
std::string webrtcAllowOrigin = "*";
std::vector<std::string> webrtcICEServers; // e.g. stun:stun.l.google.com:19302
std::string webrtcBindAddress; // ICE: bind to this local address (default: all)
uint16_t webrtcUDPPortMin = 8189;
uint16_t webrtcUDPPortMax = 8289;
// recording
std::string recordPath = "./recordings/%path/%Y-%m-%d_%H-%M-%S-%f";
int64_t recordSegmentDurationMs = 60000;
int64_t recordPartDurationMs = 1000;
// paths
std::string pathsFile;
std::vector<PathConf> paths; // paths file + command line
std::vector<PathConf> cmdPaths; // --path options only
void mergeCmdPaths(std::vector<PathConf> & out) const;
// Parses the command line (and loads the paths file). False + err on a bad option.
bool load(int argc, char ** argv, std::string & err);
static void printUsage(const char * prog);
};
bool loadPathsFile(const std::string & file, std::vector<PathConf> & out, std::string & err);
bool savePathsFile(const std::string & file, const std::vector<PathConf> & paths, std::string & err);
// "60s", "1m", "500ms", "1h", "1.5s"; plain number = seconds
bool parseDurationMs(const std::string & s, int64_t & ms);
bool validPathName(const std::string & name);
// "host:port" / ":port" -> host ("" = any) and port
bool splitHostPort(const std::string & addr, std::string & host, uint16_t & port);
// rtsp://user:pass@host/... -> rtsp://host/... (for logs)
std::string hideCredentials(const std::string & url);
} // namespace mtx

131
Projects/MediaMtx/internal/core/core.cpp

@ -0,0 +1,131 @@
#include "core.h"
#include <csignal>
#include <cstring>
#include <pthread.h>
#include <BasicUsageEnvironment.hh>
#include <liveMedia_version.hh>
#include <rtc/version.h>
#define MEDIAMTX_CPP_VERSION "0.1.0"
namespace mtx {
Core::Core() : LogParent("") {}
Core::~Core()
{
m_pApi.reset();
m_pWebrtc.reset();
m_pPaths.reset();
}
bool Core::applyConfs(const std::vector<PathConf> & confs, std::string & err)
{
std::lock_guard<std::mutex> lock(m_confMutex);
if (! m_conf.pathsFile.empty() && ! savePathsFile(m_conf.pathsFile, confs, err))
{
return false;
}
m_conf.paths = confs;
m_pPaths->applyPaths(confs);
return true;
}
void Core::reloadPathsFile()
{
std::lock_guard<std::mutex> lock(m_confMutex);
if (m_conf.pathsFile.empty())
{
log(LogLevel::Info, "SIGHUP: no paths file to reload");
return;
}
std::vector<PathConf> tPaths;
std::string tErr;
if (! loadPathsFile(m_conf.pathsFile, tPaths, tErr))
{
log(LogLevel::Error, "reload: %s - keeping the current paths", tErr.c_str());
return;
}
m_conf.mergeCmdPaths(tPaths);
log(LogLevel::Info, "reloading the paths file %s (%zu paths)", m_conf.pathsFile.c_str(), tPaths.size());
m_conf.paths = tPaths;
m_pPaths->applyPaths(tPaths);
}
int Core::run(int argc, char ** argv)
{
std::string tErr;
if (! m_conf.load(argc, argv, tErr))
{
if (tErr != "help")
{
fprintf(stderr, "ERR: %s\n", tErr.c_str());
}
Conf::printUsage(argv[0]);
return tErr == "help" ? 0 : 1;
}
Logger::instance().setLevel(m_conf.logLevel);
Logger::instance().setDestinations(m_conf.logStdout, m_conf.logFile);
log(LogLevel::Info, "MediaMtx (C++) %s (live555 %s, libdatachannel %s)", MEDIAMTX_CPP_VERSION, LIVEMEDIA_LIBRARY_VERSION_STRING, RTC_VERSION);
// signals are taken by sigwait() in this thread: block them before any other thread starts
sigset_t tSigs;
sigemptyset(&tSigs);
sigaddset(&tSigs, SIGINT);
sigaddset(&tSigs, SIGTERM);
sigaddset(&tSigs, SIGHUP);
pthread_sigmask(SIG_BLOCK, &tSigs, nullptr);
signal(SIGPIPE, SIG_IGN);
m_pPaths.reset(new PathManager(m_conf));
m_pWebrtc.reset(new WebrtcServer(m_conf, m_pPaths.get()));
if (! m_pWebrtc->start(tErr))
{
log(LogLevel::Error, "%s", tErr.c_str());
return 1;
}
if (! m_conf.apiAddress.empty())
{
m_pApi.reset(new Api(m_conf, m_pPaths.get(), [this](const std::vector<PathConf> & c, std::string & e) { return applyConfs(c, e); }));
if (! m_pApi->start(tErr))
{
log(LogLevel::Error, "%s", tErr.c_str());
return 1;
}
}
{
std::lock_guard<std::mutex> lock(m_confMutex);
m_pPaths->applyPaths(m_conf.paths);
}
if (m_conf.paths.empty())
{
log(LogLevel::Warn, "no paths configured (use --paths FILE, --path NAME=URL or the API)");
}
while (true)
{
int tSig = 0;
if (sigwait(&tSigs, &tSig) != 0)
{
continue;
}
if (tSig == SIGHUP)
{
reloadPathsFile();
continue;
}
log(LogLevel::Info, "shutting down gracefully");
break;
}
if (m_pApi)
{
m_pApi->stop();
}
m_pWebrtc->stop();
m_pPaths->closeAll(); // closes the recordings
return 0;
}
} // namespace mtx

39
Projects/MediaMtx/internal/core/core.h

@ -0,0 +1,39 @@
/*
MediaMtx (C++) - core (MediaMTX: internal/core/core.go)
Creates the path manager, the WebRTC server and the API; SIGHUP reloads the paths file,
SIGINT / SIGTERM stop.
*/
#pragma once
#include <memory>
#include <mutex>
#include <string>
#include "../api/api.h"
#include "../conf/conf.h"
#include "../servers/webrtc/webrtcServer.h"
#include "pathManager.h"
namespace mtx {
class Core : public LogParent
{
public:
Core();
~Core();
// returns the process exit code
int run(int argc, char ** argv);
private:
bool applyConfs(const std::vector<PathConf> & confs, std::string & err);
void reloadPathsFile();
Conf m_conf;
std::mutex m_confMutex;
std::unique_ptr<PathManager> m_pPaths;
std::unique_ptr<WebrtcServer> m_pWebrtc;
std::unique_ptr<Api> m_pApi;
};
} // namespace mtx

119
Projects/MediaMtx/internal/core/path.cpp

@ -0,0 +1,119 @@
#include "path.h"
#include "../recorder/recorder.h"
namespace mtx {
Path::Path(const PathConf & conf, const Conf & global) : LogParent("[path " + conf.name + "] "), m_conf(conf), m_global(global) {}
Path::~Path()
{
stop();
}
void Path::start()
{
m_pSource.reset(new RtspSource(m_conf, m_global, this));
m_pSource->start();
}
void Path::stop()
{
if (m_pSource)
{
m_pSource->stop(); // calls sourceSetNotReady() if it was ready
m_pSource.reset();
}
}
PathInfo Path::info() const
{
std::lock_guard<std::mutex> lock(m_mutex);
PathInfo tI;
tI.name = m_conf.name;
tI.source = m_conf.source;
tI.record = m_conf.record;
tI.ready = (m_pStream != nullptr);
tI.readySinceUs = m_tReadySinceUs;
tI.readers = m_readers.size();
if (m_pStream)
{
tI.desc = m_pStream->desc();
tI.bytesReceived = m_pStream->bytesReceived();
}
return tI;
}
bool Path::addReader(PathReader * r, StreamDesc & desc, std::string & err)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (! m_pStream)
{
err = "no stream is available on path '" + m_conf.name + "'";
return false;
}
desc = m_pStream->desc();
m_readers.insert(r);
m_pStream->addReader(r);
return true;
}
void Path::removeReader(PathReader * r)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_readers.erase(r) > 0 && m_pStream)
{
m_pStream->removeReader(r);
}
}
void Path::sourceSetReady(const StreamDesc & desc)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_pStream = std::make_shared<Stream>(desc);
m_tReadySinceUs = nowUs();
log(LogLevel::Info, "stream is available and online, 1 track (H264 %dx%d)", desc.width, desc.height);
if (m_conf.record)
{
m_pRecorder.reset(new Recorder(m_conf.name, m_global, m_pStream, this));
m_pRecorder->start();
}
}
void Path::sourceSetNotReady()
{
std::unique_ptr<Recorder> tRec;
{
std::lock_guard<std::mutex> lock(m_mutex);
if (! m_pStream)
{
return;
}
for (PathReader * r : m_readers)
{
m_pStream->removeReader(r);
r->pathNotReady();
}
m_readers.clear();
tRec = std::move(m_pRecorder);
m_pStream.reset();
m_tReadySinceUs = 0;
}
tRec.reset(); // closes the segment
log(LogLevel::Info, "stream is not available anymore");
}
void Path::sourceWriteUnit(const UnitPtr & unit)
{
std::shared_ptr<Stream> tStream;
{
std::lock_guard<std::mutex> lock(m_mutex);
tStream = m_pStream;
}
if (tStream)
{
tStream->writeUnit(unit);
}
}
} // namespace mtx

75
Projects/MediaMtx/internal/core/path.h

@ -0,0 +1,75 @@
/*
MediaMtx (C++) - path (MediaMTX: internal/core/path.go)
A path has a static source (RTSP camera), a stream while the source is ready, an optional recorder and
the readers (WebRTC sessions).
*/
#pragma once
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include "../conf/conf.h"
#include "../logger/logger.h"
#include "../staticsources/rtsp/rtspSource.h"
#include "../stream/stream.h"
namespace mtx {
class Recorder;
class PathReader : public StreamReader
{
public:
// The source of the path is gone: the reader must close (called with the path locked: do not block,
// do not call back into the path)
virtual void pathNotReady() = 0;
};
struct PathInfo
{
std::string name;
std::string source;
bool record = false;
bool ready = false;
int64_t readySinceUs = 0;
StreamDesc desc;
size_t readers = 0;
uint64_t bytesReceived = 0;
};
class Path : public SourceParent, public LogParent
{
public:
Path(const PathConf & conf, const Conf & global);
~Path() override;
void start();
void stop();
const PathConf & conf() const { return m_conf; }
PathInfo info() const;
// false + err when the path has no stream
bool addReader(PathReader * r, StreamDesc & desc, std::string & err);
void removeReader(PathReader * r);
// SourceParent
void sourceSetReady(const StreamDesc & desc) override;
void sourceSetNotReady() override;
void sourceWriteUnit(const UnitPtr & unit) override;
private:
PathConf m_conf;
Conf m_global;
std::unique_ptr<RtspSource> m_pSource;
mutable std::mutex m_mutex;
std::shared_ptr<Stream> m_pStream;
std::unique_ptr<Recorder> m_pRecorder;
std::set<PathReader *> m_readers;
int64_t m_tReadySinceUs = 0;
};
} // namespace mtx

110
Projects/MediaMtx/internal/core/pathManager.cpp

@ -0,0 +1,110 @@
#include "pathManager.h"
namespace mtx {
PathManager::PathManager(const Conf & global) : LogParent("[path manager] "), m_global(global) {}
PathManager::~PathManager()
{
closeAll();
}
void PathManager::applyPaths(const std::vector<PathConf> & paths)
{
std::vector<std::shared_ptr<Path>> tStop;
std::vector<std::shared_ptr<Path>> tStart;
{
std::lock_guard<std::mutex> lock(m_mutex);
for (auto it = m_paths.begin(); it != m_paths.end();)
{
const PathConf * tNew = nullptr;
for (const PathConf & p : paths)
{
if (p.name == it->first)
{
tNew = &p;
}
}
if (tNew == nullptr || *tNew != it->second->conf())
{
tStop.push_back(it->second);
it = m_paths.erase(it);
}
else
{
++it;
}
}
for (const PathConf & p : paths)
{
if (m_paths.find(p.name) == m_paths.end())
{
auto tPath = std::make_shared<Path>(p, m_global);
m_paths[p.name] = tPath;
tStart.push_back(tPath);
}
}
}
// outside the lock: stopping joins the source thread
for (auto & p : tStop)
{
log(LogLevel::Info, "removing path %s", p->conf().name.c_str());
p->stop();
}
for (auto & p : tStart)
{
log(LogLevel::Info, "adding path %s (source %s%s)", p->conf().name.c_str(), hideCredentials(p->conf().source).c_str(), p->conf().record ? ", recording" : "");
p->start();
}
}
void PathManager::closeAll()
{
std::map<std::string, std::shared_ptr<Path>> tAll;
{
std::lock_guard<std::mutex> lock(m_mutex);
tAll.swap(m_paths);
}
for (auto & p : tAll)
{
p.second->stop();
}
}
std::shared_ptr<Path> PathManager::find(const std::string & name) const
{
std::lock_guard<std::mutex> lock(m_mutex);
auto it = m_paths.find(name);
return it == m_paths.end() ? nullptr : it->second;
}
std::vector<PathInfo> PathManager::list() const
{
std::vector<std::shared_ptr<Path>> tAll;
{
std::lock_guard<std::mutex> lock(m_mutex);
for (auto & p : m_paths)
{
tAll.push_back(p.second);
}
}
std::vector<PathInfo> tOut;
for (auto & p : tAll)
{
tOut.push_back(p->info());
}
return tOut;
}
std::vector<PathConf> PathManager::confs() const
{
std::lock_guard<std::mutex> lock(m_mutex);
std::vector<PathConf> tOut;
for (auto & p : m_paths)
{
tOut.push_back(p.second->conf());
}
return tOut;
}
} // namespace mtx

37
Projects/MediaMtx/internal/core/pathManager.h

@ -0,0 +1,37 @@
/*
MediaMtx (C++) - path manager (MediaMTX: internal/core/path_manager.go)
*/
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "../conf/conf.h"
#include "path.h"
namespace mtx {
class PathManager : public LogParent
{
public:
explicit PathManager(const Conf & global);
~PathManager();
// Starts new paths, stops removed ones, restarts changed ones
void applyPaths(const std::vector<PathConf> & paths);
void closeAll();
std::shared_ptr<Path> find(const std::string & name) const;
std::vector<PathInfo> list() const;
std::vector<PathConf> confs() const;
private:
Conf m_global;
mutable std::mutex m_mutex;
std::map<std::string, std::shared_ptr<Path>> m_paths;
};
} // namespace mtx

121
Projects/MediaMtx/internal/logger/logger.cpp

@ -0,0 +1,121 @@
#include "logger.h"
#include <cstdio>
#include <ctime>
#include <sys/time.h>
namespace mtx {
Logger & Logger::instance()
{
static Logger s_logger;
return s_logger;
}
void Logger::setLevel(LogLevel level)
{
m_level = level;
}
void Logger::setDestinations(bool toStdout, const std::string & file)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_toStdout = toStdout;
m_file = file;
}
void Logger::log(LogLevel level, const char * fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vlog(level, fmt, ap);
va_end(ap);
}
void Logger::vlog(LogLevel level, const char * fmt, va_list ap)
{
if (level < m_level)
{
return;
}
static const char * s_tags[] = {"DEB", "INF", "WAR", "ERR"};
char tLine[2048];
time_t tNow = time(nullptr);
struct tm tTm;
localtime_r(&tNow, &tTm);
int tLen = (int) strftime(tLine, sizeof(tLine), "%Y/%m/%d %H:%M:%S ", &tTm);
tLen += snprintf(tLine + tLen, sizeof(tLine) - tLen, "%s ", s_tags[(int) level]);
if (tLen < (int) sizeof(tLine))
{
int tN = vsnprintf(tLine + tLen, sizeof(tLine) - tLen, fmt, ap);
tLen = (tN < 0) ? tLen : tLen + tN;
}
if (tLen > (int) sizeof(tLine) - 2)
{
tLen = (int) sizeof(tLine) - 2;
}
tLine[tLen++] = '\n';
tLine[tLen] = 0;
std::lock_guard<std::mutex> lock(m_mutex);
if (m_toStdout)
{
fwrite(tLine, 1, tLen, stdout);
fflush(stdout);
}
if (! m_file.empty())
{
FILE * tF = fopen(m_file.c_str(), "a");
if (tF != nullptr)
{
fwrite(tLine, 1, tLen, tF);
fclose(tF);
}
}
}
void LogParent::log(LogLevel level, const char * fmt, ...) const
{
Logger & tL = Logger::instance();
if (level < tL.level())
{
return;
}
char tMsg[1800];
va_list ap;
va_start(ap, fmt);
vsnprintf(tMsg, sizeof(tMsg), fmt, ap);
va_end(ap);
tL.log(level, "%s%s", m_prefix.c_str(), tMsg);
}
LogLevel parseLogLevel(const std::string & s, bool * ok)
{
if (ok)
{
*ok = true;
}
if (s == "debug")
{
return LogLevel::Debug;
}
if (s == "info")
{
return LogLevel::Info;
}
if (s == "warn")
{
return LogLevel::Warn;
}
if (s == "error")
{
return LogLevel::Error;
}
if (ok)
{
*ok = false;
}
return LogLevel::Info;
}
} // namespace mtx

53
Projects/MediaMtx/internal/logger/logger.h

@ -0,0 +1,53 @@
/*
MediaMtx (C++) - logger
Line format of MediaMTX: "2026/12/02 16:43:01 INF [path stream_3] [RTSP source] ready: 1 track (H264)"
la_mojo (kernelHelperMediaMTX) parses these lines (ERR / INF, "[path ", "RTSP source", "online").
*/
#pragma once
#include <cstdarg>
#include <mutex>
#include <string>
namespace mtx {
enum class LogLevel { Debug = 0, Info = 1, Warn = 2, Error = 3 };
class Logger
{
public:
static Logger & instance();
void setLevel(LogLevel level);
LogLevel level() const { return m_level; }
// stdout and / or a file. The file is opened in append mode on every line, so it can be truncated
// by another process (la_mojo cleans the log above 40 KB).
void setDestinations(bool toStdout, const std::string & file);
void log(LogLevel level, const char * fmt, ...) __attribute__((format(printf, 3, 4)));
void vlog(LogLevel level, const char * fmt, va_list ap);
private:
Logger() = default;
std::mutex m_mutex;
LogLevel m_level = LogLevel::Info;
bool m_toStdout = true;
std::string m_file;
};
// Prefixes every line with a tag, e.g. "[path stream_3] [RTSP source] "
class LogParent
{
public:
explicit LogParent(std::string prefix = std::string()) : m_prefix(std::move(prefix)) {}
void setLogPrefix(const std::string & prefix) { m_prefix = prefix; }
const std::string & logPrefix() const { return m_prefix; }
void log(LogLevel level, const char * fmt, ...) const __attribute__((format(printf, 3, 4)));
private:
std::string m_prefix;
};
LogLevel parseLogLevel(const std::string & s, bool * ok = nullptr);
} // namespace mtx

393
Projects/MediaMtx/internal/protocols/httpp/httpServer.cpp

@ -0,0 +1,393 @@
#include "httpServer.h"
#include <arpa/inet.h>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include "../../conf/conf.h"
namespace mtx {
namespace {
const size_t MAX_HEADER_SIZE = 16 * 1024;
const size_t MAX_BODY_SIZE = 1024 * 1024;
const int IDLE_TIMEOUT_MS = 15000;
} // namespace
const char * httpStatusText(int status)
{
switch (status)
{
case 200: return "OK";
case 201: return "Created";
case 204: return "No Content";
case 301: return "Moved Permanently";
case 400: return "Bad Request";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 409: return "Conflict";
case 413: return "Payload Too Large";
case 415: return "Unsupported Media Type";
case 500: return "Internal Server Error";
case 503: return "Service Unavailable";
default: return "Status";
}
}
static std::string urlDecode(const std::string & s)
{
std::string tOut;
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] == '%' && i + 2 < s.size() && isxdigit((unsigned char) s[i + 1]) && isxdigit((unsigned char) s[i + 2]))
{
tOut.push_back((char) strtol(s.substr(i + 1, 2).c_str(), nullptr, 16));
i += 2;
}
else
{
tOut.push_back(s[i]);
}
}
return tOut;
}
bool HttpServer::start(const std::string & address, Handler handler, std::string & err)
{
std::string tHost;
uint16_t tPort = 0;
if (! splitHostPort(address, tHost, tPort))
{
err = "bad address " + address;
return false;
}
struct addrinfo tHints;
memset(&tHints, 0, sizeof(tHints));
tHints.ai_family = AF_UNSPEC;
tHints.ai_socktype = SOCK_STREAM;
tHints.ai_flags = AI_PASSIVE;
struct addrinfo * tRes = nullptr;
std::string tPortS = std::to_string(tPort);
if (getaddrinfo(tHost.empty() ? nullptr : tHost.c_str(), tPortS.c_str(), &tHints, &tRes) != 0 || tRes == nullptr)
{
err = "cannot resolve " + address;
return false;
}
// with an empty host prefer IPv6 any (dual stack); fall back to the other results (no IPv6 support)
std::vector<struct addrinfo *> tOrder;
for (struct addrinfo * a = tRes; a != nullptr; a = a->ai_next)
{
if (tHost.empty() && a->ai_family == AF_INET6)
{
tOrder.insert(tOrder.begin(), a);
}
else
{
tOrder.push_back(a);
}
}
err.clear();
for (struct addrinfo * a : tOrder)
{
m_nListenFd = socket(a->ai_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (m_nListenFd < 0)
{
err = std::string("socket: ") + strerror(errno);
continue;
}
int tOne = 1;
setsockopt(m_nListenFd, SOL_SOCKET, SO_REUSEADDR, &tOne, sizeof(tOne));
if (a->ai_family == AF_INET6)
{
int tZero = 0;
setsockopt(m_nListenFd, IPPROTO_IPV6, IPV6_V6ONLY, &tZero, sizeof(tZero));
}
if (bind(m_nListenFd, a->ai_addr, a->ai_addrlen) == 0 && listen(m_nListenFd, 64) == 0)
{
err.clear();
break;
}
err = "listen on " + address + ": " + strerror(errno);
close(m_nListenFd);
m_nListenFd = -1;
}
if (m_nListenFd < 0)
{
freeaddrinfo(tRes);
return false;
}
freeaddrinfo(tRes);
if (pipe(m_aWake) != 0)
{
err = "pipe failed";
close(m_nListenFd);
m_nListenFd = -1;
return false;
}
m_handler = std::move(handler);
m_bRun = true;
m_thread = std::thread(&HttpServer::acceptLoop, this);
return true;
}
void HttpServer::stop()
{
if (! m_bRun.exchange(false))
{
return;
}
if (write(m_aWake[1], "x", 1) < 0)
{
// the accept loop also wakes up on its poll timeout
}
if (m_thread.joinable())
{
m_thread.join();
}
{
std::lock_guard<std::mutex> lock(m_connMutex);
for (int fd : m_vConnFds)
{
shutdown(fd, SHUT_RDWR);
}
}
// connection threads are detached: wait until they are gone
for (int i = 0; i < 500 && m_nConnections > 0; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
close(m_nListenFd);
close(m_aWake[0]);
close(m_aWake[1]);
m_nListenFd = -1;
}
void HttpServer::acceptLoop()
{
while (m_bRun)
{
struct pollfd tP[2] = {{m_nListenFd, POLLIN, 0}, {m_aWake[0], POLLIN, 0}};
int tN = poll(tP, 2, 1000);
if (tN <= 0 || ! m_bRun)
{
continue;
}
if (tP[0].revents & POLLIN)
{
struct sockaddr_storage tAddr;
socklen_t tLen = sizeof(tAddr);
int fd = accept4(m_nListenFd, (struct sockaddr *) &tAddr, &tLen, SOCK_CLOEXEC);
if (fd < 0)
{
continue;
}
char tHost[INET6_ADDRSTRLEN] = "?";
if (tAddr.ss_family == AF_INET)
{
inet_ntop(AF_INET, &((struct sockaddr_in *) &tAddr)->sin_addr, tHost, sizeof(tHost));
}
else if (tAddr.ss_family == AF_INET6)
{
inet_ntop(AF_INET6, &((struct sockaddr_in6 *) &tAddr)->sin6_addr, tHost, sizeof(tHost));
if (strncmp(tHost, "::ffff:", 7) == 0)
{
memmove(tHost, tHost + 7, strlen(tHost + 7) + 1);
}
}
int tOne = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &tOne, sizeof(tOne));
{
std::lock_guard<std::mutex> lock(m_connMutex);
m_vConnFds.push_back(fd);
}
m_nConnections++;
std::thread(&HttpServer::serveConnection, this, fd, std::string(tHost)).detach();
}
}
}
static bool sendAll(int fd, const std::string & data)
{
size_t tOff = 0;
while (tOff < data.size())
{
ssize_t n = send(fd, data.data() + tOff, data.size() - tOff, MSG_NOSIGNAL);
if (n <= 0)
{
if (n < 0 && errno == EINTR)
{
continue;
}
return false;
}
tOff += (size_t) n;
}
return true;
}
void HttpServer::serveConnection(int fd, std::string remote)
{
std::string tBuf;
bool tKeep = true;
while (tKeep && m_bRun)
{
// read the header
size_t tHdrEnd;
while ((tHdrEnd = tBuf.find("\r\n\r\n")) == std::string::npos)
{
if (tBuf.size() > MAX_HEADER_SIZE)
{
tKeep = false;
break;
}
struct pollfd tP = {fd, POLLIN, 0};
if (poll(&tP, 1, IDLE_TIMEOUT_MS) <= 0)
{
tKeep = false;
break;
}
char tChunk[4096];
ssize_t n = recv(fd, tChunk, sizeof(tChunk), 0);
if (n <= 0)
{
tKeep = false;
break;
}
tBuf.append(tChunk, (size_t) n);
}
if (! tKeep)
{
break;
}
HttpRequest tReq;
tReq.remoteAddr = remote;
std::string tHead = tBuf.substr(0, tHdrEnd);
tBuf.erase(0, tHdrEnd + 4);
size_t tEol = tHead.find("\r\n");
std::string tLine = tHead.substr(0, tEol);
size_t s1 = tLine.find(' '), s2 = tLine.rfind(' ');
if (s1 == std::string::npos || s2 == s1)
{
break;
}
tReq.method = tLine.substr(0, s1);
std::string tUri = tLine.substr(s1 + 1, s2 - s1 - 1);
std::string tVer = tLine.substr(s2 + 1);
size_t tQ = tUri.find('?');
tReq.path = urlDecode(tQ == std::string::npos ? tUri : tUri.substr(0, tQ));
tReq.query = (tQ == std::string::npos) ? std::string() : tUri.substr(tQ + 1);
size_t tPos = (tEol == std::string::npos) ? tHead.size() : tEol + 2;
while (tPos < tHead.size())
{
size_t tE = tHead.find("\r\n", tPos);
std::string h = tHead.substr(tPos, (tE == std::string::npos ? tHead.size() : tE) - tPos);
tPos = (tE == std::string::npos) ? tHead.size() : tE + 2;
size_t tC = h.find(':');
if (tC == std::string::npos)
{
continue;
}
std::string k = h.substr(0, tC);
std::transform(k.begin(), k.end(), k.begin(), ::tolower);
size_t tV = h.find_first_not_of(" \t", tC + 1);
tReq.headers[k] = (tV == std::string::npos) ? std::string() : h.substr(tV);
}
std::string tConn = tReq.header("connection");
std::transform(tConn.begin(), tConn.end(), tConn.begin(), ::tolower);
tKeep = (tVer == "HTTP/1.1") ? (tConn != "close") : (tConn == "keep-alive");
HttpResponse tRes;
size_t tLen = (size_t) strtoul(tReq.header("content-length").c_str(), nullptr, 10);
if (! tReq.header("transfer-encoding").empty())
{
tRes.status = 400;
tKeep = false;
}
else if (tLen > MAX_BODY_SIZE)
{
tRes.status = 413;
tKeep = false;
}
else
{
while (tBuf.size() < tLen)
{
struct pollfd tP = {fd, POLLIN, 0};
if (poll(&tP, 1, IDLE_TIMEOUT_MS) <= 0)
{
tKeep = false;
break;
}
char tChunk[8192];
ssize_t n = recv(fd, tChunk, sizeof(tChunk), 0);
if (n <= 0)
{
tKeep = false;
break;
}
tBuf.append(tChunk, (size_t) n);
}
if (tBuf.size() < tLen)
{
break;
}
tReq.body = tBuf.substr(0, tLen);
tBuf.erase(0, tLen);
try
{
m_handler(tReq, tRes);
}
catch (const std::exception & e)
{
if (m_pParent)
{
m_pParent->log(LogLevel::Error, "HTTP handler: %s", e.what());
}
tRes = HttpResponse();
tRes.status = 500;
}
}
std::string tOut = "HTTP/1.1 " + std::to_string(tRes.status) + " " + httpStatusText(tRes.status) + "\r\n";
bool tHasType = false;
for (auto & h : tRes.headers)
{
tOut += h.first + ": " + h.second + "\r\n";
if (strcasecmp(h.first.c_str(), "Content-Type") == 0)
{
tHasType = true;
}
}
if (! tHasType && ! tRes.body.empty())
{
tOut += "Content-Type: text/plain\r\n";
}
tOut += "Server: MediaMtx\r\nContent-Length: " + std::to_string(tRes.body.size()) + "\r\n";
tOut += tKeep ? "Connection: keep-alive\r\n\r\n" : "Connection: close\r\n\r\n";
if (tReq.method != "HEAD")
{
tOut += tRes.body;
}
if (! sendAll(fd, tOut))
{
break;
}
}
{
std::lock_guard<std::mutex> lock(m_connMutex);
m_vConnFds.erase(std::remove(m_vConnFds.begin(), m_vConnFds.end(), fd), m_vConnFds.end());
}
close(fd);
m_nConnections--;
}
} // namespace mtx

74
Projects/MediaMtx/internal/protocols/httpp/httpServer.h

@ -0,0 +1,74 @@
/*
MediaMtx (C++) - small HTTP/1.1 server (MediaMTX: internal/protocols/httpp)
Used by the WebRTC (WHEP) server and the control API. One thread per connection, keep-alive,
Content-Length bodies only (no chunked uploads), small requests (signalling / API).
*/
#pragma once
#include <atomic>
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "../../logger/logger.h"
namespace mtx {
struct HttpRequest
{
std::string method;
std::string path; // decoded, without the query
std::string query;
std::map<std::string, std::string> headers; // lower case names
std::string body;
std::string remoteAddr;
std::string header(const std::string & lowerName) const
{
auto it = headers.find(lowerName);
return it == headers.end() ? std::string() : it->second;
}
};
struct HttpResponse
{
int status = 200;
std::vector<std::pair<std::string, std::string>> headers;
std::string body;
void setHeader(const std::string & name, const std::string & value) { headers.emplace_back(name, value); }
};
class HttpServer
{
public:
typedef std::function<void(const HttpRequest &, HttpResponse &)> Handler;
explicit HttpServer(const LogParent * parent) : m_pParent(parent) {}
~HttpServer() { stop(); }
bool start(const std::string & address, Handler handler, std::string & err);
void stop();
private:
void acceptLoop();
void serveConnection(int fd, std::string remote);
const LogParent * m_pParent;
Handler m_handler;
int m_nListenFd = -1;
int m_aWake[2] = {-1, -1};
std::atomic<bool> m_bRun{false};
std::atomic<int> m_nConnections{0};
std::thread m_thread;
std::mutex m_connMutex;
std::vector<int> m_vConnFds;
};
const char * httpStatusText(int status);
} // namespace mtx

415
Projects/MediaMtx/internal/recorder/fmp4Writer.cpp

@ -0,0 +1,415 @@
#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

58
Projects/MediaMtx/internal/recorder/fmp4Writer.h

@ -0,0 +1,58 @@
/*
MediaMtx (C++) - fragmented MP4 segment writer (MediaMTX: internal/recorder/format_fmp4*.go)
One file per segment: ftyp + moov (init, avc1/avcC, mvex) followed by moof + mdat fragments.
A fragment is written (and flushed) every part duration, so the file is playable while it grows and
after a crash everything up to the last fragment is kept. Browsers play these files with <video src>.
The samples are written as they came from the camera (no transcoding); H264 without B-frames
(dts = pts), which is what IP cameras send.
*/
#pragma once
#include <cstdio>
#include <string>
#include <vector>
#include "../unit/unit.h"
namespace mtx {
class Fmp4Writer
{
public:
Fmp4Writer() = default;
~Fmp4Writer() { close(); }
// Creates the file and writes the init part
bool open(const std::string & file, const Bytes & sps, const Bytes & pps, int width, int height, std::string & err);
// Adds a sample; dts relative to the segment start, 90 kHz
void addSample(int64_t dts, const UnitPtr & unit);
// Writes the pending samples as one fragment. nextDts: dts of the following sample (gives the
// duration of the last one); final: no following sample (end of the segment)
bool flushFragment(int64_t nextDts, bool final, std::string & err);
void close();
bool isOpen() const { return m_pFile != nullptr; }
int64_t pendingSpan() const; // 90 kHz, first to last pending sample
const std::string & fileName() const { return m_sFile; }
private:
struct Sample
{
int64_t dts;
Bytes data; // AVCC
bool idr;
};
FILE * m_pFile = nullptr;
std::string m_sFile;
std::vector<Sample> m_vPending;
uint32_t m_nSequence = 0;
int64_t m_nLastDuration = 3000; // 30 fps until known
};
// Expands %path %Y %m %d %H %M %S %f (microseconds) %s (unix seconds) and adds ".mp4"
std::string expandRecordPath(const std::string & pattern, const std::string & pathName, int64_t timeUs);
bool mkdirAll(const std::string & dir);
} // namespace mtx

120
Projects/MediaMtx/internal/recorder/recorder.cpp

@ -0,0 +1,120 @@
#include "recorder.h"
#include "../codecs/h264/h264.h"
namespace mtx {
Recorder::Recorder(const std::string & pathName, const Conf & global, std::shared_ptr<Stream> stream, const LogParent * pathLog)
: LogParent(pathLog->logPrefix() + "[recorder] "), m_sPath(pathName), m_global(global), m_pStream(std::move(stream)), m_reader(this, 1024)
{
}
Recorder::~Recorder()
{
m_pStream->removeReader(&m_reader);
m_reader.stop();
closeSegment();
}
void Recorder::start()
{
m_reader.start([this](const UnitPtr & u) { onUnit(u); });
m_pStream->addReader(&m_reader);
std::string tPattern = m_global.recordPath;
size_t tPos = tPattern.find("%path");
if (tPos != std::string::npos)
{
tPattern.replace(tPos, 5, m_sPath);
}
log(LogLevel::Info, "recording to %s.mp4 (segments of %lld s)", tPattern.c_str(), (long long) (m_global.recordSegmentDurationMs / 1000));
}
void Recorder::closeSegment()
{
if (m_writer.isOpen())
{
std::string tFile = m_writer.fileName();
m_writer.close();
log(LogLevel::Debug, "segment closed: %s", tFile.c_str());
}
}
void Recorder::onUnit(const UnitPtr & unit)
{
if (m_writer.isOpen())
{
int64_t tDts = unit->pts - m_nSegmentStartPts;
std::string tErr;
// 20 ms tolerance: the timestamps of a 2 s GOP may give 9.99999 s for a 10 s segment
bool tNewSegment = unit->idr && tDts + 1800 >= m_global.recordSegmentDurationMs * 90;
if (tNewSegment)
{
if (! m_writer.flushFragment(tDts, false, tErr))
{
log(LogLevel::Error, "%s", tErr.c_str());
}
closeSegment();
}
else
{
if (m_writer.pendingSpan() * 1000 / 90000 >= m_global.recordPartDurationMs && ! m_writer.flushFragment(tDts, false, tErr))
{
log(LogLevel::Error, "%s", tErr.c_str());
closeSegment();
return;
}
m_writer.addSample(tDts, unit);
return;
}
}
if (! unit->idr)
{
return; // a segment starts with a random access point
}
StreamDesc tDesc = m_pStream->desc();
for (const Bytes & n : unit->nalus)
{
if (h264::naluType(n) == h264::NALU_SPS)
{
tDesc.sps = n;
}
else if (h264::naluType(n) == h264::NALU_PPS)
{
tDesc.pps = n;
}
}
h264::SpsInfo tInfo;
if (h264::parseSps(tDesc.sps, tInfo))
{
tDesc.width = tInfo.width;
tDesc.height = tInfo.height;
}
// file name from the wall clock of the first sample
int64_t tTime = unit->ntpUs;
int64_t tNow = nowUs();
if (tTime <= 0 || tTime > tNow + 86400000000LL || tTime < tNow - 86400000000LL)
{
tTime = tNow;
}
std::string tFile = expandRecordPath(m_global.recordPath, m_sPath, tTime);
std::string tErr;
if (! m_writer.open(tFile, tDesc.sps, tDesc.pps, tDesc.width, tDesc.height, tErr))
{
if (! m_bFailed)
{
log(LogLevel::Error, "%s", tErr.c_str());
}
m_bFailed = true;
return;
}
if (m_bFailed)
{
log(LogLevel::Info, "recording works again");
}
m_bFailed = false;
m_nSegmentStartPts = unit->pts;
log(LogLevel::Debug, "segment opened: %s", tFile.c_str());
m_writer.addSample(0, unit);
}
} // namespace mtx

42
Projects/MediaMtx/internal/recorder/recorder.h

@ -0,0 +1,42 @@
/*
MediaMtx (C++) - recorder (MediaMTX: internal/recorder)
Reads the path's stream and writes fMP4 segments:
<recordPath with %path and the time of the first sample>.mp4
A segment starts at an IDR; after recordSegmentDuration the next IDR starts a new segment. A fragment is
written every recordPartDuration. Deleting old segments is left to the application (la_mojo).
*/
#pragma once
#include <memory>
#include <string>
#include "../conf/conf.h"
#include "../logger/logger.h"
#include "../stream/stream.h"
#include "fmp4Writer.h"
namespace mtx {
class Recorder : public LogParent
{
public:
Recorder(const std::string & pathName, const Conf & global, std::shared_ptr<Stream> stream, const LogParent * pathLog);
~Recorder();
void start();
private:
void onUnit(const UnitPtr & unit);
void closeSegment();
std::string m_sPath;
Conf m_global;
std::shared_ptr<Stream> m_pStream;
AsyncReader m_reader;
Fmp4Writer m_writer;
int64_t m_nSegmentStartPts = 0;
bool m_bFailed = false;
};
} // namespace mtx

349
Projects/MediaMtx/internal/servers/webrtc/session.cpp

@ -0,0 +1,349 @@
#include "session.h"
#include <sstream>
#include <strings.h>
#include "../../codecs/h264/h264.h"
namespace mtx {
namespace {
std::string fmtpValue(const std::string & fmtp, const std::string & key)
{
std::istringstream tIn(fmtp);
std::string tPart;
while (std::getline(tIn, tPart, ';'))
{
size_t b = tPart.find_first_not_of(' ');
if (b == std::string::npos)
{
continue;
}
tPart = tPart.substr(b);
size_t e = tPart.find('=');
if (e != std::string::npos && tPart.substr(0, e) == key)
{
return tPart.substr(e + 1);
}
}
return std::string();
}
} // namespace
WebrtcSession::WebrtcSession(const std::string & secret, std::shared_ptr<Path> path, const Conf & global, const std::string & remoteAddr)
: LogParent("[WebRTC] [session " + secret.substr(0, 8) + "] "), m_sSecret(secret), m_pPath(std::move(path)), m_global(global), m_sRemote(remoteAddr),
m_reader(this, 512)
{
m_tCreated = nowMs();
}
WebrtcSession::~WebrtcSession()
{
close();
}
bool WebrtcSession::create(const std::string & offerSdp, std::string & answer, int & status, std::string & err)
{
log(LogLevel::Info, "created by %s", m_sRemote.c_str());
status = 400;
rtc::Description tOffer("", rtc::Description::Type::Offer);
try
{
tOffer = rtc::Description(offerSdp, rtc::Description::Type::Offer);
}
catch (const std::exception & e)
{
err = std::string("invalid SDP offer: ") + e.what();
return false;
}
if (! m_pPath->addReader(this, m_desc, err))
{
status = 404;
return false;
}
m_bReading = true;
// The video section of the offer and its best H264 payload type
std::string tMid;
int tPt = -1;
std::string tFmtp;
int tBest = -1;
int tStreamPrf = m_desc.sps.size() > 1 ? m_desc.sps[1] : 66;
for (int i = 0; i < tOffer.mediaCount() && tMid.empty(); i++)
{
auto tM = tOffer.media(i);
if (! std::holds_alternative<rtc::Description::Media *>(tM))
{
continue;
}
rtc::Description::Media * tMedia = std::get<rtc::Description::Media *>(tM);
if (tMedia->type() != "video")
{
continue;
}
if (tMedia->direction() != rtc::Description::Direction::RecvOnly && tMedia->direction() != rtc::Description::Direction::SendRecv)
{
continue;
}
for (int pt : tMedia->payloadTypes())
{
const rtc::Description::Media::RtpMap * tMap = tMedia->rtpMap(pt);
if (tMap == nullptr || strcasecmp(tMap->format.c_str(), "H264") != 0)
{
continue;
}
std::string tF = tMap->fmtps.empty() ? std::string() : tMap->fmtps[0];
if (fmtpValue(tF, "packetization-mode") != "1")
{
continue;
}
std::string tPrf = fmtpValue(tF, "profile-level-id");
int tIdc = tPrf.size() >= 2 ? (int) strtol(tPrf.substr(0, 2).c_str(), nullptr, 16) : 66;
int tScore = (tIdc == tStreamPrf) ? 3 : (tPrf.compare(0, 4, "42e0") == 0 ? 2 : 1);
if (tScore > tBest)
{
tBest = tScore;
tPt = pt;
tFmtp = tF;
}
}
if (tPt >= 0)
{
tMid = tMedia->mid();
}
}
if (tPt < 0)
{
err = "the offer has no H264 (packetization-mode=1) video section";
return false;
}
rtc::Configuration tCfg;
for (const std::string & s : m_global.webrtcICEServers)
{
tCfg.iceServers.emplace_back(s);
}
if (! m_global.webrtcBindAddress.empty())
{
tCfg.bindAddress = m_global.webrtcBindAddress;
}
tCfg.portRangeBegin = m_global.webrtcUDPPortMin;
tCfg.portRangeEnd = m_global.webrtcUDPPortMax;
tCfg.disableAutoNegotiation = true;
m_pPc = std::make_shared<rtc::PeerConnection>(tCfg);
m_pPc->onGatheringStateChange([this](rtc::PeerConnection::GatheringState s) {
if (s == rtc::PeerConnection::GatheringState::Complete)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_bGathered = true;
m_cond.notify_all();
}
});
m_pPc->onStateChange([this](rtc::PeerConnection::State s) {
if (s == rtc::PeerConnection::State::Connected)
{
if (! m_bConnected.exchange(true))
{
log(LogLevel::Info, "peer connection established");
}
}
else if (s == rtc::PeerConnection::State::Failed || s == rtc::PeerConnection::State::Closed || s == rtc::PeerConnection::State::Disconnected)
{
if (! m_bClosing.exchange(true))
{
log(LogLevel::Info, "peer connection %s", s == rtc::PeerConnection::State::Failed ? "failed" : "closed");
}
}
});
uint32_t tSsrc = (uint32_t) (std::hash<std::string>()(m_sSecret) & 0x7fffffff) | 1;
rtc::Description::Video tVideo(tMid, rtc::Description::Direction::SendOnly);
tVideo.addH264Codec(tPt, tFmtp);
tVideo.addSSRC(tSsrc, "mediamtx", "mediamtx", "video");
m_pTrack = m_pPc->addTrack(tVideo);
m_pRtpConfig = std::make_shared<rtc::RtpPacketizationConfig>(tSsrc, "mediamtx", (uint8_t) tPt, rtc::H264RtpPacketizer::defaultClockRate);
auto tPacketizer = std::make_shared<rtc::H264RtpPacketizer>(rtc::H264RtpPacketizer::Separator::LongStartSequence, m_pRtpConfig, 1200);
m_pSrReporter = std::make_shared<rtc::RtcpSrReporter>(m_pRtpConfig);
tPacketizer->addToChain(m_pSrReporter);
tPacketizer->addToChain(std::make_shared<rtc::RtcpNackResponder>());
m_pTrack->setMediaHandler(tPacketizer);
m_pTrack->onOpen([this]() { m_bTrackOpen = true; });
try
{
m_pPc->setRemoteDescription(tOffer);
m_pPc->setLocalDescription(rtc::Description::Type::Answer);
}
catch (const std::exception & e)
{
err = std::string("negotiation failed: ") + e.what();
return false;
}
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait_for(lock, std::chrono::seconds(5), [this] { return m_bGathered; });
}
auto tLocal = m_pPc->localDescription();
if (! tLocal)
{
status = 500;
err = "no local description";
return false;
}
answer = std::string(*tLocal);
m_reader.start([this](const UnitPtr & u) { onUnit(u); });
log(LogLevel::Info, "is reading from path '%s', 1 track (H264 %dx%d, payload type %d)", m_pPath->conf().name.c_str(), m_desc.width, m_desc.height, tPt);
status = 201;
return true;
}
bool WebrtcSession::addRemoteCandidates(const std::string & sdpFrag, std::string & err)
{
if (! m_pPc)
{
err = "session not ready";
return false;
}
std::istringstream tIn(sdpFrag);
std::string tLine;
std::string tMid;
while (std::getline(tIn, tLine))
{
if (! tLine.empty() && tLine.back() == '\r')
{
tLine.pop_back();
}
if (tLine.compare(0, 6, "a=mid:") == 0)
{
tMid = tLine.substr(6);
}
else if (tLine.compare(0, 12, "a=candidate:") == 0)
{
try
{
m_pPc->addRemoteCandidate(tMid.empty() ? rtc::Candidate(tLine.substr(2)) : rtc::Candidate(tLine.substr(2), tMid));
}
catch (const std::exception & e)
{
err = std::string("invalid candidate: ") + e.what();
return false;
}
}
}
return true;
}
void WebrtcSession::pathNotReady()
{
// called with the path locked: only mark, the server closes the session
m_bReading = false;
if (! m_bClosing.exchange(true))
{
log(LogLevel::Info, "the source of path '%s' is gone", m_pPath->conf().name.c_str());
}
}
void WebrtcSession::close()
{
if (m_bClosed)
{
return;
}
m_bClosed = true;
m_bClosing = true;
if (m_bReading)
{
m_pPath->removeReader(this);
m_bReading = false;
}
m_reader.stop();
if (m_pPc)
{
m_pPc->onStateChange(nullptr);
m_pPc->onGatheringStateChange(nullptr);
if (m_pTrack)
{
m_pTrack->onOpen(nullptr);
}
m_pPc->close();
}
m_pTrack.reset();
m_pPc.reset();
log(LogLevel::Info, "closed (%llu bytes sent)", (unsigned long long) m_nBytesSent);
}
void WebrtcSession::onUnit(const UnitPtr & unit)
{
if (! m_bTrackOpen || m_bClosing)
{
return;
}
if (! m_bStarted)
{
if (! unit->idr)
{
return; // the browser needs a random access point
}
m_bStarted = true;
m_nFirstPts = unit->pts;
}
std::vector<Bytes> tNalus;
if (unit->idr)
{
// make sure every IDR carries the parameter sets (cameras often send them only in the SDP)
bool tSps = false, tPps = false;
for (const Bytes & n : unit->nalus)
{
tSps |= h264::naluType(n) == h264::NALU_SPS;
tPps |= h264::naluType(n) == h264::NALU_PPS;
}
if (! tSps && ! m_desc.sps.empty())
{
tNalus.push_back(m_desc.sps);
}
if (! tPps && ! m_desc.pps.empty())
{
tNalus.push_back(m_desc.pps);
}
}
for (const Bytes & n : unit->nalus)
{
int t = h264::naluType(n);
if (t == h264::NALU_SPS)
{
m_desc.sps = n;
}
else if (t == h264::NALU_PPS)
{
m_desc.pps = n;
}
tNalus.push_back(n);
}
Bytes tFrame = h264::toAnnexB(tNalus);
m_pRtpConfig->timestamp = m_pRtpConfig->startTimestamp + (uint32_t) (unit->pts - m_nFirstPts);
int64_t tNow = nowMs();
if (tNow - m_tLastSr > 1000)
{
m_tLastSr = tNow;
m_pSrReporter->setNeedsToReport();
}
try
{
m_pTrack->send(reinterpret_cast<const rtc::byte *>(tFrame.data()), tFrame.size());
m_nBytesSent += tFrame.size();
}
catch (const std::exception & e)
{
if (! m_bClosing.exchange(true))
{
log(LogLevel::Warn, "send failed: %s", e.what());
}
}
}
} // namespace mtx

74
Projects/MediaMtx/internal/servers/webrtc/session.h

@ -0,0 +1,74 @@
/*
MediaMtx (C++) - WebRTC (WHEP) reader session (MediaMTX: internal/servers/webrtc/session.go)
The browser POSTs its SDP offer (recvonly video); the answer contains one H264 send-only track and
all local ICE candidates (the la_mojo dashboard does not trickle). The camera's H264 is sent as it is
(no transcoding), starting at the next IDR.
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <rtc/rtc.hpp>
#include "../../conf/conf.h"
#include "../../core/path.h"
#include "../../logger/logger.h"
#include "../../stream/stream.h"
namespace mtx {
class WebrtcSession : public PathReader, public LogParent
{
public:
WebrtcSession(const std::string & secret, std::shared_ptr<Path> path, const Conf & global, const std::string & remoteAddr);
~WebrtcSession() override;
// Returns the answer SDP; on failure false + http status + error
bool create(const std::string & offer, std::string & answer, int & status, std::string & err);
bool addRemoteCandidates(const std::string & sdpFrag, std::string & err);
void close();
// The server removes sessions that are closing, failed or never connected
bool isClosing() const { return m_bClosing; }
bool connectTimedOut(int64_t nowMsValue) const { return ! m_bConnected && nowMsValue - m_tCreated > 20000; }
const std::string & secret() const { return m_sSecret; }
const std::string & pathName() const { return m_pPath->conf().name; }
// PathReader
void push(const UnitPtr & unit) override { m_reader.push(unit); }
void pathNotReady() override;
private:
void onUnit(const UnitPtr & unit);
std::string m_sSecret;
std::shared_ptr<Path> m_pPath;
Conf m_global;
std::string m_sRemote;
AsyncReader m_reader;
std::shared_ptr<rtc::PeerConnection> m_pPc;
std::shared_ptr<rtc::Track> m_pTrack;
std::shared_ptr<rtc::RtpPacketizationConfig> m_pRtpConfig;
std::shared_ptr<rtc::RtcpSrReporter> m_pSrReporter;
StreamDesc m_desc;
std::mutex m_mutex;
std::condition_variable m_cond;
bool m_bGathered = false;
std::atomic<bool> m_bTrackOpen{false};
std::atomic<bool> m_bConnected{false};
std::atomic<bool> m_bClosing{false};
bool m_bReading = false;
bool m_bClosed = false;
bool m_bStarted = false; // first IDR sent
int64_t m_nFirstPts = 0;
int64_t m_tCreated = 0;
int64_t m_tLastSr = 0;
uint64_t m_nBytesSent = 0;
};
} // namespace mtx

285
Projects/MediaMtx/internal/servers/webrtc/webrtcServer.cpp

@ -0,0 +1,285 @@
#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

49
Projects/MediaMtx/internal/servers/webrtc/webrtcServer.h

@ -0,0 +1,49 @@
/*
MediaMtx (C++) - WebRTC server, WHEP (MediaMTX: internal/servers/webrtc)
POST /<path>/whep SDP offer -> 201 + SDP answer, Location /<path>/whep/<secret>
PATCH /<path>/whep/<secret> trickle ICE (application/trickle-ice-sdpfrag)
DELETE /<path>/whep/<secret> close the session
OPTIONS CORS preflight
GET /<path>/ a small player page
*/
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <thread>
#include "../../conf/conf.h"
#include "../../core/pathManager.h"
#include "../../protocols/httpp/httpServer.h"
#include "session.h"
namespace mtx {
class WebrtcServer : public LogParent
{
public:
WebrtcServer(const Conf & global, PathManager * paths);
~WebrtcServer();
bool start(std::string & err);
void stop();
size_t sessionCount() const;
private:
void handle(const HttpRequest & req, HttpResponse & res);
void janitor();
Conf m_global;
PathManager * m_pPaths;
HttpServer m_http;
mutable std::mutex m_mutex;
std::map<std::string, std::shared_ptr<WebrtcSession>> m_sessions;
std::thread m_janitor;
std::mutex m_stopMutex;
std::condition_variable m_stopCond;
bool m_bRun = false;
};
} // namespace mtx

543
Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.cpp

@ -0,0 +1,543 @@
#include "rtspSource.h"
#include <BasicUsageEnvironment.hh>
#include <GroupsockHelper.hh>
#include <liveMedia.hh>
#include <type_traits>
#include "../../codecs/h264/h264.h"
namespace mtx {
namespace {
// live555 changed the event loop watch variable from "char volatile" to std::atomic_char: take the type
// from TaskScheduler::doEventLoop so both versions build.
template <class C, class A> A watchArgType(void (C::*)(A));
typedef std::remove_pointer<decltype(watchArgType(&TaskScheduler::doEventLoop))>::type WatchVar;
const unsigned SINK_BUFFER_SIZE = 4 * 1024 * 1024;
const unsigned UDP_RECEIVE_BUFFER = 4 * 1024 * 1024;
const unsigned CHECK_INTERVAL_US = 200 * 1000;
const char * APPLICATION_NAME = "MediaMtx";
class RtspSession;
class MtxRTSPClient : public RTSPClient
{
public:
static MtxRTSPClient * createNew(UsageEnvironment & env, const char * url, RtspSession * owner)
{
return new MtxRTSPClient(env, url, owner);
}
RtspSession * owner;
protected:
MtxRTSPClient(UsageEnvironment & env, const char * url, RtspSession * o) : RTSPClient(env, url, 0, APPLICATION_NAME, 0, -1), owner(o) {}
};
class H264Sink : public MediaSink
{
public:
static H264Sink * createNew(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp) { return new H264Sink(env, owner, rtp); }
protected:
H264Sink(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp);
~H264Sink() override { delete[] m_pBuffer; }
private:
static void afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned);
void afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime);
Boolean continuePlaying() override;
void flush();
RtspSession * m_pOwner;
RTPSource * m_pRtp;
uint8_t * m_pBuffer;
std::vector<Bytes> m_vNalus;
int64_t m_nPtUs = 0; // presentation time of the access unit being collected
bool m_bHavePts = false;
bool m_bSynced = false; // presentation times are RTCP synchronised
int64_t m_nOffset = 0; // keeps pts continuous over the RTCP sync jump
int64_t m_nLastRaw = 0;
int64_t m_nLastPts = 0;
int64_t m_nLastDelta = 3000;
unsigned m_nTruncLogs = 0;
};
class RtspSession
{
public:
explicit RtspSession(RtspSource * src) : m_pSrc(src) {}
void run();
void end(const std::string & error);
void onUnit(std::vector<Bytes> && nalus, int64_t pts, int64_t ntpUs);
void dataReceived() { m_tLastData = nowMs(); }
RtspSource * source() { return m_pSrc; }
static void continueAfterDescribe(RTSPClient * c, int resultCode, char * resultString);
static void continueAfterSetup(RTSPClient * c, int resultCode, char * resultString);
static void continueAfterPlay(RTSPClient * c, int resultCode, char * resultString);
static void ignoreResponse(RTSPClient *, int, char * resultString) { delete[] resultString; }
static void onSubsessionBye(void * clientData);
static void onSinkClosed(void * clientData);
static void periodicCheck(void * clientData);
static void sendKeepalive(void * clientData);
private:
void afterDescribe(int resultCode, char * resultString);
void afterSetup(int resultCode, char * resultString);
void afterPlay(int resultCode, char * resultString);
void cleanup();
RtspSource * m_pSrc;
TaskScheduler * m_pScheduler = nullptr;
UsageEnvironment * m_pEnv = nullptr;
MtxRTSPClient * m_pClient = nullptr;
MediaSession * m_pSession = nullptr;
MediaSubsession * m_pVideo = nullptr;
WatchVar m_watch{0};
bool m_bEnded = false;
bool m_bPlaying = false;
bool m_bReady = false;
StreamDesc m_desc;
int64_t m_tStart = 0;
int64_t m_tLastData = 0;
TaskToken m_checkTask = nullptr;
TaskToken m_aliveTask = nullptr;
};
// ---------------------------------------------------------------- sink
H264Sink::H264Sink(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp) : MediaSink(env), m_pOwner(owner), m_pRtp(rtp)
{
m_pBuffer = new uint8_t[SINK_BUFFER_SIZE];
}
Boolean H264Sink::continuePlaying()
{
if (fSource == nullptr)
{
return False;
}
fSource->getNextFrame(m_pBuffer, SINK_BUFFER_SIZE, afterGettingFrame, this, RtspSession::onSinkClosed, m_pOwner);
return True;
}
void H264Sink::afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned)
{
static_cast<H264Sink *>(clientData)->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime);
}
void H264Sink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime)
{
m_pOwner->dataReceived();
// live555 keeps the RTP timestamp private: the presentation time is derived from it (exact, until the
// first RTCP sender report moves it onto the sender's wall clock - see flush())
int64_t tPtUs = (int64_t) presentationTime.tv_sec * 1000000 + presentationTime.tv_usec;
bool tMarker = m_pRtp->curPacketMarkerBit();
if (numTruncatedBytes > 0 && m_nTruncLogs++ < 5)
{
m_pOwner->source()->log(LogLevel::Warn, "NAL unit truncated by %u bytes", numTruncatedBytes);
}
// An access unit ends with the RTP marker bit. A camera that does not set it: a new presentation time
// starts a new unit. Small changes are not a new unit: every RTCP sender report moves live555's
// mapping of RTP time to presentation time a little, also between packets of the same picture.
if (! m_vNalus.empty() && (tPtUs - m_nPtUs > 2000 || m_nPtUs - tPtUs > 2000))
{
flush();
}
if (frameSize > 0)
{
int tType = m_pBuffer[0] & 0x1f;
if (tType != h264::NALU_AUD && tType != 0)
{
m_vNalus.emplace_back(m_pBuffer, m_pBuffer + frameSize);
}
}
if (m_vNalus.size() <= 1)
{
m_nPtUs = tPtUs; // the time of the unit is the time of its first NAL unit
}
if (tMarker)
{
flush();
}
continuePlaying();
}
void H264Sink::flush()
{
if (m_vNalus.empty())
{
return;
}
// 90 kHz pts starting at 0. When live555 synchronises with the first RTCP sender report the presentation
// times jump onto the sender's clock: the offset keeps the pts continuous (one frame interval).
int64_t tRaw = m_nPtUs * 9 / 100;
bool tSynced = m_pRtp->hasBeenSynchronizedUsingRTCP();
if (! m_bHavePts)
{
m_bHavePts = true;
m_bSynced = tSynced;
m_nOffset = -tRaw;
}
else if (tSynced != m_bSynced)
{
m_bSynced = tSynced;
m_nOffset = m_nLastPts + m_nLastDelta - tRaw;
}
int64_t tPts = tRaw + m_nOffset;
if (tPts > m_nLastPts && tPts - m_nLastPts < 90000)
{
m_nLastDelta = tPts - m_nLastPts;
}
m_nLastRaw = tRaw;
m_nLastPts = tPts;
m_pOwner->onUnit(std::move(m_vNalus), tPts, m_nPtUs);
m_vNalus.clear();
}
// ---------------------------------------------------------------- session
void RtspSession::run()
{
m_pScheduler = BasicTaskScheduler::createNew();
m_pEnv = BasicUsageEnvironment::createNew(*m_pScheduler);
m_tStart = nowMs();
m_pSrc->log(LogLevel::Info, "started");
m_pClient = MtxRTSPClient::createNew(*m_pEnv, m_pSrc->pathConf().source.c_str(), this);
if (m_pClient == nullptr)
{
end(std::string("cannot create the RTSP client: ") + m_pEnv->getResultMsg());
}
else
{
m_pClient->sendDescribeCommand(continueAfterDescribe);
m_checkTask = m_pScheduler->scheduleDelayedTask(CHECK_INTERVAL_US, periodicCheck, this);
m_pScheduler->doEventLoop(&m_watch);
}
cleanup();
}
void RtspSession::end(const std::string & error)
{
if (m_bEnded)
{
return;
}
m_bEnded = true;
if (! error.empty())
{
m_pSrc->log(LogLevel::Error, "%s", error.c_str());
}
m_watch = 1;
}
void RtspSession::cleanup()
{
if (m_pScheduler != nullptr)
{
m_pScheduler->unscheduleDelayedTask(m_checkTask);
m_pScheduler->unscheduleDelayedTask(m_aliveTask);
}
if (m_pSession != nullptr)
{
if (m_pClient != nullptr && m_bPlaying)
{
m_pClient->sendTeardownCommand(*m_pSession, ignoreResponse);
}
MediaSubsessionIterator tIter(*m_pSession);
MediaSubsession * tSub;
while ((tSub = tIter.next()) != nullptr)
{
if (tSub->sink != nullptr)
{
tSub->sink->stopPlaying();
Medium::close(tSub->sink);
tSub->sink = nullptr;
}
}
Medium::close(m_pSession);
m_pSession = nullptr;
}
if (m_pClient != nullptr)
{
Medium::close(m_pClient);
m_pClient = nullptr;
}
if (m_bReady)
{
m_pSrc->parent()->sourceSetNotReady();
m_bReady = false;
}
if (m_pEnv != nullptr)
{
m_pEnv->reclaim();
m_pEnv = nullptr;
}
delete m_pScheduler;
m_pScheduler = nullptr;
}
void RtspSession::continueAfterDescribe(RTSPClient * c, int resultCode, char * resultString)
{
static_cast<MtxRTSPClient *>(c)->owner->afterDescribe(resultCode, resultString);
}
void RtspSession::continueAfterSetup(RTSPClient * c, int resultCode, char * resultString)
{
static_cast<MtxRTSPClient *>(c)->owner->afterSetup(resultCode, resultString);
}
void RtspSession::continueAfterPlay(RTSPClient * c, int resultCode, char * resultString)
{
static_cast<MtxRTSPClient *>(c)->owner->afterPlay(resultCode, resultString);
}
static std::string resultText(int resultCode, const char * resultString, UsageEnvironment * env)
{
if (resultCode < 0)
{
// network error, the message is in the environment
return std::string(env->getResultMsg());
}
return "bad status code: " + std::to_string(resultCode) + (resultString ? std::string(" (") + resultString + ")" : std::string());
}
void RtspSession::afterDescribe(int resultCode, char * resultString)
{
if (resultCode != 0)
{
end("DESCRIBE failed: " + resultText(resultCode, resultString, m_pEnv));
delete[] resultString;
return;
}
m_pSession = MediaSession::createNew(*m_pEnv, resultString);
delete[] resultString;
if (m_pSession == nullptr || ! m_pSession->hasSubsessions())
{
end(std::string("invalid SDP: ") + m_pEnv->getResultMsg());
return;
}
MediaSubsessionIterator tIter(*m_pSession);
MediaSubsession * tSub;
while ((tSub = tIter.next()) != nullptr)
{
if (m_pVideo == nullptr && strcmp(tSub->mediumName(), "video") == 0 && strcmp(tSub->codecName(), "H264") == 0)
{
m_pVideo = tSub;
}
else
{
m_pSrc->log(LogLevel::Warn, "skipping track %s/%s (only H264 video is supported)", tSub->mediumName(), tSub->codecName());
}
}
if (m_pVideo == nullptr)
{
end("the stream has no H264 video track");
return;
}
if (! m_pVideo->initiate())
{
end(std::string("cannot initiate the video track: ") + m_pEnv->getResultMsg());
return;
}
if (m_pSrc->pathConf().transport == RtspTransport::Udp && m_pVideo->rtpSource() != nullptr)
{
increaseReceiveBufferTo(*m_pEnv, m_pVideo->rtpSource()->RTPgs()->socketNum(), UDP_RECEIVE_BUFFER);
}
// codec parameters from the SDP (sprop-parameter-sets), if any
for (const Bytes & n : h264::decodeSpropParameterSets(m_pVideo->fmtp_spropparametersets()))
{
if (h264::naluType(n) == h264::NALU_SPS)
{
m_desc.sps = n;
}
else if (h264::naluType(n) == h264::NALU_PPS)
{
m_desc.pps = n;
}
}
m_pClient->sendSetupCommand(*m_pVideo, continueAfterSetup, False, m_pSrc->pathConf().transport == RtspTransport::Tcp ? True : False);
}
void RtspSession::afterSetup(int resultCode, char * resultString)
{
delete[] resultString;
if (resultCode != 0)
{
end("SETUP failed: " + resultText(resultCode, nullptr, m_pEnv));
return;
}
H264Sink * tSink = H264Sink::createNew(*m_pEnv, this, m_pVideo->rtpSource());
m_pVideo->sink = tSink;
if (m_pVideo->rtcpInstance() != nullptr)
{
m_pVideo->rtcpInstance()->setByeHandler(onSubsessionBye, this);
}
tSink->startPlaying(*m_pVideo->readSource(), nullptr, nullptr);
m_pClient->sendPlayCommand(*m_pSession, continueAfterPlay);
}
void RtspSession::afterPlay(int resultCode, char * resultString)
{
delete[] resultString;
if (resultCode != 0)
{
end("PLAY failed: " + resultText(resultCode, nullptr, m_pEnv));
return;
}
m_bPlaying = true;
m_tLastData = nowMs();
m_pSrc->log(LogLevel::Info, "ready: 1 track (H264)");
unsigned tTimeout = m_pClient->sessionTimeoutParameter();
unsigned tEvery = (tTimeout > 10) ? tTimeout / 2 : 30;
m_aliveTask = m_pScheduler->scheduleDelayedTask((int64_t) tEvery * 1000000, sendKeepalive, this);
}
void RtspSession::onUnit(std::vector<Bytes> && nalus, int64_t pts, int64_t ntpUs)
{
if (! m_bReady)
{
for (const Bytes & n : nalus)
{
if (h264::naluType(n) == h264::NALU_SPS)
{
m_desc.sps = n;
}
else if (h264::naluType(n) == h264::NALU_PPS)
{
m_desc.pps = n;
}
}
if (m_desc.sps.empty() || m_desc.pps.empty())
{
return; // a reader cannot use the stream without the codec parameters
}
h264::SpsInfo tInfo;
if (h264::parseSps(m_desc.sps, tInfo))
{
m_desc.width = tInfo.width;
m_desc.height = tInfo.height;
}
m_bReady = true;
m_pSrc->parent()->sourceSetReady(m_desc);
}
auto tUnit = std::make_shared<Unit>();
tUnit->pts = pts;
tUnit->ntpUs = ntpUs;
tUnit->nalus = std::move(nalus);
for (const Bytes & n : tUnit->nalus)
{
if (h264::naluType(n) == h264::NALU_IDR)
{
tUnit->idr = true;
break;
}
}
m_pSrc->parent()->sourceWriteUnit(tUnit);
}
void RtspSession::onSubsessionBye(void * clientData)
{
static_cast<RtspSession *>(clientData)->end("received RTCP BYE");
}
void RtspSession::onSinkClosed(void * clientData)
{
static_cast<RtspSession *>(clientData)->end("the stream was closed by the server");
}
void RtspSession::periodicCheck(void * clientData)
{
RtspSession * s = static_cast<RtspSession *>(clientData);
s->m_checkTask = nullptr;
if (s->m_pSrc->stopRequested())
{
s->end("");
return;
}
int64_t tNow = nowMs();
int64_t tTimeout = s->m_pSrc->global().readTimeoutMs;
if (s->m_bPlaying && tNow - s->m_tLastData > tTimeout)
{
s->end("no data for " + std::to_string((tNow - s->m_tLastData) / 1000) + " s");
return;
}
if (! s->m_bPlaying && tNow - s->m_tStart > tTimeout)
{
s->end("timed out waiting for the server");
return;
}
s->m_checkTask = s->m_pScheduler->scheduleDelayedTask(CHECK_INTERVAL_US, periodicCheck, s);
}
void RtspSession::sendKeepalive(void * clientData)
{
RtspSession * s = static_cast<RtspSession *>(clientData);
s->m_aliveTask = nullptr;
s->m_pClient->sendOptionsCommand(ignoreResponse);
unsigned tTimeout = s->m_pClient->sessionTimeoutParameter();
unsigned tEvery = (tTimeout > 10) ? tTimeout / 2 : 30;
s->m_aliveTask = s->m_pScheduler->scheduleDelayedTask((int64_t) tEvery * 1000000, sendKeepalive, s);
}
} // namespace
// ---------------------------------------------------------------- source
RtspSource::RtspSource(const PathConf & conf, const Conf & global, SourceParent * parent)
: LogParent("[path " + conf.name + "] [RTSP source] "), m_conf(conf), m_global(global), m_pParent(parent)
{
}
RtspSource::~RtspSource()
{
stop();
}
void RtspSource::start()
{
m_bStop = false;
m_thread = std::thread(&RtspSource::run, this);
}
void RtspSource::stop()
{
m_bStop = true;
m_cond.notify_all();
if (m_thread.joinable())
{
m_thread.join();
log(LogLevel::Info, "stopped");
}
}
void RtspSource::run()
{
while (! m_bStop)
{
runSession();
if (! m_bStop)
{
waitRetry();
}
}
}
void RtspSource::runSession()
{
RtspSession tSession(this);
tSession.run();
}
void RtspSource::waitRetry()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait_for(lock, std::chrono::milliseconds(m_global.sourceRetryPauseMs), [this] { return m_bStop.load(); });
}
} // namespace mtx

63
Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.h

@ -0,0 +1,63 @@
/*
MediaMtx (C++) - RTSP static source (MediaMTX: internal/staticsources/rtsp)
Pulls a camera stream with live555 (DESCRIBE / SETUP / PLAY), in its own thread with its own live555
event loop. Only H264 video is taken; other tracks are skipped. On an error or when no data arrives
for readTimeout the session is torn down and opened again after sourceRetryPause.
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
#include "../../conf/conf.h"
#include "../../logger/logger.h"
#include "../../stream/stream.h"
namespace mtx {
class SourceParent
{
public:
virtual ~SourceParent() {}
// The source has the codec parameters: the path creates its stream
virtual void sourceSetReady(const StreamDesc & desc) = 0;
// The source lost its connection: the path destroys its stream
virtual void sourceSetNotReady() = 0;
// A unit of the source (called from the source thread)
virtual void sourceWriteUnit(const UnitPtr & unit) = 0;
};
class RtspSource : public LogParent
{
public:
RtspSource(const PathConf & conf, const Conf & global, SourceParent * parent);
~RtspSource();
void start();
void stop();
// called by the live555 session (same thread)
bool stopRequested() const { return m_bStop; }
SourceParent * parent() { return m_pParent; }
const PathConf & pathConf() const { return m_conf; }
const Conf & global() const { return m_global; }
private:
void run();
void runSession();
void waitRetry();
PathConf m_conf;
Conf m_global;
SourceParent * m_pParent;
std::atomic<bool> m_bStop{false};
std::mutex m_mutex;
std::condition_variable m_cond;
std::thread m_thread;
};
} // namespace mtx

160
Projects/MediaMtx/internal/stream/stream.cpp

@ -0,0 +1,160 @@
#include "stream.h"
#include <algorithm>
#include <chrono>
#include "../codecs/h264/h264.h"
namespace mtx {
int64_t nowMs()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
int64_t nowUs()
{
return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
Stream::Stream(const StreamDesc & desc) : m_desc(desc) {}
void Stream::addReader(StreamReader * r)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_readers.push_back(r);
}
void Stream::removeReader(StreamReader * r)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_readers.erase(std::remove(m_readers.begin(), m_readers.end(), r), m_readers.end());
}
size_t Stream::readerCount() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_readers.size();
}
StreamDesc Stream::desc() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_desc;
}
void Stream::writeUnit(const UnitPtr & unit)
{
m_nBytes += unit->byteSize();
std::lock_guard<std::mutex> lock(m_mutex);
for (const Bytes & n : unit->nalus)
{
int t = h264::naluType(n);
if (t == h264::NALU_SPS && n != m_desc.sps)
{
m_desc.sps = n;
h264::SpsInfo tInfo;
if (h264::parseSps(n, tInfo))
{
m_desc.width = tInfo.width;
m_desc.height = tInfo.height;
}
}
else if (t == h264::NALU_PPS && n != m_desc.pps)
{
m_desc.pps = n;
}
}
for (StreamReader * r : m_readers)
{
r->push(unit);
}
}
AsyncReader::AsyncReader(const LogParent * parent, size_t queueSize) : m_pParent(parent), m_nQueueSize(queueSize) {}
AsyncReader::~AsyncReader()
{
stop();
}
void AsyncReader::start(Handler handler)
{
m_handler = std::move(handler);
m_bRun = true;
m_thread = std::thread(&AsyncReader::run, this);
}
void AsyncReader::stop()
{
{
std::lock_guard<std::mutex> lock(m_mutex);
if (! m_bRun)
{
return;
}
m_bRun = false;
}
m_cond.notify_all();
if (m_thread.joinable())
{
m_thread.join();
}
}
void AsyncReader::push(const UnitPtr & unit)
{
{
std::lock_guard<std::mutex> lock(m_mutex);
if (! m_bRun)
{
return;
}
if (m_bWaitIdr)
{
if (! unit->idr)
{
return;
}
m_bWaitIdr = false;
}
if (m_queue.size() >= m_nQueueSize)
{
// Reader too slow: drop what is queued and resume at the next IDR
m_nDropped += m_queue.size() + 1;
m_queue.clear();
m_bWaitIdr = true;
int64_t tNow = nowMs();
if (m_pParent != nullptr && tNow - m_tLastDropLog > 1000)
{
m_tLastDropLog = tNow;
m_pParent->log(LogLevel::Warn, "reader is too slow, discarding %llu units", (unsigned long long) m_nDropped);
m_nDropped = 0;
}
return;
}
m_queue.push_back(unit);
}
m_cond.notify_one();
}
void AsyncReader::run()
{
while (true)
{
UnitPtr tUnit;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait(lock, [this] { return ! m_bRun || ! m_queue.empty(); });
if (! m_bRun)
{
return;
}
tUnit = m_queue.front();
m_queue.pop_front();
}
m_handler(tUnit);
}
}
} // namespace mtx

98
Projects/MediaMtx/internal/stream/stream.h

@ -0,0 +1,98 @@
/*
MediaMtx (C++) - stream (MediaMTX: internal/stream)
A Stream exists while the path's source is ready. The source writes units into it, the stream hands
every unit to all readers. Each reader has its own queue and thread (AsyncReader), so a slow reader
(e.g. a WebRTC client on a bad link, or the disk) never blocks the source or the other readers.
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "../logger/logger.h"
#include "../unit/unit.h"
namespace mtx {
struct StreamDesc
{
std::string codec = "H264";
Bytes sps;
Bytes pps;
int width = 0;
int height = 0;
};
class StreamReader
{
public:
virtual ~StreamReader() {}
// Called from the source thread: must not block
virtual void push(const UnitPtr & unit) = 0;
};
class Stream
{
public:
explicit Stream(const StreamDesc & desc);
void addReader(StreamReader * r);
void removeReader(StreamReader * r);
size_t readerCount() const;
// From the source: in-band SPS/PPS update the description
void writeUnit(const UnitPtr & unit);
StreamDesc desc() const;
uint64_t bytesReceived() const { return m_nBytes; }
private:
mutable std::mutex m_mutex;
StreamDesc m_desc;
std::vector<StreamReader *> m_readers;
std::atomic<uint64_t> m_nBytes{0};
};
/*
Reader with its own thread. The handler gets the units in order; when the queue overflows the units are
dropped and the handler gets units again from the next IDR (a decoder needs a random access point).
*/
class AsyncReader : public StreamReader
{
public:
typedef std::function<void(const UnitPtr &)> Handler;
AsyncReader(const LogParent * parent, size_t queueSize = 512);
~AsyncReader() override;
void start(Handler handler);
void stop();
void push(const UnitPtr & unit) override;
private:
void run();
const LogParent * m_pParent;
size_t m_nQueueSize;
Handler m_handler;
std::mutex m_mutex;
std::condition_variable m_cond;
std::deque<UnitPtr> m_queue;
bool m_bRun = false;
bool m_bWaitIdr = false;
uint64_t m_nDropped = 0;
int64_t m_tLastDropLog = 0;
std::thread m_thread;
};
int64_t nowMs();
int64_t nowUs();
} // namespace mtx

34
Projects/MediaMtx/internal/unit/unit.h

@ -0,0 +1,34 @@
/*
MediaMtx (C++) - a unit of media data (MediaMTX: internal/unit)
One H264 access unit (all NAL units of one picture) with its timestamps.
*/
#pragma once
#include <cstdint>
#include <memory>
#include <vector>
namespace mtx {
typedef std::vector<uint8_t> Bytes;
struct Unit
{
int64_t pts = 0; // presentation time, 90 kHz clock, from the source's RTP timestamps (unwrapped)
int64_t ntpUs = 0; // wall clock of the unit (us since the epoch)
bool idr = false; // contains an IDR picture (random access point)
std::vector<Bytes> nalus; // NAL units without start codes
size_t byteSize() const
{
size_t n = 0;
for (const Bytes & b : nalus)
{
n += b.size();
}
return n;
}
};
typedef std::shared_ptr<const Unit> UnitPtr;
} // namespace mtx

14
Projects/MediaMtx/main.cpp

@ -0,0 +1,14 @@
/*
MediaMtx (C++)
A C++ rewrite of the parts of MediaMTX (https://github.com/bluenviron/mediamtx, MIT license) that
la_mojo uses: RTSP camera streams are pulled, served to browsers over WebRTC (WHEP) and recorded as
fragmented MP4 segments. The source tree keeps MediaMTX's module layout (internal/...).
*/
#include "internal/core/core.h"
int main(int argc, char ** argv)
{
mtx::Core tCore;
return tCore.run(argc, argv);
}

70
Projects/MediaMtx/makefile

@ -0,0 +1,70 @@
# MediaMtx (C++) - make CFG=Release (default) or make CFG=Debug
#
# Needs: live555 (pkg-config live555, as for la_mojo), libdatachannel (>= 0.20, installed in /usr/local),
# OpenSSL. JSON: JsonCpp of dr_frucht (../../lib/include/json, ../../lib/data/json).
# Other locations: make LIVE555_CFLAGS=... LIVE555_LIBS=... DATACHANNEL_CFLAGS=-I... DATACHANNEL_LIBS="-L... -ldatachannel"
CFG ?= Release
ifeq ($(CFG),Debug)
OUTDIR = Debug
OPT = -O0 -g -DDEBUG
else
OUTDIR = Release
OPT = -O2
endif
LIVE555_CFLAGS ?= $(shell pkg-config --cflags live555 2>/dev/null)
LIVE555_LIBS ?= $(shell pkg-config --libs live555 2>/dev/null || echo -lliveMedia -lgroupsock -lBasicUsageEnvironment -lUsageEnvironment)
DATACHANNEL_CFLAGS ?=
DATACHANNEL_LIBS ?= -ldatachannel
CXX ?= g++
DFSL = ../..
CXXFLAGS += -std=c++17 -Wall -Wextra -Wno-unused-parameter $(OPT) $(LIVE555_CFLAGS) $(DATACHANNEL_CFLAGS) -I$(DFSL)/lib/include
LIBS = $(DATACHANNEL_LIBS) $(LIVE555_LIBS) -lssl -lcrypto -lpthread
TARGET = $(OUTDIR)/mediamtx
SRCS = main.cpp \
internal/logger/logger.cpp \
internal/conf/conf.cpp \
internal/codecs/h264/h264.cpp \
internal/stream/stream.cpp \
internal/staticsources/rtsp/rtspSource.cpp \
internal/protocols/httpp/httpServer.cpp \
internal/core/path.cpp \
internal/core/pathManager.cpp \
internal/core/core.cpp \
internal/recorder/fmp4Writer.cpp \
internal/recorder/recorder.cpp \
internal/servers/webrtc/session.cpp \
internal/servers/webrtc/webrtcServer.cpp \
internal/api/api.cpp
# JsonCpp from dr_frucht
JSON_SRCS = $(DFSL)/lib/data/json/json_reader.cpp \
$(DFSL)/lib/data/json/json_value.cpp \
$(DFSL)/lib/data/json/json_writer.cpp
OBJS = $(patsubst %.cpp,$(OUTDIR)/obj/%.o,$(SRCS)) $(patsubst $(DFSL)/lib/data/json/%.cpp,$(OUTDIR)/obj/jsoncpp/%.o,$(JSON_SRCS))
DEPS = $(OBJS:.o=.d)
all: $(TARGET)
$(TARGET): $(OBJS)
$(CXX) -o $@ $(OBJS) $(LDFLAGS) $(LIBS)
$(OUTDIR)/obj/%.o: %.cpp
@mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@
$(OUTDIR)/obj/jsoncpp/%.o: $(DFSL)/lib/data/json/%.cpp
@mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -w -MMD -MP -c $< -o $@
clean:
rm -rf $(OUTDIR)
-include $(DEPS)
.PHONY: all clean

6
Projects/MediaMtx/mediamtx.paths.example

@ -0,0 +1,6 @@
# MediaMtx paths: one line per stream
# name source options
# record=yes|no write fMP4 segments (--recordPath)
# transport=tcp|udp RTSP transport (tcp works through NAT / Internet)
stream_3 rtsp://user:pass@10.0.0.5:554/stream1 record=yes transport=tcp
stream_4 rtsp://10.0.0.6/live record=no transport=udp

15
Projects/MediaMtx/mediamtx.service.example

@ -0,0 +1,15 @@
# systemd unit - kernelHelperMediaMTX reads WorkingDirectory (mediamtx.log) and restarts "mediamtx.service"
[Unit]
Description=MediaMtx (C++) - RTSP cameras to WebRTC and fMP4 recordings
After=network-online.target
Wants=network-online.target
[Service]
WorkingDirectory=/srv/mediamtx
ExecStart=/usr/local/bin/mediamtx --paths /srv/mediamtx/mediamtx.paths --logFile /srv/mediamtx/mediamtx.log --logStdout no --recordPath ./recordings/%%path/%%Y-%%m-%%d_%%H-%%M-%%S-%%f --recordSegmentDuration 60s
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
Loading…
Cancel
Save