Browse Source

Alarm clips from the recorder segments; record video only once

When the embedded recorder writes segments (live_mode on, live_record on),
the alarm clips now come from those segments and the old encoder is not
started, so the video is no longer encoded and written twice.

- Recorder: ServerConf::onSegmentDone is called for every closed segment
  (file, local start time, duration, size).
- kernelModuleEmbedVideo keeps the closed segments of each path for
  3 minutes. An alarm (saveStreamPicture -> clipAlarm) hands over the
  segments within 5 s before / 5 s after it to the kernel like the old
  encoder's clips (hard link <scratch>/<md5>.mp4 + EVT_CAPTURE_DONE). The
  event is bound to the segment it happened in, with its frame offset.
  Old and left-over segments are deleted (sweepClips); the MediaMTX
  helper no longer indexes or deletes them.
- With live_record off the old encoder makes the clips as before.
- streamHandler: no encoder thread in decode-only mode (it left an empty
  segment file in the scratch folder per stream).
- VIDEO_SEGMENT_INFO of EVT_CAPTURE_DONE is a heap copy owned by the
  receiver (mojoKernel deletes it). The old encoder memcpy'd a struct
  with std::vector members (shared buffers) and leaked the copy.
- streamHandler: m_mEncodedProtector was unlocked every frame without
  being locked when EVE_WORK_WITH_MEDIAMTX is defined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
pull/28/head
Claude 2 hours ago
parent
commit
7b343a9988
Failed to extract signature
  1. 5
      lib/App/common/kernelHelperMediaMTX.cpp
  2. 6
      lib/App/common/kernelHelperMediaMTX.h
  3. 269
      lib/App/common/kernelModuleEmbedVideo.cpp
  4. 39
      lib/App/common/kernelModuleEmbedVideo.h
  5. 18
      lib/App/common/streamHandler.cpp
  6. 5
      lib/App/mojo/mojoKernel.cpp
  7. 14
      lib/data/media/mtx/conf/serverConf.h
  8. 25
      lib/data/media/mtx/recorder/recorder.cpp
  9. 8
      lib/data/media/mtx/recorder/recorder.h

5
lib/App/common/kernelHelperMediaMTX.cpp

@ -31,8 +31,9 @@ kernelHelperMediaMTX::kernelHelperMediaMTX(): basicThread() {
m_bRecordMode = false;
m_tLastRestart = 0;
#ifdef KH_MTX_EMBEDDED
// la_mojo records: segments of kernelModuleEmbedVideo (live_record), base folder fixed
m_bRecordMode = true;
// la_mojo records: segments of kernelModuleEmbedVideo (live_record), base folder fixed. The module keeps,
// hands over (alarm clips) and deletes them itself (kernelModuleEmbedVideo::sweepClips): no indexing here
m_bRecordMode = false;
strncpy( m_sRecordsBase, mtx_scratch_path, sizeof( m_sRecordsBase ) - 1 );
m_sRecordsBase[sizeof( m_sRecordsBase ) - 1] = (char) 0;
m_bStatus = KH_STATUS_MTX_INIT;

6
lib/App/common/kernelHelperMediaMTX.h

@ -16,9 +16,9 @@
/*
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.
service; it only stops the service once (it would hold port 8889). The recorded segments
(<mtx_scratch_path>/stream_<node>/*.mp4) are kept, turned into alarm clips and deleted by
kernelModuleEmbedVideo (sweepClips). Undefine it to go back to the external MediaMTX service.
*/
#define KH_MTX_EMBEDDED

269
lib/App/common/kernelModuleEmbedVideo.cpp

@ -24,6 +24,8 @@
#include <arpa/inet.h>
#include <ctype.h>
#include <dirent.h>
#include <sys/stat.h>
#include <err.h>
#include <errno.h>
#include <getopt.h>
@ -110,6 +112,7 @@ kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) :
};
m_bDetached = true;
m_tLiveRetry = 0;
m_tClipsScan = 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) {
@ -350,7 +353,20 @@ bool kernelModuleEmbedVideo::isProcessingVideoStream(){
};
};
m_mStreamHandlersProtector.unlock();
return RV;( m_mapHANDLERS.size() > 0 );
if (! RV)
{
// recorder clips: an alarm whose clip is not handed over yet
std::lock_guard<std::mutex> lock(m_mClips);
for (auto & c : m_mapClips)
{
if (! c.second.alarms.empty())
{
RV = true;
break;
};
};
};
return RV;
};
uint8_t kernelModuleEmbedVideo::getMediaMode(void)
{
@ -1717,6 +1733,7 @@ bool kernelModuleEmbedVideo::validate()
};
};
};
sweepClips(); // old recorded segments, alarms whose clip is overdue
// 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)
{
@ -2162,7 +2179,14 @@ bool kernelModuleEmbedVideo::saveStreamPicture(DBC_SNAPSHOT_DATA * ptr)
#ifdef DEBUG
LOG("Saving Video!");
#endif
if (ptr->assoc_event_ids.size())
if (ptr->assoc_event_ids.size() && liveClipsActive())
{
for (DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++)
{
clipAlarm(ptr->stream_id, *idx);
};
}
else if (ptr->assoc_event_ids.size())
{
m_mStreamHandlersProtector.lock();
mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(ptr->stream_id);
@ -2342,7 +2366,8 @@ bool kernelModuleEmbedVideo::registerStream(uint32_t streamID, uint8_t flip_mode
LOG( "Create New Stream Handler!" );
#endif
if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO)
// Alarm clips: from the recorder segments when it records (liveClipsActive), else the old encoder
if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO || liveClipsActive())
{
tData = new streamHandler(this, MS_MODE_DECODE_FRAMES, flip_mode);
}
@ -2378,7 +2403,7 @@ bool kernelModuleEmbedVideo::registerStream(uint32_t streamID, uint8_t flip_mode
#endif
streamHandler * tSH = NULL;
// Create New One
if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO)
if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO || liveClipsActive())
{
#ifdef DEBUG_EXTRA
LOG("New 1");
@ -2465,6 +2490,7 @@ void kernelModuleEmbedVideo::applyLiveSettings()
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.onSegmentDone = [this](const mtx::SegmentInfo & info) { onLiveSegment(info); };
m_sLiveConf.webrtcICEServers.clear();
std::string tIce(m_sEmbedVideoData.live_ice_servers);
size_t tPos = 0;
@ -2555,6 +2581,241 @@ std::shared_ptr<mtx::MediaPath> kernelModuleEmbedVideo::findPath(const std::stri
return (it == m_mapLivePaths.end()) ? nullptr : it->second;
}
/* ---------------------------------------------------------------- alarm clips from the recorder
When the recorder writes segments (live_record), the alarm clips come from them and the old encoder
(MS_MODE_ENCODE_FRAMES) is not started, so the video is no longer encoded and written twice.
- every closed segment is kept for EVE_CLIP_KEEP_MS (<scratch>/stream_<node>/...mp4), then deleted;
- an alarm (saveStreamPicture -> clipAlarm) wants the segments within EVE_CLIP_PRE_ALARM_MS before
and EVE_CLIP_POST_ALARM_MS after it. Those segments are handed to the kernel like the old encoder's
clips: a hard link <scratch>/<md5>.mp4 in a VIDEO_SEGMENT_INFO with EVT_CAPTURE_DONE. The alarm is
bound (eventIDS / eventFrames) to the segment it happened in;
- mojoKernel::handleVideo copies the clip into the report and deletes the link (or the remote server
keeps it); the recorder's own file is deleted by sweepClips() as usual.
*/
#ifndef EVE_CLIP_PRE_ALARM_MS
#define EVE_CLIP_PRE_ALARM_MS 5000
#endif
#ifndef EVE_CLIP_POST_ALARM_MS
#define EVE_CLIP_POST_ALARM_MS 5000
#endif
#ifndef EVE_CLIP_KEEP_MS
#define EVE_CLIP_KEEP_MS 180000 // recorded segments kept for clips of later alarms (pre-alarm part)
#endif
bool kernelModuleEmbedVideo::liveClipsActive(void) const
{
return m_sEmbedVideoData.live_mode != EVE_LIVE_OFF && m_sEmbedVideoData.live_record;
}
void kernelModuleEmbedVideo::registerClipStream(const std::string & path, uint32_t streamID, uint64_t sourceID, uint8_t fps)
{
std::lock_guard<std::mutex> lock(m_mClips);
EveClipStream & tS = m_mapClips[path];
tS.streamID = streamID;
tS.sourceID = sourceID;
tS.fps = fps ? fps : 25;
}
void kernelModuleEmbedVideo::clipAlarm(uint32_t streamID, uint32_t eventID)
{
int64_t tNow = mtx::nowUs();
std::lock_guard<std::mutex> lock(m_mClips);
for (auto & c : m_mapClips)
{
if (c.second.streamID == streamID)
{
c.second.alarms.push_back({eventID, tNow, false});
matchClipsLocked(c.second, tNow); // the pre-alarm part may be recorded already
return;
};
};
char tB[128];
snprintf(tB, sizeof(tB), "Alarm clip: stream %u is not recorded - no clip for event %u", streamID, eventID);
LOG_ERROR(tB);
}
// Recorder thread: a segment is complete
void kernelModuleEmbedVideo::onLiveSegment(const mtx::SegmentInfo & info)
{
std::lock_guard<std::mutex> lock(m_mClips);
EveClipStream & tS = m_mapClips[info.path];
tS.segments.push_back({info.file, info.startUs, info.startUs + info.durationUs, info.width, info.height, false});
matchClipsLocked(tS, mtx::nowUs());
}
void kernelModuleEmbedVideo::matchClipsLocked(EveClipStream & stream, int64_t nowUs)
{
if (stream.alarms.empty())
{
return;
};
for (EveClipSegment & tSeg : stream.segments)
{
if (tSeg.handed)
{
continue;
};
for (const EveClipAlarm & a : stream.alarms)
{
if (a.timeUs - EVE_CLIP_PRE_ALARM_MS * 1000LL < tSeg.endUs && a.timeUs + EVE_CLIP_POST_ALARM_MS * 1000LL > tSeg.startUs)
{
handOffClipLocked(stream, tSeg);
break;
};
};
};
// An alarm is done when its segment is handed over and the post-alarm time is recorded
int64_t tRecordedUntil = stream.segments.empty() ? 0 : stream.segments.back().endUs;
for (auto it = stream.alarms.begin(); it != stream.alarms.end();)
{
bool tDone = it->bound && tRecordedUntil >= it->timeUs + EVE_CLIP_POST_ALARM_MS * 1000LL;
// nothing recorded for it (stream down): give up after a while
bool tLost = ! it->bound && nowUs - it->timeUs > EVE_CLIP_KEEP_MS * 1000LL;
if (tLost)
{
char tB[128];
snprintf(tB, sizeof(tB), "Alarm clip: nothing recorded for event %u - no clip", it->eventID);
LOG_ERROR(tB);
};
if (tDone || tLost || (it->bound && nowUs - it->timeUs > EVE_CLIP_KEEP_MS * 1000LL))
{
it = stream.alarms.erase(it);
}
else
{
++it;
};
};
}
bool kernelModuleEmbedVideo::handOffClipLocked(EveClipStream & stream, EveClipSegment & seg)
{
seg.handed = true; // also on failure: do not retry every time
if (stream.streamID == 0)
{
return false; // a path no stream handler registered (cannot happen: initLive registers it)
};
CSTR tMD5 = getUniqID_MD5();
if (tMD5 == NULL)
{
LOG_ERROR("Alarm clip: no MD5");
return false;
};
VIDEO_SEGMENT_INFO * tSI = new VIDEO_SEGMENT_INFO(); // owned by the receiver (mojoKernel deletes it)
snprintf(tSI->scratchPath, sizeof(tSI->scratchPath), "%s/%s.mp4", m_pVideoScratchPath, tMD5);
strncpy(tSI->recordMD5, tMD5, 32);
tSI->recordMD5[32] = (char) 0;
free(tMD5);
// a hard link: the recorder's file stays until sweepClips(), the kernel deletes its link
if (link(seg.file.c_str(), tSI->scratchPath) != 0 && fileCopy(seg.file.c_str(), tSI->scratchPath) != 0)
{
char tB[PATH_MAX + 64];
snprintf(tB, sizeof(tB), "Alarm clip: cannot link %s (%s)", seg.file.c_str(), strerror(errno));
LOG_ERROR(tB);
delete tSI;
return false;
};
strncpy(tSI->recordEXT, "mp4", sizeof(tSI->recordEXT));
tSI->stream_id = stream.streamID;
tSI->streamTSS = (uint32_t) (seg.startUs / 1000000);
tSI->streamTMS = (uint32_t) ((seg.startUs / 1000) % 1000);
tSI->streamFPS = stream.fps;
tSI->streamWidth = (uint16_t) seg.width;
tSI->streamHeight = (uint16_t) seg.height;
struct stat tSt;
tSI->dataSize = (stat(tSI->scratchPath, &tSt) == 0) ? (uint32_t) tSt.st_size : 0;
for (EveClipAlarm & a : stream.alarms)
{
// the segment the alarm happened in (or the first one after it: nothing recorded at its time)
if (! a.bound && a.timeUs < seg.endUs)
{
a.bound = true;
int64_t tOffset = a.timeUs > seg.startUs ? a.timeUs - seg.startUs : 0;
tSI->eventIDS.push_back(a.eventID);
tSI->eventTSS.push_back((uint32_t) (a.timeUs / 1000000));
tSI->eventTMS.push_back((uint32_t) ((a.timeUs / 1000) % 1000));
tSI->eventFrames.push_back((uint32_t) (tOffset * stream.fps / 1000000));
};
};
EVENT_CONTAINER * bEVT = createBasicEvent(stream.sourceID, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, tSI);
if (bEVT == NULL)
{
LOG_ERROR("Alarm clip: event creation failure!");
unlink(tSI->scratchPath);
delete tSI;
return false;
};
char tB[PATH_MAX + 96];
snprintf(tB, sizeof(tB), "Alarm clip: %s (%u event(s))", seg.file.c_str(), (unsigned) tSI->eventIDS.size());
LOG(tB);
basicEventHeap::getInstance()->broadcast(bEVT);
return true;
}
// validate(): deletes old segments, checks the alarms; every minute also left-overs (a previous run)
void kernelModuleEmbedVideo::sweepClips(void)
{
int64_t tNow = mtx::nowUs();
{
std::lock_guard<std::mutex> lock(m_mClips);
for (auto & c : m_mapClips)
{
std::deque<EveClipSegment> & tSegs = c.second.segments;
while (! tSegs.empty() && tNow - tSegs.front().endUs > EVE_CLIP_KEEP_MS * 1000LL)
{
unlink(tSegs.front().file.c_str());
tSegs.pop_front();
};
matchClipsLocked(c.second, tNow);
};
}
time_t tSec = time(NULL);
if (tSec - m_tClipsScan < 60)
{
return;
};
m_tClipsScan = tSec;
// <scratch>/stream_*/*.mp4 older than the keep time (+1 min): not tracked any more (restart, path gone)
DIR * tDir = opendir(m_pVideoScratchPath);
if (tDir == NULL)
{
return;
};
struct dirent * tE;
while ((tE = readdir(tDir)) != NULL)
{
if (strncmp(tE->d_name, "stream_", 7) != 0)
{
continue;
};
std::string tSub = std::string(m_pVideoScratchPath) + "/" + tE->d_name;
DIR * tD = opendir(tSub.c_str());
if (tD == NULL)
{
continue;
};
struct dirent * tF;
while ((tF = readdir(tD)) != NULL)
{
size_t tLen = strlen(tF->d_name);
if (tLen < 4 || strcmp(tF->d_name + tLen - 4, ".mp4") != 0)
{
continue;
};
std::string tFile = tSub + "/" + tF->d_name;
struct stat tSt;
if (stat(tFile.c_str(), &tSt) == 0 && S_ISREG(tSt.st_mode) && (tSec - tSt.st_mtime) * 1000LL > EVE_CLIP_KEEP_MS + 60000)
{
unlink(tFile.c_str());
};
};
closedir(tD);
};
closedir(tDir);
}
#undef TLOG
#undef TLOG_ERROR

39
lib/App/common/kernelModuleEmbedVideo.h

@ -19,6 +19,7 @@ extern const char * m_pVideoScratchPath;
#include "../../components/base/basicMediaDestination.h"
#include "../../components/base/basicMediaSource.h"
#include "../../data/media/mtx/core/mediaPath.h"
#include <deque>
#include <map>
#include <memory>
#include <mutex>
@ -145,6 +146,41 @@ class kernelModuleEmbedVideo : public kernelModule, public mtx::PathProvider
void applyLiveSettings();
bool startLive();
void stopLive();
// Alarm clips from the recorded segments (live_record), replacing the old encoder's clips:
// recent segments are kept for a while, a segment around an alarm is handed to the kernel
// (EVT_CAPTURE_DONE -> Reports/History) like the old encoder's clips.
struct EveClipSegment
{
std::string file;
int64_t startUs;
int64_t endUs;
int width;
int height;
bool handed;
};
struct EveClipAlarm
{
uint32_t eventID;
int64_t timeUs;
bool bound; // the segment with the alarm in it is handed over
};
struct EveClipStream
{
uint32_t streamID = 0;
uint64_t sourceID = 0;
uint8_t fps = 0;
std::deque<EveClipSegment> segments; // oldest first
std::vector<EveClipAlarm> alarms;
};
std::mutex m_mClips;
std::map<std::string, EveClipStream> m_mapClips; // path name -> stream
time_t m_tClipsScan; // last scan of the scratch folders for left-over segments
bool liveClipsActive(void) const;
void onLiveSegment(const mtx::SegmentInfo & info);
void matchClipsLocked(EveClipStream & stream, int64_t nowUs);
bool handOffClipLocked(EveClipStream & stream, EveClipSegment & seg);
void sweepClips(void);
#ifndef EVE_WORK_WITH_MEDIAMTX
protected:
@ -181,6 +217,9 @@ class kernelModuleEmbedVideo : public kernelModule, public mtx::PathProvider
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);
// Alarm clips (live_record): the stream of a path, and an alarm on a stream
void registerClipStream(const std::string & path, uint32_t streamID, uint64_t sourceID, uint8_t fps);
void clipAlarm(uint32_t streamID, uint32_t eventID);
// 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;

18
lib/App/common/streamHandler.cpp

@ -335,6 +335,9 @@ bool streamHandler::create(dataBinder * ptr, uint32_t stremID)
if ( m_pSource ){
#ifdef EVE_ENABLE_VIDEO
// Decode only (no video output, or the clips come from the recorder): no encoder thread. It opened
// an empty segment file in the scratch folder that was never written nor deleted.
if ( m_eWM == MS_MODE_DECODE_FRAMES ) return true;
return initVideoOutput();
#else
return true;
@ -355,6 +358,9 @@ void streamHandler::initLive(uint32_t nodeID)
m_bLiveMode = EVE_LIVE_OFF;
return;
};
// alarm clips come from this path's recorded segments (when it records)
m_pMaster->registerClipStream(m_pLivePath->name(), m_sStreamData.id, m_sStreamData.source_id,
m_bLiveMode == EVE_LIVE_ENCODE ? m_pMaster->getLiveFps() : m_sStreamData.fps);
char tB[160];
if (m_bLiveMode == EVE_LIVE_ENCODE)
{
@ -733,8 +739,8 @@ bool streamHandler::pushFrame(cv::Mat & Frame, void * src)
m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId].clear();
cv::imencode(".jpg", dst, m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId], compression_params);
#endif
#endif // !EVE_WORK_WITH_MEDIAMTX
m_pMaster->m_mEncodedProtector.unlock();
#endif // !EVE_WORK_WITH_MEDIAMTX
#ifdef EVE_ENABLE_VIDEO
// if only decode Video Stream -> Exit
@ -3187,15 +3193,15 @@ bool streamHandler::pushFrame(cv::Mat & Frame, void * src)
avio_close( m_pFormatCtx->pb );
#endif //! OPENCV_VIDEO_OUTPUT
#endif //! DIRECT_MJPEG_COMPOSING
VIDEO_SEGMENT_INFO *tData = (VIDEO_SEGMENT_INFO*) malloc( sizeof(VIDEO_SEGMENT_INFO));
// a copy owned by the receiver (mojoKernel deletes it); memcpy shared the vectors with this struct
VIDEO_SEGMENT_INFO *tData = new VIDEO_SEGMENT_INFO( m_sStreamSegmentInfo );
if( tData ){
memcpy( tData, &m_sStreamSegmentInfo, sizeof( VIDEO_SEGMENT_INFO ));
EVENT_CONTAINER * bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, tData );
if( bEVT ){
basicEventHeap::getInstance()->broadcast(bEVT);
} else {
LOG_ERROR("Event Creation failure!");
free(tData);
delete tData;
};
};
#ifdef DEBUG_EXTRA
@ -3454,7 +3460,7 @@ bool streamHandler::pushFrame(cv::Mat & Frame, void * src)
avio_close(m_pFormatCtxA->pb);
#endif //! OPENCV_VIDEO_OUTPUT
#endif //! DIRECT_MJPEG_COMPOSING
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0]);
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, new VIDEO_SEGMENT_INFO(m_sStreamSegmentInfo[0]));
if (bEVT)
{
basicEventHeap::getInstance()->broadcast(bEVT);
@ -3548,7 +3554,7 @@ bool streamHandler::pushFrame(cv::Mat & Frame, void * src)
avio_close(m_pFormatCtxB->pb);
#endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1]);
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, new VIDEO_SEGMENT_INFO(m_sStreamSegmentInfo[1]));
if (bEVT)
{
basicEventHeap::getInstance()->broadcast(bEVT);

5
lib/App/mojo/mojoKernel.cpp

@ -1480,8 +1480,9 @@ bool mojoKernel::dispatchEvent(EVENT_CONTAINER * Evt)
if (Evt->m_pEvtData)
{
handleVideo((VIDEO_SEGMENT_INFO *) Evt->m_pEvtData);
// Dont free Data - it points to static struct of Encoder!!
memset(Evt->m_pEvtData, 0, sizeof(VIDEO_SEGMENT_INFO));
// Every sender allocates a copy with new (streamHandler encoder, kernelModuleEmbedVideo
// recorder clips); the remote client copies what it needs (init)
delete (VIDEO_SEGMENT_INFO *) Evt->m_pEvtData;
Evt->m_pEvtData = NULL;
#ifdef DEBUG_EXTRA
LOG("VIDEO_SEGMENT_INFO Cleared!");

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

@ -8,11 +8,23 @@
#pragma once
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
namespace mtx {
// A finished recording segment (the file is closed and complete)
struct SegmentInfo
{
std::string path; // path name (e.g. stream_12)
std::string file; // full file name
int64_t startUs = 0; // local wall clock when its first sample was written (us since the epoch)
int64_t durationUs = 0; // from the timestamps of the samples
int width = 0;
int height = 0;
};
struct ServerConf
{
// WebRTC (WHEP)
@ -27,6 +39,8 @@ struct ServerConf
std::string recordPath = "./recordings/%path/%Y-%m-%d_%H-%M-%S-%f";
int64_t recordSegmentDurationMs = 60000;
int64_t recordPartDurationMs = 1000;
// Called (from the recorder thread) for every closed segment; must not block. Optional.
std::function<void(const SegmentInfo &)> onSegmentDone;
};
// "60s", "1m", "500ms", "1h", "1.5s"; plain number = seconds

25
lib/data/media/mtx/recorder/recorder.cpp

@ -29,13 +29,24 @@ void Recorder::start()
log(LogLevel::Info, "recording to %s.mp4 (segments of %lld s)", tPattern.c_str(), (long long) (m_global.recordSegmentDurationMs / 1000));
}
void Recorder::closeSegment()
void Recorder::closeSegment(int64_t endDts)
{
if (m_writer.isOpen())
{
std::string tFile = m_writer.fileName();
m_writer.close();
log(LogLevel::Debug, "segment closed: %s", tFile.c_str());
if (m_global.onSegmentDone)
{
SegmentInfo tInfo;
tInfo.path = m_sPath;
tInfo.file = tFile;
tInfo.startUs = m_nSegmentStartUs;
tInfo.durationUs = (endDts >= 0 ? endDts : m_nLastDts + m_nLastDelta) * 1000 / 90;
tInfo.width = m_nWidth;
tInfo.height = m_nHeight;
m_global.onSegmentDone(tInfo);
}
}
}
@ -53,7 +64,7 @@ void Recorder::onUnit(const UnitPtr & unit)
{
log(LogLevel::Error, "%s", tErr.c_str());
}
closeSegment();
closeSegment(tDts);
}
else
{
@ -63,6 +74,11 @@ void Recorder::onUnit(const UnitPtr & unit)
closeSegment();
return;
}
if (tDts > m_nLastDts)
{
m_nLastDelta = tDts - m_nLastDts;
}
m_nLastDts = tDts;
m_writer.addSample(tDts, unit);
return;
}
@ -113,6 +129,11 @@ void Recorder::onUnit(const UnitPtr & unit)
}
m_bFailed = false;
m_nSegmentStartPts = unit->pts;
m_nSegmentStartUs = tNow; // local clock: the camera's clock (RTCP) may be off
m_nLastDts = 0;
m_nLastDelta = 0;
m_nWidth = tDesc.width;
m_nHeight = tDesc.height;
log(LogLevel::Debug, "segment opened: %s", tFile.c_str());
m_writer.addSample(0, unit);
}

8
lib/data/media/mtx/recorder/recorder.h

@ -28,7 +28,8 @@ class Recorder : public LogParent
private:
void onUnit(const UnitPtr & unit);
void closeSegment();
// endDts: end of the segment (90 kHz) when known, else the last sample plus its duration
void closeSegment(int64_t endDts = -1);
std::string m_sPath;
ServerConf m_global;
@ -36,6 +37,11 @@ class Recorder : public LogParent
AsyncReader m_reader;
Fmp4Writer m_writer;
int64_t m_nSegmentStartPts = 0;
int64_t m_nSegmentStartUs = 0; // local wall clock of the first sample
int64_t m_nLastDts = 0; // last sample of the open segment (90 kHz)
int64_t m_nLastDelta = 0; // its duration
int m_nWidth = 0;
int m_nHeight = 0;
bool m_bFailed = false;
};

Loading…
Cancel
Save