Browse Source
Embed MediaMTX functionality (WebRTC live view + recording) in kernelModuleEmbedVideo
Embed MediaMTX functionality (WebRTC live view + recording) in kernelModuleEmbedVideo
- Move reusable MediaMtx code (logger, codecs, stream, httpp, recorder, webrtc server) to lib/data/media/mtx; add ServerConf, MediaPath/ PathProvider and H264Feeder. Standalone Projects/MediaMtx builds against it. - kernelModuleEmbedVideo hosts a WHEP server (:8889/stream_<node>/whep) and one MediaPath per camera stream with fMP4 segment recording. - streamHandler feeds each path either with camera H264 passthrough (videoAVLIBSource / videoLive555AVLibSource forward encoded NALs) or with re-encoded processed frames incl. overlays (streamLiveEncoder), selected by module_eve.live_mode (optional columns, defaults apply). - kernelHelperMediaMTX: external mediamtx.service is stopped, segment indexing of the scratch folder is kept. - live555 watch variable type deduced so old and new live555 build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16pull/28/head
Failed to extract signature
49 changed files with 7780 additions and 6345 deletions
-
2Projects/MediaMtx/internal/api/api.h
-
76Projects/MediaMtx/internal/conf/conf.cpp
-
24Projects/MediaMtx/internal/conf/conf.h
-
2Projects/MediaMtx/internal/core/core.h
-
93Projects/MediaMtx/internal/core/path.cpp
-
50Projects/MediaMtx/internal/core/path.h
-
4Projects/MediaMtx/internal/core/pathManager.h
-
2Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.cpp
-
17Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.h
-
29Projects/MediaMtx/makefile
-
47Projects/la_mojo/makefile
-
38lib/App/common/MySQL_dataBinder.cpp
-
38lib/App/common/SQLite_dataBinder.cpp
-
25lib/App/common/dataBinder_structures.h
-
21lib/App/common/kernelHelperMediaMTX.cpp
-
9lib/App/common/kernelHelperMediaMTX.h
-
129lib/App/common/kernelModuleEmbedVideo.cpp
-
36lib/App/common/kernelModuleEmbedVideo.h
-
91lib/App/common/streamHandler.cpp
-
17lib/App/common/streamHandler.h
-
236lib/App/common/streamLiveEncoder.cpp
-
68lib/App/common/streamLiveEncoder.h
-
28lib/components/base/basicMediaDestination.h
-
131lib/data/media/mtx/codecs/h264/h264.cpp
-
6lib/data/media/mtx/codecs/h264/h264.h
-
83lib/data/media/mtx/conf/serverConf.cpp
-
39lib/data/media/mtx/conf/serverConf.h
-
145lib/data/media/mtx/core/mediaPath.cpp
-
100lib/data/media/mtx/core/mediaPath.h
-
209lib/data/media/mtx/feeder/h264Feeder.cpp
-
77lib/data/media/mtx/feeder/h264Feeder.h
-
15lib/data/media/mtx/logger/logger.cpp
-
6lib/data/media/mtx/logger/logger.h
-
2lib/data/media/mtx/protocols/httpp/httpServer.cpp
-
0lib/data/media/mtx/protocols/httpp/httpServer.h
-
0lib/data/media/mtx/recorder/fmp4Writer.cpp
-
0lib/data/media/mtx/recorder/fmp4Writer.h
-
2lib/data/media/mtx/recorder/recorder.cpp
-
6lib/data/media/mtx/recorder/recorder.h
-
6lib/data/media/mtx/servers/webrtc/session.cpp
-
12lib/data/media/mtx/servers/webrtc/session.h
-
4lib/data/media/mtx/servers/webrtc/webrtcServer.cpp
-
10lib/data/media/mtx/servers/webrtc/webrtcServer.h
-
0lib/data/media/mtx/stream/stream.cpp
-
0lib/data/media/mtx/stream/stream.h
-
0lib/data/media/mtx/unit/unit.h
-
26lib/data/media/video/videoAVLIBSource.cpp
-
31lib/data/media/video/videoLive555AVLibSource.cpp
-
11lib/data/media/video/videoLive555AVLibSource.h
@ -0,0 +1,236 @@ |
|||||
|
#ifndef LRF_PROXY_ONLY
|
||||
|
|
||||
|
#include "streamLiveEncoder.h"
|
||||
|
|
||||
|
extern "C" |
||||
|
{ |
||||
|
#include <libavutil/opt.h>
|
||||
|
} |
||||
|
|
||||
|
#define LOG(X) m_pLog->Log("LIVE_ENC", this, X)
|
||||
|
#define LOG_ERROR(X) m_pLog->Log("LIVE_ENC", this, _LOG_ERROR, X)
|
||||
|
|
||||
|
streamLiveEncoder::streamLiveEncoder(std::shared_ptr<mtx::MediaPath> path, int fps, int bitrateKbps) : |
||||
|
m_pLog(basicLogCollection::getInstance()), m_pPath(std::move(path)), m_oFeeder(m_pPath.get()), m_nFps(fps > 0 ? fps : 15), m_nBitrateKbps(bitrateKbps > 0 ? bitrateKbps : 2000), |
||||
|
m_bHavePending(false), m_bRun(true), m_nNextFrameUs(0), m_pCtx(NULL), m_pFrame(NULL), m_pPacket(NULL), m_pSws(NULL), m_nWidth(0), m_nHeight(0), m_nFrameIndex(0), m_nLastReaders(0), |
||||
|
m_bOpenFailed(false) |
||||
|
{ |
||||
|
m_thread = std::thread(&streamLiveEncoder::run, this); |
||||
|
} |
||||
|
|
||||
|
streamLiveEncoder::~streamLiveEncoder() |
||||
|
{ |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
m_bRun = false; |
||||
|
} |
||||
|
m_cond.notify_all(); |
||||
|
if (m_thread.joinable()) |
||||
|
{ |
||||
|
m_thread.join(); |
||||
|
} |
||||
|
m_oFeeder.setParent(nullptr); // the path is not ready any more
|
||||
|
closeEncoder(); |
||||
|
} |
||||
|
|
||||
|
void streamLiveEncoder::push(const cv::Mat & bgr) |
||||
|
{ |
||||
|
if (bgr.empty() || m_bOpenFailed) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
// Nobody watches, nothing is recorded: no CPU for encoding
|
||||
|
if (m_pPath->readerCount() == 0 && ! m_pPath->recording()) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
int64_t tNow = mtx::nowUs(); |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
if (tNow < m_nNextFrameUs) |
||||
|
{ |
||||
|
return; // above the frame rate of the live stream
|
||||
|
} |
||||
|
m_nNextFrameUs = (m_nNextFrameUs == 0 || tNow - m_nNextFrameUs > 1000000) ? tNow + 1000000 / m_nFps : m_nNextFrameUs + 1000000 / m_nFps; |
||||
|
bgr.copyTo(m_mPending); // replaces a frame the encoder did not take yet (it is late: drop)
|
||||
|
m_bHavePending = true; |
||||
|
m_cond.notify_one(); |
||||
|
} |
||||
|
|
||||
|
void streamLiveEncoder::run() |
||||
|
{ |
||||
|
pthread_setname_np(pthread_self(), "LiveEncoder"); |
||||
|
cv::Mat tFrame; |
||||
|
while (true) |
||||
|
{ |
||||
|
{ |
||||
|
std::unique_lock<std::mutex> lock(m_mutex); |
||||
|
m_cond.wait(lock, [this] { return ! m_bRun || m_bHavePending; }); |
||||
|
if (! m_bRun) |
||||
|
{ |
||||
|
break; |
||||
|
} |
||||
|
cv::swap(tFrame, m_mPending); |
||||
|
m_bHavePending = false; |
||||
|
} |
||||
|
size_t tReaders = m_pPath->readerCount(); |
||||
|
bool tIdr = tReaders > m_nLastReaders; // a new viewer: start it now, not at the next GOP
|
||||
|
m_nLastReaders = tReaders; |
||||
|
if (m_pCtx != NULL && (tFrame.cols != m_nWidth || tFrame.rows != m_nHeight)) |
||||
|
{ |
||||
|
closeEncoder(); // the frame size changed (module settings)
|
||||
|
} |
||||
|
if (m_pCtx == NULL) |
||||
|
{ |
||||
|
if (! openEncoder(tFrame.cols, tFrame.rows)) |
||||
|
{ |
||||
|
m_bOpenFailed = true; |
||||
|
break; |
||||
|
} |
||||
|
tIdr = true; |
||||
|
} |
||||
|
if (! encode(tFrame, tIdr)) |
||||
|
{ |
||||
|
closeEncoder(); // opened again with the next frame
|
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
bool streamLiveEncoder::openEncoder(int width, int height) |
||||
|
{ |
||||
|
const AVCodec * tCodec = avcodec_find_encoder_by_name("libx264"); |
||||
|
if (tCodec == NULL) |
||||
|
{ |
||||
|
tCodec = avcodec_find_encoder(AV_CODEC_ID_H264); |
||||
|
} |
||||
|
if (tCodec == NULL) |
||||
|
{ |
||||
|
LOG_ERROR("No H264 encoder in libavcodec: live view of the processed frames is not possible"); |
||||
|
return false; |
||||
|
} |
||||
|
m_pCtx = avcodec_alloc_context3(tCodec); |
||||
|
if (m_pCtx == NULL) |
||||
|
{ |
||||
|
return false; |
||||
|
} |
||||
|
m_nWidth = width & ~1; // 4:2:0 needs even sizes
|
||||
|
m_nHeight = height & ~1; |
||||
|
m_pCtx->width = m_nWidth; |
||||
|
m_pCtx->height = m_nHeight; |
||||
|
m_pCtx->pix_fmt = AV_PIX_FMT_YUV420P; |
||||
|
m_pCtx->time_base = AVRational {1, 90000}; |
||||
|
m_pCtx->framerate = AVRational {m_nFps, 1}; |
||||
|
m_pCtx->gop_size = m_nFps * 2; // a new viewer waits at most 2 s (and gets one at once, see run())
|
||||
|
m_pCtx->max_b_frames = 0; // WebRTC / fMP4 writer: dts = pts
|
||||
|
m_pCtx->bit_rate = (int64_t) m_nBitrateKbps * 1000; |
||||
|
m_pCtx->rc_max_rate = m_pCtx->bit_rate; |
||||
|
m_pCtx->rc_buffer_size = (int) m_pCtx->bit_rate; // 1 s
|
||||
|
m_pCtx->thread_count = 2; |
||||
|
m_pCtx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE; |
||||
|
if (strcmp(tCodec->name, "libx264") == 0) |
||||
|
{ |
||||
|
av_opt_set(m_pCtx->priv_data, "preset", "veryfast", 0); |
||||
|
av_opt_set(m_pCtx->priv_data, "tune", "zerolatency", 0); |
||||
|
av_opt_set(m_pCtx->priv_data, "profile", "baseline", 0); |
||||
|
av_opt_set(m_pCtx->priv_data, "x264-params", "repeat-headers=1", 0); // SPS / PPS with every IDR
|
||||
|
av_opt_set(m_pCtx->priv_data, "forced-idr", "1", 0); // a forced key frame is an IDR
|
||||
|
} |
||||
|
int tRet = avcodec_open2(m_pCtx, tCodec, NULL); |
||||
|
if (tRet < 0) |
||||
|
{ |
||||
|
char tE[128], tB[256]; |
||||
|
av_strerror(tRet, tE, sizeof(tE)); |
||||
|
snprintf(tB, sizeof(tB), "Cannot open the H264 encoder %s: %s", tCodec->name, tE); |
||||
|
LOG_ERROR(tB); |
||||
|
avcodec_free_context(&m_pCtx); |
||||
|
return false; |
||||
|
} |
||||
|
m_pFrame = av_frame_alloc(); |
||||
|
m_pPacket = av_packet_alloc(); |
||||
|
m_pSws = sws_getContext(width, height, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); |
||||
|
if (m_pFrame == NULL || m_pPacket == NULL || m_pSws == NULL) |
||||
|
{ |
||||
|
LOG_ERROR("Live encoder: allocation failed"); |
||||
|
closeEncoder(); |
||||
|
return false; |
||||
|
} |
||||
|
m_pFrame->format = AV_PIX_FMT_YUV420P; |
||||
|
m_pFrame->width = m_nWidth; |
||||
|
m_pFrame->height = m_nHeight; |
||||
|
if (av_frame_get_buffer(m_pFrame, 32) < 0) |
||||
|
{ |
||||
|
closeEncoder(); |
||||
|
return false; |
||||
|
} |
||||
|
if (m_pCtx->extradata != NULL && m_pCtx->extradata_size > 0) |
||||
|
{ |
||||
|
m_oFeeder.setExtradata(m_pCtx->extradata, m_pCtx->extradata_size); |
||||
|
} |
||||
|
char tB[200]; |
||||
|
snprintf(tB, sizeof(tB), "H264 encoder %s opened: %dx%d, %d fps, %d kbit/s", tCodec->name, m_nWidth, m_nHeight, m_nFps, m_nBitrateKbps); |
||||
|
LOG(tB); |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
void streamLiveEncoder::closeEncoder() |
||||
|
{ |
||||
|
if (m_pSws != NULL) |
||||
|
{ |
||||
|
sws_freeContext(m_pSws); |
||||
|
m_pSws = NULL; |
||||
|
} |
||||
|
av_frame_free(&m_pFrame); |
||||
|
av_packet_free(&m_pPacket); |
||||
|
avcodec_free_context(&m_pCtx); |
||||
|
m_nWidth = 0; |
||||
|
m_nHeight = 0; |
||||
|
} |
||||
|
|
||||
|
bool streamLiveEncoder::encode(const cv::Mat & bgr, bool forceIdr) |
||||
|
{ |
||||
|
if (av_frame_make_writable(m_pFrame) < 0) |
||||
|
{ |
||||
|
return false; |
||||
|
} |
||||
|
const uint8_t * tSrc[1] = {bgr.data}; |
||||
|
int tStep[1] = {(int) bgr.step[0]}; |
||||
|
sws_scale(m_pSws, tSrc, tStep, 0, bgr.rows, m_pFrame->data, m_pFrame->linesize); |
||||
|
int64_t tNowUs = mtx::nowUs(); |
||||
|
m_pFrame->pts = tNowUs * 9 / 100; // 90 kHz wall clock: the real frame timing
|
||||
|
m_pFrame->pict_type = forceIdr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE; |
||||
|
int tRet = avcodec_send_frame(m_pCtx, m_pFrame); |
||||
|
if (tRet < 0) |
||||
|
{ |
||||
|
LOG_ERROR("Live encoder: send frame failed"); |
||||
|
return false; |
||||
|
} |
||||
|
while (true) |
||||
|
{ |
||||
|
tRet = avcodec_receive_packet(m_pCtx, m_pPacket); |
||||
|
if (tRet == AVERROR(EAGAIN) || tRet == AVERROR_EOF) |
||||
|
{ |
||||
|
break; |
||||
|
} |
||||
|
if (tRet < 0) |
||||
|
{ |
||||
|
LOG_ERROR("Live encoder: receive packet failed"); |
||||
|
return false; |
||||
|
} |
||||
|
int64_t tPtsUs = (m_pPacket->pts != AV_NOPTS_VALUE) ? m_pPacket->pts * 100 / 9 : tNowUs; |
||||
|
if (m_oFeeder.avccLengthSize() > 0) |
||||
|
{ |
||||
|
m_oFeeder.pushAvcc(m_pPacket->data, m_pPacket->size, m_oFeeder.avccLengthSize(), tPtsUs); |
||||
|
} |
||||
|
else |
||||
|
{ |
||||
|
m_oFeeder.pushAnnexB(m_pPacket->data, m_pPacket->size, tPtsUs); |
||||
|
} |
||||
|
av_packet_unref(m_pPacket); |
||||
|
} |
||||
|
m_nFrameIndex++; |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
#undef LOG
|
||||
|
#undef LOG_ERROR
|
||||
|
|
||||
|
#endif // !LRF_PROXY_ONLY
|
||||
@ -0,0 +1,68 @@ |
|||||
|
#ifndef __STREAM_LIVE_ENCODER_HEADER__ |
||||
|
#define __STREAM_LIVE_ENCODER_HEADER__ |
||||
|
|
||||
|
#ifndef LRF_PROXY_ONLY |
||||
|
|
||||
|
/* |
||||
|
Live view of the processed frames (kernelModuleEmbedVideo live_mode EVE_LIVE_ENCODE) |
||||
|
|
||||
|
streamHandler hands every processed frame (scaled, flipped, with the time stamp / label / logo / event |
||||
|
marks) to push(); the encoder thread encodes the newest one to H264 (libx264 when available, zero |
||||
|
latency, no B-frames, constrained baseline: every browser decodes it) and feeds the path (WebRTC |
||||
|
readers, recorder). A slow encoder drops frames, it never blocks the source. |
||||
|
Nothing is encoded while the path has no reader and does not record. A new reader gets an IDR at once. |
||||
|
*/ |
||||
|
|
||||
|
#include <condition_variable> |
||||
|
#include <memory> |
||||
|
#include <mutex> |
||||
|
#include <thread> |
||||
|
|
||||
|
#include "../../components/base/basicLIBAV.h" |
||||
|
#include "../../components/base/basicLogCollection.h" |
||||
|
#include "../../data/media/mtx/core/mediaPath.h" |
||||
|
#include "../../data/media/mtx/feeder/h264Feeder.h" |
||||
|
|
||||
|
class streamLiveEncoder |
||||
|
{ |
||||
|
public: |
||||
|
streamLiveEncoder(std::shared_ptr<mtx::MediaPath> path, int fps, int bitrateKbps); |
||||
|
~streamLiveEncoder(); |
||||
|
|
||||
|
// From the frame thread: copies the frame when the encoder wants one (frame rate, readers) |
||||
|
void push(const cv::Mat & bgr); |
||||
|
|
||||
|
private: |
||||
|
void run(); |
||||
|
bool openEncoder(int width, int height); |
||||
|
void closeEncoder(); |
||||
|
bool encode(const cv::Mat & bgr, bool forceIdr); |
||||
|
|
||||
|
basicLogCollection * m_pLog; |
||||
|
std::shared_ptr<mtx::MediaPath> m_pPath; |
||||
|
mtx::H264Feeder m_oFeeder; |
||||
|
int m_nFps; |
||||
|
int m_nBitrateKbps; |
||||
|
|
||||
|
std::mutex m_mutex; |
||||
|
std::condition_variable m_cond; |
||||
|
cv::Mat m_mPending; |
||||
|
bool m_bHavePending; |
||||
|
bool m_bRun; |
||||
|
int64_t m_nNextFrameUs; // frame rate limit |
||||
|
std::thread m_thread; |
||||
|
|
||||
|
// encoder (encoder thread only) |
||||
|
AVCodecContext * m_pCtx; |
||||
|
AVFrame * m_pFrame; |
||||
|
AVPacket * m_pPacket; |
||||
|
SwsContext * m_pSws; |
||||
|
int m_nWidth; |
||||
|
int m_nHeight; |
||||
|
int64_t m_nFrameIndex; |
||||
|
size_t m_nLastReaders; |
||||
|
bool m_bOpenFailed; |
||||
|
}; |
||||
|
|
||||
|
#endif // !LRF_PROXY_ONLY |
||||
|
#endif |
||||
@ -0,0 +1,83 @@ |
|||||
|
#include "serverConf.h"
|
||||
|
|
||||
|
#include <cstdlib>
|
||||
|
|
||||
|
namespace mtx { |
||||
|
|
||||
|
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 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); |
||||
|
} |
||||
|
|
||||
|
} // namespace mtx
|
||||
@ -0,0 +1,39 @@ |
|||||
|
/* |
||||
|
MediaMtx (C++) - settings of the reusable parts (WebRTC server, recorder) |
||||
|
|
||||
|
Shared by the stand-alone server (Projects/MediaMtx, which adds the command line, the paths file, the |
||||
|
RTSP sources and the API) and la_mojo (kernelModuleEmbedVideo, which feeds the streams itself). |
||||
|
The names follow MediaMTX (webrtcAddress, recordPath, ...). |
||||
|
*/ |
||||
|
#pragma once |
||||
|
|
||||
|
#include <cstdint> |
||||
|
#include <string> |
||||
|
#include <vector> |
||||
|
|
||||
|
namespace mtx { |
||||
|
|
||||
|
struct ServerConf |
||||
|
{ |
||||
|
// 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; |
||||
|
}; |
||||
|
|
||||
|
// "60s", "1m", "500ms", "1h", "1.5s"; plain number = seconds |
||||
|
bool parseDurationMs(const std::string & s, int64_t & ms); |
||||
|
// "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 |
||||
@ -0,0 +1,145 @@ |
|||||
|
#include "mediaPath.h"
|
||||
|
|
||||
|
#include "../recorder/recorder.h"
|
||||
|
|
||||
|
namespace mtx { |
||||
|
|
||||
|
MediaPath::MediaPath(const std::string & name, bool record, const ServerConf & global) : LogParent("[path " + name + "] "), m_sName(name), m_bRecord(record), m_global(global) {} |
||||
|
|
||||
|
MediaPath::~MediaPath() |
||||
|
{ |
||||
|
sourceSetNotReady(); |
||||
|
} |
||||
|
|
||||
|
PathInfo MediaPath::info() const |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
PathInfo tI; |
||||
|
tI.name = m_sName; |
||||
|
tI.record = m_bRecord; |
||||
|
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 MediaPath::isReady() const |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
return m_pStream != nullptr; |
||||
|
} |
||||
|
|
||||
|
size_t MediaPath::readerCount() const |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
return m_readers.size(); |
||||
|
} |
||||
|
|
||||
|
bool MediaPath::recording() const |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
return m_bRecord; |
||||
|
} |
||||
|
|
||||
|
void MediaPath::setRecord(bool record) |
||||
|
{ |
||||
|
std::unique_ptr<Recorder> tOld; |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
if (m_bRecord == record) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
m_bRecord = record; |
||||
|
if (! record) |
||||
|
{ |
||||
|
tOld = std::move(m_pRecorder); |
||||
|
} |
||||
|
else if (m_pStream) |
||||
|
{ |
||||
|
m_pRecorder.reset(new Recorder(m_sName, m_global, m_pStream, this)); |
||||
|
m_pRecorder->start(); |
||||
|
} |
||||
|
} |
||||
|
tOld.reset(); // closes the segment (not under the lock)
|
||||
|
log(LogLevel::Info, "recording %s", record ? "enabled" : "disabled"); |
||||
|
} |
||||
|
|
||||
|
bool MediaPath::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_sName + "'"; |
||||
|
return false; |
||||
|
} |
||||
|
desc = m_pStream->desc(); |
||||
|
m_readers.insert(r); |
||||
|
m_pStream->addReader(r); |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
void MediaPath::removeReader(PathReader * r) |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
if (m_readers.erase(r) > 0 && m_pStream) |
||||
|
{ |
||||
|
m_pStream->removeReader(r); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
void MediaPath::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_bRecord) |
||||
|
{ |
||||
|
m_pRecorder.reset(new Recorder(m_sName, m_global, m_pStream, this)); |
||||
|
m_pRecorder->start(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
void MediaPath::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 MediaPath::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
|
||||
@ -0,0 +1,100 @@ |
|||||
|
/* |
||||
|
MediaMtx (C++) - media path (MediaMTX: internal/core/path.go, without the source) |
||||
|
|
||||
|
A path has a stream while its source is ready, an optional recorder and the readers (WebRTC sessions). |
||||
|
The source is whatever feeds it: an RTSP client (Projects/MediaMtx) or la_mojo's streamHandler |
||||
|
(camera H264 as it is, or the processed frames encoded again). |
||||
|
*/ |
||||
|
#pragma once |
||||
|
|
||||
|
#include <memory> |
||||
|
#include <mutex> |
||||
|
#include <set> |
||||
|
#include <string> |
||||
|
|
||||
|
#include "../conf/serverConf.h" |
||||
|
#include "../logger/logger.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; |
||||
|
}; |
||||
|
|
||||
|
// What a source calls on its path |
||||
|
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; |
||||
|
}; |
||||
|
|
||||
|
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 MediaPath : public SourceParent, public LogParent |
||||
|
{ |
||||
|
public: |
||||
|
MediaPath(const std::string & name, bool record, const ServerConf & global); |
||||
|
~MediaPath() override; |
||||
|
|
||||
|
const std::string & name() const { return m_sName; } |
||||
|
PathInfo info() const; |
||||
|
bool isReady() const; |
||||
|
size_t readerCount() const; |
||||
|
bool recording() const; |
||||
|
// Starts / stops the recorder (a running stream is recorded from its next IDR) |
||||
|
void setRecord(bool record); |
||||
|
|
||||
|
// 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; |
||||
|
|
||||
|
protected: |
||||
|
std::string m_sName; |
||||
|
bool m_bRecord; |
||||
|
ServerConf m_global; |
||||
|
|
||||
|
private: |
||||
|
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; |
||||
|
}; |
||||
|
|
||||
|
// Finds a path by name (the WebRTC server asks it for the path of a WHEP request) |
||||
|
class PathProvider |
||||
|
{ |
||||
|
public: |
||||
|
virtual ~PathProvider() {} |
||||
|
virtual std::shared_ptr<MediaPath> findPath(const std::string & name) const = 0; |
||||
|
}; |
||||
|
|
||||
|
} // namespace mtx |
||||
@ -0,0 +1,209 @@ |
|||||
|
#include "h264Feeder.h"
|
||||
|
|
||||
|
#include <memory>
|
||||
|
|
||||
|
#include "../codecs/h264/h264.h"
|
||||
|
|
||||
|
namespace mtx { |
||||
|
|
||||
|
void H264Feeder::setParent(SourceParent * parent) |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
if (parent == m_pParent) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
if (m_pParent != nullptr && m_bReady) |
||||
|
{ |
||||
|
m_pParent->sourceSetNotReady(); |
||||
|
} |
||||
|
m_pParent = parent; |
||||
|
m_bReady = false; |
||||
|
m_vNalus.clear(); |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::setParameterSets(const std::vector<Bytes> & nalus) |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
for (const Bytes & n : nalus) |
||||
|
{ |
||||
|
if (h264::naluType(n) == h264::NALU_SPS) |
||||
|
{ |
||||
|
m_sps = n; |
||||
|
} |
||||
|
else if (h264::naluType(n) == h264::NALU_PPS) |
||||
|
{ |
||||
|
m_pps = n; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::setExtradata(const uint8_t * data, size_t size) |
||||
|
{ |
||||
|
int tLen = 0; |
||||
|
std::vector<Bytes> tSets = h264::parameterSetsFromExtradata(data, size, &tLen); |
||||
|
m_nAvccLengthSize = tLen; |
||||
|
setParameterSets(tSets); |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::pushNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced) |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
// A new presentation time starts a new unit (a camera that does not set the marker bit). Small changes
|
||||
|
// are not a new unit: every RTCP sender report moves live555's mapping a little, also within a picture.
|
||||
|
if (! m_vNalus.empty() && (ptUs - m_nPtUs > 2000 || m_nPtUs - ptUs > 2000)) |
||||
|
{ |
||||
|
flushLocked(); |
||||
|
} |
||||
|
if (data != nullptr && size > 0) |
||||
|
{ |
||||
|
int tType = data[0] & 0x1f; |
||||
|
if (tType != h264::NALU_AUD && tType != 0) |
||||
|
{ |
||||
|
m_vNalus.emplace_back(data, data + size); |
||||
|
} |
||||
|
} |
||||
|
if (m_vNalus.size() <= 1) |
||||
|
{ |
||||
|
m_nPtUs = ptUs; // the time of the unit is the time of its first NAL unit
|
||||
|
m_bSynced = synced; |
||||
|
} |
||||
|
if (marker) |
||||
|
{ |
||||
|
flushLocked(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::pushAnnexB(const uint8_t * data, size_t size, int64_t ptsUs) |
||||
|
{ |
||||
|
std::vector<Bytes> tNalus = h264::splitAnnexB(data, size); |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
m_bSynced = false; |
||||
|
unitLocked(std::move(tNalus), ptsUs >= 0 ? ptsUs : nowUs(), nowUs()); |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::pushAvcc(const uint8_t * data, size_t size, int lengthSize, int64_t ptsUs) |
||||
|
{ |
||||
|
std::vector<Bytes> tNalus = h264::splitAvcc(data, size, lengthSize); |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
m_bSynced = false; |
||||
|
unitLocked(std::move(tNalus), ptsUs >= 0 ? ptsUs : nowUs(), nowUs()); |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::flushLocked() |
||||
|
{ |
||||
|
if (m_vNalus.empty()) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
std::vector<Bytes> tNalus; |
||||
|
tNalus.swap(m_vNalus); |
||||
|
unitLocked(std::move(tNalus), m_nPtUs, m_nPtUs); |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::unitLocked(std::vector<Bytes> && nalus, int64_t ptUs, int64_t wallUs) |
||||
|
{ |
||||
|
if (nalus.empty() || m_pParent == nullptr) |
||||
|
{ |
||||
|
return; |
||||
|
} |
||||
|
bool tIdr = false; |
||||
|
for (const Bytes & n : nalus) |
||||
|
{ |
||||
|
int t = h264::naluType(n); |
||||
|
if (t == h264::NALU_SPS) |
||||
|
{ |
||||
|
m_sps = n; |
||||
|
} |
||||
|
else if (t == h264::NALU_PPS) |
||||
|
{ |
||||
|
m_pps = n; |
||||
|
} |
||||
|
else if (t == h264::NALU_IDR) |
||||
|
{ |
||||
|
tIdr = true; |
||||
|
} |
||||
|
} |
||||
|
// 90 kHz pts starting at 0. A jump (RTCP synchronisation, a restarted source, a clock step) is replaced
|
||||
|
// by one frame interval: the readers need increasing time stamps.
|
||||
|
int64_t tRaw = ptUs * 9 / 100; |
||||
|
if (! m_bHavePts) |
||||
|
{ |
||||
|
m_bHavePts = true; |
||||
|
m_bLastSynced = m_bSynced; |
||||
|
m_nOffset = -tRaw; |
||||
|
} |
||||
|
else if (m_bSynced != m_bLastSynced) |
||||
|
{ |
||||
|
m_bLastSynced = m_bSynced; |
||||
|
m_nOffset = m_nLastPts + m_nLastDelta - tRaw; |
||||
|
} |
||||
|
int64_t tPts = tRaw + m_nOffset; |
||||
|
if (tPts <= m_nLastPts && m_nUnits > 0) |
||||
|
{ |
||||
|
if (tPts == m_nLastPts) |
||||
|
{ |
||||
|
tPts = m_nLastPts + 1; // same time stamp (should not happen): keep increasing
|
||||
|
} |
||||
|
else |
||||
|
{ |
||||
|
m_nOffset = m_nLastPts + m_nLastDelta - tRaw; |
||||
|
tPts = tRaw + m_nOffset; |
||||
|
} |
||||
|
} |
||||
|
else if (tPts - m_nLastPts >= 90000 * 5 && m_nUnits > 0) |
||||
|
{ |
||||
|
m_nOffset = m_nLastPts + m_nLastDelta - tRaw; // a gap of 5 s or more: a clock step, not a pause
|
||||
|
tPts = tRaw + m_nOffset; |
||||
|
} |
||||
|
else if (m_nUnits > 0 && tPts - m_nLastPts < 90000) |
||||
|
{ |
||||
|
m_nLastDelta = tPts - m_nLastPts; |
||||
|
} |
||||
|
m_nLastPts = tPts; |
||||
|
|
||||
|
if (! m_bReady) |
||||
|
{ |
||||
|
if (m_sps.empty() || m_pps.empty()) |
||||
|
{ |
||||
|
return; // a reader cannot use the stream without the codec parameters
|
||||
|
} |
||||
|
StreamDesc tDesc; |
||||
|
h264::SpsInfo tInfo; |
||||
|
tDesc.sps = m_sps; |
||||
|
tDesc.pps = m_pps; |
||||
|
if (h264::parseSps(m_sps, tInfo)) |
||||
|
{ |
||||
|
tDesc.width = tInfo.width; |
||||
|
tDesc.height = tInfo.height; |
||||
|
} |
||||
|
m_bReady = true; |
||||
|
m_pParent->sourceSetReady(tDesc); |
||||
|
} |
||||
|
auto tUnit = std::make_shared<Unit>(); |
||||
|
tUnit->pts = tPts; |
||||
|
tUnit->ntpUs = wallUs; |
||||
|
tUnit->idr = tIdr; |
||||
|
tUnit->nalus = std::move(nalus); |
||||
|
m_nUnits++; |
||||
|
m_pParent->sourceWriteUnit(tUnit); |
||||
|
} |
||||
|
|
||||
|
void H264Feeder::reset() |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
m_vNalus.clear(); |
||||
|
if (m_pParent != nullptr && m_bReady) |
||||
|
{ |
||||
|
m_pParent->sourceSetNotReady(); |
||||
|
} |
||||
|
m_bReady = false; |
||||
|
} |
||||
|
|
||||
|
bool H264Feeder::ready() const |
||||
|
{ |
||||
|
std::lock_guard<std::mutex> lock(m_mutex); |
||||
|
return m_bReady; |
||||
|
} |
||||
|
|
||||
|
} // namespace mtx
|
||||
@ -0,0 +1,77 @@ |
|||||
|
/* |
||||
|
MediaMtx (C++) - H264 feeder |
||||
|
|
||||
|
Turns the H264 an application already receives into units of a path (MediaPath): |
||||
|
- NAL units one at a time, as an RTP depacketizer (live555) gives them: grouped into access units by |
||||
|
the RTP marker bit / a new presentation time; |
||||
|
- whole access units in Annex-B (libav RTSP demuxer, H264 encoders) or length prefixed (MP4 / avcC). |
||||
|
The pts is made continuous (90 kHz, starting at 0, always increasing): a reader (recorder, WebRTC) sees |
||||
|
no jumps when the presentation times move onto the RTCP clock or a source restarts. |
||||
|
The path becomes ready when SPS and PPS are known (out of band from the SDP / extradata, or in-band), |
||||
|
and not ready on reset() (the source stopped). |
||||
|
Thread safe: the source thread pushes, any thread may reset() / setParent(). |
||||
|
*/ |
||||
|
#pragma once |
||||
|
|
||||
|
#include <cstdint> |
||||
|
#include <mutex> |
||||
|
#include <vector> |
||||
|
|
||||
|
#include "../core/mediaPath.h" |
||||
|
#include "../unit/unit.h" |
||||
|
|
||||
|
namespace mtx { |
||||
|
|
||||
|
class H264Feeder |
||||
|
{ |
||||
|
public: |
||||
|
explicit H264Feeder(SourceParent * parent = nullptr) : m_pParent(parent) {} |
||||
|
~H264Feeder() { reset(); } |
||||
|
|
||||
|
// The path to feed (nullptr: none). The previous path is set not ready. |
||||
|
void setParent(SourceParent * parent); |
||||
|
|
||||
|
// Out of band parameter sets (sprop-parameter-sets of the SDP, libav extradata) |
||||
|
void setParameterSets(const std::vector<Bytes> & nalus); |
||||
|
void setExtradata(const uint8_t * data, size_t size); |
||||
|
|
||||
|
// One NAL unit (no start code). ptUs: presentation time (us); marker: last NAL unit of the access |
||||
|
// unit (RTP marker bit); synced: the presentation times are RTCP synchronised (a change = a jump) |
||||
|
void pushNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced = false); |
||||
|
// One access unit. ptsUs: presentation time (us, any origin); < 0: use the wall clock |
||||
|
void pushAnnexB(const uint8_t * data, size_t size, int64_t ptsUs); |
||||
|
void pushAvcc(const uint8_t * data, size_t size, int lengthSize, int64_t ptsUs); |
||||
|
// length prefix size of the avcC extradata (0: the packets are Annex-B) |
||||
|
int avccLengthSize() const { return m_nAvccLengthSize; } |
||||
|
|
||||
|
// The source stopped (or reconnects): the path is set not ready, the parameter sets are kept |
||||
|
void reset(); |
||||
|
bool ready() const; |
||||
|
uint64_t units() const { return m_nUnits; } |
||||
|
|
||||
|
private: |
||||
|
void flushLocked(); |
||||
|
void unitLocked(std::vector<Bytes> && nalus, int64_t ptUs, int64_t wallUs); |
||||
|
|
||||
|
mutable std::mutex m_mutex; |
||||
|
SourceParent * m_pParent = nullptr; |
||||
|
Bytes m_sps; |
||||
|
Bytes m_pps; |
||||
|
bool m_bReady = false; |
||||
|
int m_nAvccLengthSize = 0; |
||||
|
uint64_t m_nUnits = 0; |
||||
|
|
||||
|
// NAL unit assembly |
||||
|
std::vector<Bytes> m_vNalus; |
||||
|
int64_t m_nPtUs = 0; |
||||
|
bool m_bSynced = false; |
||||
|
|
||||
|
// pts continuity |
||||
|
bool m_bHavePts = false; |
||||
|
bool m_bLastSynced = false; |
||||
|
int64_t m_nOffset = 0; |
||||
|
int64_t m_nLastPts = 0; |
||||
|
int64_t m_nLastDelta = 3000; |
||||
|
}; |
||||
|
|
||||
|
} // namespace mtx |
||||
Write
Preview
Loading…
Cancel
Save
Reference in new issue