Browse Source
Embed MediaMTX functionality (WebRTC live view + recording) in kernelModuleEmbedVideo
Embed MediaMTX functionality (WebRTC live view + recording) in kernelModuleEmbedVideo
- Move reusable MediaMtx code (logger, codecs, stream, httpp, recorder, webrtc server) to lib/data/media/mtx; add ServerConf, MediaPath/ PathProvider and H264Feeder. Standalone Projects/MediaMtx builds against it. - kernelModuleEmbedVideo hosts a WHEP server (:8889/stream_<node>/whep) and one MediaPath per camera stream with fMP4 segment recording. - streamHandler feeds each path either with camera H264 passthrough (videoAVLIBSource / videoLive555AVLibSource forward encoded NALs) or with re-encoded processed frames incl. overlays (streamLiveEncoder), selected by module_eve.live_mode (optional columns, defaults apply). - kernelHelperMediaMTX: external mediamtx.service is stopped, segment indexing of the scratch folder is kept. - live555 watch variable type deduced so old and new live555 build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16pull/28/head
Failed to extract signature
49 changed files with 7780 additions and 6345 deletions
-
2Projects/MediaMtx/internal/api/api.h
-
76Projects/MediaMtx/internal/conf/conf.cpp
-
24Projects/MediaMtx/internal/conf/conf.h
-
2Projects/MediaMtx/internal/core/core.h
-
93Projects/MediaMtx/internal/core/path.cpp
-
50Projects/MediaMtx/internal/core/path.h
-
4Projects/MediaMtx/internal/core/pathManager.h
-
2Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.cpp
-
17Projects/MediaMtx/internal/staticsources/rtsp/rtspSource.h
-
29Projects/MediaMtx/makefile
-
2409Projects/la_mojo/makefile
-
38lib/App/common/MySQL_dataBinder.cpp
-
38lib/App/common/SQLite_dataBinder.cpp
-
25lib/App/common/dataBinder_structures.h
-
1219lib/App/common/kernelHelperMediaMTX.cpp
-
179lib/App/common/kernelHelperMediaMTX.h
-
129lib/App/common/kernelModuleEmbedVideo.cpp
-
36lib/App/common/kernelModuleEmbedVideo.h
-
7711lib/App/common/streamHandler.cpp
-
789lib/App/common/streamHandler.h
-
236lib/App/common/streamLiveEncoder.cpp
-
68lib/App/common/streamLiveEncoder.h
-
28lib/components/base/basicMediaDestination.h
-
131lib/data/media/mtx/codecs/h264/h264.cpp
-
6lib/data/media/mtx/codecs/h264/h264.h
-
83lib/data/media/mtx/conf/serverConf.cpp
-
39lib/data/media/mtx/conf/serverConf.h
-
145lib/data/media/mtx/core/mediaPath.cpp
-
100lib/data/media/mtx/core/mediaPath.h
-
209lib/data/media/mtx/feeder/h264Feeder.cpp
-
77lib/data/media/mtx/feeder/h264Feeder.h
-
15lib/data/media/mtx/logger/logger.cpp
-
6lib/data/media/mtx/logger/logger.h
-
2lib/data/media/mtx/protocols/httpp/httpServer.cpp
-
0lib/data/media/mtx/protocols/httpp/httpServer.h
-
0lib/data/media/mtx/recorder/fmp4Writer.cpp
-
0lib/data/media/mtx/recorder/fmp4Writer.h
-
2lib/data/media/mtx/recorder/recorder.cpp
-
6lib/data/media/mtx/recorder/recorder.h
-
6lib/data/media/mtx/servers/webrtc/session.cpp
-
12lib/data/media/mtx/servers/webrtc/session.h
-
4lib/data/media/mtx/servers/webrtc/webrtcServer.cpp
-
10lib/data/media/mtx/servers/webrtc/webrtcServer.h
-
0lib/data/media/mtx/stream/stream.cpp
-
0lib/data/media/mtx/stream/stream.h
-
0lib/data/media/mtx/unit/unit.h
-
26lib/data/media/video/videoAVLIBSource.cpp
-
31lib/data/media/video/videoLive555AVLibSource.cpp
-
11lib/data/media/video/videoLive555AVLibSource.h
2409
Projects/la_mojo/makefile
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
1219
lib/App/common/kernelHelperMediaMTX.cpp
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
@ -1,86 +1,95 @@ |
|||
#ifndef __KERNEL_HELPER_MEDIA_MTX_HEADER__ |
|||
#define __KERNEL_HELPER_MEDIA_MTX_HEADER__ |
|||
|
|||
#ifndef LRF_PROXY_ONLY |
|||
|
|||
#include "dataBinder.h" |
|||
#include "../../components/base/basicThread.h" |
|||
#include <sys/types.h> |
|||
#include <sys/stat.h> |
|||
#include <unistd.h> |
|||
#include <vector> |
|||
|
|||
|
|||
#define mtx_scratch_path "/dev/shm/argus/video_scratch" |
|||
|
|||
typedef struct S_StreamDescRecord{ |
|||
uint32_t cam_id; |
|||
uint64_t node_id; |
|||
uint32_t stream_id; |
|||
uint8_t status; |
|||
bool valid; |
|||
char source_uri[512]; |
|||
}StreamDescRecord; |
|||
|
|||
typedef std::vector<StreamDescRecord *> V_StreamDescRecords; |
|||
|
|||
#define KH_STATUS_MTX_NA 0 |
|||
#define KH_STATUS_MTX_INIT 1 |
|||
#define KH_STATUS_MTX_AOK 2 |
|||
#define KH_STATUS_MTX_ERR 255 |
|||
|
|||
#define KH_MTX_STREAM_LOADDED 0 |
|||
#define KH_MTX_STREAM_REGISTERED 1 |
|||
#define KH_MTX_STREAM_ONLINE 2 |
|||
#define KH_MTX_STREAM_OFFLINE 3 |
|||
#define KH_MTX_STREAM_ERROR 255 |
|||
|
|||
typedef struct S_StreamSegmentRecord{ |
|||
bool keep; |
|||
VIDEO_SEGMENT_INFO SI; |
|||
}StreamSegmentRecord; |
|||
|
|||
typedef std::map<uint64_t, StreamSegmentRecord *> M_StreamMap; // inodes -> info |
|||
typedef std::map<uint64_t, M_StreamMap *> M_VideoSegmentInfo; // stream_id -> map |
|||
|
|||
|
|||
// At most one MediaMTX restart per this period (a config that keeps failing validation restarted it every second) |
|||
#ifndef KH_MTX_RESTART_MIN_S |
|||
#define KH_MTX_RESTART_MIN_S 30 |
|||
#endif |
|||
|
|||
class kernelHelperMediaMTX: public basicThread { |
|||
private: |
|||
basicLogCollection * m_pLog; |
|||
dataBinder * m_pDBC; |
|||
V_StreamDescRecords m_vStreamRecords; |
|||
M_VideoSegmentInfo m_mVideoSegments; |
|||
uint8_t m_bStatus; |
|||
char m_sWorkDir[512]; |
|||
char m_sAppLogFile[512]; |
|||
char m_sAppConfigFile[512]; |
|||
char m_sRecordsBase[MAX_PATH_LEN]; |
|||
off_t m_nLastLogSize; |
|||
bool m_bRecordMode; |
|||
time_t m_tLastRestart; // last restart() (rate limit) |
|||
bool loadConfig(); |
|||
bool loadStreams(); |
|||
StreamSegmentRecord * createSSR( uint32_t stream_id, uint32_t streamTSS, uint32_t streamTMS, CSTR path ); |
|||
void deleteSSR( StreamSegmentRecord *ptr ); |
|||
void validateSSR( StreamSegmentRecord *ptr ); |
|||
protected: |
|||
virtual void m_fThreadProc(void); |
|||
public: |
|||
kernelHelperMediaMTX(); |
|||
virtual ~kernelHelperMediaMTX(); |
|||
bool create(); |
|||
bool validateConfig(); |
|||
bool assignStream( uint32_t stream_id ); |
|||
bool updateConfig(); |
|||
bool restart(); |
|||
bool validateService(); |
|||
uint8_t getStatus(){ return m_bStatus; }; |
|||
}; |
|||
|
|||
#endif // ! LRF_PROXY_ONLY |
|||
#ifndef __KERNEL_HELPER_MEDIA_MTX_HEADER__ |
|||
#define __KERNEL_HELPER_MEDIA_MTX_HEADER__ |
|||
|
|||
#ifndef LRF_PROXY_ONLY |
|||
|
|||
#include "dataBinder.h" |
|||
#include "../../components/base/basicThread.h" |
|||
#include <sys/types.h> |
|||
#include <sys/stat.h> |
|||
#include <unistd.h> |
|||
#include <vector> |
|||
|
|||
|
|||
#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{ |
|||
uint32_t cam_id; |
|||
uint64_t node_id; |
|||
uint32_t stream_id; |
|||
uint8_t status; |
|||
bool valid; |
|||
char source_uri[512]; |
|||
}StreamDescRecord; |
|||
|
|||
typedef std::vector<StreamDescRecord *> V_StreamDescRecords; |
|||
|
|||
#define KH_STATUS_MTX_NA 0 |
|||
#define KH_STATUS_MTX_INIT 1 |
|||
#define KH_STATUS_MTX_AOK 2 |
|||
#define KH_STATUS_MTX_ERR 255 |
|||
|
|||
#define KH_MTX_STREAM_LOADDED 0 |
|||
#define KH_MTX_STREAM_REGISTERED 1 |
|||
#define KH_MTX_STREAM_ONLINE 2 |
|||
#define KH_MTX_STREAM_OFFLINE 3 |
|||
#define KH_MTX_STREAM_ERROR 255 |
|||
|
|||
typedef struct S_StreamSegmentRecord{ |
|||
bool keep; |
|||
VIDEO_SEGMENT_INFO SI; |
|||
}StreamSegmentRecord; |
|||
|
|||
typedef std::map<uint64_t, StreamSegmentRecord *> M_StreamMap; // inodes -> info |
|||
typedef std::map<uint64_t, M_StreamMap *> M_VideoSegmentInfo; // stream_id -> map |
|||
|
|||
|
|||
// At most one MediaMTX restart per this period (a config that keeps failing validation restarted it every second) |
|||
#ifndef KH_MTX_RESTART_MIN_S |
|||
#define KH_MTX_RESTART_MIN_S 30 |
|||
#endif |
|||
|
|||
class kernelHelperMediaMTX: public basicThread { |
|||
private: |
|||
basicLogCollection * m_pLog; |
|||
dataBinder * m_pDBC; |
|||
V_StreamDescRecords m_vStreamRecords; |
|||
M_VideoSegmentInfo m_mVideoSegments; |
|||
uint8_t m_bStatus; |
|||
char m_sWorkDir[512]; |
|||
char m_sAppLogFile[512]; |
|||
char m_sAppConfigFile[512]; |
|||
char m_sRecordsBase[MAX_PATH_LEN]; |
|||
off_t m_nLastLogSize; |
|||
bool m_bRecordMode; |
|||
time_t m_tLastRestart; // last restart() (rate limit) |
|||
bool loadConfig(); |
|||
bool loadStreams(); |
|||
StreamSegmentRecord * createSSR( uint32_t stream_id, uint32_t streamTSS, uint32_t streamTMS, CSTR path ); |
|||
void deleteSSR( StreamSegmentRecord *ptr ); |
|||
void validateSSR( StreamSegmentRecord *ptr ); |
|||
protected: |
|||
virtual void m_fThreadProc(void); |
|||
public: |
|||
kernelHelperMediaMTX(); |
|||
virtual ~kernelHelperMediaMTX(); |
|||
bool create(); |
|||
bool validateConfig(); |
|||
bool assignStream( uint32_t stream_id ); |
|||
bool updateConfig(); |
|||
bool restart(); |
|||
bool validateService(); |
|||
uint8_t getStatus(){ return m_bStatus; }; |
|||
}; |
|||
|
|||
#endif // ! LRF_PROXY_ONLY |
|||
#endif |
|||
7711
lib/App/common/streamHandler.cpp
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
@ -1,386 +1,403 @@ |
|||
#ifndef __STREAM_HANDLER_EMBED_VIDEO_HEADER__ |
|||
#define __STREAM_HANDLER_EMBED_VIDEO_HEADER__ |
|||
|
|||
#include "kernelModuleEmbedVideo.h" |
|||
|
|||
#ifndef LRF_PROXY_ONLY |
|||
|
|||
#include "../../components/base/basicDualThread.h" |
|||
#include "../../components/base/basicEventHeap.h" |
|||
#include "../../components/base/basicMutex.h" |
|||
#include "kernelModule.h" |
|||
#define EVE_SEQUENTAL_OUTPUT |
|||
|
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
//#define EVE_ENABLE_EASE_OUTPUT_FPS |
|||
#endif |
|||
|
|||
// #include "../../data/media/video/videoAVLIBDestination.h" |
|||
#include "../../components/base/basicMediaDestination.h" |
|||
#include "../../components/base/basicMediaSource.h" |
|||
|
|||
#ifndef DB_SHMEM_POINT |
|||
#define DB_SHMEM_POINT "/dev/shm/argus" |
|||
#endif |
|||
|
|||
#define VIDEO_SCRATCHPAD_PATH (DB_SHMEM_POINT "/video_scratch") |
|||
|
|||
//Predefine Classess |
|||
class kernelModuleEmbedVideo; |
|||
// A stream is restarted only after this many validations in a row (module factory: every ~5 s) without a |
|||
// new frame. One gap of ~5 s (a camera on a mobile link) restarted the stream and cut the recording. |
|||
#ifndef STREAM_STALL_CHECKS |
|||
#define STREAM_STALL_CHECKS 3 |
|||
#endif |
|||
|
|||
class streamHandler; |
|||
|
|||
#define FILESTREAMBUFFERSZ 1048576 |
|||
|
|||
#ifndef MEKOROT_PROJECT__ |
|||
#define EVE_ENABLE_VIDEO |
|||
#endif |
|||
|
|||
#define USE_SCALING_IN |
|||
// #define USE_CV_DENOISE |
|||
// #define USE_CV_TONEMAP |
|||
|
|||
#ifdef EVE_ENABLE_VIDEO |
|||
#define VIDEO_OUTPUT_FPS 15 |
|||
|
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
// In case of sequental video files - no need two encoders |
|||
#define SEPARATED_VIDEO_ENCODERS |
|||
#endif |
|||
// #define EVE_DONT_DELETE_SEGMENTS |
|||
|
|||
/* Video CODECS */ |
|||
#define VC_VPX 0 |
|||
#define VC_X264 1 |
|||
#define VC_MP4 2 |
|||
#define VC_MJPEG 3 |
|||
#define VC_FLV 4 |
|||
|
|||
/* Video FORMATS */ |
|||
#define VF_WEBM 0 |
|||
#define VF_MP4 1 |
|||
#define VF_MP3 2 |
|||
#define VF_AAC 3 |
|||
#define VF_OGG 4 |
|||
#define VF_MJPEG 5 |
|||
#define VF_FLV 6 |
|||
|
|||
/* Encoder PROFILES */ |
|||
#define VP_ULTRAFAST 0 |
|||
#define VP_VERYFAST 1 |
|||
#define VP_FAST 2 |
|||
#define VP_MEDIUM 3 |
|||
#define VP_SLOW 4 |
|||
#define VP_VERYSLOW 5 |
|||
#define VP_ULTRASLOW 6 |
|||
|
|||
#define VO_MJPEG 1 |
|||
#define VO_MPEG4 2 |
|||
#define VO_H264 3 |
|||
#define VO_H265 4 |
|||
#define VO_FLV 5 |
|||
#define VO_DIRECT_MJPG 6 |
|||
|
|||
#ifndef EVE_WORK_WITH_MEDIAMTX |
|||
#define DIRECT_MJPEG_COMPOSING |
|||
#endif |
|||
|
|||
#ifdef DIRECT_MJPEG_COMPOSING |
|||
#define VIDEO_OUTPUT VO_DIRECT_MJPG |
|||
#else |
|||
#define OPENCV_VIDEO_OUTPUT |
|||
//#define VIDEO_OUTPUT VO_DIRECT_MJPG |
|||
#ifndef OPENCV_VIDEO_OUTPUT |
|||
// #define VIDEO_OUTPUT VO_MJPEG |
|||
#define VIDEO_OUTPUT VO_MPEG4 |
|||
// #define VIDEO_OUTPUT VO_H264 |
|||
// #define VIDEO_OUTPUT VO_H265 |
|||
// #define VIDEO_OUTPUT VO_FLV |
|||
// #define VIDEO_OUTPUT_WIDTH 640 //1920 |
|||
// #define VIDEO_OUTPUT_HEIGHT 480 //1080 |
|||
// #define VIDEO_OUTPUT_FPS 10 |
|||
// #define VIDEO_OUTPUT_GOP 15 |
|||
#else // OPENCV_VIDEO_OUTPUT |
|||
//#define VIDEO_OUTPUT VO_MJPEG // VO_CV_MP4 |
|||
#define VIDEO_OUTPUT VO_CV_MP4 |
|||
#endif |
|||
#endif // DIRECT_MJPEG_COMPOSING |
|||
|
|||
#if (LIBAVCODEC_VERSION_MAJOR < 54) |
|||
#define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG |
|||
#define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P |
|||
#else |
|||
#if VIDEO_OUTPUT == VO_MJPEG |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P // AV_PIX_FMT_YUVJ422P |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER "mjpeg" |
|||
#elif VIDEO_OUTPUT == VO_MPEG4 |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_H264 |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H264 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_H265 |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H265 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_FLV |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "flv" |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER "flv" |
|||
#elif VIDEO_OUTPUT == VO_CV_MP4 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_DIRECT_MJPG |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" |
|||
#define VIDEO_OUTPUT_CONTAINER "mjpeg" |
|||
#endif |
|||
#endif |
|||
#endif // EVE_ENABLE_VIDEO |
|||
|
|||
typedef struct S_buffer_data |
|||
{ |
|||
uint8_t * buf; |
|||
int size; |
|||
uint8_t * ptr; |
|||
size_t room; ///< size left in the buffer |
|||
} buffer_data; |
|||
|
|||
#define NR_COLORS 4 |
|||
#define AVIO_BUFFER_SIZE 4096 |
|||
#define BD_BUFFER_SIZE 1024 |
|||
|
|||
#define PRE_ALARM_TIME_MILSECONDS 5000 // 5 sec |
|||
#define POST_ALARM_TIME_MILSECONDS 5000 // 5 sec |
|||
#define ENCODING_SEGMENT_MILSECONDS 50000 // 50 sec |
|||
#define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute |
|||
// #define ENCODING_SEGMENT_LIMIT_MILSECONDS 900000 // 15 minutes |
|||
|
|||
|
|||
// #define ENCODER_DISABLED 0 |
|||
// #define ENCODER_ENABLED 1 |
|||
|
|||
#define EVE_ENABLE_DROP_OUTPUT_FPS |
|||
|
|||
#ifdef EVE_ENABLE_VIDEO |
|||
#ifdef DIRECT_MJPEG_COMPOSING |
|||
typedef struct S_ENCODING_BUFFER |
|||
{ |
|||
uint8_t * data; |
|||
size_t size; |
|||
} ENCODING_BUFFER; |
|||
#else //! DIRECT_MJPEG_COMPOSING |
|||
#ifdef OPENCV_VIDEO_OUTPUT |
|||
typedef struct S_ENCODING_BUFFER |
|||
{ |
|||
int cols; |
|||
int rows; |
|||
uint8_t * data; |
|||
size_t size; |
|||
} ENCODING_BUFFER; |
|||
#else //! OPENCV_VIDEO_OUTPUT |
|||
typedef struct S_ENCODING_BUFFER |
|||
{ |
|||
int linesize[2]; |
|||
int rows; |
|||
uint8_t * data[2]; |
|||
size_t size; |
|||
} ENCODING_BUFFER; |
|||
#endif //! OPENCV_VIDEO_OUTPUT |
|||
#endif //! DIRECT_MJPEG_COMPOSING |
|||
|
|||
typedef std::queue<ENCODING_BUFFER *> Q_ENCODING_BUFFER; |
|||
#endif // EVE_ENABLE_VIDEO |
|||
|
|||
class streamHandler : |
|||
public basicMediaDestination |
|||
#ifdef EVE_ENABLE_VIDEO |
|||
, public basicThread |
|||
#endif |
|||
{ |
|||
private: |
|||
|
|||
basicLogCollection * m_pLog; |
|||
basicMediaSource * m_pSource; |
|||
MEDIA_SOURCE_DESC m_sSourceDesc; |
|||
char m_cSourceType; |
|||
DBC_MEDIA_STREAM_DATA m_sStreamData; |
|||
basicMutex m_mProtector; |
|||
kernelModuleEmbedVideo * m_pMaster; |
|||
uint8_t m_bEvtMarkerCounter; |
|||
uint8_t m_bCamMoveCounter; |
|||
|
|||
dataBinder * m_pDBC; |
|||
MS_WORK_MODE m_eWM; |
|||
basicMutex m_mEvtIDS_Protector; |
|||
|
|||
#ifdef EVE_ENABLE_VIDEO |
|||
|
|||
#ifdef EVE_SEQUENTAL_OUTPUT |
|||
basicMutex m_mEventBindingBlocker; |
|||
#endif |
|||
|
|||
uint32_t m_nPreAlarmFrames; |
|||
uint32_t m_nPostAlarmFrames; |
|||
uint32_t m_nSegmentLimitFrames; |
|||
uint32_t m_nHardLimitFrames; |
|||
|
|||
basicMutex m_mFrameCounterProtector; |
|||
uint64_t m_nGlobalFrameCounter; |
|||
uint64_t m_nValidatorFrameCounter; |
|||
uint8_t m_nStallChecks; // validate() calls in a row without a new frame |
|||
time_t m_tLastFrameProgress; // last validate() that saw new frames |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
uint32_t m_nSegAFrameCounter; |
|||
uint32_t m_nSegBFrameCounter; |
|||
uint32_t m_nSegAShiftFrames; |
|||
uint32_t m_nSegBShiftFrames; |
|||
uint32_t m_nSegASkippedFrames; |
|||
uint32_t m_nSegBSkippedFrames; |
|||
|
|||
uint8_t m_bActiveEncoderStream; |
|||
bool m_bSegAActive; |
|||
bool m_bSegADelete; |
|||
bool m_bSegBActive; |
|||
bool m_bSegBDelete; |
|||
VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; |
|||
#else |
|||
uint32_t m_nSegFrameCounter; |
|||
uint32_t m_nSegShiftFrames; |
|||
uint32_t m_nSegSkippedFrames; |
|||
bool m_bSegActive; |
|||
bool m_bSegDelete; |
|||
bool m_bNSegDelete; |
|||
VIDEO_SEGMENT_INFO m_sStreamSegmentInfo; |
|||
#endif |
|||
uint8_t m_bFlipMode; |
|||
basicMutex m_mCurrentOperationProtector; |
|||
uint8_t m_bCOP; |
|||
|
|||
|
|||
#ifdef DIRECT_MJPEG_COMPOSING |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
FILE * m_pOutputFD[2]; |
|||
#else |
|||
FILE * m_pOutputFD; |
|||
#endif |
|||
#else // !DIRECT_MJPEG_COMPOSING |
|||
#ifdef OPENCV_VIDEO_OUTPUT |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
cv::VideoWriter * m_pEncoderA; |
|||
cv::VideoWriter * m_pEncoderB; |
|||
#else |
|||
cv::VideoWriter * m_pEncoder; |
|||
#endif |
|||
#else //! OPENCV_VIDEO_OUTPUT |
|||
// char m_pVideoScratchPath[PATH_MAX]; |
|||
#ifdef SEPARATED_VIDEO_ENCODERS |
|||
// LibAV encoding video stuff |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
// Stream A |
|||
AVCodec * m_pVideoACodec; |
|||
AVCodecContext * m_pCodecACtx; |
|||
AVFrame * m_pAVAFrame; |
|||
uint8_t * m_pOutABuffer; |
|||
// Stream B |
|||
AVCodec * m_pVideoBCodec; |
|||
AVCodecContext * m_pCodecBCtx; |
|||
AVFrame * m_pAVBFrame; |
|||
uint8_t * m_pOutBBuffer; |
|||
#else |
|||
AVCodec * m_pVideoCodec; |
|||
AVCodecContext * m_pCodecCtx; |
|||
AVFrame * m_pAVFrame; |
|||
uint8_t * m_pOutBuffer; |
|||
#endif |
|||
#else //! SEPARATED_VIDEO_ENCODERS |
|||
// LibAV encoding video stuff |
|||
AVCodec * m_pVideoCodec; |
|||
AVCodecContext * m_pCodecCtx; |
|||
AVFrame * m_pAVFrame; |
|||
uint8_t * m_pOutBuffer; |
|||
#endif //! SEPARATED_VIDEO_ENCODERS |
|||
// Common Pix Converter ( for both streams ) |
|||
SwsContext * m_pConvertCtx; |
|||
#endif //! OPENCV_VIDEO_OUTPUT |
|||
|
|||
// char m_cSegNameA[128]; |
|||
// char m_cSegMD5A[33]; |
|||
// char m_cSegNameB[128]; |
|||
// char m_cSegMD5B[33]; |
|||
|
|||
AVOutputFormat * m_pFormat; |
|||
#ifdef SEPARATED_VIDEO_ENCODERS |
|||
// File Context 2 units |
|||
AVFormatContext * m_pFormatCtxA; |
|||
AVFormatContext * m_pFormatCtxB; |
|||
AVStream * m_pVideoStrA; |
|||
AVStream * m_pVideoStrB; |
|||
#else |
|||
// File Context 1 units |
|||
AVFormatContext * m_pFormatCtx; |
|||
AVStream * m_pVideoStr; |
|||
#endif |
|||
// common output options |
|||
AVDictionary * m_pFormatOpts; |
|||
#endif //! DIRECT_MJPEG_COMPOSING |
|||
basicMutex m_mEncodingQueueProtector; |
|||
Q_ENCODING_BUFFER m_qEncodingQueue; |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
bool openSegmentA(void); |
|||
void closeSegmentA(void); |
|||
bool openSegmentB(void); |
|||
void closeSegmentB(void); |
|||
void swapActiveStreams(void); |
|||
#endif |
|||
void closeAll(); |
|||
bool initVideoOutput(); |
|||
|
|||
protected: |
|||
|
|||
void m_fThreadProc(void); |
|||
#endif //! EVE_ENABLE_VIDEO |
|||
|
|||
public: |
|||
|
|||
explicit streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M = MS_MODE_DECODE_FRAMES, uint8_t flip_mode = 0); |
|||
virtual ~streamHandler(); |
|||
bool create(dataBinder * ptr, uint32_t stremID); |
|||
/* from Media Destination */ |
|||
virtual bool pushFrame(AVFrame * Frame, void * src = NULL); |
|||
// virtual void pushFrame( cv::Mat* Frame, void* src = NULL); |
|||
virtual bool pushFrame(cv::Mat & Frame, void * src = NULL); |
|||
bool triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame); |
|||
bool triggerCamMove(void); |
|||
bool validate(void); |
|||
bool preservingCurrentRecording(){ |
|||
#ifdef EVE_SEQUENTAL_OUTPUT |
|||
return !m_bSegDelete; |
|||
#else |
|||
return !( m_bSegADelete || m_bSegBDelete ); |
|||
#endif |
|||
}; |
|||
}; |
|||
|
|||
#endif // !LRF_PROXY_ONLY |
|||
|
|||
#endif |
|||
#ifndef __STREAM_HANDLER_EMBED_VIDEO_HEADER__ |
|||
#define __STREAM_HANDLER_EMBED_VIDEO_HEADER__ |
|||
|
|||
#include "kernelModuleEmbedVideo.h" |
|||
|
|||
#ifndef LRF_PROXY_ONLY |
|||
|
|||
#include "../../components/base/basicDualThread.h" |
|||
#include "../../components/base/basicEventHeap.h" |
|||
#include "../../components/base/basicMutex.h" |
|||
#include "kernelModule.h" |
|||
#define EVE_SEQUENTAL_OUTPUT |
|||
|
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
//#define EVE_ENABLE_EASE_OUTPUT_FPS |
|||
#endif |
|||
|
|||
// #include "../../data/media/video/videoAVLIBDestination.h" |
|||
#include "../../components/base/basicMediaDestination.h" |
|||
#include "../../components/base/basicMediaSource.h" |
|||
#include "../../data/media/mtx/feeder/h264Feeder.h" |
|||
#include "streamLiveEncoder.h" |
|||
#include <memory> |
|||
|
|||
#ifndef DB_SHMEM_POINT |
|||
#define DB_SHMEM_POINT "/dev/shm/argus" |
|||
#endif |
|||
|
|||
#define VIDEO_SCRATCHPAD_PATH (DB_SHMEM_POINT "/video_scratch") |
|||
|
|||
//Predefine Classess |
|||
class kernelModuleEmbedVideo; |
|||
// A stream is restarted only after this many validations in a row (module factory: every ~5 s) without a |
|||
// new frame. One gap of ~5 s (a camera on a mobile link) restarted the stream and cut the recording. |
|||
#ifndef STREAM_STALL_CHECKS |
|||
#define STREAM_STALL_CHECKS 3 |
|||
#endif |
|||
|
|||
class streamHandler; |
|||
|
|||
#define FILESTREAMBUFFERSZ 1048576 |
|||
|
|||
#ifndef MEKOROT_PROJECT__ |
|||
#define EVE_ENABLE_VIDEO |
|||
#endif |
|||
|
|||
#define USE_SCALING_IN |
|||
// #define USE_CV_DENOISE |
|||
// #define USE_CV_TONEMAP |
|||
|
|||
#ifdef EVE_ENABLE_VIDEO |
|||
#define VIDEO_OUTPUT_FPS 15 |
|||
|
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
// In case of sequental video files - no need two encoders |
|||
#define SEPARATED_VIDEO_ENCODERS |
|||
#endif |
|||
// #define EVE_DONT_DELETE_SEGMENTS |
|||
|
|||
/* Video CODECS */ |
|||
#define VC_VPX 0 |
|||
#define VC_X264 1 |
|||
#define VC_MP4 2 |
|||
#define VC_MJPEG 3 |
|||
#define VC_FLV 4 |
|||
|
|||
/* Video FORMATS */ |
|||
#define VF_WEBM 0 |
|||
#define VF_MP4 1 |
|||
#define VF_MP3 2 |
|||
#define VF_AAC 3 |
|||
#define VF_OGG 4 |
|||
#define VF_MJPEG 5 |
|||
#define VF_FLV 6 |
|||
|
|||
/* Encoder PROFILES */ |
|||
#define VP_ULTRAFAST 0 |
|||
#define VP_VERYFAST 1 |
|||
#define VP_FAST 2 |
|||
#define VP_MEDIUM 3 |
|||
#define VP_SLOW 4 |
|||
#define VP_VERYSLOW 5 |
|||
#define VP_ULTRASLOW 6 |
|||
|
|||
#define VO_MJPEG 1 |
|||
#define VO_MPEG4 2 |
|||
#define VO_H264 3 |
|||
#define VO_H265 4 |
|||
#define VO_FLV 5 |
|||
#define VO_DIRECT_MJPG 6 |
|||
|
|||
#ifndef EVE_WORK_WITH_MEDIAMTX |
|||
#define DIRECT_MJPEG_COMPOSING |
|||
#endif |
|||
|
|||
#ifdef DIRECT_MJPEG_COMPOSING |
|||
#define VIDEO_OUTPUT VO_DIRECT_MJPG |
|||
#else |
|||
#define OPENCV_VIDEO_OUTPUT |
|||
//#define VIDEO_OUTPUT VO_DIRECT_MJPG |
|||
#ifndef OPENCV_VIDEO_OUTPUT |
|||
// #define VIDEO_OUTPUT VO_MJPEG |
|||
#define VIDEO_OUTPUT VO_MPEG4 |
|||
// #define VIDEO_OUTPUT VO_H264 |
|||
// #define VIDEO_OUTPUT VO_H265 |
|||
// #define VIDEO_OUTPUT VO_FLV |
|||
// #define VIDEO_OUTPUT_WIDTH 640 //1920 |
|||
// #define VIDEO_OUTPUT_HEIGHT 480 //1080 |
|||
// #define VIDEO_OUTPUT_FPS 10 |
|||
// #define VIDEO_OUTPUT_GOP 15 |
|||
#else // OPENCV_VIDEO_OUTPUT |
|||
//#define VIDEO_OUTPUT VO_MJPEG // VO_CV_MP4 |
|||
#define VIDEO_OUTPUT VO_CV_MP4 |
|||
#endif |
|||
#endif // DIRECT_MJPEG_COMPOSING |
|||
|
|||
#if (LIBAVCODEC_VERSION_MAJOR < 54) |
|||
#define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG |
|||
#define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P |
|||
#else |
|||
#if VIDEO_OUTPUT == VO_MJPEG |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P // AV_PIX_FMT_YUVJ422P |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER "mjpeg" |
|||
#elif VIDEO_OUTPUT == VO_MPEG4 |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_H264 |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H264 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_H265 |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H265 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_FLV |
|||
#define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "flv" |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER "flv" |
|||
#elif VIDEO_OUTPUT == VO_CV_MP4 |
|||
#define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P |
|||
#define VIDEO_OUTPUT_BITRATE 4000000 |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mp4" |
|||
#define VIDEO_OUTPUT_CONTAINER "mp4" |
|||
#elif VIDEO_OUTPUT == VO_DIRECT_MJPG |
|||
#define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" |
|||
#define VIDEO_OUTPUT_CONTAINER "mjpeg" |
|||
#endif |
|||
#endif |
|||
#endif // EVE_ENABLE_VIDEO |
|||
|
|||
typedef struct S_buffer_data |
|||
{ |
|||
uint8_t * buf; |
|||
int size; |
|||
uint8_t * ptr; |
|||
size_t room; ///< size left in the buffer |
|||
} buffer_data; |
|||
|
|||
#define NR_COLORS 4 |
|||
#define AVIO_BUFFER_SIZE 4096 |
|||
#define BD_BUFFER_SIZE 1024 |
|||
|
|||
#define PRE_ALARM_TIME_MILSECONDS 5000 // 5 sec |
|||
#define POST_ALARM_TIME_MILSECONDS 5000 // 5 sec |
|||
#define ENCODING_SEGMENT_MILSECONDS 50000 // 50 sec |
|||
#define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute |
|||
// #define ENCODING_SEGMENT_LIMIT_MILSECONDS 900000 // 15 minutes |
|||
|
|||
|
|||
// #define ENCODER_DISABLED 0 |
|||
// #define ENCODER_ENABLED 1 |
|||
|
|||
#define EVE_ENABLE_DROP_OUTPUT_FPS |
|||
|
|||
#ifdef EVE_ENABLE_VIDEO |
|||
#ifdef DIRECT_MJPEG_COMPOSING |
|||
typedef struct S_ENCODING_BUFFER |
|||
{ |
|||
uint8_t * data; |
|||
size_t size; |
|||
} ENCODING_BUFFER; |
|||
#else //! DIRECT_MJPEG_COMPOSING |
|||
#ifdef OPENCV_VIDEO_OUTPUT |
|||
typedef struct S_ENCODING_BUFFER |
|||
{ |
|||
int cols; |
|||
int rows; |
|||
uint8_t * data; |
|||
size_t size; |
|||
} ENCODING_BUFFER; |
|||
#else //! OPENCV_VIDEO_OUTPUT |
|||
typedef struct S_ENCODING_BUFFER |
|||
{ |
|||
int linesize[2]; |
|||
int rows; |
|||
uint8_t * data[2]; |
|||
size_t size; |
|||
} ENCODING_BUFFER; |
|||
#endif //! OPENCV_VIDEO_OUTPUT |
|||
#endif //! DIRECT_MJPEG_COMPOSING |
|||
|
|||
typedef std::queue<ENCODING_BUFFER *> Q_ENCODING_BUFFER; |
|||
#endif // EVE_ENABLE_VIDEO |
|||
|
|||
class streamHandler : |
|||
public basicMediaDestination |
|||
#ifdef EVE_ENABLE_VIDEO |
|||
, public basicThread |
|||
#endif |
|||
{ |
|||
private: |
|||
|
|||
basicLogCollection * m_pLog; |
|||
basicMediaSource * m_pSource; |
|||
MEDIA_SOURCE_DESC m_sSourceDesc; |
|||
char m_cSourceType; |
|||
DBC_MEDIA_STREAM_DATA m_sStreamData; |
|||
basicMutex m_mProtector; |
|||
kernelModuleEmbedVideo * m_pMaster; |
|||
uint8_t m_bEvtMarkerCounter; |
|||
uint8_t m_bCamMoveCounter; |
|||
|
|||
dataBinder * m_pDBC; |
|||
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; |
|||
|
|||
#ifdef EVE_ENABLE_VIDEO |
|||
|
|||
#ifdef EVE_SEQUENTAL_OUTPUT |
|||
basicMutex m_mEventBindingBlocker; |
|||
#endif |
|||
|
|||
uint32_t m_nPreAlarmFrames; |
|||
uint32_t m_nPostAlarmFrames; |
|||
uint32_t m_nSegmentLimitFrames; |
|||
uint32_t m_nHardLimitFrames; |
|||
|
|||
basicMutex m_mFrameCounterProtector; |
|||
uint64_t m_nGlobalFrameCounter; |
|||
uint64_t m_nValidatorFrameCounter; |
|||
uint8_t m_nStallChecks; // validate() calls in a row without a new frame |
|||
time_t m_tLastFrameProgress; // last validate() that saw new frames |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
uint32_t m_nSegAFrameCounter; |
|||
uint32_t m_nSegBFrameCounter; |
|||
uint32_t m_nSegAShiftFrames; |
|||
uint32_t m_nSegBShiftFrames; |
|||
uint32_t m_nSegASkippedFrames; |
|||
uint32_t m_nSegBSkippedFrames; |
|||
|
|||
uint8_t m_bActiveEncoderStream; |
|||
bool m_bSegAActive; |
|||
bool m_bSegADelete; |
|||
bool m_bSegBActive; |
|||
bool m_bSegBDelete; |
|||
VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; |
|||
#else |
|||
uint32_t m_nSegFrameCounter; |
|||
uint32_t m_nSegShiftFrames; |
|||
uint32_t m_nSegSkippedFrames; |
|||
bool m_bSegActive; |
|||
bool m_bSegDelete; |
|||
bool m_bNSegDelete; |
|||
VIDEO_SEGMENT_INFO m_sStreamSegmentInfo; |
|||
#endif |
|||
uint8_t m_bFlipMode; |
|||
basicMutex m_mCurrentOperationProtector; |
|||
uint8_t m_bCOP; |
|||
|
|||
|
|||
#ifdef DIRECT_MJPEG_COMPOSING |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
FILE * m_pOutputFD[2]; |
|||
#else |
|||
FILE * m_pOutputFD; |
|||
#endif |
|||
#else // !DIRECT_MJPEG_COMPOSING |
|||
#ifdef OPENCV_VIDEO_OUTPUT |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
cv::VideoWriter * m_pEncoderA; |
|||
cv::VideoWriter * m_pEncoderB; |
|||
#else |
|||
cv::VideoWriter * m_pEncoder; |
|||
#endif |
|||
#else //! OPENCV_VIDEO_OUTPUT |
|||
// char m_pVideoScratchPath[PATH_MAX]; |
|||
#ifdef SEPARATED_VIDEO_ENCODERS |
|||
// LibAV encoding video stuff |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
// Stream A |
|||
AVCodec * m_pVideoACodec; |
|||
AVCodecContext * m_pCodecACtx; |
|||
AVFrame * m_pAVAFrame; |
|||
uint8_t * m_pOutABuffer; |
|||
// Stream B |
|||
AVCodec * m_pVideoBCodec; |
|||
AVCodecContext * m_pCodecBCtx; |
|||
AVFrame * m_pAVBFrame; |
|||
uint8_t * m_pOutBBuffer; |
|||
#else |
|||
AVCodec * m_pVideoCodec; |
|||
AVCodecContext * m_pCodecCtx; |
|||
AVFrame * m_pAVFrame; |
|||
uint8_t * m_pOutBuffer; |
|||
#endif |
|||
#else //! SEPARATED_VIDEO_ENCODERS |
|||
// LibAV encoding video stuff |
|||
AVCodec * m_pVideoCodec; |
|||
AVCodecContext * m_pCodecCtx; |
|||
AVFrame * m_pAVFrame; |
|||
uint8_t * m_pOutBuffer; |
|||
#endif //! SEPARATED_VIDEO_ENCODERS |
|||
// Common Pix Converter ( for both streams ) |
|||
SwsContext * m_pConvertCtx; |
|||
#endif //! OPENCV_VIDEO_OUTPUT |
|||
|
|||
// char m_cSegNameA[128]; |
|||
// char m_cSegMD5A[33]; |
|||
// char m_cSegNameB[128]; |
|||
// char m_cSegMD5B[33]; |
|||
|
|||
AVOutputFormat * m_pFormat; |
|||
#ifdef SEPARATED_VIDEO_ENCODERS |
|||
// File Context 2 units |
|||
AVFormatContext * m_pFormatCtxA; |
|||
AVFormatContext * m_pFormatCtxB; |
|||
AVStream * m_pVideoStrA; |
|||
AVStream * m_pVideoStrB; |
|||
#else |
|||
// File Context 1 units |
|||
AVFormatContext * m_pFormatCtx; |
|||
AVStream * m_pVideoStr; |
|||
#endif |
|||
// common output options |
|||
AVDictionary * m_pFormatOpts; |
|||
#endif //! DIRECT_MJPEG_COMPOSING |
|||
basicMutex m_mEncodingQueueProtector; |
|||
Q_ENCODING_BUFFER m_qEncodingQueue; |
|||
#ifndef EVE_SEQUENTAL_OUTPUT |
|||
bool openSegmentA(void); |
|||
void closeSegmentA(void); |
|||
bool openSegmentB(void); |
|||
void closeSegmentB(void); |
|||
void swapActiveStreams(void); |
|||
#endif |
|||
void closeAll(); |
|||
bool initVideoOutput(); |
|||
|
|||
protected: |
|||
|
|||
void m_fThreadProc(void); |
|||
#endif //! EVE_ENABLE_VIDEO |
|||
|
|||
public: |
|||
|
|||
explicit streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M = MS_MODE_DECODE_FRAMES, uint8_t flip_mode = 0); |
|||
virtual ~streamHandler(); |
|||
bool create(dataBinder * ptr, uint32_t stremID); |
|||
/* from Media Destination */ |
|||
virtual bool pushFrame(AVFrame * Frame, void * src = NULL); |
|||
// virtual void 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 triggerCamMove(void); |
|||
bool validate(void); |
|||
bool preservingCurrentRecording(){ |
|||
#ifdef EVE_SEQUENTAL_OUTPUT |
|||
return !m_bSegDelete; |
|||
#else |
|||
return !( m_bSegADelete || m_bSegBDelete ); |
|||
#endif |
|||
}; |
|||
}; |
|||
|
|||
#endif // !LRF_PROXY_ONLY |
|||
|
|||
#endif |
|||
@ -0,0 +1,236 @@ |
|||
#ifndef LRF_PROXY_ONLY
|
|||
|
|||
#include "streamLiveEncoder.h"
|
|||
|
|||
extern "C" |
|||
{ |
|||
#include <libavutil/opt.h>
|
|||
} |
|||
|
|||
#define LOG(X) m_pLog->Log("LIVE_ENC", this, X)
|
|||
#define LOG_ERROR(X) m_pLog->Log("LIVE_ENC", this, _LOG_ERROR, X)
|
|||
|
|||
streamLiveEncoder::streamLiveEncoder(std::shared_ptr<mtx::MediaPath> path, int fps, int bitrateKbps) : |
|||
m_pLog(basicLogCollection::getInstance()), m_pPath(std::move(path)), m_oFeeder(m_pPath.get()), m_nFps(fps > 0 ? fps : 15), m_nBitrateKbps(bitrateKbps > 0 ? bitrateKbps : 2000), |
|||
m_bHavePending(false), m_bRun(true), m_nNextFrameUs(0), m_pCtx(NULL), m_pFrame(NULL), m_pPacket(NULL), m_pSws(NULL), m_nWidth(0), m_nHeight(0), m_nFrameIndex(0), m_nLastReaders(0), |
|||
m_bOpenFailed(false) |
|||
{ |
|||
m_thread = std::thread(&streamLiveEncoder::run, this); |
|||
} |
|||
|
|||
streamLiveEncoder::~streamLiveEncoder() |
|||
{ |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
m_bRun = false; |
|||
} |
|||
m_cond.notify_all(); |
|||
if (m_thread.joinable()) |
|||
{ |
|||
m_thread.join(); |
|||
} |
|||
m_oFeeder.setParent(nullptr); // the path is not ready any more
|
|||
closeEncoder(); |
|||
} |
|||
|
|||
void streamLiveEncoder::push(const cv::Mat & bgr) |
|||
{ |
|||
if (bgr.empty() || m_bOpenFailed) |
|||
{ |
|||
return; |
|||
} |
|||
// Nobody watches, nothing is recorded: no CPU for encoding
|
|||
if (m_pPath->readerCount() == 0 && ! m_pPath->recording()) |
|||
{ |
|||
return; |
|||
} |
|||
int64_t tNow = mtx::nowUs(); |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
if (tNow < m_nNextFrameUs) |
|||
{ |
|||
return; // above the frame rate of the live stream
|
|||
} |
|||
m_nNextFrameUs = (m_nNextFrameUs == 0 || tNow - m_nNextFrameUs > 1000000) ? tNow + 1000000 / m_nFps : m_nNextFrameUs + 1000000 / m_nFps; |
|||
bgr.copyTo(m_mPending); // replaces a frame the encoder did not take yet (it is late: drop)
|
|||
m_bHavePending = true; |
|||
m_cond.notify_one(); |
|||
} |
|||
|
|||
void streamLiveEncoder::run() |
|||
{ |
|||
pthread_setname_np(pthread_self(), "LiveEncoder"); |
|||
cv::Mat tFrame; |
|||
while (true) |
|||
{ |
|||
{ |
|||
std::unique_lock<std::mutex> lock(m_mutex); |
|||
m_cond.wait(lock, [this] { return ! m_bRun || m_bHavePending; }); |
|||
if (! m_bRun) |
|||
{ |
|||
break; |
|||
} |
|||
cv::swap(tFrame, m_mPending); |
|||
m_bHavePending = false; |
|||
} |
|||
size_t tReaders = m_pPath->readerCount(); |
|||
bool tIdr = tReaders > m_nLastReaders; // a new viewer: start it now, not at the next GOP
|
|||
m_nLastReaders = tReaders; |
|||
if (m_pCtx != NULL && (tFrame.cols != m_nWidth || tFrame.rows != m_nHeight)) |
|||
{ |
|||
closeEncoder(); // the frame size changed (module settings)
|
|||
} |
|||
if (m_pCtx == NULL) |
|||
{ |
|||
if (! openEncoder(tFrame.cols, tFrame.rows)) |
|||
{ |
|||
m_bOpenFailed = true; |
|||
break; |
|||
} |
|||
tIdr = true; |
|||
} |
|||
if (! encode(tFrame, tIdr)) |
|||
{ |
|||
closeEncoder(); // opened again with the next frame
|
|||
} |
|||
} |
|||
} |
|||
|
|||
bool streamLiveEncoder::openEncoder(int width, int height) |
|||
{ |
|||
const AVCodec * tCodec = avcodec_find_encoder_by_name("libx264"); |
|||
if (tCodec == NULL) |
|||
{ |
|||
tCodec = avcodec_find_encoder(AV_CODEC_ID_H264); |
|||
} |
|||
if (tCodec == NULL) |
|||
{ |
|||
LOG_ERROR("No H264 encoder in libavcodec: live view of the processed frames is not possible"); |
|||
return false; |
|||
} |
|||
m_pCtx = avcodec_alloc_context3(tCodec); |
|||
if (m_pCtx == NULL) |
|||
{ |
|||
return false; |
|||
} |
|||
m_nWidth = width & ~1; // 4:2:0 needs even sizes
|
|||
m_nHeight = height & ~1; |
|||
m_pCtx->width = m_nWidth; |
|||
m_pCtx->height = m_nHeight; |
|||
m_pCtx->pix_fmt = AV_PIX_FMT_YUV420P; |
|||
m_pCtx->time_base = AVRational {1, 90000}; |
|||
m_pCtx->framerate = AVRational {m_nFps, 1}; |
|||
m_pCtx->gop_size = m_nFps * 2; // a new viewer waits at most 2 s (and gets one at once, see run())
|
|||
m_pCtx->max_b_frames = 0; // WebRTC / fMP4 writer: dts = pts
|
|||
m_pCtx->bit_rate = (int64_t) m_nBitrateKbps * 1000; |
|||
m_pCtx->rc_max_rate = m_pCtx->bit_rate; |
|||
m_pCtx->rc_buffer_size = (int) m_pCtx->bit_rate; // 1 s
|
|||
m_pCtx->thread_count = 2; |
|||
m_pCtx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE; |
|||
if (strcmp(tCodec->name, "libx264") == 0) |
|||
{ |
|||
av_opt_set(m_pCtx->priv_data, "preset", "veryfast", 0); |
|||
av_opt_set(m_pCtx->priv_data, "tune", "zerolatency", 0); |
|||
av_opt_set(m_pCtx->priv_data, "profile", "baseline", 0); |
|||
av_opt_set(m_pCtx->priv_data, "x264-params", "repeat-headers=1", 0); // SPS / PPS with every IDR
|
|||
av_opt_set(m_pCtx->priv_data, "forced-idr", "1", 0); // a forced key frame is an IDR
|
|||
} |
|||
int tRet = avcodec_open2(m_pCtx, tCodec, NULL); |
|||
if (tRet < 0) |
|||
{ |
|||
char tE[128], tB[256]; |
|||
av_strerror(tRet, tE, sizeof(tE)); |
|||
snprintf(tB, sizeof(tB), "Cannot open the H264 encoder %s: %s", tCodec->name, tE); |
|||
LOG_ERROR(tB); |
|||
avcodec_free_context(&m_pCtx); |
|||
return false; |
|||
} |
|||
m_pFrame = av_frame_alloc(); |
|||
m_pPacket = av_packet_alloc(); |
|||
m_pSws = sws_getContext(width, height, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); |
|||
if (m_pFrame == NULL || m_pPacket == NULL || m_pSws == NULL) |
|||
{ |
|||
LOG_ERROR("Live encoder: allocation failed"); |
|||
closeEncoder(); |
|||
return false; |
|||
} |
|||
m_pFrame->format = AV_PIX_FMT_YUV420P; |
|||
m_pFrame->width = m_nWidth; |
|||
m_pFrame->height = m_nHeight; |
|||
if (av_frame_get_buffer(m_pFrame, 32) < 0) |
|||
{ |
|||
closeEncoder(); |
|||
return false; |
|||
} |
|||
if (m_pCtx->extradata != NULL && m_pCtx->extradata_size > 0) |
|||
{ |
|||
m_oFeeder.setExtradata(m_pCtx->extradata, m_pCtx->extradata_size); |
|||
} |
|||
char tB[200]; |
|||
snprintf(tB, sizeof(tB), "H264 encoder %s opened: %dx%d, %d fps, %d kbit/s", tCodec->name, m_nWidth, m_nHeight, m_nFps, m_nBitrateKbps); |
|||
LOG(tB); |
|||
return true; |
|||
} |
|||
|
|||
void streamLiveEncoder::closeEncoder() |
|||
{ |
|||
if (m_pSws != NULL) |
|||
{ |
|||
sws_freeContext(m_pSws); |
|||
m_pSws = NULL; |
|||
} |
|||
av_frame_free(&m_pFrame); |
|||
av_packet_free(&m_pPacket); |
|||
avcodec_free_context(&m_pCtx); |
|||
m_nWidth = 0; |
|||
m_nHeight = 0; |
|||
} |
|||
|
|||
bool streamLiveEncoder::encode(const cv::Mat & bgr, bool forceIdr) |
|||
{ |
|||
if (av_frame_make_writable(m_pFrame) < 0) |
|||
{ |
|||
return false; |
|||
} |
|||
const uint8_t * tSrc[1] = {bgr.data}; |
|||
int tStep[1] = {(int) bgr.step[0]}; |
|||
sws_scale(m_pSws, tSrc, tStep, 0, bgr.rows, m_pFrame->data, m_pFrame->linesize); |
|||
int64_t tNowUs = mtx::nowUs(); |
|||
m_pFrame->pts = tNowUs * 9 / 100; // 90 kHz wall clock: the real frame timing
|
|||
m_pFrame->pict_type = forceIdr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE; |
|||
int tRet = avcodec_send_frame(m_pCtx, m_pFrame); |
|||
if (tRet < 0) |
|||
{ |
|||
LOG_ERROR("Live encoder: send frame failed"); |
|||
return false; |
|||
} |
|||
while (true) |
|||
{ |
|||
tRet = avcodec_receive_packet(m_pCtx, m_pPacket); |
|||
if (tRet == AVERROR(EAGAIN) || tRet == AVERROR_EOF) |
|||
{ |
|||
break; |
|||
} |
|||
if (tRet < 0) |
|||
{ |
|||
LOG_ERROR("Live encoder: receive packet failed"); |
|||
return false; |
|||
} |
|||
int64_t tPtsUs = (m_pPacket->pts != AV_NOPTS_VALUE) ? m_pPacket->pts * 100 / 9 : tNowUs; |
|||
if (m_oFeeder.avccLengthSize() > 0) |
|||
{ |
|||
m_oFeeder.pushAvcc(m_pPacket->data, m_pPacket->size, m_oFeeder.avccLengthSize(), tPtsUs); |
|||
} |
|||
else |
|||
{ |
|||
m_oFeeder.pushAnnexB(m_pPacket->data, m_pPacket->size, tPtsUs); |
|||
} |
|||
av_packet_unref(m_pPacket); |
|||
} |
|||
m_nFrameIndex++; |
|||
return true; |
|||
} |
|||
|
|||
#undef LOG
|
|||
#undef LOG_ERROR
|
|||
|
|||
#endif // !LRF_PROXY_ONLY
|
|||
@ -0,0 +1,68 @@ |
|||
#ifndef __STREAM_LIVE_ENCODER_HEADER__ |
|||
#define __STREAM_LIVE_ENCODER_HEADER__ |
|||
|
|||
#ifndef LRF_PROXY_ONLY |
|||
|
|||
/* |
|||
Live view of the processed frames (kernelModuleEmbedVideo live_mode EVE_LIVE_ENCODE) |
|||
|
|||
streamHandler hands every processed frame (scaled, flipped, with the time stamp / label / logo / event |
|||
marks) to push(); the encoder thread encodes the newest one to H264 (libx264 when available, zero |
|||
latency, no B-frames, constrained baseline: every browser decodes it) and feeds the path (WebRTC |
|||
readers, recorder). A slow encoder drops frames, it never blocks the source. |
|||
Nothing is encoded while the path has no reader and does not record. A new reader gets an IDR at once. |
|||
*/ |
|||
|
|||
#include <condition_variable> |
|||
#include <memory> |
|||
#include <mutex> |
|||
#include <thread> |
|||
|
|||
#include "../../components/base/basicLIBAV.h" |
|||
#include "../../components/base/basicLogCollection.h" |
|||
#include "../../data/media/mtx/core/mediaPath.h" |
|||
#include "../../data/media/mtx/feeder/h264Feeder.h" |
|||
|
|||
class streamLiveEncoder |
|||
{ |
|||
public: |
|||
streamLiveEncoder(std::shared_ptr<mtx::MediaPath> path, int fps, int bitrateKbps); |
|||
~streamLiveEncoder(); |
|||
|
|||
// From the frame thread: copies the frame when the encoder wants one (frame rate, readers) |
|||
void push(const cv::Mat & bgr); |
|||
|
|||
private: |
|||
void run(); |
|||
bool openEncoder(int width, int height); |
|||
void closeEncoder(); |
|||
bool encode(const cv::Mat & bgr, bool forceIdr); |
|||
|
|||
basicLogCollection * m_pLog; |
|||
std::shared_ptr<mtx::MediaPath> m_pPath; |
|||
mtx::H264Feeder m_oFeeder; |
|||
int m_nFps; |
|||
int m_nBitrateKbps; |
|||
|
|||
std::mutex m_mutex; |
|||
std::condition_variable m_cond; |
|||
cv::Mat m_mPending; |
|||
bool m_bHavePending; |
|||
bool m_bRun; |
|||
int64_t m_nNextFrameUs; // frame rate limit |
|||
std::thread m_thread; |
|||
|
|||
// encoder (encoder thread only) |
|||
AVCodecContext * m_pCtx; |
|||
AVFrame * m_pFrame; |
|||
AVPacket * m_pPacket; |
|||
SwsContext * m_pSws; |
|||
int m_nWidth; |
|||
int m_nHeight; |
|||
int64_t m_nFrameIndex; |
|||
size_t m_nLastReaders; |
|||
bool m_bOpenFailed; |
|||
}; |
|||
|
|||
#endif // !LRF_PROXY_ONLY |
|||
#endif |
|||
@ -0,0 +1,83 @@ |
|||
#include "serverConf.h"
|
|||
|
|||
#include <cstdlib>
|
|||
|
|||
namespace mtx { |
|||
|
|||
bool parseDurationMs(const std::string & s, int64_t & ms) |
|||
{ |
|||
if (s.empty()) |
|||
{ |
|||
return false; |
|||
} |
|||
char * tEnd = nullptr; |
|||
double tV = strtod(s.c_str(), &tEnd); |
|||
if (tEnd == s.c_str() || tV < 0) |
|||
{ |
|||
return false; |
|||
} |
|||
std::string tUnit(tEnd); |
|||
double tMul; |
|||
if (tUnit.empty() || tUnit == "s") |
|||
{ |
|||
tMul = 1000.0; |
|||
} |
|||
else if (tUnit == "ms") |
|||
{ |
|||
tMul = 1.0; |
|||
} |
|||
else if (tUnit == "m") |
|||
{ |
|||
tMul = 60000.0; |
|||
} |
|||
else if (tUnit == "h") |
|||
{ |
|||
tMul = 3600000.0; |
|||
} |
|||
else |
|||
{ |
|||
return false; |
|||
} |
|||
ms = (int64_t) (tV * tMul + 0.5); |
|||
return true; |
|||
} |
|||
|
|||
bool splitHostPort(const std::string & addr, std::string & host, uint16_t & port) |
|||
{ |
|||
size_t tColon = addr.rfind(':'); |
|||
if (tColon == std::string::npos) |
|||
{ |
|||
return false; |
|||
} |
|||
host = addr.substr(0, tColon); |
|||
int tPort = atoi(addr.c_str() + tColon + 1); |
|||
if (tPort <= 0 || tPort > 65535) |
|||
{ |
|||
return false; |
|||
} |
|||
port = (uint16_t) tPort; |
|||
if (host.size() >= 2 && host.front() == '[' && host.back() == ']') |
|||
{ |
|||
host = host.substr(1, host.size() - 2); |
|||
} |
|||
return true; |
|||
} |
|||
|
|||
std::string hideCredentials(const std::string & url) |
|||
{ |
|||
size_t tScheme = url.find("://"); |
|||
if (tScheme == std::string::npos) |
|||
{ |
|||
return url; |
|||
} |
|||
size_t tHostStart = tScheme + 3; |
|||
size_t tSlash = url.find('/', tHostStart); |
|||
size_t tAt = url.rfind('@', tSlash == std::string::npos ? url.size() : tSlash); |
|||
if (tAt == std::string::npos || tAt < tHostStart) |
|||
{ |
|||
return url; |
|||
} |
|||
return url.substr(0, tHostStart) + url.substr(tAt + 1); |
|||
} |
|||
|
|||
} // namespace mtx
|
|||
@ -0,0 +1,39 @@ |
|||
/* |
|||
MediaMtx (C++) - settings of the reusable parts (WebRTC server, recorder) |
|||
|
|||
Shared by the stand-alone server (Projects/MediaMtx, which adds the command line, the paths file, the |
|||
RTSP sources and the API) and la_mojo (kernelModuleEmbedVideo, which feeds the streams itself). |
|||
The names follow MediaMTX (webrtcAddress, recordPath, ...). |
|||
*/ |
|||
#pragma once |
|||
|
|||
#include <cstdint> |
|||
#include <string> |
|||
#include <vector> |
|||
|
|||
namespace mtx { |
|||
|
|||
struct ServerConf |
|||
{ |
|||
// WebRTC (WHEP) |
|||
std::string webrtcAddress = ":8889"; |
|||
std::string webrtcAllowOrigin = "*"; |
|||
std::vector<std::string> webrtcICEServers; // e.g. stun:stun.l.google.com:19302 |
|||
std::string webrtcBindAddress; // ICE: bind to this local address (default: all) |
|||
uint16_t webrtcUDPPortMin = 8189; |
|||
uint16_t webrtcUDPPortMax = 8289; |
|||
|
|||
// recording |
|||
std::string recordPath = "./recordings/%path/%Y-%m-%d_%H-%M-%S-%f"; |
|||
int64_t recordSegmentDurationMs = 60000; |
|||
int64_t recordPartDurationMs = 1000; |
|||
}; |
|||
|
|||
// "60s", "1m", "500ms", "1h", "1.5s"; plain number = seconds |
|||
bool parseDurationMs(const std::string & s, int64_t & ms); |
|||
// "host:port" / ":port" -> host ("" = any) and port |
|||
bool splitHostPort(const std::string & addr, std::string & host, uint16_t & port); |
|||
// rtsp://user:pass@host/... -> rtsp://host/... (for logs) |
|||
std::string hideCredentials(const std::string & url); |
|||
|
|||
} // namespace mtx |
|||
@ -0,0 +1,145 @@ |
|||
#include "mediaPath.h"
|
|||
|
|||
#include "../recorder/recorder.h"
|
|||
|
|||
namespace mtx { |
|||
|
|||
MediaPath::MediaPath(const std::string & name, bool record, const ServerConf & global) : LogParent("[path " + name + "] "), m_sName(name), m_bRecord(record), m_global(global) {} |
|||
|
|||
MediaPath::~MediaPath() |
|||
{ |
|||
sourceSetNotReady(); |
|||
} |
|||
|
|||
PathInfo MediaPath::info() const |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
PathInfo tI; |
|||
tI.name = m_sName; |
|||
tI.record = m_bRecord; |
|||
tI.ready = (m_pStream != nullptr); |
|||
tI.readySinceUs = m_tReadySinceUs; |
|||
tI.readers = m_readers.size(); |
|||
if (m_pStream) |
|||
{ |
|||
tI.desc = m_pStream->desc(); |
|||
tI.bytesReceived = m_pStream->bytesReceived(); |
|||
} |
|||
return tI; |
|||
} |
|||
|
|||
bool MediaPath::isReady() const |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
return m_pStream != nullptr; |
|||
} |
|||
|
|||
size_t MediaPath::readerCount() const |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
return m_readers.size(); |
|||
} |
|||
|
|||
bool MediaPath::recording() const |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
return m_bRecord; |
|||
} |
|||
|
|||
void MediaPath::setRecord(bool record) |
|||
{ |
|||
std::unique_ptr<Recorder> tOld; |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
if (m_bRecord == record) |
|||
{ |
|||
return; |
|||
} |
|||
m_bRecord = record; |
|||
if (! record) |
|||
{ |
|||
tOld = std::move(m_pRecorder); |
|||
} |
|||
else if (m_pStream) |
|||
{ |
|||
m_pRecorder.reset(new Recorder(m_sName, m_global, m_pStream, this)); |
|||
m_pRecorder->start(); |
|||
} |
|||
} |
|||
tOld.reset(); // closes the segment (not under the lock)
|
|||
log(LogLevel::Info, "recording %s", record ? "enabled" : "disabled"); |
|||
} |
|||
|
|||
bool MediaPath::addReader(PathReader * r, StreamDesc & desc, std::string & err) |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
if (! m_pStream) |
|||
{ |
|||
err = "no stream is available on path '" + m_sName + "'"; |
|||
return false; |
|||
} |
|||
desc = m_pStream->desc(); |
|||
m_readers.insert(r); |
|||
m_pStream->addReader(r); |
|||
return true; |
|||
} |
|||
|
|||
void MediaPath::removeReader(PathReader * r) |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
if (m_readers.erase(r) > 0 && m_pStream) |
|||
{ |
|||
m_pStream->removeReader(r); |
|||
} |
|||
} |
|||
|
|||
void MediaPath::sourceSetReady(const StreamDesc & desc) |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
m_pStream = std::make_shared<Stream>(desc); |
|||
m_tReadySinceUs = nowUs(); |
|||
log(LogLevel::Info, "stream is available and online, 1 track (H264 %dx%d)", desc.width, desc.height); |
|||
if (m_bRecord) |
|||
{ |
|||
m_pRecorder.reset(new Recorder(m_sName, m_global, m_pStream, this)); |
|||
m_pRecorder->start(); |
|||
} |
|||
} |
|||
|
|||
void MediaPath::sourceSetNotReady() |
|||
{ |
|||
std::unique_ptr<Recorder> tRec; |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
if (! m_pStream) |
|||
{ |
|||
return; |
|||
} |
|||
for (PathReader * r : m_readers) |
|||
{ |
|||
m_pStream->removeReader(r); |
|||
r->pathNotReady(); |
|||
} |
|||
m_readers.clear(); |
|||
tRec = std::move(m_pRecorder); |
|||
m_pStream.reset(); |
|||
m_tReadySinceUs = 0; |
|||
} |
|||
tRec.reset(); // closes the segment
|
|||
log(LogLevel::Info, "stream is not available anymore"); |
|||
} |
|||
|
|||
void MediaPath::sourceWriteUnit(const UnitPtr & unit) |
|||
{ |
|||
std::shared_ptr<Stream> tStream; |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
tStream = m_pStream; |
|||
} |
|||
if (tStream) |
|||
{ |
|||
tStream->writeUnit(unit); |
|||
} |
|||
} |
|||
|
|||
} // namespace mtx
|
|||
@ -0,0 +1,100 @@ |
|||
/* |
|||
MediaMtx (C++) - media path (MediaMTX: internal/core/path.go, without the source) |
|||
|
|||
A path has a stream while its source is ready, an optional recorder and the readers (WebRTC sessions). |
|||
The source is whatever feeds it: an RTSP client (Projects/MediaMtx) or la_mojo's streamHandler |
|||
(camera H264 as it is, or the processed frames encoded again). |
|||
*/ |
|||
#pragma once |
|||
|
|||
#include <memory> |
|||
#include <mutex> |
|||
#include <set> |
|||
#include <string> |
|||
|
|||
#include "../conf/serverConf.h" |
|||
#include "../logger/logger.h" |
|||
#include "../stream/stream.h" |
|||
|
|||
namespace mtx { |
|||
|
|||
class Recorder; |
|||
|
|||
class PathReader : public StreamReader |
|||
{ |
|||
public: |
|||
// The source of the path is gone: the reader must close (called with the path locked: do not block, |
|||
// do not call back into the path) |
|||
virtual void pathNotReady() = 0; |
|||
}; |
|||
|
|||
// What a source calls on its path |
|||
class SourceParent |
|||
{ |
|||
public: |
|||
virtual ~SourceParent() {} |
|||
// The source has the codec parameters: the path creates its stream |
|||
virtual void sourceSetReady(const StreamDesc & desc) = 0; |
|||
// The source lost its connection: the path destroys its stream |
|||
virtual void sourceSetNotReady() = 0; |
|||
// A unit of the source (called from the source thread) |
|||
virtual void sourceWriteUnit(const UnitPtr & unit) = 0; |
|||
}; |
|||
|
|||
struct PathInfo |
|||
{ |
|||
std::string name; |
|||
std::string source; |
|||
bool record = false; |
|||
bool ready = false; |
|||
int64_t readySinceUs = 0; |
|||
StreamDesc desc; |
|||
size_t readers = 0; |
|||
uint64_t bytesReceived = 0; |
|||
}; |
|||
|
|||
class MediaPath : public SourceParent, public LogParent |
|||
{ |
|||
public: |
|||
MediaPath(const std::string & name, bool record, const ServerConf & global); |
|||
~MediaPath() override; |
|||
|
|||
const std::string & name() const { return m_sName; } |
|||
PathInfo info() const; |
|||
bool isReady() const; |
|||
size_t readerCount() const; |
|||
bool recording() const; |
|||
// Starts / stops the recorder (a running stream is recorded from its next IDR) |
|||
void setRecord(bool record); |
|||
|
|||
// false + err when the path has no stream |
|||
bool addReader(PathReader * r, StreamDesc & desc, std::string & err); |
|||
void removeReader(PathReader * r); |
|||
|
|||
// SourceParent |
|||
void sourceSetReady(const StreamDesc & desc) override; |
|||
void sourceSetNotReady() override; |
|||
void sourceWriteUnit(const UnitPtr & unit) override; |
|||
|
|||
protected: |
|||
std::string m_sName; |
|||
bool m_bRecord; |
|||
ServerConf m_global; |
|||
|
|||
private: |
|||
mutable std::mutex m_mutex; |
|||
std::shared_ptr<Stream> m_pStream; |
|||
std::unique_ptr<Recorder> m_pRecorder; |
|||
std::set<PathReader *> m_readers; |
|||
int64_t m_tReadySinceUs = 0; |
|||
}; |
|||
|
|||
// Finds a path by name (the WebRTC server asks it for the path of a WHEP request) |
|||
class PathProvider |
|||
{ |
|||
public: |
|||
virtual ~PathProvider() {} |
|||
virtual std::shared_ptr<MediaPath> findPath(const std::string & name) const = 0; |
|||
}; |
|||
|
|||
} // namespace mtx |
|||
@ -0,0 +1,209 @@ |
|||
#include "h264Feeder.h"
|
|||
|
|||
#include <memory>
|
|||
|
|||
#include "../codecs/h264/h264.h"
|
|||
|
|||
namespace mtx { |
|||
|
|||
void H264Feeder::setParent(SourceParent * parent) |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
if (parent == m_pParent) |
|||
{ |
|||
return; |
|||
} |
|||
if (m_pParent != nullptr && m_bReady) |
|||
{ |
|||
m_pParent->sourceSetNotReady(); |
|||
} |
|||
m_pParent = parent; |
|||
m_bReady = false; |
|||
m_vNalus.clear(); |
|||
} |
|||
|
|||
void H264Feeder::setParameterSets(const std::vector<Bytes> & nalus) |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
for (const Bytes & n : nalus) |
|||
{ |
|||
if (h264::naluType(n) == h264::NALU_SPS) |
|||
{ |
|||
m_sps = n; |
|||
} |
|||
else if (h264::naluType(n) == h264::NALU_PPS) |
|||
{ |
|||
m_pps = n; |
|||
} |
|||
} |
|||
} |
|||
|
|||
void H264Feeder::setExtradata(const uint8_t * data, size_t size) |
|||
{ |
|||
int tLen = 0; |
|||
std::vector<Bytes> tSets = h264::parameterSetsFromExtradata(data, size, &tLen); |
|||
m_nAvccLengthSize = tLen; |
|||
setParameterSets(tSets); |
|||
} |
|||
|
|||
void H264Feeder::pushNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced) |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
// A new presentation time starts a new unit (a camera that does not set the marker bit). Small changes
|
|||
// are not a new unit: every RTCP sender report moves live555's mapping a little, also within a picture.
|
|||
if (! m_vNalus.empty() && (ptUs - m_nPtUs > 2000 || m_nPtUs - ptUs > 2000)) |
|||
{ |
|||
flushLocked(); |
|||
} |
|||
if (data != nullptr && size > 0) |
|||
{ |
|||
int tType = data[0] & 0x1f; |
|||
if (tType != h264::NALU_AUD && tType != 0) |
|||
{ |
|||
m_vNalus.emplace_back(data, data + size); |
|||
} |
|||
} |
|||
if (m_vNalus.size() <= 1) |
|||
{ |
|||
m_nPtUs = ptUs; // the time of the unit is the time of its first NAL unit
|
|||
m_bSynced = synced; |
|||
} |
|||
if (marker) |
|||
{ |
|||
flushLocked(); |
|||
} |
|||
} |
|||
|
|||
void H264Feeder::pushAnnexB(const uint8_t * data, size_t size, int64_t ptsUs) |
|||
{ |
|||
std::vector<Bytes> tNalus = h264::splitAnnexB(data, size); |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
m_bSynced = false; |
|||
unitLocked(std::move(tNalus), ptsUs >= 0 ? ptsUs : nowUs(), nowUs()); |
|||
} |
|||
|
|||
void H264Feeder::pushAvcc(const uint8_t * data, size_t size, int lengthSize, int64_t ptsUs) |
|||
{ |
|||
std::vector<Bytes> tNalus = h264::splitAvcc(data, size, lengthSize); |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
m_bSynced = false; |
|||
unitLocked(std::move(tNalus), ptsUs >= 0 ? ptsUs : nowUs(), nowUs()); |
|||
} |
|||
|
|||
void H264Feeder::flushLocked() |
|||
{ |
|||
if (m_vNalus.empty()) |
|||
{ |
|||
return; |
|||
} |
|||
std::vector<Bytes> tNalus; |
|||
tNalus.swap(m_vNalus); |
|||
unitLocked(std::move(tNalus), m_nPtUs, m_nPtUs); |
|||
} |
|||
|
|||
void H264Feeder::unitLocked(std::vector<Bytes> && nalus, int64_t ptUs, int64_t wallUs) |
|||
{ |
|||
if (nalus.empty() || m_pParent == nullptr) |
|||
{ |
|||
return; |
|||
} |
|||
bool tIdr = false; |
|||
for (const Bytes & n : nalus) |
|||
{ |
|||
int t = h264::naluType(n); |
|||
if (t == h264::NALU_SPS) |
|||
{ |
|||
m_sps = n; |
|||
} |
|||
else if (t == h264::NALU_PPS) |
|||
{ |
|||
m_pps = n; |
|||
} |
|||
else if (t == h264::NALU_IDR) |
|||
{ |
|||
tIdr = true; |
|||
} |
|||
} |
|||
// 90 kHz pts starting at 0. A jump (RTCP synchronisation, a restarted source, a clock step) is replaced
|
|||
// by one frame interval: the readers need increasing time stamps.
|
|||
int64_t tRaw = ptUs * 9 / 100; |
|||
if (! m_bHavePts) |
|||
{ |
|||
m_bHavePts = true; |
|||
m_bLastSynced = m_bSynced; |
|||
m_nOffset = -tRaw; |
|||
} |
|||
else if (m_bSynced != m_bLastSynced) |
|||
{ |
|||
m_bLastSynced = m_bSynced; |
|||
m_nOffset = m_nLastPts + m_nLastDelta - tRaw; |
|||
} |
|||
int64_t tPts = tRaw + m_nOffset; |
|||
if (tPts <= m_nLastPts && m_nUnits > 0) |
|||
{ |
|||
if (tPts == m_nLastPts) |
|||
{ |
|||
tPts = m_nLastPts + 1; // same time stamp (should not happen): keep increasing
|
|||
} |
|||
else |
|||
{ |
|||
m_nOffset = m_nLastPts + m_nLastDelta - tRaw; |
|||
tPts = tRaw + m_nOffset; |
|||
} |
|||
} |
|||
else if (tPts - m_nLastPts >= 90000 * 5 && m_nUnits > 0) |
|||
{ |
|||
m_nOffset = m_nLastPts + m_nLastDelta - tRaw; // a gap of 5 s or more: a clock step, not a pause
|
|||
tPts = tRaw + m_nOffset; |
|||
} |
|||
else if (m_nUnits > 0 && tPts - m_nLastPts < 90000) |
|||
{ |
|||
m_nLastDelta = tPts - m_nLastPts; |
|||
} |
|||
m_nLastPts = tPts; |
|||
|
|||
if (! m_bReady) |
|||
{ |
|||
if (m_sps.empty() || m_pps.empty()) |
|||
{ |
|||
return; // a reader cannot use the stream without the codec parameters
|
|||
} |
|||
StreamDesc tDesc; |
|||
h264::SpsInfo tInfo; |
|||
tDesc.sps = m_sps; |
|||
tDesc.pps = m_pps; |
|||
if (h264::parseSps(m_sps, tInfo)) |
|||
{ |
|||
tDesc.width = tInfo.width; |
|||
tDesc.height = tInfo.height; |
|||
} |
|||
m_bReady = true; |
|||
m_pParent->sourceSetReady(tDesc); |
|||
} |
|||
auto tUnit = std::make_shared<Unit>(); |
|||
tUnit->pts = tPts; |
|||
tUnit->ntpUs = wallUs; |
|||
tUnit->idr = tIdr; |
|||
tUnit->nalus = std::move(nalus); |
|||
m_nUnits++; |
|||
m_pParent->sourceWriteUnit(tUnit); |
|||
} |
|||
|
|||
void H264Feeder::reset() |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
m_vNalus.clear(); |
|||
if (m_pParent != nullptr && m_bReady) |
|||
{ |
|||
m_pParent->sourceSetNotReady(); |
|||
} |
|||
m_bReady = false; |
|||
} |
|||
|
|||
bool H264Feeder::ready() const |
|||
{ |
|||
std::lock_guard<std::mutex> lock(m_mutex); |
|||
return m_bReady; |
|||
} |
|||
|
|||
} // namespace mtx
|
|||
@ -0,0 +1,77 @@ |
|||
/* |
|||
MediaMtx (C++) - H264 feeder |
|||
|
|||
Turns the H264 an application already receives into units of a path (MediaPath): |
|||
- NAL units one at a time, as an RTP depacketizer (live555) gives them: grouped into access units by |
|||
the RTP marker bit / a new presentation time; |
|||
- whole access units in Annex-B (libav RTSP demuxer, H264 encoders) or length prefixed (MP4 / avcC). |
|||
The pts is made continuous (90 kHz, starting at 0, always increasing): a reader (recorder, WebRTC) sees |
|||
no jumps when the presentation times move onto the RTCP clock or a source restarts. |
|||
The path becomes ready when SPS and PPS are known (out of band from the SDP / extradata, or in-band), |
|||
and not ready on reset() (the source stopped). |
|||
Thread safe: the source thread pushes, any thread may reset() / setParent(). |
|||
*/ |
|||
#pragma once |
|||
|
|||
#include <cstdint> |
|||
#include <mutex> |
|||
#include <vector> |
|||
|
|||
#include "../core/mediaPath.h" |
|||
#include "../unit/unit.h" |
|||
|
|||
namespace mtx { |
|||
|
|||
class H264Feeder |
|||
{ |
|||
public: |
|||
explicit H264Feeder(SourceParent * parent = nullptr) : m_pParent(parent) {} |
|||
~H264Feeder() { reset(); } |
|||
|
|||
// The path to feed (nullptr: none). The previous path is set not ready. |
|||
void setParent(SourceParent * parent); |
|||
|
|||
// Out of band parameter sets (sprop-parameter-sets of the SDP, libav extradata) |
|||
void setParameterSets(const std::vector<Bytes> & nalus); |
|||
void setExtradata(const uint8_t * data, size_t size); |
|||
|
|||
// One NAL unit (no start code). ptUs: presentation time (us); marker: last NAL unit of the access |
|||
// unit (RTP marker bit); synced: the presentation times are RTCP synchronised (a change = a jump) |
|||
void pushNalu(const uint8_t * data, size_t size, int64_t ptUs, bool marker, bool synced = false); |
|||
// One access unit. ptsUs: presentation time (us, any origin); < 0: use the wall clock |
|||
void pushAnnexB(const uint8_t * data, size_t size, int64_t ptsUs); |
|||
void pushAvcc(const uint8_t * data, size_t size, int lengthSize, int64_t ptsUs); |
|||
// length prefix size of the avcC extradata (0: the packets are Annex-B) |
|||
int avccLengthSize() const { return m_nAvccLengthSize; } |
|||
|
|||
// The source stopped (or reconnects): the path is set not ready, the parameter sets are kept |
|||
void reset(); |
|||
bool ready() const; |
|||
uint64_t units() const { return m_nUnits; } |
|||
|
|||
private: |
|||
void flushLocked(); |
|||
void unitLocked(std::vector<Bytes> && nalus, int64_t ptUs, int64_t wallUs); |
|||
|
|||
mutable std::mutex m_mutex; |
|||
SourceParent * m_pParent = nullptr; |
|||
Bytes m_sps; |
|||
Bytes m_pps; |
|||
bool m_bReady = false; |
|||
int m_nAvccLengthSize = 0; |
|||
uint64_t m_nUnits = 0; |
|||
|
|||
// NAL unit assembly |
|||
std::vector<Bytes> m_vNalus; |
|||
int64_t m_nPtUs = 0; |
|||
bool m_bSynced = false; |
|||
|
|||
// pts continuity |
|||
bool m_bHavePts = false; |
|||
bool m_bLastSynced = false; |
|||
int64_t m_nOffset = 0; |
|||
int64_t m_nLastPts = 0; |
|||
int64_t m_nLastDelta = 3000; |
|||
}; |
|||
|
|||
} // namespace mtx |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue