Browse Source

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_0139veDo3XyavMuVhdnHcN16
pull/28/head
Claude 9 hours ago
parent
commit
13387b3f0d
Failed to extract signature
  1. 2
      Projects/MediaMtx/internal/api/api.h
  2. 76
      Projects/MediaMtx/internal/conf/conf.cpp
  3. 24
      Projects/MediaMtx/internal/conf/conf.h
  4. 2
      Projects/MediaMtx/internal/core/core.h
  5. 93
      Projects/MediaMtx/internal/core/path.cpp
  6. 50
      Projects/MediaMtx/internal/core/path.h
  7. 4
      Projects/MediaMtx/internal/core/pathManager.h
  8. 2
      Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.cpp
  9. 17
      Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.h
  10. 29
      Projects/MediaMtx/makefile
  11. 47
      Projects/la_mojo/makefile
  12. 38
      lib/App/common/MySQL_dataBinder.cpp
  13. 38
      lib/App/common/SQLite_dataBinder.cpp
  14. 25
      lib/App/common/dataBinder_structures.h
  15. 21
      lib/App/common/kernelHelperMediaMTX.cpp
  16. 9
      lib/App/common/kernelHelperMediaMTX.h
  17. 129
      lib/App/common/kernelModuleEmbedVideo.cpp
  18. 36
      lib/App/common/kernelModuleEmbedVideo.h
  19. 91
      lib/App/common/streamHandler.cpp
  20. 17
      lib/App/common/streamHandler.h
  21. 236
      lib/App/common/streamLiveEncoder.cpp
  22. 68
      lib/App/common/streamLiveEncoder.h
  23. 28
      lib/components/base/basicMediaDestination.h
  24. 131
      lib/data/media/mtx/codecs/h264/h264.cpp
  25. 6
      lib/data/media/mtx/codecs/h264/h264.h
  26. 83
      lib/data/media/mtx/conf/serverConf.cpp
  27. 39
      lib/data/media/mtx/conf/serverConf.h
  28. 145
      lib/data/media/mtx/core/mediaPath.cpp
  29. 100
      lib/data/media/mtx/core/mediaPath.h
  30. 209
      lib/data/media/mtx/feeder/h264Feeder.cpp
  31. 77
      lib/data/media/mtx/feeder/h264Feeder.h
  32. 15
      lib/data/media/mtx/logger/logger.cpp
  33. 6
      lib/data/media/mtx/logger/logger.h
  34. 2
      lib/data/media/mtx/protocols/httpp/httpServer.cpp
  35. 0
      lib/data/media/mtx/protocols/httpp/httpServer.h
  36. 0
      lib/data/media/mtx/recorder/fmp4Writer.cpp
  37. 0
      lib/data/media/mtx/recorder/fmp4Writer.h
  38. 2
      lib/data/media/mtx/recorder/recorder.cpp
  39. 6
      lib/data/media/mtx/recorder/recorder.h
  40. 6
      lib/data/media/mtx/servers/webrtc/session.cpp
  41. 12
      lib/data/media/mtx/servers/webrtc/session.h
  42. 4
      lib/data/media/mtx/servers/webrtc/webrtcServer.cpp
  43. 10
      lib/data/media/mtx/servers/webrtc/webrtcServer.h
  44. 0
      lib/data/media/mtx/stream/stream.cpp
  45. 0
      lib/data/media/mtx/stream/stream.h
  46. 0
      lib/data/media/mtx/unit/unit.h
  47. 26
      lib/data/media/video/videoAVLIBSource.cpp
  48. 31
      lib/data/media/video/videoLive555AVLibSource.cpp
  49. 11
      lib/data/media/video/videoLive555AVLibSource.h

2
Projects/MediaMtx/internal/api/api.h

@ -20,7 +20,7 @@
#include "../conf/conf.h" #include "../conf/conf.h"
#include "../core/pathManager.h" #include "../core/pathManager.h"
#include "../protocols/httpp/httpServer.h"
#include <protocols/httpp/httpServer.h>
namespace mtx { namespace mtx {

76
Projects/MediaMtx/internal/conf/conf.cpp

@ -34,44 +34,6 @@ static bool parseBool(const std::string & v, bool & out)
return false; 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) bool validPathName(const std::string & name)
{ {
if (name.empty() || name.size() > 128) if (name.empty() || name.size() > 128)
@ -88,44 +50,6 @@ bool validPathName(const std::string & name)
return name != "." && name != ".."; 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) static bool parsePathLine(const std::string & line, PathConf & pc, std::string & err)
{ {
std::istringstream tIn(line); std::istringstream tIn(line);

24
Projects/MediaMtx/internal/conf/conf.h

@ -17,7 +17,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "../logger/logger.h"
#include <conf/serverConf.h>
#include <logger/logger.h>
namespace mtx { namespace mtx {
@ -34,7 +35,7 @@ struct PathConf
bool operator!=(const PathConf & o) const { return ! (*this == o); } bool operator!=(const PathConf & o) const { return ! (*this == o); }
}; };
struct Conf
struct Conf : public ServerConf
{ {
// general // general
LogLevel logLevel = LogLevel::Info; LogLevel logLevel = LogLevel::Info;
@ -46,19 +47,6 @@ struct Conf
// control API (empty address: disabled) // control API (empty address: disabled)
std::string apiAddress = "127.0.0.1:9997"; 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 // paths
std::string pathsFile; std::string pathsFile;
std::vector<PathConf> paths; // paths file + command line std::vector<PathConf> paths; // paths file + command line
@ -73,12 +61,6 @@ struct Conf
bool loadPathsFile(const std::string & file, std::vector<PathConf> & out, std::string & err); 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); 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); 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 } // namespace mtx

2
Projects/MediaMtx/internal/core/core.h

@ -11,7 +11,7 @@
#include "../api/api.h" #include "../api/api.h"
#include "../conf/conf.h" #include "../conf/conf.h"
#include "../servers/webrtc/webrtcServer.h"
#include <servers/webrtc/webrtcServer.h>
#include "pathManager.h" #include "pathManager.h"
namespace mtx { namespace mtx {

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

@ -1,10 +1,8 @@
#include "path.h" #include "path.h"
#include "../recorder/recorder.h"
namespace mtx { namespace mtx {
Path::Path(const PathConf & conf, const Conf & global) : LogParent("[path " + conf.name + "] "), m_conf(conf), m_global(global) {}
Path::Path(const PathConf & conf, const Conf & global) : MediaPath(conf.name, conf.record, global), m_conf(conf), m_fullConf(global) {}
Path::~Path() Path::~Path()
{ {
@ -13,7 +11,7 @@ Path::~Path()
void Path::start() void Path::start()
{ {
m_pSource.reset(new RtspSource(m_conf, m_global, this));
m_pSource.reset(new RtspSource(m_conf, m_fullConf, this));
m_pSource->start(); m_pSource->start();
} }
@ -28,92 +26,9 @@ void Path::stop()
PathInfo Path::info() const 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();
}
PathInfo tI = MediaPath::info();
tI.source = m_conf.source;
return tI; 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 } // namespace mtx

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

@ -1,46 +1,20 @@
/* /*
MediaMtx (C++) - path (MediaMTX: internal/core/path.go) 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).
A MediaPath (lib/data/media/mtx: stream, readers, recorder) with a static source (RTSP camera).
*/ */
#pragma once #pragma once
#include <memory> #include <memory>
#include <mutex>
#include <set>
#include <string> #include <string>
#include <core/mediaPath.h>
#include "../conf/conf.h" #include "../conf/conf.h"
#include "../logger/logger.h"
#include "../staticsources/rtsp/rtspSource.h" #include "../staticsources/rtsp/rtspSource.h"
#include "../stream/stream.h"
namespace mtx { 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
class Path : public MediaPath
{ {
public: public:
Path(const PathConf & conf, const Conf & global); Path(const PathConf & conf, const Conf & global);
@ -52,24 +26,10 @@ class Path : public SourceParent, public LogParent
const PathConf & conf() const { return m_conf; } const PathConf & conf() const { return m_conf; }
PathInfo info() const; 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: private:
PathConf m_conf; PathConf m_conf;
Conf m_global;
Conf m_fullConf;
std::unique_ptr<RtspSource> m_pSource; 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 } // namespace mtx

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

@ -14,7 +14,7 @@
namespace mtx { namespace mtx {
class PathManager : public LogParent
class PathManager : public LogParent, public PathProvider
{ {
public: public:
explicit PathManager(const Conf & global); explicit PathManager(const Conf & global);
@ -25,6 +25,8 @@ class PathManager : public LogParent
void closeAll(); void closeAll();
std::shared_ptr<Path> find(const std::string & name) const; std::shared_ptr<Path> find(const std::string & name) const;
// PathProvider (WebRTC server)
std::shared_ptr<MediaPath> findPath(const std::string & name) const override { return find(name); }
std::vector<PathInfo> list() const; std::vector<PathInfo> list() const;
std::vector<PathConf> confs() const; std::vector<PathConf> confs() const;

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

@ -6,7 +6,7 @@
#include <type_traits> #include <type_traits>
#include "../../codecs/h264/h264.h"
#include <codecs/h264/h264.h>
namespace mtx { namespace mtx {

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

@ -14,23 +14,12 @@
#include <thread> #include <thread>
#include "../../conf/conf.h" #include "../../conf/conf.h"
#include "../../logger/logger.h"
#include "../../stream/stream.h"
#include <logger/logger.h>
#include <stream/stream.h>
#include <core/mediaPath.h>
namespace mtx { 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 class RtspSource : public LogParent
{ {
public: public:

29
Projects/MediaMtx/makefile

@ -20,33 +20,38 @@ DATACHANNEL_LIBS ?= -ldatachannel
CXX ?= g++ CXX ?= g++
DFSL = ../.. DFSL = ../..
CXXFLAGS += -std=c++17 -Wall -Wextra -Wno-unused-parameter $(OPT) $(LIVE555_CFLAGS) $(DATACHANNEL_CFLAGS) -I$(DFSL)/lib/include
MTXLIB = $(DFSL)/lib/data/media/mtx
CXXFLAGS += -std=c++17 -Wall -Wextra -Wno-unused-parameter $(OPT) $(LIVE555_CFLAGS) $(DATACHANNEL_CFLAGS) -I$(DFSL)/lib/include -I$(MTXLIB)
LIBS = $(DATACHANNEL_LIBS) $(LIVE555_LIBS) -lssl -lcrypto -lpthread LIBS = $(DATACHANNEL_LIBS) $(LIVE555_LIBS) -lssl -lcrypto -lpthread
TARGET = $(OUTDIR)/mediamtx TARGET = $(OUTDIR)/mediamtx
SRCS = main.cpp \ SRCS = main.cpp \
internal/logger/logger.cpp \
internal/conf/conf.cpp \ internal/conf/conf.cpp \
internal/codecs/h264/h264.cpp \
internal/stream/stream.cpp \
internal/staticsources/rtsp/rtspSource.cpp \ internal/staticsources/rtsp/rtspSource.cpp \
internal/protocols/httpp/httpServer.cpp \
internal/core/path.cpp \ internal/core/path.cpp \
internal/core/pathManager.cpp \ internal/core/pathManager.cpp \
internal/core/core.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 internal/api/api.cpp
# Shared with la_mojo (kernelModuleEmbedVideo): lib/data/media/mtx
LIB_SRCS = $(MTXLIB)/logger/logger.cpp \
$(MTXLIB)/conf/serverConf.cpp \
$(MTXLIB)/codecs/h264/h264.cpp \
$(MTXLIB)/stream/stream.cpp \
$(MTXLIB)/protocols/httpp/httpServer.cpp \
$(MTXLIB)/core/mediaPath.cpp \
$(MTXLIB)/recorder/fmp4Writer.cpp \
$(MTXLIB)/recorder/recorder.cpp \
$(MTXLIB)/servers/webrtc/session.cpp \
$(MTXLIB)/servers/webrtc/webrtcServer.cpp
# JsonCpp from dr_frucht # JsonCpp from dr_frucht
JSON_SRCS = $(DFSL)/lib/data/json/json_reader.cpp \ JSON_SRCS = $(DFSL)/lib/data/json/json_reader.cpp \
$(DFSL)/lib/data/json/json_value.cpp \ $(DFSL)/lib/data/json/json_value.cpp \
$(DFSL)/lib/data/json/json_writer.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))
OBJS = $(patsubst %.cpp,$(OUTDIR)/obj/%.o,$(SRCS)) $(patsubst $(MTXLIB)/%.cpp,$(OUTDIR)/obj/mtxlib/%.o,$(LIB_SRCS)) $(patsubst $(DFSL)/lib/data/json/%.cpp,$(OUTDIR)/obj/jsoncpp/%.o,$(JSON_SRCS))
DEPS = $(OBJS:.o=.d) DEPS = $(OBJS:.o=.d)
all: $(TARGET) all: $(TARGET)
@ -58,6 +63,10 @@ $(OUTDIR)/obj/%.o: %.cpp
@mkdir -p $(dir $@) @mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@ $(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@
$(OUTDIR)/obj/mtxlib/%.o: $(MTXLIB)/%.cpp
@mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@
$(OUTDIR)/obj/jsoncpp/%.o: $(DFSL)/lib/data/json/%.cpp $(OUTDIR)/obj/jsoncpp/%.o: $(DFSL)/lib/data/json/%.cpp
@mkdir -p $(dir $@) @mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -w -MMD -MP -c $< -o $@ $(CXX) $(CXXFLAGS) -w -MMD -MP -c $< -o $@

47
Projects/la_mojo/makefile

@ -7,6 +7,11 @@ MKDIR=mkdir
# -----Begin user-editable area----- # -----Begin user-editable area-----
# Live view (WebRTC / WHEP) and recording of kernelModuleEmbedVideo: MediaMtx library + libdatachannel
# (>= 0.20, default /usr/local). Other locations: make DATACHANNEL_CFLAGS=-I... DATACHANNEL_LIBS="-L... -ldatachannel"
DATACHANNEL_CFLAGS ?=
DATACHANNEL_LIBS ?= -ldatachannel
# -----End user-editable area----- # -----End user-editable area-----
# If no configuration is specified, "Debug" will be used # If no configuration is specified, "Debug" will be used
@ -1069,6 +1074,48 @@ clean:
cleanall: clean cleanall: clean
endif endif
#
# MediaMtx library (lib/data/media/mtx): every configuration except the LRF proxy
#
ifneq "$(CFG)" "LRF_Proxy_ONLY"
MTX_OBJ=$(OUTDIR)/logger.o $(OUTDIR)/serverConf.o $(OUTDIR)/h264.o \
$(OUTDIR)/stream.o $(OUTDIR)/httpServer.o $(OUTDIR)/mediaPath.o \
$(OUTDIR)/h264Feeder.o $(OUTDIR)/fmp4Writer.o $(OUTDIR)/recorder.o \
$(OUTDIR)/session.o $(OUTDIR)/webrtcServer.o $(OUTDIR)/streamLiveEncoder.o
OBJ+=$(MTX_OBJ)
ALL_OBJ+=$(MTX_OBJ) $(DATACHANNEL_LIBS) -lssl -lcrypto -lpthread
CFG_INC+=$(DATACHANNEL_CFLAGS)
# the rule of each configuration lists $(OBJ) as it was then: add the library objects
$(OUTFILE): $(MTX_OBJ)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/logger/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/conf/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/codecs/h264/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/stream/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/protocols/httpp/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/core/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/feeder/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/recorder/%.cpp
$(COMPILE)
$(OUTDIR)/%.o : ../../lib/data/media/mtx/servers/webrtc/%.cpp
$(COMPILE)
endif
# #
# include dependencies: # include dependencies:
# #

38
lib/App/common/MySQL_dataBinder.cpp

@ -5391,6 +5391,44 @@ DBC_MODULE_EMBED_VIDEO_DATA * mysqlDBC::getEmbedVideoData(uint32_t ID)
strncpy(tPtr->logo_md5, it->second.c_str(), 32); strncpy(tPtr->logo_md5, it->second.c_str(), 32);
tPtr->logo_md5[32] = (char) 0; tPtr->logo_md5[32] = (char) 0;
}; };
// Live view (optional columns)
dbcEmbedVideoLiveDefaults(tPtr);
it = cArr->find("live_mode");
if (it != cArr->end() && ! it->second.empty())
{
tPtr->live_mode = (uint8_t) atoi(it->second.c_str());
};
it = cArr->find("live_port");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_port = (uint16_t) atoi(it->second.c_str());
};
it = cArr->find("live_record");
if (it != cArr->end() && ! it->second.empty())
{
tPtr->live_record = (bool) atoi(it->second.c_str());
};
it = cArr->find("live_record_segment");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_record_segment = (uint16_t) atoi(it->second.c_str());
};
it = cArr->find("live_bitrate");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_bitrate = (uint16_t) atoi(it->second.c_str());
};
it = cArr->find("live_fps");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_fps = (uint8_t) atoi(it->second.c_str());
};
it = cArr->find("live_ice_servers");
if (it != cArr->end())
{
strncpy(tPtr->live_ice_servers, it->second.c_str(), sizeof(tPtr->live_ice_servers) - 1);
tPtr->live_ice_servers[sizeof(tPtr->live_ice_servers) - 1] = (char) 0;
};
}; };
}; };
}; };

38
lib/App/common/SQLite_dataBinder.cpp

@ -1908,6 +1908,44 @@ DBC_MODULE_EMBED_VIDEO_DATA * sqliteDBC::getEmbedVideoData(uint32_t ID)
strncpy(tPtr->logo_md5, it->second.c_str(), 32); strncpy(tPtr->logo_md5, it->second.c_str(), 32);
tPtr->logo_md5[32] = (char) 0; tPtr->logo_md5[32] = (char) 0;
}; };
// Live view (optional columns)
dbcEmbedVideoLiveDefaults(tPtr);
it = cArr->find("live_mode");
if (it != cArr->end() && ! it->second.empty())
{
tPtr->live_mode = (uint8_t) atoi(it->second.c_str());
};
it = cArr->find("live_port");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_port = (uint16_t) atoi(it->second.c_str());
};
it = cArr->find("live_record");
if (it != cArr->end() && ! it->second.empty())
{
tPtr->live_record = (bool) atoi(it->second.c_str());
};
it = cArr->find("live_record_segment");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_record_segment = (uint16_t) atoi(it->second.c_str());
};
it = cArr->find("live_bitrate");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_bitrate = (uint16_t) atoi(it->second.c_str());
};
it = cArr->find("live_fps");
if (it != cArr->end() && atoi(it->second.c_str()) > 0)
{
tPtr->live_fps = (uint8_t) atoi(it->second.c_str());
};
it = cArr->find("live_ice_servers");
if (it != cArr->end())
{
strncpy(tPtr->live_ice_servers, it->second.c_str(), sizeof(tPtr->live_ice_servers) - 1);
tPtr->live_ice_servers[sizeof(tPtr->live_ice_servers) - 1] = (char) 0;
};
}; };
}; };
}; };

25
lib/App/common/dataBinder_structures.h

@ -344,8 +344,33 @@ typedef struct S_DBC_MODULE_EMBED_VIDEO_DATA
int logo_x; int logo_x;
int logo_y; int logo_y;
char logo_md5[33]; char logo_md5[33];
// Live view (WebRTC / WHEP) and continuous recording, replacing MediaMTX (optional columns of
// module_eve: the defaults apply when a column does not exist)
uint8_t live_mode; // EVE_LIVE_OFF / EVE_LIVE_PASSTHROUGH (default) / EVE_LIVE_ENCODE
uint16_t live_port; // WHEP port (default 8889, as MediaMTX: the dashboard uses it)
bool live_record; // continuous fMP4 segments of every stream (default on)
uint16_t live_record_segment; // segment length, seconds (default 60)
uint16_t live_bitrate; // EVE_LIVE_ENCODE: kbit/s (default 2000)
uint8_t live_fps; // EVE_LIVE_ENCODE: frames per second (default 15)
char live_ice_servers[256]; // STUN / TURN servers, comma separated (default none: LAN)
} DBC_MODULE_EMBED_VIDEO_DATA; } DBC_MODULE_EMBED_VIDEO_DATA;
#define EVE_LIVE_OFF 0 // no WebRTC server, no recording
#define EVE_LIVE_PASSTHROUGH 1 // the camera's H264 as it is (no CPU, original quality, no overlays)
#define EVE_LIVE_ENCODE 2 // the processed frames (overlays) encoded to H264 again
// The defaults of the live view settings (also when the module has no DB record)
inline void dbcEmbedVideoLiveDefaults(DBC_MODULE_EMBED_VIDEO_DATA * p)
{
p->live_mode = EVE_LIVE_PASSTHROUGH;
p->live_port = 8889;
p->live_record = true;
p->live_record_segment = 60;
p->live_bitrate = 2000;
p->live_fps = 15;
p->live_ice_servers[0] = (char) 0;
}
/* /*
typedef struct S_DBC_SOCKET_DATA{ typedef struct S_DBC_SOCKET_DATA{
uint32_t socket_id; uint32_t socket_id;

21
lib/App/common/kernelHelperMediaMTX.cpp

@ -3,6 +3,7 @@
#include "kernelHelperMediaMTX.h" #include "kernelHelperMediaMTX.h"
#include "SQLite_dataBinder.h" #include "SQLite_dataBinder.h"
#include <cerrno>
#include <stdexcept> #include <stdexcept>
#define LOG(X) m_pLog->Log("KHMTX", this, X) #define LOG(X) m_pLog->Log("KHMTX", this, X)
@ -29,7 +30,15 @@ kernelHelperMediaMTX::kernelHelperMediaMTX(): basicThread() {
m_nLastLogSize = 0; m_nLastLogSize = 0;
m_bRecordMode = false; m_bRecordMode = false;
m_tLastRestart = 0; m_tLastRestart = 0;
#ifdef KH_MTX_EMBEDDED
// la_mojo records: segments of kernelModuleEmbedVideo (live_record), base folder fixed
m_bRecordMode = true;
strncpy( m_sRecordsBase, mtx_scratch_path, sizeof( m_sRecordsBase ) - 1 );
m_sRecordsBase[sizeof( m_sRecordsBase ) - 1] = (char) 0;
m_bStatus = KH_STATUS_MTX_INIT;
#else
if( loadConfig() ) m_bStatus = KH_STATUS_MTX_INIT; if( loadConfig() ) m_bStatus = KH_STATUS_MTX_INIT;
#endif
} }
kernelHelperMediaMTX::~kernelHelperMediaMTX(){ kernelHelperMediaMTX::~kernelHelperMediaMTX(){
@ -41,6 +50,12 @@ kernelHelperMediaMTX::~kernelHelperMediaMTX(){
bool kernelHelperMediaMTX::create(){ bool kernelHelperMediaMTX::create(){
LOG("Create!"); LOG("Create!");
if ( m_bStatus == KH_STATUS_MTX_NA ) return false; if ( m_bStatus == KH_STATUS_MTX_NA ) return false;
#ifdef KH_MTX_EMBEDDED
// The live view is served by la_mojo: the MediaMTX service would hold the WebRTC port (8889)
LOG( "Embedded live view: stopping the MediaMTX service (queued)" );
if ( system( "systemctl --no-block stop mediamtx.service >/dev/null 2>&1" ) == -1 ) LOG_ERROR( "systemctl failed" );
return true; // no log to follow
#endif
struct stat tStatbuf; struct stat tStatbuf;
if( stat( m_sAppLogFile, &tStatbuf ) == -1 ) return false; if( stat( m_sAppLogFile, &tStatbuf ) == -1 ) return false;
m_nLastLogSize = tStatbuf.st_size; m_nLastLogSize = tStatbuf.st_size;
@ -277,7 +292,11 @@ bool kernelHelperMediaMTX::loadStreams(){
#include <dirent.h> #include <dirent.h>
bool kernelHelperMediaMTX::validateService(){ bool kernelHelperMediaMTX::validateService(){
loadStreams(); loadStreams();
#ifdef KH_MTX_EMBEDDED
if( false ) {
#else
if( !validateConfig() ) { if( !validateConfig() ) {
#endif
updateConfig(); updateConfig();
return restart(); return restart();
} else { } else {
@ -342,7 +361,7 @@ bool kernelHelperMediaMTX::validateService(){
}; };
}; };
closedir( dir ); closedir( dir );
} else {
} else if ( errno != ENOENT ) { // no folder: nothing recorded yet (stream not online)
LOG_ERROR("Unable to open directory!"); LOG_ERROR("Unable to open directory!");
}; };
}; };

9
lib/App/common/kernelHelperMediaMTX.h

@ -13,6 +13,15 @@
#define mtx_scratch_path "/dev/shm/argus/video_scratch" #define mtx_scratch_path "/dev/shm/argus/video_scratch"
/*
KH_MTX_EMBEDDED: la_mojo serves the live view and records by itself (kernelModuleEmbedVideo with the
MediaMtx library). The helper no longer writes mediamtx.yml, restarts or reads the log of the MediaMTX
service; it stops the service once (it would hold port 8889) and only indexes the recorded segments
(<mtx_scratch_path>/stream_<node>/*.mp4). Undefine it to go back to the external MediaMTX service.
The helper is to be removed once the indexing moved into kernelModuleEmbedVideo.
*/
#define KH_MTX_EMBEDDED
typedef struct S_StreamDescRecord{ typedef struct S_StreamDescRecord{
uint32_t cam_id; uint32_t cam_id;
uint64_t node_id; uint64_t node_id;

129
lib/App/common/kernelModuleEmbedVideo.cpp

@ -20,6 +20,7 @@
#include "../alg/generic/base64.h" #include "../alg/generic/base64.h"
#include "../data/media/video/videoAVLIBSource.h" #include "../data/media/video/videoAVLIBSource.h"
#include "../data/media/video/videoLive555AVLibSource.h" #include "../data/media/video/videoLive555AVLibSource.h"
#include "../../data/media/mtx/servers/webrtc/webrtcServer.h"
#include <arpa/inet.h> #include <arpa/inet.h>
#include <ctype.h> #include <ctype.h>
@ -100,6 +101,7 @@ kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) :
LOG_ERROR("No DB Data Error!"); LOG_ERROR("No DB Data Error!");
memset(&m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); memset(&m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA));
m_sEmbedVideoData.port = 8972; m_sEmbedVideoData.port = 8972;
dbcEmbedVideoLiveDefaults(&m_sEmbedVideoData);
}; };
} }
else else
@ -107,6 +109,24 @@ kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) :
LOG_ERROR("DB Error!"); LOG_ERROR("DB Error!");
}; };
m_bDetached = true; m_bDetached = true;
m_tLiveRetry = 0;
// The MediaMtx library logs into the la_mojo log (tag MTX)
mtx::Logger::instance().setDestinations(false, std::string());
mtx::Logger::instance().setSink([](mtx::LogLevel level, const char * line) {
if (level == mtx::LogLevel::Debug)
{
return;
}
if (level == mtx::LogLevel::Error)
{
basicLogCollection::getInstance()->Log("MTX", NULL, _LOG_ERROR, line);
}
else
{
basicLogCollection::getInstance()->Log("MTX", NULL, line);
}
});
applyLiveSettings();
n_pNoSignalData = NULL; n_pNoSignalData = NULL;
m_nNoSignalSize = 0; m_nNoSignalSize = 0;
#ifdef HAVE_SMAL_PREVIEW_STREAMS #ifdef HAVE_SMAL_PREVIEW_STREAMS
@ -194,6 +214,7 @@ kernelModuleEmbedVideo::~kernelModuleEmbedVideo()
{ {
stopService(true); stopService(true);
}; };
stopLive(); // the WebRTC server uses this object (PathProvider): stop it before the members go
// Sanity check // Sanity check
LOG("Sanity check in Destructor!"); LOG("Sanity check in Destructor!");
@ -1536,6 +1557,8 @@ bool kernelModuleEmbedVideo::startService()
#else // !EVE_WORK_WITH_MEDIAMTX #else // !EVE_WORK_WITH_MEDIAMTX
m_bEnabled = true; m_bEnabled = true;
#endif // !EVE_WORK_WITH_MEDIAMTX #endif // !EVE_WORK_WITH_MEDIAMTX
applyLiveSettings();
startLive(); // a failure (port in use) is retried by validate()
return m_bEnabled; return m_bEnabled;
} }
@ -1567,6 +1590,7 @@ bool kernelModuleEmbedVideo::stopService(bool force)
m_mapHANDLERS.clear(); m_mapHANDLERS.clear();
}; };
m_mStreamHandlersProtector.unlock(); m_mStreamHandlersProtector.unlock();
stopLive(); // after the handlers: they released their feeds
#ifndef EVE_WORK_WITH_MEDIAMTX #ifndef EVE_WORK_WITH_MEDIAMTX
@ -1691,6 +1715,11 @@ bool kernelModuleEmbedVideo::reloadSettings()
bool kernelModuleEmbedVideo::validate() bool kernelModuleEmbedVideo::validate()
{ {
bool RetVal = true; bool RetVal = true;
// The WebRTC server could not start (e.g. the port was still used by the MediaMTX service): retry
if (m_bEnabled && m_sEmbedVideoData.live_mode != EVE_LIVE_OFF && ! m_pWebrtc && time(NULL) >= m_tLiveRetry)
{
startLive();
};
deviceNode ** tA = NULL; deviceNode ** tA = NULL;
uint32_t tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_STATIC_CAMERA, tA); uint32_t tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_STATIC_CAMERA, tA);
if( tCNT ){ if( tCNT ){
@ -2424,6 +2453,106 @@ cv::Mat *kernelModuleEmbedVideo::getCurrentFrame( uint32_t streamID ){
return retVal; return retVal;
} }
/* ---------------------------------------------------------------- live view (WebRTC) and recording */
void kernelModuleEmbedVideo::applyLiveSettings()
{
m_sLiveConf = mtx::ServerConf();
m_sLiveConf.webrtcAddress = ":" + std::to_string(m_sEmbedVideoData.live_port ? m_sEmbedVideoData.live_port : 8889);
// next to the module's own clips; kernelHelperMediaMTX indexes <scratch>/stream_<node>/*.mp4
m_sLiveConf.recordPath = std::string(m_pVideoScratchPath) + "/%path/%Y-%m-%d_%H-%M-%S-%f";
m_sLiveConf.recordSegmentDurationMs = (int64_t) (m_sEmbedVideoData.live_record_segment ? m_sEmbedVideoData.live_record_segment : 60) * 1000;
m_sLiveConf.recordPartDurationMs = 1000;
m_sLiveConf.webrtcICEServers.clear();
std::string tIce(m_sEmbedVideoData.live_ice_servers);
size_t tPos = 0;
while (tPos < tIce.size())
{
size_t tEnd = tIce.find_first_of(", ", tPos);
std::string tOne = tIce.substr(tPos, tEnd == std::string::npos ? std::string::npos : tEnd - tPos);
if (! tOne.empty())
{
m_sLiveConf.webrtcICEServers.push_back(tOne);
};
if (tEnd == std::string::npos)
{
break;
};
tPos = tEnd + 1;
};
}
bool kernelModuleEmbedVideo::startLive()
{
if (m_sEmbedVideoData.live_mode == EVE_LIVE_OFF)
{
return true;
};
if (m_pWebrtc)
{
return true;
};
std::unique_ptr<mtx::WebrtcServer> tServer(new mtx::WebrtcServer(m_sLiveConf, this));
std::string tErr;
if (! tServer->start(tErr))
{
char tB[512];
snprintf(tB, sizeof(tB), "Live view: the WebRTC server cannot listen on %s (%s) - retry in 10 s", m_sLiveConf.webrtcAddress.c_str(), tErr.c_str());
LOG_ERROR(tB);
m_tLiveRetry = time(NULL) + 10;
return false;
};
m_pWebrtc = std::move(tServer);
char tB[256];
snprintf(tB, sizeof(tB), "Live view: WebRTC (WHEP) on %s, %s, recording %s", m_sLiveConf.webrtcAddress.c_str(),
m_sEmbedVideoData.live_mode == EVE_LIVE_ENCODE ? "processed frames (encoded)" : "camera H264 (passthrough)", m_sEmbedVideoData.live_record ? "on" : "off");
LOG(tB);
return true;
}
void kernelModuleEmbedVideo::stopLive()
{
if (m_pWebrtc)
{
m_pWebrtc->stop(); // closes the sessions (they hold their paths)
m_pWebrtc.reset();
};
std::map<std::string, std::shared_ptr<mtx::MediaPath>> tPaths;
{
std::lock_guard<std::mutex> lock(m_mLivePaths);
tPaths.swap(m_mapLivePaths);
}
for (auto & p : tPaths)
{
p.second->sourceSetNotReady(); // closes the recording
};
}
std::shared_ptr<mtx::MediaPath> kernelModuleEmbedVideo::livePath(uint32_t nodeID)
{
if (m_sEmbedVideoData.live_mode == EVE_LIVE_OFF || nodeID == 0)
{
return nullptr;
};
std::string tName = "stream_" + std::to_string(nodeID);
std::lock_guard<std::mutex> lock(m_mLivePaths);
auto it = m_mapLivePaths.find(tName);
if (it != m_mapLivePaths.end())
{
return it->second;
};
auto tPath = std::make_shared<mtx::MediaPath>(tName, m_sEmbedVideoData.live_record, m_sLiveConf);
m_mapLivePaths[tName] = tPath;
return tPath;
}
std::shared_ptr<mtx::MediaPath> kernelModuleEmbedVideo::findPath(const std::string & name) const
{
std::lock_guard<std::mutex> lock(m_mLivePaths);
auto it = m_mapLivePaths.find(name);
return (it == m_mapLivePaths.end()) ? nullptr : it->second;
}
#undef TLOG #undef TLOG
#undef TLOG_ERROR #undef TLOG_ERROR

36
lib/App/common/kernelModuleEmbedVideo.h

@ -18,6 +18,12 @@ extern const char * m_pVideoScratchPath;
// #include "../../data/media/video/videoAVLIBDestination.h" // #include "../../data/media/video/videoAVLIBDestination.h"
#include "../../components/base/basicMediaDestination.h" #include "../../components/base/basicMediaDestination.h"
#include "../../components/base/basicMediaSource.h" #include "../../components/base/basicMediaSource.h"
#include "../../data/media/mtx/core/mediaPath.h"
#include <map>
#include <memory>
#include <mutex>
#include <string>
namespace mtx { class WebrtcServer; }
class streamHandler; class streamHandler;
typedef map<uint32_t, streamHandler *> mapSTREAMHANDLERS; typedef map<uint32_t, streamHandler *> mapSTREAMHANDLERS;
#ifndef EVE_WORK_WITH_MEDIAMTX #ifndef EVE_WORK_WITH_MEDIAMTX
@ -72,7 +78,18 @@ typedef struct S_VIDEO_EVT
typedef map<uint32_t, cv::Mat> mapSTREAMMAPS; typedef map<uint32_t, cv::Mat> mapSTREAMMAPS;
class kernelModuleEmbedVideo : public kernelModule
/*
Live view and continuous recording (replaces the MediaMTX service)
Every stream handler feeds a path "stream_<camera node id>" (the names MediaMTX had: the dashboard
plays http://<host>:8889/stream_<node>/whep). live_mode selects what the path carries:
- EVE_LIVE_PASSTHROUGH: the camera's H264 as the source receives it (no CPU, original quality)
- EVE_LIVE_ENCODE: the processed frames of this module (time stamp, label, logo, event marks)
encoded to H264 (streamLiveEncoder)
The paths outlive the stream handlers (a stalled stream is rebuilt; the viewers reconnect to the same
path). The WebRTC (WHEP) server and the recorder are the MediaMtx library (lib/data/media/mtx).
*/
class kernelModuleEmbedVideo : public kernelModule, public mtx::PathProvider
#ifndef EVE_WORK_WITH_MEDIAMTX #ifndef EVE_WORK_WITH_MEDIAMTX
, public basicDualThread , public basicDualThread
@ -113,6 +130,16 @@ class kernelModuleEmbedVideo : public kernelModule
bool saveStreamPicture(uint32_t id); bool saveStreamPicture(uint32_t id);
bool saveStreamPicture(DBC_SNAPSHOT_DATA * ptr); bool saveStreamPicture(DBC_SNAPSHOT_DATA * ptr);
bool generateSavePicPath(CSTR MD5, CSTR Output); bool generateSavePicPath(CSTR MD5, CSTR Output);
// Live view (WebRTC) and recording
mtx::ServerConf m_sLiveConf;
std::unique_ptr<mtx::WebrtcServer> m_pWebrtc;
time_t m_tLiveRetry; // next start attempt of the WebRTC server
mutable std::mutex m_mLivePaths;
std::map<std::string, std::shared_ptr<mtx::MediaPath>> m_mapLivePaths;
void applyLiveSettings();
bool startLive();
void stopLive();
#ifndef EVE_WORK_WITH_MEDIAMTX #ifndef EVE_WORK_WITH_MEDIAMTX
protected: protected:
@ -144,6 +171,13 @@ class kernelModuleEmbedVideo : public kernelModule
uint8_t getMediaMode(void); uint8_t getMediaMode(void);
bool isProcessingVideoStream(); bool isProcessingVideoStream();
cv::Mat * getCurrentFrame( uint32_t streamID ); cv::Mat * getCurrentFrame( uint32_t streamID );
// Live view: the mode, and the path of a camera node (created on first use; nullptr: live view off)
uint8_t getLiveMode(void) const { return m_sEmbedVideoData.live_mode; }
uint8_t getLiveFps(void) const { return m_sEmbedVideoData.live_fps; }
uint16_t getLiveBitrate(void) const { return m_sEmbedVideoData.live_bitrate; }
std::shared_ptr<mtx::MediaPath> livePath(uint32_t nodeID);
// mtx::PathProvider (the WebRTC server looks up the path of a WHEP request)
std::shared_ptr<mtx::MediaPath> findPath(const std::string & name) const override;
friend class streamHandler; friend class streamHandler;
}; };
#else //LRF_PROXY_ONLY #else //LRF_PROXY_ONLY

91
lib/App/common/streamHandler.cpp

@ -75,6 +75,7 @@ streamHandler::streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M, uint8
m_bEvtMarkerCounter = 0; m_bEvtMarkerCounter = 0;
m_bCamMoveCounter = 0; m_bCamMoveCounter = 0;
m_bFlipMode = flip_mode; m_bFlipMode = flip_mode;
m_bLiveMode = EVE_LIVE_OFF;
#ifdef EVE_ENABLE_VIDEO #ifdef EVE_ENABLE_VIDEO
#ifdef EVE_SEQUENTAL_OUTPUT #ifdef EVE_SEQUENTAL_OUTPUT
@ -149,6 +150,7 @@ streamHandler::~streamHandler()
case 'A': delete((videoAVLIBSource *) m_pSource); break; case 'A': delete((videoAVLIBSource *) m_pSource); break;
}; };
}; };
stopLive(); // the source no longer pushes: the path is set not ready (viewers are closed)
#ifdef EVE_ENABLE_VIDEO #ifdef EVE_ENABLE_VIDEO
closeAll(); closeAll();
#endif // EVE_ENABLE_VIDEO #endif // EVE_ENABLE_VIDEO
@ -233,6 +235,8 @@ bool streamHandler::create(dataBinder * ptr, uint32_t stremID)
sprintf(m_sSourceDesc.mediaName, "No-Name-Cam"); sprintf(m_sSourceDesc.mediaName, "No-Name-Cam");
}; };
initLive(tNID);
m_cSourceType = m_sStreamData.source_type[0]; m_cSourceType = m_sStreamData.source_type[0];
switch (m_cSourceType) switch (m_cSourceType)
@ -340,6 +344,88 @@ bool streamHandler::create(dataBinder * ptr, uint32_t stremID)
return false; return false;
} }
/* ---------------------------------------------------------------- live view / recording */
void streamHandler::initLive(uint32_t nodeID)
{
m_bLiveMode = m_pMaster->getLiveMode();
m_pLivePath = m_pMaster->livePath(nodeID);
if (! m_pLivePath)
{
m_bLiveMode = EVE_LIVE_OFF;
return;
};
char tB[160];
if (m_bLiveMode == EVE_LIVE_ENCODE)
{
m_pLiveEncoder.reset(new streamLiveEncoder(m_pLivePath, m_pMaster->getLiveFps(), m_pMaster->getLiveBitrate()));
snprintf(tB, sizeof(tB), "Live view: path %s, processed frames (encoded)", m_pLivePath->name().c_str());
}
else
{
m_oLiveFeeder.setParent(m_pLivePath.get());
snprintf(tB, sizeof(tB), "Live view: path %s, camera H264", m_pLivePath->name().c_str());
};
LOG(tB);
}
void streamHandler::stopLive(void)
{
m_pLiveEncoder.reset(); // its feeder sets the path not ready
m_oLiveFeeder.setParent(nullptr); // passthrough: the same
m_pLivePath.reset();
m_bLiveMode = EVE_LIVE_OFF;
}
void streamHandler::pushEncodedParams(const uint8_t * data, size_t size, bool extradata, void * src)
{
if (src) src = NULL;
if (m_bLiveMode != EVE_LIVE_PASSTHROUGH || data == NULL || size == 0)
{
return;
};
if (extradata)
{
m_oLiveFeeder.setExtradata(data, size);
}
else
{
m_oLiveFeeder.setParameterSets(std::vector<mtx::Bytes>(1, mtx::Bytes(data, data + size)));
};
}
void streamHandler::pushEncodedNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced, void * src)
{
if (src) src = NULL;
if (m_bLiveMode == EVE_LIVE_PASSTHROUGH)
{
m_oLiveFeeder.pushNalu(data, size, ptUs, marker, synced);
};
}
void streamHandler::pushEncodedPacket(const uint8_t * data, size_t size, int64_t ptsUs, void * src)
{
if (src) src = NULL;
if (m_bLiveMode != EVE_LIVE_PASSTHROUGH)
{
return;
};
if (m_oLiveFeeder.avccLengthSize() > 0)
{
m_oLiveFeeder.pushAvcc(data, size, m_oLiveFeeder.avccLengthSize(), ptsUs);
}
else
{
m_oLiveFeeder.pushAnnexB(data, size, ptsUs);
};
}
void streamHandler::encodedSourceStopped(void * src)
{
if (src) src = NULL;
m_oLiveFeeder.reset();
}
bool streamHandler::pushFrame(AVFrame * Frame, void * src) bool streamHandler::pushFrame(AVFrame * Frame, void * src)
{ {
if( !Frame ) return false; if( !Frame ) return false;
@ -615,6 +701,11 @@ bool streamHandler::pushFrame(cv::Mat & Frame, void * src)
cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](roi); cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](roi);
m_pMaster->m_mLogoPic.copyTo(destinationROI, m_pMaster->m_mLogoMask); m_pMaster->m_mLogoPic.copyTo(destinationROI, m_pMaster->m_mLogoMask);
}; };
// Live view of the processed frame (EVE_LIVE_ENCODE): copied for the encoder thread
if (m_pLiveEncoder)
{
m_pLiveEncoder->push(m_pMaster->m_mapMATS[tMD->mediaStreamId]);
};
#ifndef EVE_WORK_WITH_MEDIAMTX #ifndef EVE_WORK_WITH_MEDIAMTX
vector<int> compression_params; vector<int> compression_params;

17
lib/App/common/streamHandler.h

@ -18,6 +18,9 @@
// #include "../../data/media/video/videoAVLIBDestination.h" // #include "../../data/media/video/videoAVLIBDestination.h"
#include "../../components/base/basicMediaDestination.h" #include "../../components/base/basicMediaDestination.h"
#include "../../components/base/basicMediaSource.h" #include "../../components/base/basicMediaSource.h"
#include "../../data/media/mtx/feeder/h264Feeder.h"
#include "streamLiveEncoder.h"
#include <memory>
#ifndef DB_SHMEM_POINT #ifndef DB_SHMEM_POINT
#define DB_SHMEM_POINT "/dev/shm/argus" #define DB_SHMEM_POINT "/dev/shm/argus"
@ -231,6 +234,15 @@ class streamHandler :
dataBinder * m_pDBC; dataBinder * m_pDBC;
MS_WORK_MODE m_eWM; MS_WORK_MODE m_eWM;
// Live view / recording (kernelModuleEmbedVideo::livePath): the camera's H264 through the feeder,
// or the processed frames through the encoder
uint8_t m_bLiveMode;
std::shared_ptr<mtx::MediaPath> m_pLivePath;
mtx::H264Feeder m_oLiveFeeder;
std::unique_ptr<streamLiveEncoder> m_pLiveEncoder;
void initLive(uint32_t nodeID);
void stopLive(void);
basicMutex m_mEvtIDS_Protector; basicMutex m_mEvtIDS_Protector;
#ifdef EVE_ENABLE_VIDEO #ifdef EVE_ENABLE_VIDEO
@ -369,6 +381,11 @@ class streamHandler :
virtual bool pushFrame(AVFrame * Frame, void * src = NULL); virtual bool pushFrame(AVFrame * Frame, void * src = NULL);
// virtual void pushFrame( cv::Mat* Frame, void* src = NULL); // virtual void pushFrame( cv::Mat* Frame, void* src = NULL);
virtual bool pushFrame(cv::Mat & Frame, void * src = NULL); virtual bool pushFrame(cv::Mat & Frame, void * src = NULL);
/* compressed H264 of the source (live view passthrough) */
virtual void pushEncodedParams(const uint8_t * data, size_t size, bool extradata, void * src = NULL);
virtual void pushEncodedNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced, void * src = NULL);
virtual void pushEncodedPacket(const uint8_t * data, size_t size, int64_t ptsUs, void * src = NULL);
virtual void encodedSourceStopped(void * src = NULL);
bool triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame); bool triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame);
bool triggerCamMove(void); bool triggerCamMove(void);
bool validate(void); bool validate(void);

236
lib/App/common/streamLiveEncoder.cpp

@ -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

68
lib/App/common/streamLiveEncoder.h

@ -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

28
lib/components/base/basicMediaDestination.h

@ -63,6 +63,34 @@ class basicMediaDestination
{ {
return false; return false;
} }
/*
Compressed H264 of the source, before it is decoded (live view / recording without re-encoding,
see streamHandler). A destination that does not need it ignores these calls.
*/
// Parameter sets: SPS / PPS NAL units (sprop-parameter-sets of the SDP) or libav extradata
// (Annex-B or avcC). Called when the source (re)connects, before the first packet.
virtual void pushEncodedParams(const uint8_t * data, size_t size, bool extradata, void * src = NULL)
{
if (data || size || extradata || src) return;
}
// One NAL unit without start code (RTP depacketizer, live555). marker: last NAL unit of the
// picture; synced: the presentation times are RTCP synchronised
virtual void pushEncodedNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced, void * src = NULL)
{
if (data || size || ptUs || marker || synced || src) return;
}
// One access unit (libav packet): Annex-B, or length prefixed when the extradata was avcC.
// ptsUs < 0: not known
virtual void pushEncodedPacket(const uint8_t * data, size_t size, int64_t ptsUs, void * src = NULL)
{
if (data || size || ptsUs || src) return;
}
// The source lost its stream (it reconnects): the next data starts again with the parameters
virtual void encodedSourceStopped(void * src = NULL)
{
if (src) return;
}
}; };
inline basicMediaDestination::basicMediaDestination() inline basicMediaDestination::basicMediaDestination()

Projects/MediaMtx/internal/codecs/h264/h264.cpp → lib/data/media/mtx/codecs/h264/h264.cpp

Projects/MediaMtx/internal/codecs/h264/h264.h → lib/data/media/mtx/codecs/h264/h264.h

83
lib/data/media/mtx/conf/serverConf.cpp

@ -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

39
lib/data/media/mtx/conf/serverConf.h

@ -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

145
lib/data/media/mtx/core/mediaPath.cpp

@ -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

100
lib/data/media/mtx/core/mediaPath.h

@ -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

209
lib/data/media/mtx/feeder/h264Feeder.cpp

@ -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

77
lib/data/media/mtx/feeder/h264Feeder.h

@ -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

Projects/MediaMtx/internal/logger/logger.cpp → lib/data/media/mtx/logger/logger.cpp

Projects/MediaMtx/internal/logger/logger.h → lib/data/media/mtx/logger/logger.h

Projects/MediaMtx/internal/protocols/httpp/httpServer.cpp → lib/data/media/mtx/protocols/httpp/httpServer.cpp

Projects/MediaMtx/internal/protocols/httpp/httpServer.h → lib/data/media/mtx/protocols/httpp/httpServer.h

Projects/MediaMtx/internal/recorder/fmp4Writer.cpp → lib/data/media/mtx/recorder/fmp4Writer.cpp

Projects/MediaMtx/internal/recorder/fmp4Writer.h → lib/data/media/mtx/recorder/fmp4Writer.h

Projects/MediaMtx/internal/recorder/recorder.cpp → lib/data/media/mtx/recorder/recorder.cpp

Projects/MediaMtx/internal/recorder/recorder.h → lib/data/media/mtx/recorder/recorder.h

Projects/MediaMtx/internal/servers/webrtc/session.cpp → lib/data/media/mtx/servers/webrtc/session.cpp

Projects/MediaMtx/internal/servers/webrtc/session.h → lib/data/media/mtx/servers/webrtc/session.h

Projects/MediaMtx/internal/servers/webrtc/webrtcServer.cpp → lib/data/media/mtx/servers/webrtc/webrtcServer.cpp

Projects/MediaMtx/internal/servers/webrtc/webrtcServer.h → lib/data/media/mtx/servers/webrtc/webrtcServer.h

Projects/MediaMtx/internal/stream/stream.cpp → lib/data/media/mtx/stream/stream.cpp

Projects/MediaMtx/internal/stream/stream.h → lib/data/media/mtx/stream/stream.h

Projects/MediaMtx/internal/unit/unit.h → lib/data/media/mtx/unit/unit.h

26
lib/data/media/video/videoAVLIBSource.cpp

@ -940,6 +940,7 @@ void videoAVLIBSource::m_fThreadProc(void)
uint8_t * pBGRbuffer = NULL; uint8_t * pBGRbuffer = NULL;
int dec_ret; int dec_ret;
char tB[2048]; char tB[2048];
bool tEncodedParamsSent = false; // H264 extradata given to the destination (compressed feed)
/** @todo Valgrind is reporting several important memory leaks in this method. /** @todo Valgrind is reporting several important memory leaks in this method.
* *
@ -1021,6 +1022,22 @@ void videoAVLIBSource::m_fThreadProc(void)
if (Packet->stream_index == m_pVideoState->m_iVideoStreamID) if (Packet->stream_index == m_pVideoState->m_iVideoStreamID)
{ {
m_pVideoState->m_bStatus = MS_PRESENT; m_pVideoState->m_bStatus = MS_PRESENT;
// The packet as it came from the camera: live view / recording without re-encoding
AVStream * tVS = m_pVideoState->m_pFormatCtx->streams[Packet->stream_index];
if (m_pMediaDestination != NULL && tVS->codecpar->codec_id == AV_CODEC_ID_H264)
{
if (! tEncodedParamsSent)
{
tEncodedParamsSent = true;
m_pMediaDestination->pushEncodedParams(tVS->codecpar->extradata, tVS->codecpar->extradata_size, true, m_pOpaque);
};
int64_t tPtsUs = -1;
if (Packet->pts != AV_NOPTS_VALUE)
{
tPtsUs = av_rescale_q(Packet->pts, tVS->time_base, AVRational {1, 1000000});
};
m_pMediaDestination->pushEncodedPacket(Packet->data, Packet->size, tPtsUs, m_pOpaque);
};
dec_ret = avcodec_send_packet(m_pVideoState->m_pCodecCtx, Packet); dec_ret = avcodec_send_packet(m_pVideoState->m_pCodecCtx, Packet);
if (dec_ret < 0 && dec_ret != AVERROR(EAGAIN) /* && dec_ret != AVERROR_EOF */) if (dec_ret < 0 && dec_ret != AVERROR(EAGAIN) /* && dec_ret != AVERROR_EOF */)
{ {
@ -1085,6 +1102,11 @@ void videoAVLIBSource::m_fThreadProc(void)
{ {
if (dec_ret == AVERROR_EOF) if (dec_ret == AVERROR_EOF)
{ {
if (m_pMediaDestination != NULL && tEncodedParamsSent)
{
m_pMediaDestination->encodedSourceStopped(m_pOpaque);
};
tEncodedParamsSent = false;
avformat_close_input(&m_pVideoState->m_pFormatCtx); avformat_close_input(&m_pVideoState->m_pFormatCtx);
if ((dec_ret = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts)) != 0) if ((dec_ret = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts)) != 0)
{ {
@ -1107,6 +1129,10 @@ void videoAVLIBSource::m_fThreadProc(void)
#ifdef DEBUG #ifdef DEBUG
LOG("Video Source Ended!"); LOG("Video Source Ended!");
#endif #endif
if (m_pMediaDestination != NULL && tEncodedParamsSent)
{
m_pMediaDestination->encodedSourceStopped(m_pOpaque);
};
if ( Packet ) { if ( Packet ) {
av_packet_free( &Packet ); av_packet_free( &Packet );
}; };

31
lib/data/media/video/videoLive555AVLibSource.cpp

@ -498,6 +498,13 @@ void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes
//LOG("FRM"); //LOG("FRM");
if ( presentationTime.tv_sec ) presentationTime.tv_sec = presentationTime.tv_sec; if ( presentationTime.tv_sec ) presentationTime.tv_sec = presentationTime.tv_sec;
if ( numTruncatedBytes ) numTruncatedBytes = numTruncatedBytes; if ( numTruncatedBytes ) numTruncatedBytes = numTruncatedBytes;
if (m_eCodecProbe == AV_CODEC_ID_H264 && frameSize > 0)
{
// The NAL unit as it came from the camera: live view / recording without re-encoding
RTPSource * tRtp = m_sSubSession.rtpSource();
int64_t tPt = (int64_t) presentationTime.tv_sec * 1000000 + presentationTime.tv_usec;
m_pSession->consumeEncodedNalu(m_pReceiveBuffer, frameSize, tPt, tRtp != NULL && tRtp->curPacketMarkerBit(), tRtp != NULL && tRtp->hasBeenSynchronizedUsingRTCP());
};
if ( m_eCodecProbe != AV_CODEC_ID_NONE) if ( m_eCodecProbe != AV_CODEC_ID_NONE)
{ {
int got_picture = 0; int got_picture = 0;
@ -709,6 +716,10 @@ void DummySink::setSprop(const u_int8_t * prop, unsigned size)
}; };
memcpy(buf_start, prop, size); memcpy(buf_start, prop, size);
m_sAvPkt.size = size + 4; m_sAvPkt.size = size + 4;
if (m_eCodecProbe == AV_CODEC_ID_H264)
{
m_pSession->consumeEncodedParams(prop, size); // SPS / PPS of the SDP
};
if ((m_pSession->getWM() & MS_MODE_DECODE_FRAMES) && canDecode()){ if ((m_pSession->getWM() & MS_MODE_DECODE_FRAMES) && canDecode()){
int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt ); int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt );
if( ret < 0 ){ if( ret < 0 ){
@ -1208,6 +1219,10 @@ void videoLIVE555Source::shutdownStream(RTSPClient * rtspClient, int exitCode)
LOG("Shutdown EVT"); LOG("Shutdown EVT");
#endif #endif
StreamClientState & streamClientState = MM->getStreamClientState(); // alias StreamClientState & streamClientState = MM->getStreamClientState(); // alias
if (m_pMediaDestination != NULL)
{
m_pMediaDestination->encodedSourceStopped(m_pOpaque); // the compressed stream ends here
};
// First, check whether any subsessions have still to be closed (as live555 testRTSPClient): // First, check whether any subsessions have still to be closed (as live555 testRTSPClient):
// the sinks were never closed before - they leaked and kept reading a deleted source // the sinks were never closed before - they leaked and kept reading a deleted source
@ -1290,6 +1305,22 @@ bool videoLIVE555Source::_open(CSTR URI, bool ShowDeviceMenu, float framerate, i
return true; return true;
} }
void videoLIVE555Source::consumeEncodedParams(const uint8_t * nalu, size_t size)
{
if (m_pMediaDestination != NULL)
{
m_pMediaDestination->pushEncodedParams(nalu, size, false, m_pOpaque);
};
}
void videoLIVE555Source::consumeEncodedNalu(const uint8_t * nalu, size_t size, int64_t ptUs, bool marker, bool synced)
{
if (m_pMediaDestination != NULL)
{
m_pMediaDestination->pushEncodedNalu(nalu, size, ptUs, marker, synced, m_pOpaque);
};
}
void videoLIVE555Source::consumeFrame(cv::Mat * frm) void videoLIVE555Source::consumeFrame(cv::Mat * frm)
{ {
if (m_pMediaDestination == NULL) if (m_pMediaDestination == NULL)

11
lib/data/media/video/videoLive555AVLibSource.h

@ -22,6 +22,12 @@
class videoLIVE555Source; class videoLIVE555Source;
// live555 changed the event loop watch variable from "char volatile" to std::atomic_char (2023): take the
// type from TaskScheduler::doEventLoop so both versions build
#include <type_traits>
template <class C, class A> A live555WatchArgType(void (C::*)(A));
typedef std::remove_pointer<decltype(live555WatchArgType(&TaskScheduler::doEventLoop))>::type LIVE555_WATCH_VARIABLE;
class StreamClientState class StreamClientState
{ {
public: public:
@ -158,7 +164,7 @@ class videoLIVE555Source : public basicMediaSource, public basicThread
UsageEnvironment * m_pUsageEnvironment; UsageEnvironment * m_pUsageEnvironment;
MediaSession * m_pMediaSession; MediaSession * m_pMediaSession;
volatile char _eventLoopWatchVariable;
LIVE555_WATCH_VARIABLE _eventLoopWatchVariable;
CustomRTSPClient * m_pRtspClient; CustomRTSPClient * m_pRtspClient;
DummySink * m_pSink; DummySink * m_pSink;
@ -224,6 +230,9 @@ class videoLIVE555Source : public basicMediaSource, public basicThread
bool setName(CSTR Name); bool setName(CSTR Name);
bool setFrameAspectRatio(FrameAspectRatio AspectRatio); bool setFrameAspectRatio(FrameAspectRatio AspectRatio);
void consumeFrame(cv::Mat * frm); void consumeFrame(cv::Mat * frm);
// Compressed H264 for the destination (live view / recording without re-encoding)
void consumeEncodedParams(const uint8_t * nalu, size_t size);
void consumeEncodedNalu(const uint8_t * nalu, size_t size, int64_t ptUs, bool marker, bool synced);
MediaSession * getMS(void) MediaSession * getMS(void)
{ {

Loading…
Cancel
Save