diff --git a/Projects/argus/argus.vpj b/Projects/argus/argus.vpj index 312e9d39..1c0973c3 100644 --- a/Projects/argus/argus.vpj +++ b/Projects/argus/argus.vpj @@ -130,6 +130,7 @@ + diff --git a/Projects/argus/makefile b/Projects/argus/makefile index fef5b9c4..369ee263 100644 --- a/Projects/argus/makefile +++ b/Projects/argus/makefile @@ -25,8 +25,8 @@ CFG_LIB=-lpthread -lmysqlclient -lssl -lcurl -lm -lcrypto -lconfig \ -lz -lv4l1 -lv4l2 -lhidapi-libusb `pkg-config libavcodec libavdevice \ libavfilter libavformat libavutil libpostproc libswresample \ libswscale --libs` -latomic `pkg-config --libs openssl opencv4 \ - rdkafka++` -lliveMedia -lgroupsock -lBasicUsageEnvironment \ - -lUsageEnvironment + rdkafka++` -lwiringPi -lliveMedia -lgroupsock \ + -lBasicUsageEnvironment -lUsageEnvironment CFG_OBJ= COMMON_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/basicCameraInfo.o $(OUTDIR)/basicDualThread.o \ @@ -134,8 +134,8 @@ ALL_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ -lmysqlclient -lssl -lcurl -lm -lcrypto -lconfig -lz -lv4l1 -lv4l2 \ -lhidapi-libusb `pkg-config libavcodec libavdevice libavfilter \ libavformat libavutil libpostproc libswresample libswscale --libs` \ - -latomic `pkg-config --libs openssl opencv4 rdkafka++` -lliveMedia \ - -lgroupsock -lBasicUsageEnvironment -lUsageEnvironment + -latomic `pkg-config --libs openssl opencv4 rdkafka++` -lwiringPi \ + -lliveMedia -lgroupsock -lBasicUsageEnvironment -lUsageEnvironment COMPILE=g++ -c -x c++ "-DDEBUG" "-D__STDC_CONSTANT_MACROS" "-D_CLIENT_APPLICATION_" "-D_OPENCV_" "-DRASPI_HARDWARE" -O0 -g3 -ggdb -std=c++11 -Wno-write-strings -I../../lib/include -I/usr/local/include/liveMedia -I/usr/local/include/BasicUsageEnvironment -I/usr/local/include/UsageEnvironment -I/usr/local/include/groupsock `pkg-config opencv4 libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< LINK=g++ -O0 -g3 -ggdb -o "$(OUTFILE)" $(ALL_OBJ) diff --git a/lib/components/base/basicTypes.h b/lib/components/base/basicTypes.h index b6457424..782dd979 100644 --- a/lib/components/base/basicTypes.h +++ b/lib/components/base/basicTypes.h @@ -105,6 +105,14 @@ typedef enum{ MS_CLOSED = 8 } MediaStateStatus; +typedef enum E_MS_WORK_MODE{ + MS_MODE_DEV_NULL = 0, + MS_MODE_DECODE_FRAMES = 1, + MS_MODE_STREAM_PROXY = 2, + MS_MODE_ENCODE_FRAMES = 4, + MS_MODE_OVERLAYED_LOOPS = 8 +} MS_WORK_MODE; + typedef struct _S_SOURCE_INFO{ int type; int subtype; diff --git a/lib/data/media/video/videoLive555AVLibSource.cpp b/lib/data/media/video/videoLive555AVLibSource.cpp index b9f968ad..c09d9025 100644 --- a/lib/data/media/video/videoLive555AVLibSource.cpp +++ b/lib/data/media/video/videoLive555AVLibSource.cpp @@ -60,151 +60,540 @@ DummySink* DummySink::createNew( videoLIVE555Source* session, UsageEnvironment& return new DummySink( session, env, subsession, streamId, w, h, ww, hh ); } -DummySink::DummySink(videoLIVE555Source* session, UsageEnvironment& env, MediaSubsession& subsession, char const* streamId, int w, int h, int ww, int hh ) +void someStaticFunc( void * data ){ + +}; + +DummySink::DummySink( videoLIVE555Source* session, UsageEnvironment& env, MediaSubsession& subsession, char const* streamId, int w, int h, int ww, int hh ) : MediaSink(env), - session(session), - frameIndex(0), - fSubsession(subsession) { + m_pSession(session), + m_iFrameIndex(0), + m_sSubSession(subsession) { m_pLog = basicLogCollection::getInstance(); - fStreamId = strDup(streamId); + m_pStreamId = strDup(streamId); + + m_nCurrentOutFile = 0; + m_pOutFile[0] = m_pOutFile[1] = NULL; m_nInWidth = w; m_nInHeight = h; m_nOutWidth = ww; m_nOutHeight = hh; - fReceiveBuffer = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE]; - fReceiveBufferAV = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE + 4]; + m_pReceiveBuffer = new uint8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE]; + m_pReceiveBufferAV = new uint8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE + 4]; + + m_pReceiveBufferAV[0] = 0; + m_pReceiveBufferAV[1] = 0; + m_pReceiveBufferAV[2] = 0; + m_pReceiveBufferAV[3] = 1; - fReceiveBufferAV[0] = 0; - fReceiveBufferAV[1] = 0; - fReceiveBufferAV[2] = 0; - fReceiveBufferAV[3] = 1; + av_init_packet( &m_sAvPkt ); + m_sAvPkt.flags |= AV_PKT_FLAG_KEY; + m_sAvPkt.pts = m_sAvPkt.dts = 0; - av_init_packet(&avpkt); - avpkt.flags |= AV_PKT_FLAG_KEY; - avpkt.pts = avpkt.dts = 0; + memset( m_aInBuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE ); - memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE); + LOG( m_sSubSession.codecName() ); - LOG( subsession.codecName() ); m_eCodecProbe = AV_CODEC_ID_NONE; - if( strcmp(fSubsession.codecName(),"H264") == 0 ){ + + if( strcmp( m_sSubSession.codecName(),"H264") == 0 ){ m_eCodecProbe = AV_CODEC_ID_H264; }; - if( strcmp(fSubsession.codecName(),"JPEG") == 0 ){ + if( strcmp( m_sSubSession.codecName(),"JPEG") == 0 ){ m_eCodecProbe = AV_CODEC_ID_MJPEG; }; - if( strcmp(fSubsession.codecName(),"H265") == 0 ){ + if( strcmp( m_sSubSession.codecName(),"H265") == 0 ){ m_eCodecProbe = AV_CODEC_ID_HEVC; }; - codec = avcodec_find_decoder( m_eCodecProbe ); - if (!codec) { + m_pCodec = avcodec_find_decoder( m_eCodecProbe ); + if( m_pCodec == NULL ) { LOG_ERROR( "codec not found!" ); + + return; }; - codecContext = avcodec_alloc_context3(codec); - frame = av_frame_alloc(); - rgbFrame = av_frame_alloc(); - //avpicture_alloc( ( AVPicture *) rgbFrame, AV_PIX_FMT_RGB24, 1920, 1080); - avpicture_alloc( ( AVPicture *) rgbFrame, AV_PIX_FMT_BGR24, 1280, 720 ); + m_pCodecContext = avcodec_alloc_context3( m_pCodec ); - if (codec->capabilities & AV_CODEC_CAP_TRUNCATED) { - codecContext->flags |= AV_CODEC_FLAG_TRUNCATED; // we do not send complete frames - } + if ( m_pCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) { + m_pCodecContext->flags |= AV_CODEC_FLAG_TRUNCATED; // we do not send complete frames + }; - if ( ( fSubsession.videoWidth() > 0 ) && ( fSubsession.videoHeight() > 0 ) ) { - m_nInWidth = fSubsession.videoWidth(); - m_nInHeight = fSubsession.videoHeight(); + if ( ( m_sSubSession.videoWidth() > 0 ) && ( m_sSubSession.videoHeight() > 0 ) ) { + m_nInWidth = m_sSubSession.videoWidth(); + m_nInHeight = m_sSubSession.videoHeight(); }; - codecContext->width = m_nInWidth; - codecContext->height = m_nInHeight; - codecContext->pix_fmt = AV_PIX_FMT_YUV420P; + m_pCodecContext->width = m_nInWidth; + m_pCodecContext->height = m_nInHeight; - if (avcodec_open2(codecContext,codec,NULL) < 0) { - LOG_ERROR( "could not open codec" ); - } + //Must be carefull! and get pix_fmt from stream + m_pCodecContext->pix_fmt = AV_PIX_FMT_YUV420P; + + if( avcodec_open2( m_pCodecContext, m_pCodec, NULL ) < 0 ){ + LOG_ERROR( "could not open codec!" ); + return; + }; + if( m_pSession->getWM() & MS_MODE_STREAM_PROXY ) { + m_pH264 = (uint8_t *) malloc( 256 * 1024 ); + m_pOutFormatCtx = NULL; + m_pOutFormatOpts = NULL; + if ( avformat_alloc_output_context2( &m_pOutFormatCtx, NULL, NULL, "test.mp4") < 0 ) { + LOG_ERROR("VideoFormat Context Memory Allocation Error"); + //return false; + } else { + m_pOutFormatCtx->oformat = av_guess_format( "mp4", NULL, NULL ); + if ( m_pOutFormatCtx->oformat != NULL ) { + + av_dict_set( &m_pOutFormatOpts, "brand", "mp42", NULL ); + av_dict_set( &m_pOutFormatOpts, "movflags", "faststart", NULL ); + m_pOutFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + + m_pOutStream = avformat_new_stream( m_pOutFormatCtx, NULL ); + + if( m_pOutStream != NULL ){ + + AVCodecContext *c = m_pOutStream->codec; + + c->codec_id = m_eCodecProbe; + c->codec_type = AVMEDIA_TYPE_VIDEO; + + /* put sample parameters */ + c->bit_rate = m_sSubSession.bandwidth();// 400000; + /* resolution must be a multiple of two */ + c->width = m_sSubSession.videoWidth(); + c->height = m_sSubSession.videoHeight(); + /* time base: this is the fundamental unit of time (in seconds) in terms + of which frame timestamps are represented. for fixed-fps content, + timebase should be 1/framerate and timestamp increments should be + identically 1. */ + c->time_base.den = m_sSubSession.videoFPS(); + c->time_base.num = 1; + c->gop_size = 12; /* emit one intra frame every twelve frames at most */ + c->pix_fmt = AV_PIX_FMT_YUV420P; + + if( c->codec_id == AV_CODEC_ID_MPEG2VIDEO ){ + /* just for testing, we also add B frames */ + c->max_b_frames = 2; + } + if( c->codec_id == AV_CODEC_ID_MPEG1VIDEO ){ + /* needed to avoid using macroblocks in which some coeffs overflow + this doesnt happen with normal video, it just happens here as the + motion of the chroma plane doesnt match the luma plane */ + c->mb_decision=2; + } + // some formats want stream headers to be seperate + if(!strcmp( m_pOutFormatCtx->oformat->name, "mp4") || !strcmp( m_pOutFormatCtx->oformat->name, "mov") || !strcmp( m_pOutFormatCtx->oformat->name, "3gp")) { + c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + LOG("Global Header Flag is Set!"); + }; + + if( avio_open(&m_pOutFormatCtx->pb, "test_99.mp4", AVIO_FLAG_WRITE ) < 0 ){ + LOG_ERROR("Could not open output file."); + //return false; + }; + if( avformat_write_header( m_pOutFormatCtx, &m_pOutFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + //return false; + }; + } + }; + }; + /* + m_pOutCodec = = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); + if( m_pOutCodec == NULL ) { + LOG_ERROR( "output codec not found!" ); + //m_pSession->setWM( m_pSession->getWM() & ( ~ MS_MODE_STREAM_PROXY ) ); + return; + }; + + m_pOutCodecContext = avcodec_alloc_context3( m_pOutCodec ); + if( m_pOutCodecContext == NULL ){ + LOG_ERROR("VideoCodec Context Memory Allocation Error"); + return; + } else { + LOG("Codec Context3 Allocated"); + }; + + if( avformat_alloc_output_context2( &m_pOutFormatCtx, NULL, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("VideoFormat Context Memory Allocation Error"); + return; + }; + + m_pOutFormatCtx->oformat = av_guess_format( VIDEO_OUTPUT_CONTAINER, NULL, NULL ); + if( m_pOutFormatCtx->oformat == NULL ){ + LOG_ERROR("VideoFormat Format Not Guessed!"); + return; + } else { + LOG("Video Container Format Guessed"); + }; + + m_pOutVideoStr = avformat_new_stream( m_pOutFormatCtx, m_pOutCodec ); + if( m_pOutVideoStr == NULL){ + LOG_ERROR("VideoStream Not Created!"); + } else { + LOG("VideoStream is Created"); + }; + m_pOutCodecContext->codec_id = VIDEO_OUTPUT_CODEC; + m_pOutCodecContext->codec_type = AVMEDIA_TYPE_VIDEO; + m_pOutCodecContext->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pOutCodecContext->bit_rate = VIDEO_OUTPUT_BITRATE; + //m_pOutCodecContext->bit_rate_tolerance = 1; + //m_pOutCodecContext->global_quality = 100; + //m_pOutCodecContext->compression_level = 2; + m_pOutCodecContext->width = m_nWidth; + m_pOutCodecContext->height = m_nHeight; + m_pOutCodecContext->time_base.num = 1; + m_pOutCodecContext->time_base.den = VIDEO_OUTPUT_FPS; + m_pOutCodecContext->gop_size = VIDEO_OUTPUT_GOP; // emit one intra frame every ten frames + //m_pVideoState->m_pCodecCtx->qmin = 15; + //m_pVideoState->m_pCodecCtx->qmax = 30; + m_pOutCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER; + + if( m_pVideoState->m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ){ + //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + //Set format's privater options, to be passed to avformat_write_header() + LOG("Begin Options!"); + int RetVal = 0; + //RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "movflags", "faststart", 0); + //if( RetVal < 0 ){ + // LOG_ERROR( "av_dict_set movflags!"); + //}; + + //default brand is "isom", which fails on some devices + RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "brand", "mp42", 0); + if( RetVal < 0 ){ + LOG_ERROR( "av_dict_set brand!" ); + }; + //m_pVideoState->m_pCodecCtx->max_b_frames = 1; + m_pVideoState->m_pCodecCtx->level = 31; + RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "crf", "12", 0); + if( RetVal < 0 ){ + LOG_ERROR("av_opt_set crf"); + }; + RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "profile", "main", 0); + if( RetVal < 0 ){ + LOG_ERROR("av_opt_set profile"); + }; + RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "preset", "slow", 0); + if( RetVal < 0 ){ + LOG_ERROR("av_opt_set preset"); + }; + // Disable b-pyramid. CLI options for this is "-b-pyramid 0" + // Because Quicktime (ie. iOS) doesn't support this option + RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "b-pyramid", "0", 0); + if( RetVal < 0 ){ + LOG_ERROR("av_opt_set b-pyramid"); + }; + LOG("End Options!"); + }; + + //See up one page -> + avcodec_get_context_defaults3(m_pVideoState->m_pVideoStr->codec, m_pVideoState->m_pVideoCodec); + const AVRational dst_fps = { VIDEO_OUTPUT_FPS, 1 }; + m_pVideoState->m_pVideoStr->codec->width = m_nWidth; + m_pVideoState->m_pVideoStr->codec->height = m_nHeight; + m_pVideoState->m_pVideoStr->codec->pix_fmt = m_pVideoState->m_pVideoCodec->pix_fmts[0]; + m_pVideoState->m_pVideoStr->codec->time_base = m_pVideoState->m_pVideoStr->time_base = av_inv_q(dst_fps); + m_pVideoState->m_pVideoStr->r_frame_rate = m_pVideoState->m_pVideoStr->avg_frame_rate = dst_fps; + + if (m_pVideoState->m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER) m_pVideoState->m_pVideoStr->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + //---->> + if (avcodec_is_open(m_pVideoState->m_pCodecCtx) == 0) { + LOG("output codec context is closed, opening"); + int ret = avcodec_open2(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoCodec, NULL); + if (ret < 0) { + LOG_ERROR("Error opening2 encoder"); + char buffer[200]; + sprintf(buffer, "Error code: %i", ret ); + LOG_ERROR(buffer); + return false; + } + }else{ + LOG("output codec context is opened"); + }; + */ + //https://github.com/rgaufman/live555/blob/master/testProgs/playCommon.cpp + //http://www.live555.com/liveMedia//doxygen/html/QuickTimeFileSink_8hh_source.html + //qtOut = QuickTimeFileSink::createNew(*env, *session, outFileName, + // fileSinkBufferSize, + // movieWidth, movieHeight, + // movieFPS, + // packetLossCompensate, + // syncStreams, + // generateHintTracks, + // generateMP4Format); + /* qtOut = QuickTimeFileSink::createNew( env, *session->getMS(), "TEST.mp4", + 100000, + subsession.videoWidth(), subsession.videoHeight(), + subsession.videoFPS(), + 0, + 0, + 0, + 1); + */ + qtOut = (H264or5VideoFileSink *) H264VideoFileSink::createNew( env, "TEST22.mp4" ); + if( qtOut != NULL ){ + LOG( "Created QTFS ---> Test.mp4" ); + //qtOut->startPlaying( NULL, NULL ); + LOG( "QTFS Started Play" ); + }; + } else { + LOG("No Stream Proxy Mode!"); + m_pOutCodec = NULL; + }; + + if( m_pSession->getWM() & MS_MODE_DECODE_FRAMES) { + m_pFrame = av_frame_alloc(); + m_pRGBFrame = av_frame_alloc(); + //avpicture_alloc( ( AVPicture *) rgbFrame, AV_PIX_FMT_RGB24, 1920, 1080); + //avpicture_alloc( ( AVPicture *) rgbFrame, AV_PIX_FMT_BGR24, 1280, 720 ); + avpicture_alloc( ( AVPicture *) m_pRGBFrame, AV_PIX_FMT_BGR24, m_nOutWidth, m_nOutHeight ); + //this->swsContext = sws_getContext( codecContext->width, codecContext->height, codecContext->pix_fmt, 1920, 1080, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL); + m_pSwsContext = sws_getContext( m_pCodecContext->width, m_pCodecContext->height, m_pCodecContext->pix_fmt, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL); + m_pRGB = new cv::Mat( m_nOutHeight, m_nOutWidth, CV_8UC3, cv::Scalar( 255, 0, 255 ) ); + } else { + m_pFrame = m_pRGBFrame = NULL; + m_pSwsContext = NULL; + m_pRGB = NULL; + }; - //this->swsContext = sws_getContext( codecContext->width, codecContext->height, codecContext->pix_fmt, 1920, 1080, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL); - this->swsContext = sws_getContext( codecContext->width, codecContext->height, codecContext->pix_fmt, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL); - m_pRGB = new cv::Mat( m_nOutHeight, m_nOutWidth, CV_8UC3, cv::Scalar( 255, 0, 255 ) ); +#ifdef DEBUG char tB[128]; - sprintf( tB, "Created Sink [%dx%d]->[1280x720]", codecContext->width,codecContext->height ); + sprintf( tB, "Created Sink [%dx%d]->[1280x720]", m_pCodecContext->width, m_pCodecContext->height ); LOG( tB ); +#endif }; DummySink::~DummySink() { - delete[] fReceiveBuffer; - delete [] fReceiveBufferAV; - delete[] fStreamId; + + if( m_pOutFormatCtx != NULL ) { + av_write_trailer( m_pOutFormatCtx ); + avio_close( m_pOutFormatCtx->pb ); + }; + + if( qtOut != NULL ) { + Medium::close(qtOut); + qtOut = NULL; + }; + /*Medium::close(qtOut); qtOut = NULL; + Medium::close(aviOut); aviOut = NULL; + + if (session == NULL) return; + MediaSubsessionIterator iter(*session); + MediaSubsession* subsession; + while ((subsession = iter.next()) != NULL) { + Medium::close(subsession->sink); + subsession->sink = NULL; + }*/ + + if( m_pOutFile[0] != NULL ){ + fflush( m_pOutFile[0] ); + pclose( m_pOutFile[0] ); + }; + if( m_pOutFile[1] != NULL ){ + fflush( m_pOutFile[1] ); + pclose( m_pOutFile[1] ); + }; + + if ( m_pFrame ) { + }; + if ( m_pRGBFrame ) { + }; + if ( m_pSwsContext ) { + }; + if ( m_pCodecContext ) { + }; + if ( m_pCodec ) { + }; + delete[] m_pReceiveBuffer; + delete [] m_pReceiveBufferAV; + delete[] m_pStreamId; } void DummySink::afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds ) { - DummySink* sink = (DummySink*)clientData; - sink->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds); + DummySink* sink = (DummySink*) clientData; + sink->afterGettingFrame( frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds ); }; -void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned /*durationInMicroseconds*/) { +void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds ) { // We've just received a frame of data. (Optionally) print out information about it: //if (strcmp(fSubsession.codecName(),"H264") == 0) { if( m_eCodecProbe != AV_CODEC_ID_NONE ) { - avpkt.data = fReceiveBufferAV; - avpkt.size = frameSize + 4; - memcpy (fReceiveBufferAV + 4, fReceiveBuffer, frameSize); - avpkt.data = fReceiveBufferAV; - len = avcodec_decode_video2 (codecContext, frame, &got_picture, &avpkt); - if (len < 0) { - //LOG_ERROR( "Error while decoding frame " );// << frameIndex << "\n"; - } else if (got_picture) { - //envir() << "->Picture decoded :" << frameIndex << "\n"; - //LOG( "Picture decoded" ); - sws_scale( this->swsContext, this->frame->data,this->frame->linesize, 0, this->codecContext->height, this->rgbFrame->data, this->rgbFrame->linesize ); - memcpy( m_pRGB->data, this->rgbFrame->data[0], this->rgbFrame->linesize[0] * m_nOutHeight ); - this->session->consumeFrame( m_pRGB ); - frameIndex ++; + int got_picture; + + memcpy( m_pReceiveBufferAV + 4, m_pReceiveBuffer, frameSize ); + + av_init_packet( &m_sAvPkt ); + + m_sAvPkt.size = frameSize + 4; + m_sAvPkt.data = m_pReceiveBufferAV; + + if ( m_pSession->getWM() & MS_MODE_DECODE_FRAMES ) { + if( avcodec_decode_video2( m_pCodecContext, m_pFrame, &got_picture, &m_sAvPkt ) < 0 ){ + //LOG_ERROR( "Error while decoding frame " );// << frameIndex << "\n"; + } else if( got_picture ){ + //envir() << "->Picture decoded :" << frameIndex << "\n"; + //LOG( "Picture decoded" ); + sws_scale( m_pSwsContext, m_pFrame->data, m_pFrame->linesize, 0, m_pCodecContext->height, m_pRGBFrame->data, m_pRGBFrame->linesize ); + memcpy( m_pRGB->data, m_pRGBFrame->data[0], m_pRGBFrame->linesize[0] * m_nOutHeight ); + m_pSession->consumeFrame( m_pRGB ); + m_iFrameIndex ++; + }; + }; + if ( m_pSession->getWM() & MS_MODE_STREAM_PROXY ) { + + if ( m_pSession->getWM() & MS_MODE_OVERLAYED_LOOPS ) { + // Sega - Mega - Drive + }; + // write packet + + #if(0) + // We've just received a frame of data. (Optionally) print out information about it: + #ifdef DEBUG_PRINT_EACH_RECEIVED_FRAME + if( fStreamId != NULL ) envir() << "Stream \"" << fStreamId << "\"; "; + envir() << fSubsession.mediumName() << "/" << fSubsession.codecName() << ":\tReceived " << frameSize << " bytes"; + if (numTruncatedBytes > 0) envir() << " (with " << numTruncatedBytes << " bytes truncated)"; + char uSecsStr[6+1]; // used to output the 'microseconds' part of the presentation time + sprintf(uSecsStr, "%06u", (unsigned)presentationTime.tv_usec); + envir() << ".\tPresentation time: " << (int)presentationTime.tv_sec << "." << uSecsStr; + if (fSubsession.rtpSource() != NULL && !fSubsession.rtpSource()->hasBeenSynchronizedUsingRTCP()) { + envir() << "!"; // mark the debugging output to indicate that this presentation time is not RTCP-synchronized + } + #ifdef DEBUG_PRINT_NPT + envir() << "\tNPT: " << fSubsession.getNormalPlayTime(presentationTime); + #endif + envir() << "\n"; + #endif + #else + //* + // printf("__FUNCTION__ = %s\n", __FUNCTION__ ); + // if(0 == strncmp(fSubsession.codecName(), "H264", 16) ){ + unsigned char nalu_header[4] = { 0, 0, 0, 1 }; + unsigned char extraData[256]; + unsigned int num = 0; + + SPropRecord * pSPropRecord; + pSPropRecord = parseSPropParameterSets( m_sSubSession.fmtp_spropparametersets(), num ); + + unsigned int extraLen; + extraLen = 0; + + //p_record[0] is sps + //p+record[1] is pps + for(unsigned int i = 0; i < num; i++){ + memcpy( &extraData[extraLen], &nalu_header[0], 4 ); + extraLen += 4; + memcpy( &extraData[extraLen], pSPropRecord[i].sPropBytes, pSPropRecord[i].sPropLength ); + extraLen += pSPropRecord[i].sPropLength; + }; + + memcpy( &extraData[extraLen], &nalu_header[0], 4 ); + extraLen += 4; + + delete[] pSPropRecord; + + memcpy( m_pH264, &extraData[0], extraLen ); + memcpy( m_pH264 + extraLen, m_pReceiveBuffer, frameSize ); + + int totalSize; + totalSize = extraLen + frameSize; + + if( m_pOutFile[m_nCurrentOutFile] == NULL ){ + //m_pOutFile[m_nCurrentOutFile] = fopen("saved.h264", "wb" ); + LOG("Opening"); + //m_pOutFile[m_nCurrentOutFile] = popen("ffmpeg -y -hide_banner -i - -vcodec copy -movflags faststart -an ./ttt123.mp4", "w" ); + m_pOutFile[m_nCurrentOutFile] = popen("ffmpeg -y -hide_banner -i - -vcodec copy -reserve_index_space 50k -an ./ttt123.mkv", "w" ); + + if ( m_pOutFile[m_nCurrentOutFile] == NULL ) { + LOG("Error !!"); + }; + }; + if( m_pOutFile[m_nCurrentOutFile] != NULL ){ + fwrite( m_pH264, 1, totalSize, m_pOutFile[m_nCurrentOutFile] ); + fflush( m_pOutFile[m_nCurrentOutFile] ); + //fclose( fp ); + }; + + //qtOut->addData( m_pH264, totalSize, presentationTime ); + + //printf("\tsaved %d bytes\n", totalSize ); + // }/*if 0 == strncmp(fSubsession.codecName(), "H264", 16)*/ + //if( got_picture ) { + if (m_pOutFormatCtx != NULL) { + m_sAvPkt.duration = durationInMicroseconds; + if( got_picture ) m_sAvPkt.flags |= AV_PKT_FLAG_KEY; + m_sAvPkt.stream_index= m_pOutStream->index; + m_sAvPkt.size = totalSize; + m_sAvPkt.data = m_pH264; + //m_sAvPkt.size = frameSize; + //m_sAvPkt.data = m_pReceiveBuffer; + //av_packet_rescale_ts( &avpkt, m_pOutCodec->time_base, time_base ); + int r = av_write_frame( m_pOutFormatCtx, &m_sAvPkt ); + if( r < 0 ){ + char tB[256]; + av_strerror( r, tB, 256 ); + LOG_ERROR( "Trouble with Video Output!" ); + LOG_ERROR( tB ); + }; + } + //} + #endif }; - } else{ +#ifdef DEBUG + } else { LOG("Codec Not Handled!"); - LOG( fSubsession.codecName() ); + LOG( m_sSubSession.codecName() ); +#endif }; // Then continue, to request the next frame of data: continuePlaying(); } Boolean DummySink::continuePlaying() { - if (fSource == NULL) return False; // sanity check (should not happen) + if( fSource == NULL) return False; // sanity check (should not happen) // Request the next frame of data from our input source. "afterGettingFrame()" will get called later, when it arrives: - fSource->getNextFrame(fReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE, + fSource->getNextFrame( m_pReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE, afterGettingFrame, this, onSourceClosure, this); return True; } void DummySink::setSprop(u_int8_t const* prop, unsigned size) { - uint8_t *buf; - uint8_t *buf_start; - buf = (uint8_t *)malloc(1000); + uint8_t * buf; + uint8_t * buf_start; + buf = (uint8_t *) malloc(1004); buf_start = buf + 4; - avpkt.data = buf; - avpkt.data[0] = 0; - avpkt.data[1] = 0; - avpkt.data[2] = 0; - avpkt.data[3] = 1; - memcpy (buf_start, prop, size); - avpkt.size = size + 4; - len = avcodec_decode_video2 (codecContext, frame, &got_picture, &avpkt); - if (len < 0) { - //envir() << "Error while decoding frame" << frame; + m_sAvPkt.data = buf; + m_sAvPkt.data[0] = 0; + m_sAvPkt.data[1] = 0; + m_sAvPkt.data[2] = 0; + m_sAvPkt.data[3] = 1; + if ( size > 1000 ) { + LOG_ERROR("Data Chunk too large!! Increase Mem!"); + free( buf ); + m_sAvPkt.data = NULL; + m_sAvPkt.size = 0; + return; + }; + memcpy( buf_start, prop, size ); + m_sAvPkt.size = size + 4; + int got_picture; + if ( avcodec_decode_video2 ( m_pCodecContext, m_pFrame, &got_picture, &m_sAvPkt ) < 0 ) { LOG_ERROR( "Error while decoding frame" ); - // exit(6); + free( buf ); + m_sAvPkt.data = NULL; + m_sAvPkt.size = 0; + return; }; - LOG( "after setSprop" ); - // exit (111); + free( buf ); + m_sAvPkt.data = NULL; + m_sAvPkt.size = 0; }; #undef LOG_ERROR @@ -230,11 +619,15 @@ videoLIVE555Source::videoLIVE555Source( void *opaque ): basicThread(), m_pLog(basicLogCollection::getInstance()), m_pOpaque(opaque){ + m_bIsParamsSet = false; + //Default -> only decode frames + m_eWM = MS_MODE_DECODE_FRAMES; + m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1; if( !initLibAV() ) return; }; -videoLIVE555Source::videoLIVE555Source( CSTR URI, void *opaque ): +videoLIVE555Source::videoLIVE555Source( CSTR URI, void *opaque, MS_WORK_MODE mode ): m_pScheduler(BasicTaskScheduler::createNew()), m_pUsageEnvironment(BasicUsageEnvironment::createNew(*m_pScheduler)), basicMediaSource(), @@ -242,9 +635,11 @@ videoLIVE555Source::videoLIVE555Source( CSTR URI, void *opaque ): basicThread(), m_pLog(basicLogCollection::getInstance()), m_pOpaque(opaque){ + m_bIsParamsSet = true; + m_eWM = mode; m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1; if( !initLibAV() ) return; - _open( URI ); + _open(URI); }; videoLIVE555Source::~videoLIVE555Source(){ @@ -298,11 +693,13 @@ void videoLIVE555Source::continueAfterDESCRIBE( RTSPClient* rtspClient, int resu break; }; + ME->m_pMediaSession = scs.session; + // Then, create and set up our data source objects for the session. We do this by iterating over the session's 'subsessions', // calling "MediaSubsession::initiate()", and then sending a RTSP "SETUP" command, on each one. // (Each 'subsession' will have its own data source.) scs.iter = new MediaSubsessionIterator(*scs.session); - ME->setupNextSubsession(rtspClient); + ME->setupNextSubsession( rtspClient ); return; } while (0); // An unrecoverable error occurred with this stream. @@ -400,6 +797,7 @@ void videoLIVE555Source::continueAfterSETUP( RTSPClient* rtspClient, int resultC // Set up the next subsession, if any: ME->setupNextSubsession(rtspClient); }; + void videoLIVE555Source::continueAfterPLAY( RTSPClient* rtspClient, int resultCode, char* resultString){ Boolean success = False; CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; @@ -432,10 +830,10 @@ void videoLIVE555Source::continueAfterPLAY( RTSPClient* rtspClient, int resultCo // } success = True; - } while (0); - delete[] resultString; - + } while( 0 ); + //delete[] resultString; if (!success) { + MLOG("Shutdown!"); // An unrecoverable error occurred with this stream. ME->shutdownStream(rtspClient); }; @@ -462,6 +860,25 @@ void videoLIVE555Source::subsessionAfterPlaying( void* clientData ){ ME->shutdownStream(rtspClient); }; +void videoLIVE555Source::sessionAfterPlaying( void* clientData ){ + MediaSession* session = (MediaSession*)clientData; + if ( session->hasSubsessions() ) { + MediaSubsessionIterator *itr = new MediaSubsessionIterator(*session); + if( itr!= NULL ){ + MediaSubsession* subsession = itr->next(); + while ( subsession != NULL ) { + RTSPClient * rtspClient = (RTSPClient*)subsession->miscPtr; + CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; + videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); + UsageEnvironment& env = rtspClient->envir(); + MLOG("sessionAfterPlaying!"); + subsession = itr->next(); + }; + delete itr; + }; + }; +}; + // called when a RTCP "BYE" is received for a subsession void videoLIVE555Source::subsessionByeHandler( void* clientData ){//, char const* reason ){ MediaSubsession* subsession = (MediaSubsession*)clientData; @@ -492,6 +909,7 @@ void videoLIVE555Source::streamTimerHandler( void* clientData ){ void videoLIVE555Source::openURL(UsageEnvironment& env, char const* progName, char const* rtspURL){ LOG("openURL Called!"); }; + // Used to iterate through each stream's 'subsessions', setting up each one: void videoLIVE555Source::setupNextSubsession(RTSPClient* rtspClient){ CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; @@ -552,6 +970,15 @@ void videoLIVE555Source::shutdownStream(RTSPClient* rtspClient, int exitCode ){ // https://chowdera.com/2021/01/20210102084512591N.html // https://github.com/drriguz/Kamera bool videoLIVE555Source::_open( CSTR URI, bool ShowDeviceMenu, float framerate, int inputPin, int width, int height, int s_width, int s_height ){ + + if ( URI == NULL ) { + LOG_ERROR("Trying to open MediaSource without MRL!"); + return false; + }; + //if( !m_bIsParamsSet ) { + // LOG_ERROR("Trying to open MediaSource without all needded parameters!"); + // return false; + //}; m_nInHeight = height; m_nInWidth = width; @@ -565,24 +992,29 @@ bool videoLIVE555Source::_open( CSTR URI, bool ShowDeviceMenu, float framerate, LOG_ERROR( tB ); return false; }; - m_pRtspClient->sendDescribeCommand(continueAfterDESCRIBE); + m_pRtspClient->sendDescribeCommand( continueAfterDESCRIBE ); return init(); }; void videoLIVE555Source::consumeFrame( cv::Mat *frm ){ - if ( m_pMediaDestination == NULL ) return; - if(!m_pMediaDestination->pushFrame( *frm, m_pOpaque )){ + if( m_pMediaDestination == NULL ) return; + if( !m_pMediaDestination->pushFrame( *frm, m_pOpaque ) ){ m_pMediaDestination = NULL; + LOG_ERROR("Error Consume Frame by Media Destination!"); }; }; bool videoLIVE555Source::_close( void ){ + LOG("CLOSE!"); return _stop(); }; bool videoLIVE555Source::_stop( void ){ + LOG("STOP!"); shutdownStream( m_pRtspClient ); + LOG("SHUTDOWN!"); _eventLoopWatchVariable = 1; basicThread::waitThreadEnd( true ); + LOG("TH ENDED!"); return true; }; bool videoLIVE555Source::isFinished( void ){ return false;}; diff --git a/lib/data/media/video/videoLive555AVLibSource.h b/lib/data/media/video/videoLive555AVLibSource.h index 5b8759d7..9f334075 100644 --- a/lib/data/media/video/videoLive555AVLibSource.h +++ b/lib/data/media/video/videoLive555AVLibSource.h @@ -91,44 +91,58 @@ class DummySink: public MediaSink { virtual Boolean continuePlaying(); public: - void setSprop(u_int8_t const* prop, unsigned size); + void setSprop( u_int8_t const* prop, unsigned size ); private: - videoLIVE555Source* session; + videoLIVE555Source * m_pSession; private: - u_int8_t* fReceiveBuffer; - u_int8_t* fReceiveBufferAV; - MediaSubsession& fSubsession; - char* fStreamId; + uint8_t * m_pReceiveBuffer; + uint8_t * m_pReceiveBufferAV; + MediaSubsession & m_sSubSession; + char * m_pStreamId; + H264or5VideoFileSink * qtOut; + FILE * m_pOutFile[2]; + uint8_t m_nCurrentOutFile; private: - AVCodec *codec; - AVCodecContext *codecContext; - int frameIndex; - int got_picture; - int len; - AVFrame *frame; - AVFrame *rgbFrame; - SwsContext* swsContext; - uint8_t inbuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; - char buf[1024]; - AVPacket avpkt; + AVCodec * m_pCodec; + AVCodecContext * m_pCodecContext; + + AVCodec * m_pOutCodec; + AVCodecContext * m_pOutCodecContext; + AVFormatContext * m_pOutFormatCtx; + AVDictionary * m_pOutFormatOpts; + AVStream * m_pOutStream; + uint8_t * m_pH264; + + uint64_t m_iFrameIndex; + AVFrame * m_pFrame; + AVFrame * m_pRGBFrame; + SwsContext * m_pSwsContext; + + uint8_t m_aInBuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; + //char buf[1024]; + AVPacket m_sAvPkt; }; class videoLIVE555Source : public basicMediaSource, public basicThread { private: basicLogCollection * m_pLog; void * m_pOpaque; + bool m_bIsParamsSet; int m_nInWidth; int m_nInHeight; int m_nOutWidth; int m_nOutHeight; + MS_WORK_MODE m_eWM; StreamClientState streamClientState; virtual Boolean continuePlaying(); uint8_t * fReceiveBuffer; TaskScheduler * m_pScheduler; + UsageEnvironment * m_pUsageEnvironment; + MediaSession * m_pMediaSession; char _eventLoopWatchVariable; @@ -142,6 +156,7 @@ class videoLIVE555Source : public basicMediaSource, public basicThread { static void continueAfterPLAY( RTSPClient* rtspClient, int resultCode, char* resultString); // Other event handler functions: static void subsessionAfterPlaying( void* clientData ); + // called when a stream's subsession (e.g., audio or video substream) ends static void subsessionByeHandler( void* clientData );//, char const* reason ); // called when a RTCP "BYE" is received for a subsession @@ -159,14 +174,20 @@ class videoLIVE555Source : public basicMediaSource, public basicThread { void m_fThreadProc( void ); public: + static void sessionAfterPlaying( void* clientData ); + virtual bool _open( CSTR URI, bool ShowDeviceMenu = false, float framerate=-1.0f, int inputPin = -1, int width = -1, int height = -1 , int s_width=-1, int s_height=-1 ); virtual bool _close( void ); virtual bool _stop( void ); bool isFinished( void ); + MS_WORK_MODE getWM( void ) const { return m_eWM; }; + void setWM( int M ){ m_eWM = (MS_WORK_MODE) M; }; MediaStateStatus getStatus( void ); - videoLIVE555Source( void *opaque=NULL ); - videoLIVE555Source( CSTR URI, void *opaque=NULL ); + + explicit videoLIVE555Source( void *opaque=NULL ); + explicit videoLIVE555Source( CSTR URI, void *opaque=NULL, MS_WORK_MODE mode = MS_MODE_DECODE_FRAMES ); virtual ~videoLIVE555Source(); + bool setSize( int Width, int Height ); bool setProportionalByWidth( int Width ); @@ -175,6 +196,7 @@ class videoLIVE555Source : public basicMediaSource, public basicThread { bool setName( CSTR Name ); bool setFrameAspectRatio( FrameAspectRatio AspectRatio ); void consumeFrame( cv::Mat *frm ); + MediaSession * getMS( void ){ return m_pMediaSession; }; }; #endif diff --git a/lib/data/protocol/protocolKAFKA.cpp b/lib/data/protocol/protocolKAFKA.cpp index a42bf37d..fd79795a 100644 --- a/lib/data/protocol/protocolKAFKA.cpp +++ b/lib/data/protocol/protocolKAFKA.cpp @@ -244,6 +244,7 @@ bool protocolKAFKA::init(){ LOG_ERROR("Eror Creating Producer Conf!"); return false; }; + //ToDo: Checking in case of SSL -> if library is build with SSL support!! #ifdef DEBUG_KAFKA LOG("RdKafka::Conf::CONF_GLOBAL Created"); std::string features; diff --git a/lib/rgoose/rgooseCamera.cpp b/lib/rgoose/rgooseCamera.cpp index b5aaadc0..2ab4ab76 100644 --- a/lib/rgoose/rgooseCamera.cpp +++ b/lib/rgoose/rgooseCamera.cpp @@ -101,8 +101,8 @@ ARGUS_Camera::ARGUS_Camera( uint32_t NodeID ): argusNetNode( NodeID ), basicThre m_bRelativeMoveMatrix = 0; m_fSpeedRise = 0.03f; m_fRM_Pan = m_fRM_Tilt = m_fRM_Zoom = .0f; - m_bSourceConnected = false; - m_pSource = NULL; + //m_bSourceConnected = false; + //m_pSource = NULL; }; ARGUS_Camera::ARGUS_Camera( DBC_NODE_DATA *Data ): argusNetNode( Data ), basicThread(){ @@ -121,8 +121,8 @@ ARGUS_Camera::ARGUS_Camera( DBC_NODE_DATA *Data ): argusNetNode( Data ), basicT m_bRelativeMoveMatrix = 0; m_fSpeedRise = 0.03f; m_fRM_Pan = m_fRM_Tilt = m_fRM_Zoom = .0f; - m_bSourceConnected = false; - m_pSource = NULL; + //m_bSourceConnected = false; + //m_pSource = NULL; }; ARGUS_Camera::~ARGUS_Camera(){ @@ -165,13 +165,13 @@ ARGUS_Camera::~ARGUS_Camera(){ LOG("Proto Del OK"); //if( m_pPosition != NULL ) delete( m_pPosition ); //LOG("Pos Del OK"); - if( m_bSourceConnected ){ - if( m_pSource != NULL ){ - m_pSource->_close(); - delete( m_pSource ); - }; - }; - LOG("Stream Del OK"); + //if( m_bSourceConnected ){ + // if( m_pSource != NULL ){ + // m_pSource->_close(); + // delete( m_pSource ); + // }; + //}; + //LOG("Stream Del OK"); }; void ARGUS_Camera::updateOpticalParameters( uint16_t frame_width, uint16_t frame_heigth ){ @@ -663,16 +663,17 @@ DBC_SNAPSHOT_DATA *ARGUS_Camera::fusion_translate_ROI( CAM_ROI *(&ptr) ){ DBC_SNAPSHOT_DATA *rVal = NULL; if( ptr == NULL ) return NULL; if( ptr->targets.size() ){ - if( m_bSourceConnected ){ + //if( m_bSourceConnected ){ rVal = (DBC_SNAPSHOT_DATA *)malloc(sizeof(DBC_SNAPSHOT_DATA)); if( rVal ){ memset( rVal, 0, sizeof(DBC_SNAPSHOT_DATA) ); - rVal->stream_id = m_nActiveStreamID; + //rVal->stream_id = m_nActiveStreamID; + rVal->stream_id = m_sNodeData.aux_parameter; for( vCAM_TRACK_RECORDS::iterator idx = ptr->targets.begin(); idx < ptr->targets.end(); idx++ ) { rVal->assoc_event_ids.push_back( (*idx)->evt_db_ID ); }; }; - }; + //}; ptr->targets.clear(); }; // Destruct ROI MEM @@ -758,9 +759,9 @@ void ARGUS_Camera::m_fThreadProc( void ){ m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ) { //Local Recorder - if( m_bSourceConnected ) { - - }; + //if( m_bSourceConnected ) { +// + // }; uint8_t tState = getWM(); char tB[128]; @@ -1260,6 +1261,7 @@ bool ARGUS_Camera::makeSnap( uint32_t TargetRefID ){ }; bool ARGUS_Camera::connectToStream( uint32_t id ){ + /* if( id ){ argusKernelModule * tKM = NULL; argusKernel * tKRNL = NULL; @@ -1282,6 +1284,7 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ return false; }; if( tKM ) { + // New Module DBC_MEDIA_STREAM_DATA *tDATA = m_pDBC->getMediaStreamData( id ); if( tDATA ) { m_sMediaSource.mediaStreamId = id; @@ -1290,7 +1293,7 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sMediaSource); } else { if (m_pSource != NULL) delete((videoLIVE555Source*)m_pSource); - m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sMediaSource); + m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sMediaSource ); }; if( m_pSource != NULL ) { @@ -1298,6 +1301,8 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ #ifdef DEBUG LOG("Source OK"); #endif + ((videoLIVE555Source*)m_pSource)->setWM( MS_MODE_STREAM_PROXY | MS_MODE_OVERLAYED_LOOPS | MS_MODE_DECODE_FRAMES ); + int tW = ((argusModuleEmbedVideo*)tKM)->getWidh(); int tH = ((argusModuleEmbedVideo*)tKM)->getHeight(); int pix = -1; @@ -1336,7 +1341,12 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ if( m_pSource->_open( tMRL, false, -1.0f, pix, tDATA->width, tDATA->height, tW, tH ) ){ m_bSourceConnected = m_pSource->attachDestination( (argusModuleEmbedVideo*) tKM ); if ( !m_bSourceConnected ) { - delete( m_pSource ); + //delete( m_pSource ); + if( strncmp(tDATA->mrl_proto, "v4l2", 4) == 0 ) { + delete((videoAVLIBSource*)m_pSource); + } else { + delete((videoLIVE555Source*)m_pSource); + }; m_pSource = NULL; } else { m_nActiveStreamID = id; @@ -1346,7 +1356,12 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ }; } else { LOG_ERROR("Can not Open Video Source!"); - delete( m_pSource ); + //delete( m_pSource ); + if( strncmp(tDATA->mrl_proto, "v4l2", 4) == 0 ) { + delete((videoAVLIBSource*)m_pSource); + } else { + delete((videoLIVE555Source*)m_pSource); + }; m_pSource = NULL; }; } else { @@ -1360,11 +1375,14 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ #endif ; }; + LOG("Connect Finished!"); return m_bSourceConnected; + */ + return true; }; bool ARGUS_Camera::disconnectFromStream( void ){ - if( m_bSourceConnected ) { + /*if( m_bSourceConnected ) { if( m_pSource ){ delete( m_pSource ); m_pSource = NULL; @@ -1372,9 +1390,12 @@ bool ARGUS_Camera::disconnectFromStream( void ){ m_bSourceConnected = false; }; return !m_bSourceConnected; + */ + return true; }; bool ARGUS_Camera::validateStream( void ){ + /* if( m_bSourceConnected ) { if( m_pSource ) { if( m_pSource->isAttached() ){ @@ -1391,6 +1412,8 @@ bool ARGUS_Camera::validateStream( void ){ disconnectFromStream(); }; return false; + */ + return true; }; #undef LOG diff --git a/lib/rgoose/rgooseCamera.h b/lib/rgoose/rgooseCamera.h index 5ca1424a..24b6fe7a 100644 --- a/lib/rgoose/rgooseCamera.h +++ b/lib/rgoose/rgooseCamera.h @@ -20,8 +20,7 @@ #include "../components/base/basicThread.h" #include "../components/base/basicMutex.h" #include "../data/protocol/protocolPTZ.h" -#include "../data/media/video/videoAVLIBSource.h" -#include "../data/media/video/videoLive555AVLibSource.h" + #include "../components/base/basicEventHeap.h" #include "rgooseDBConnector.h" #include "rgooseNode.h" @@ -113,7 +112,7 @@ typedef std::vector vCAM_ROIS; class ARGUS_Camera: public argusNetNode, public basicThread { private: - basicLogCollection * m_pLog; + basicLogCollection * m_pLog; //basicPosition * m_pPosition; basicPosition m_oPosition; //argusDBC * m_pDBC; @@ -144,7 +143,7 @@ class ARGUS_Camera: public argusNetNode, public basicThread { //videoAVLIBSource * m_pSource; //videoLIVE555Source * m_pSource; - basicMediaSource * m_pSource; + //basicMediaSource * m_pSource; uint32_t m_nRelativeMoveCounter; uint8_t m_bRelativeMoveMatrix; float m_fSpeedRise; @@ -172,8 +171,8 @@ class ARGUS_Camera: public argusNetNode, public basicThread { DBC_CAM_DATA m_sCamData; MEDIA_SOURCE_DESC m_sMediaSource; basicEventHeap * m_pBEH; - bool m_bSourceConnected; - uint32_t m_nActiveStreamID; + //bool m_bSourceConnected; + //uint32_t m_nActiveStreamID; //bool inTheFOV( float lat, float lon, float alt ); bool testFOV( C3D_WGS84_LOC ); //Global Coords diff --git a/lib/rgoose/rgooseDBConnector.cpp b/lib/rgoose/rgooseDBConnector.cpp index b118065e..6f535608 100644 --- a/lib/rgoose/rgooseDBConnector.cpp +++ b/lib/rgoose/rgooseDBConnector.cpp @@ -32,6 +32,7 @@ argusDBC::argusDBC( config_setting_t * Settings ){ m_pLog = basicLogCollection::getInstance(); m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DBC" ); m_bIsConnected = false; + m_bIsServerLocal = false; m_nSiteID = 0; m_pDatabase = NULL; }; @@ -55,7 +56,16 @@ bool argusDBC::connect( void ){ LOG("No DB Host Setting! Using default!"); }; sprintf(m_pDbHost, "%s", config_setting_get_string(tSetting)); - tSetting = config_setting_get_member( m_pSettings, "DATABASE_NAME" ); + + //Check if using local database + if( strstr( m_pDbHost, "localhost" )!= NULL ){ + m_bIsServerLocal = true; + } else { + // Check if setting is local IP address + + }; + + tSetting = config_setting_get_member(m_pSettings, "DATABASE_NAME"); if( tSetting == NULL ){ tSetting = config_setting_add(m_pSettings, "DATABASE_NAME", CONFIG_TYPE_STRING ); config_setting_set_string( tSetting, "dfsl_gunter" ); @@ -2112,13 +2122,13 @@ DBC_INT_LIST *argusDBC::listMediaStreams( uint32_t SiteId, uint8_t listMode ){ AAssoc *result; switch( listMode ){ case LIST_VALID_RECORDS: - sprintf(tQBuf, "SELECT id FROM media_streams WHERE `valid`=1 AND `site_id`=%d", SiteId ); + sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13) AND `nd`.`site_id`=%d AND `ms`.`valid`=1 AND `nd`.`online`=1", SiteId ); break; case LIST_INVALID_RECORDS: - sprintf(tQBuf, "SELECT id FROM media_streams WHERE `valid`=0 AND `site_id`=%d", SiteId ); + sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13) AND `nd`.`site_id`=%d AND `ms`.`valid`=1 AND `nd`.`online`=0", SiteId ); break; default: - sprintf(tQBuf, "SELECT id FROM media_streams WHERE `site_id`=%d", SiteId ); + sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13) AND `nd`.`site_id`=%d AND `ms`.`valid`=1", SiteId ); }; #ifdef DEBUG_ALL LOG(tQBuf); diff --git a/lib/rgoose/rgooseDBConnector.h b/lib/rgoose/rgooseDBConnector.h index aff77614..ddeede00 100644 --- a/lib/rgoose/rgooseDBConnector.h +++ b/lib/rgoose/rgooseDBConnector.h @@ -3,7 +3,6 @@ #include "../components/base/basicSettingsProvider.h" #include "../data/mysql/database_class.h" -//#include "../data/protocol/onvifMediaObserver.h" #include "../alg/generic/md5.h" #include "../alg/lgs/mask.h" #include "rgooseTypes.h" @@ -14,6 +13,7 @@ class argusDBC{ config_setting_t * m_pSettings; MySQL_Connector * m_pDatabase; bool m_bIsConnected; + bool m_bIsServerLocal; char m_pDbHost[CLOG]; char m_pDbUsername[CLOG]; char m_pDbPassword[CLOG]; @@ -25,7 +25,7 @@ class argusDBC{ virtual ~argusDBC(); /* Functionality */ bool connect( void ); - + bool isLocal( void ) const { return m_bIsServerLocal; }; //SET GLOBAL tmp_table_size = 1024 * 1024 * 1024 * 2; //SET GLOBAL max_heap_table_size = 1024 * 1024 * 1024 * 2; diff --git a/lib/rgoose/rgooseModuleEmbedVideo.cpp b/lib/rgoose/rgooseModuleEmbedVideo.cpp index 4c5f74da..7b140b98 100644 --- a/lib/rgoose/rgooseModuleEmbedVideo.cpp +++ b/lib/rgoose/rgooseModuleEmbedVideo.cpp @@ -1,7 +1,11 @@ #include "rgooseModuleEmbedVideo.h" #include "rgooseHardwareResourceNetworkProvider.h" +#include "rgooseKernel.h" #include "../alg/generic/base64.h" +#include "../data/media/video/videoAVLIBSource.h" +#include "../data/media/video/videoLive555AVLibSource.h" + #include #include #include @@ -62,7 +66,7 @@ static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_ou //buffer_data bd[1]={0}; -argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicMediaDestination(), basicThread(){ +argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicThread(){ m_pEventHeap = basicEventHeap::getInstance(); if( m_pDBC ){ DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); @@ -491,7 +495,8 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ }; }; - + // validate active streams ? + SLEEP( 50 ); }; }; @@ -681,6 +686,7 @@ bool argusModuleEmbedVideo::reloadSettings(){ }; bool argusModuleEmbedVideo::validate(){ + bool RetVal = true; if( m_pDBC ){ DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); if( tDATA ) { @@ -690,217 +696,26 @@ bool argusModuleEmbedVideo::validate(){ return reloadSettings(); }; free( tDATA ); - return true; - }; - } else { - LOG_ERROR( "DB Error!" ); - }; - return false; -}; - -bool argusModuleEmbedVideo::pushFrame( AVFrame *Frame, void* src){ - if( !m_bEnabled ) return false; - MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src; - if( tMD ) { - }; - return true; -}; - -bool argusModuleEmbedVideo::pushFrame( cv::Mat &Frame, void* src ){ - if( !m_bEnabled ) return false; - MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; - char tBuffer[128]; - if( tMD ) { - float mK, oK; - cv::Rect ROI; - //if( !m_mPictureProtector.try_lock() ) return; - m_mPictureProtector.lock(); - if( m_mapMATS[tMD->mediaStreamId].cols == 0 ) { - LOG("First Frame Enqueued"); - sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId ); - LOG( tBuffer ); - - m_mapMATS[tMD->mediaStreamId].create( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 ); - cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.height, m_sEmbedVideoData.width ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); - }; -#ifdef USE_SCALING_IN - oK = ((float)m_sEmbedVideoData.height )/ ((float)m_sEmbedVideoData.width); - mK = ((float)Frame.rows )/ ((float)Frame.cols); - //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); - if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) { - ROI.width = (int) m_sEmbedVideoData.width; - ROI.height = (int) m_sEmbedVideoData.height; - ROI.x = (int) 0; - ROI.y = (int) 0; - } else { - if( mK < oK ) { - ROI.width = (int) m_sEmbedVideoData.width; - ROI.height = (int) (((float)m_sEmbedVideoData.width) * mK ); - ROI.x = (int) 0; - ROI.y = (int)( m_sEmbedVideoData.height - ROI.height ) >> 1; - } else { - ROI.height = (int) m_sEmbedVideoData.height; - ROI.width = (int) (((float)m_sEmbedVideoData.height) / mK ); - ROI.y = (int) 0; - ROI.x = (int) ( m_sEmbedVideoData.width - ROI.width ) >> 1; - }; - }; - cv::Mat mROI = m_mapMATS[tMD->mediaStreamId]( ROI ); - cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR ); -#else - if(( m_sEmbedVideoData.height==Frame.rows )&&( m_sEmbedVideoData.width==Frame.cols )){ - Frame.copyTo( m_mapMATS[tMD->mediaStreamId] ); } else { - //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows)); - //src.copyTo(dst_roi); - - if (m_sEmbedVideoData.width == Frame.cols ) { - ROI.width = Frame.cols; - ROI.height = Frame.rows; - ROI.x = 0; - ROI.y = ( m_sEmbedVideoData.height - Frame.rows ) >> 1; - cv::Mat mROI = m_mapMATS[tMD->mediaStreamId]( ROI ); - Frame.copyTo(mROI); - } else { - ROI.width = Frame.cols; - ROI.height = Frame.rows; - ROI.x = ( m_sEmbedVideoData.width - Frame.cols ) >> 1; - ROI.y = 0; - cv::Mat mROI = m_mapMATS[tMD->mediaStreamId]( ROI ); - Frame.copyTo(mROI); - }; + RetVal = false; }; -#endif - if( m_sEmbedVideoData.show_label ){ - time_t t = time( NULL ); - struct tm * tmp = gmtime( &t ); - if( tmp ){ - char tsb[64]; - if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ - - sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); - int baseline=0; - cv::Size textSize = cv::getTextSize( tBuffer, - m_sEmbedVideoData.label_font_face, - m_sEmbedVideoData.label_font_scale, - m_sEmbedVideoData.label_font_thickness, - &baseline - ); - int x = m_sEmbedVideoData.label_x; - int y = m_sEmbedVideoData.label_y; - if( x < 0 ) { - x = m_sEmbedVideoData.width+x-textSize.width; - }; - if( y < 0 ) { - y = m_sEmbedVideoData.height+y-baseline;// - }; - if( !m_sEmbedVideoData.label_transperant ) { - cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); - }; - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( x, y ), - (cv::HersheyFonts) m_sEmbedVideoData.label_font_face, - m_sEmbedVideoData.label_font_scale, cv::Scalar( 0, 255, 0 ), - m_sEmbedVideoData.label_font_thickness, - m_sEmbedVideoData.label_line_type - ); - }; - }; - } else { - if( m_sEmbedVideoData.show_ts ){ - time_t t = time( NULL ); - struct tm * tmp = gmtime( &t ); - if( tmp ){ - if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){ - uint8_t shift_x = 0; - uint8_t shift_y = 15; - if( !m_sEmbedVideoData.ts_transperant ) { - if( m_sEmbedVideoData.ts_font_face ) { - shift_y = 15; - cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( m_sEmbedVideoData.ts_x, m_sEmbedVideoData.ts_y ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); - } else { - shift_y = 23; - cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( m_sEmbedVideoData.ts_x, m_sEmbedVideoData.ts_y ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); - }; - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_sEmbedVideoData.ts_x + shift_x, m_sEmbedVideoData.ts_y + shift_y ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - } else { - if( m_sEmbedVideoData.ts_font_face ) { - shift_y = 15; - } else { - shift_y = 23; - }; - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_sEmbedVideoData.ts_x + shift_x - 1, m_sEmbedVideoData.ts_y + shift_y - 1 ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_sEmbedVideoData.ts_x + shift_x + 1, m_sEmbedVideoData.ts_y + shift_y - 1 ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_sEmbedVideoData.ts_x + shift_x - 1, m_sEmbedVideoData.ts_y + shift_y + 1 ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_sEmbedVideoData.ts_x + shift_x - 1, m_sEmbedVideoData.ts_y + shift_y + 2 ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_sEmbedVideoData.ts_x + shift_x, m_sEmbedVideoData.ts_y + shift_y ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - } - }; - }; - }; - }; - if( m_sEmbedVideoData.show_logo ){ - cv::Rect roi( cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h )); - cv::Mat destinationROI = m_mapMATS[tMD->mediaStreamId]( roi ); - m_mLogoPic.copyTo( destinationROI, m_mLogoMask ); - }; - - vector compression_params; - //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); - //compression_params.push_back(9); - compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); - compression_params.push_back( m_sEmbedVideoData.compression_quality ); - m_mEncodedProtector.lock(); - m_mapCAPTURES[tMD->mediaStreamId].clear(); - cv::imencode( ".jpg", m_mapMATS[tMD->mediaStreamId], m_mapCAPTURES[tMD->mediaStreamId], compression_params ); - m_mEncodedProtector.unlock(); - /*ToDo: Move Broadcast Pic From Push Frame Procedure - uint32_t DataSize = m_mapCAPTURES[tMD->mediaStreamId].size(); //buf.size(); - - if( DataSize ) { - uint8_t *pData = m_mapCAPTURES[tMD->mediaStreamId].data(); //buf.data(); - if( m_vHandlersPool.size() ) { - for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { - if( (*idx)->CTX->mediaStreamId == tMD->mediaStreamId ) { - write( (*idx)->CTX->m_iEncoderPipe[1], &DataSize, sizeof(uint32_t)); - write( (*idx)->CTX->m_iEncoderPipe[1], pData, DataSize ); + if ( RetVal ) { + DBC_INT_LIST *tList = m_pDBC->listMediaStreams(m_pKernel->getSiteId(), LIST_VALID_RECORDS); + if ( tList != NULL ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ){ + if( !registerStream( *idx ) ){ + RetVal = false; + break; }; }; + delete ( tList ); }; }; - */ - m_mPictureProtector.unlock(); + } else { + LOG_ERROR( "DB Error!" ); + RetVal = false; }; - return true; + return RetVal; }; bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){ @@ -1086,6 +901,1141 @@ bool argusModuleEmbedVideo::generateSavePicPath( CSTR MD5, CSTR Output ){ return true; }; +bool argusModuleEmbedVideo::registerStream( uint32_t streamID ){ + //Check if stream is not allready exists + //for ( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ){ + // if ( (*idx)->CTX->mediaStreamId == streamID ) return true; + //}; + + try { + streamHandler * tData = m_mapHANDLERS.at( streamID ); + if( tData!= NULL ) return true; + } catch (const std::out_of_range& oor ) { + //std::cerr << "Out of Range error: " << oor.what() << '\n'; + m_mapHANDLERS[streamID] = new streamHandler( this ); + if ( m_mapHANDLERS[streamID] != NULL ) return m_mapHANDLERS[streamID]->create( streamID ); + }; + return false; +}; + +bool argusModuleEmbedVideo::unregisterStream( uint32_t streamID ){ + return true; +}; + +#undef LOG +#undef LOG_ERROR + +#define LOG( X ) streamHandler::m_pLog->Log( "MEV_STR", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, X ); +#endif + + +streamHandler::streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() { + m_pLog = basicLogCollection::getInstance( ); + memset( &m_sStreamData, 0, sizeof( DBC_MEDIA_STREAM_DATA ) ); + m_pSource = NULL; +#ifdef EVE_ENABLE_VIDEO + m_nPreAlarmFrames = 0; + m_nPostAlarmFrames = 0; + m_nSegAFrameCounter = 0; + m_nSegBFrameCounter = 0; + m_nGlobalFrameCounter = 0; + m_nVideoRegisteredDBID = 0; + m_nAlarmShiftFrames = 0; + m_nNoAlarmSegmentFrames = 0; + m_nHardLimitFrames = 0; + m_bActiveEncoderStream = 0; + m_bActiveSegmentNoDelete = false; + m_bSegAActive = false; + m_bSegBActive = false; +#endif //EVE_ENABLE_VIDEO +}; + +streamHandler::~streamHandler(){ + LOG("DESTRUCT!"); + if ( m_sStreamData.id ) { + if (m_pMaster != NULL) m_pMaster->unregisterStream(m_sStreamData.id); + if ( m_pSource != NULL ) { + switch( m_sStreamData.source_type[0] ) { + case 'D': delete( ( videoLIVE555Source *) m_pSource ); break; + case 'A': delete( ( videoAVLIBSource *) m_pSource ); break; + }; + }; +#ifdef EVE_ENABLE_VIDEO + closeAll(); +#endif //EVE_ENABLE_VIDEO + }; + +}; + +bool streamHandler::create( uint32_t stremID ){ + if( stremID ) { + DBC_MEDIA_STREAM_DATA *tData = argusDBC::getInstance()->getMediaStreamData( stremID ); + if ( tData ) { + memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); + free(tData); + DBC_CAM_DATA *tCAM = argusDBC::getInstance()->getCamData( m_sStreamData.source_id ); + if( tCAM ){ + CSTR tNAM = argusDBC::getInstance()->getNodeName( tCAM->node_id ); + m_sSourceDesc.mediaStreamId = stremID; + m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; + if ( tNAM!= NULL ) { + strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); + m_sSourceDesc.mediaName[127] = (char)0; + free( tNAM ); + } else { + sprintf(m_sSourceDesc.mediaName, "No Name Cam"); + }; + + switch( m_sStreamData.source_type[0] ) { + case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break; + case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break; + }; + if( m_pSource != NULL ) { + char tMRL[1024]; + #ifdef DEBUG + LOG("Source OK"); + #endif + int tW = m_pMaster->getWidh(); + int tH = m_pMaster->getHeight(); + int pix = -1; + bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 ); + bool out_16_9 = (((tW*100) / tH ) > 140 ); + //if( tW > 0 ){ + // //m_pSource->setProportionalByWidth( tW ); + // m_pSource->setSize( tW, tH ); + //}; + if( in_16_9 != out_16_9 ){ + if( in_16_9 ){ + tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000; + } else { + tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000; + }; + }; + if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) { + sprintf( tMRL, m_sStreamData.mrl ); + } else { + sprintf( tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl ); + }; + LOG( tMRL ); + if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){ + if( !m_pSource->attachDestination( this ) ){ + delete( m_pSource ); + m_pSource = NULL; + } else { +#ifdef DEBUG + LOG("Source is Connected to Output."); +#endif + }; + } else { + LOG_ERROR("Can not Open Video Source!"); + delete( m_pSource ); + m_pSource = NULL; + }; + } else { + LOG_ERROR("Video Source Stream Failure!"); + }; + free( tCAM ); + } else { + LOG_ERROR("Error Getting CAM Data!"); + m_pSource = NULL; + return false; + }; + }; + }; + + if( m_pSource ){ +#ifdef EVE_ENABLE_VIDEO + return initVideoOutput(); +#else + return true; +#endif // EVE_ENABLE_VIDEO + }; + + return false; +}; + +bool streamHandler::pushFrame( AVFrame *Frame, void* src){ + if( m_pMaster == NULL ) return false; + MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src; + if( tMD ) { + }; + return true; +}; + +bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ + if( m_pMaster == NULL ) return false; + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + char tBuffer[128]; + if( tMD ) { + float mK, oK; + cv::Rect ROI; + + m_pMaster->m_mPictureProtector.lock(); + + if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) { + LOG("First Frame Enqueued"); + sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId ); + LOG( tBuffer ); + + m_pMaster->m_mapMATS[tMD->mediaStreamId].create( + m_pMaster->m_sEmbedVideoData.height, + m_pMaster->m_sEmbedVideoData.width, + CV_8UC3 + ); + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( 0, 0 ), + cv::Point( + m_pMaster->m_sEmbedVideoData.height, + m_pMaster->m_sEmbedVideoData.width + ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; +#ifdef USE_SCALING_IN + oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width); + mK = ((float)Frame.rows )/ ((float)Frame.cols); + //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); + if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.x = (int) 0; + ROI.y = (int) 0; + } else { + if( mK < oK ) { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK ); + ROI.x = (int) 0; + ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1; + } else { + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK ); + ROI.y = (int) 0; + ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1; + }; + }; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR ); +#else + if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){ + Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] ); + } else { + //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows)); + //src.copyTo(dst_roi); + + if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = 0; + ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + Frame.copyTo(mROI); + } else { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1; + ROI.y = 0; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + Frame.copyTo(mROI); + }; + }; +#endif + if( m_pMaster->m_sEmbedVideoData.show_label ){ + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + char tsb[64]; + if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ + + sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); + int baseline=0; + cv::Size textSize = cv::getTextSize( tBuffer, + m_pMaster->m_sEmbedVideoData.label_font_face, + m_pMaster->m_sEmbedVideoData.label_font_scale, + m_pMaster->m_sEmbedVideoData.label_font_thickness, + &baseline + ); + int x = m_pMaster->m_sEmbedVideoData.label_x; + int y = m_pMaster->m_sEmbedVideoData.label_y; + if( x < 0 ) { + x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width; + }; + if( y < 0 ) { + y = m_pMaster->m_sEmbedVideoData.height+y-baseline;// + }; + if( !m_pMaster->m_sEmbedVideoData.label_transperant ) { + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( x, y ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, + m_pMaster->m_sEmbedVideoData.label_font_scale, + cv::Scalar( 0, 255, 0 ), + m_pMaster->m_sEmbedVideoData.label_font_thickness, + m_pMaster->m_sEmbedVideoData.label_line_type + ); + }; + }; + } else { + if( m_pMaster->m_sEmbedVideoData.show_ts ){ + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){ + uint8_t shift_x = 0; + uint8_t shift_y = 15; + if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) { + if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { + shift_y = 15; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x, + m_pMaster->m_sEmbedVideoData.ts_y + ), + cv::Point( 490, 60 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + } else { + shift_y = 23; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x, + m_pMaster->m_sEmbedVideoData.ts_y + ), + cv::Point( 490, 60 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 255, 255 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + } else { + if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { + shift_y = 15; + } else { + shift_y = 23; + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 255, 255 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + } + }; + }; + }; + }; + if( m_pMaster->m_sEmbedVideoData.show_logo ){ + cv::Rect roi( + cv::Point( + m_pMaster->m_sEmbedVideoData.logo_x, + m_pMaster->m_sEmbedVideoData.logo_y + ), + cv::Size( + m_pMaster->m_sEmbedVideoData.logo_w, + m_pMaster->m_sEmbedVideoData.logo_h + ) + ); + cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi ); + m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask ); + }; + + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality ); + + m_pMaster->m_mEncodedProtector.lock(); + + m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); + cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); + m_pMaster->m_mEncodedProtector.unlock(); + +#ifdef EVE_ENABLE_VIDEO + // encode Video Stream + + + //m_nPreAlarmFrames + //m_nPostAlarmFrames + //m_nNoAlarmSegmentFrames + //m_nHardLimitFrames + + if ( m_bSegAActive || m_bSegBActive ) { + + m_mFrameCounterProtector.lock(); + //if ( ( m_nGlobalFrameCounter % 15 ) == 0 ) { + // char tB[64]; + // m_mEncodingQueueProtector.lock(); + // sprintf( tB, "in Queue %d Frames", m_qEncodingQueue.size() ); + // m_mEncodingQueueProtector.unlock(); + // LOG( tB ); + //}; + if (m_bSegAActive) { + if( m_nSegAFrameCounter > m_nHardLimitFrames ){ + closeSegmentA(); + } else { + int vCNT = m_nSegAFrameCounter - m_nAlarmShiftFrames; + + }; + } else { + + }; + if( m_bSegBActive ) { + if ( m_nSegBFrameCounter > m_nHardLimitFrames ) { + closeSegmentB(); + } else { + int vCNT = m_nSegBFrameCounter - m_nAlarmShiftFrames; + + }; + } else { + + }; + m_mFrameCounterProtector.unlock(); + + ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER)); + if ( tData ) { + tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize(); + tData->linesize[1] = 0; + tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; + tData->size = tData->linesize[0]*tData->rows; + tData->data[1] = NULL; + tData->data[0] = (uint8_t *)malloc( tData->size ); + if ( tData->data[0] ) { + memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size ); + m_mEncodingQueueProtector.lock(); + m_qEncodingQueue.push( tData ); + m_mEncodingQueueProtector.unlock(); + } else { + free( tData ); + }; + }; + /* + const uint8_t* dataPTR[2]; + dataPTR[0] = (uint8_t *) m_pMaster->m_mapMATS[tMD->mediaStreamId].data; + dataPTR[1] = NULL; + sws_scale( m_pConvertCtx, + dataPTR, + linesize, + 0, + m_pMaster->m_mapMATS[tMD->mediaStreamId].rows, + m_pAVFrame->data, + m_pAVFrame->linesize + ); + int bGotPacket; + + if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) { + m_pAVFrame->key_frame = 1; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; + }; + + m_pAVFrame->pts = m_nGlobalFrameCounter + 1;//( m_nCurrentSegmentFrames % m_sStreamData.fps ) + 1; + + AVPacket mPacket; + + av_init_packet( &mPacket ); + / * + int ret = 0; + do { + if( ret == AVERROR(EAGAIN) ){ + av_packet_unref( &mPacket ); + ret = avcodec_receive_packet( m_pCodecCtx, &mPacket ); + if( ret ) break; // deal with error + av_write_frame( m_pFormatCtxA, &mPacket ); + } //else if(ret) deal with error + ret = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + } while(ret); + * / + //* + mPacket.data = NULL; + mPacket.size = 0; + avcodec_encode_video2( m_pCodecCtx, &mPacket, m_pAVFrame, &bGotPacket ); + if( bGotPacket ){ + //char bobo[64]; + //if( m_pCodecCtx->coded_frame->key_frame ) { + // mPacket.flags |= AV_PKT_FLAG_KEY; + // sprintf( bobo, "k-frame [%d]", m_nCurrentSegmentFrames ); + // LOG( bobo ); + //} else { + // sprintf( bobo, "n-frame [%d]", m_nCurrentSegmentFrames ); + // LOG( bobo ); + //}; + // write packet + if ( m_bSegAActive ) { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + //av_packet_rescale_ts( &mPacket, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket ) < 0 ) LOG_ERROR( "Trouble with Video Output!" ); + if( av_write_frame( m_pFormatCtxA, &mPacket ) < 0 ) LOG_ERROR("Trouble with Video Output A!"); + m_nSegAFrameCounter++; + }; + if ( m_bSegBActive ) { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + //av_packet_rescale_ts( &mPacket, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket ) < 0 ) LOG_ERROR( "Trouble with Video Output!" ); + if( av_write_frame( m_pFormatCtxB, &mPacket) < 0 ) LOG_ERROR("Trouble with Video Output B!"); + m_nSegBFrameCounter++; + }; + av_packet_unref( &mPacket ); + m_nGlobalFrameCounter++; + }; + // av_free_packet(&mPacket); + //*/ + + }; + +#endif // EVE_ENABLE_VIDEO + m_pMaster->m_mPictureProtector.unlock(); + } else { + LOG_ERROR("No PayLoad!"); + }; + return true; +}; + +void streamHandler::closeSegmentA( void ){ + m_mCurrentOperationProtector.lock(); + if ( m_bCOP == 0 ) m_bCOP = 0x01; + m_mCurrentOperationProtector.unlock(); + LOG("Closing Stream A"); +}; + +void streamHandler::closeSegmentB( void ){ + m_mCurrentOperationProtector.lock(); + if ( m_bCOP == 0 ) m_bCOP = 0x02; + m_mCurrentOperationProtector.unlock(); + LOG("Closing Stream B"); +}; + +void streamHandler::closeAll(){ + waitThreadEnd( true ); + avcodec_send_frame( m_pCodecCtx, NULL ); + int ret = 0; + AVPacket *avp = av_packet_alloc(); + if ( avp ) { + do { + av_packet_unref( avp ); + ret = avcodec_receive_packet( m_pCodecCtx, avp ); + if ( !ret ) { + if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp ); + if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp ); + }; + } while ( !ret ); + av_packet_unref( avp ); + av_packet_free( &avp ); + }; + if ( m_bSegAActive ) { + av_write_trailer(m_pFormatCtxA); + avformat_close_input( &m_pFormatCtxA ); + m_bSegAActive = false; + }; + if ( m_bSegBActive ) { + av_write_trailer(m_pFormatCtxB); + avformat_close_input( &m_pFormatCtxB ); + m_bSegBActive = false; + }; +}; + +bool streamHandler::openSegmentA( void ){ + CSTR tAM = getUniqID_MD5(); + m_bSegAActive = false; + if ( tAM ) { + sprintf( m_cSegNameA, "%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + free( tAM ); + if ( avio_open( &m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE ) < 0 ){ + LOG_ERROR("Could not open output file."); + return m_bSegAActive; + }; + if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegAActive; + }; + m_nSegAFrameCounter = 0; + m_bSegAActive = true; + }; + return m_bSegAActive; +}; + +bool streamHandler::openSegmentB( void ){ + CSTR tAM = getUniqID_MD5(); + m_bSegBActive = false; + if ( tAM ) { + sprintf( m_cSegNameB, "%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + free( tAM ); + if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ + LOG_ERROR("Could not open output file."); + return m_bSegBActive; + }; + if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegBActive; + }; + m_nSegBFrameCounter = 0; + m_bSegBActive = true; + }; + return m_bSegBActive; +}; + +bool streamHandler::initVideoOutput(){ + m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nNoAlarmSegmentFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; + + if( !initLibAV() ) return false; + + m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); + + if ( m_pFormat == NULL ) { + LOG_ERROR("Out VideoFormat Not Found!"); + return false; + } else { + LOG("Output video Format"); + LOG( VIDEO_OUTPUT_CONTAINER ); + }; + + if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX A alloc error!"); + av_free( m_pFormat ); + return false; + } else { + av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX B alloc error!"); + avformat_free_context( m_pFormatCtxA ); + av_free( m_pFormat ); + return false; + } else { + av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); + if( m_pVideoCodec == NULL ){ + LOG_ERROR("Out VideoCodec Not Found!"); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + av_free( m_pFormat ); + return false; + } else { + LOG("Out Video Codec Found"); + }; + + m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec ); + if ( m_pCodecCtx == NULL){ + LOG_ERROR("Out VideoCodec Context Memory Allocation Error"); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + av_free( m_pFormat ); + return false; + } else { + LOG("Out Codec Context3 Allocated"); + }; + + m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec ); + if ( m_pVideoStrA == NULL){ + LOG_ERROR("VideoStream A Not Created!"); + avcodec_free_context( &m_pCodecCtx ); + av_free( m_pCodecCtx ); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + av_free( m_pFormat ); + return false; + }else{ + LOG("VideoStream A is Created"); + }; + + m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec ); + if ( m_pVideoStrB == NULL){ + LOG_ERROR("VideoStream B Not Created!"); + avcodec_free_context( &m_pCodecCtx ); + av_free( m_pCodecCtx ); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + av_free( m_pFormat ); + return false; + } else { + LOG("VideoStream B is Created"); + }; + + m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + //m_pCodecCtx->thread_count = 1; + //m_pCodecCtx->bit_rate_tolerance = 1; + //m_pCodecCtx->global_quality = 100; + //m_pCodecCtx->compression_level = 2; + m_pCodecCtx->max_b_frames=1; + m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecCtx->time_base.num = 1; + m_pCodecCtx->time_base.den = m_sStreamData.fps; + m_pCodecCtx->framerate.num = m_sStreamData.fps; + m_pCodecCtx->framerate.den = 1; + + //https://pastebin.com/yG37YhWW + + //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec + //G@ avcodec encode NALU mp4 + +#if (LIBAVCODEC_VERSION_MAJOR > 54) + m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); +#endif + m_pFormatOpts = NULL; + + // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + + if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){ + LOG("Begin Options!"); + //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + //Set format's privater options, to be passed to avformat_write_header() + + /* + + mp4 muxer AVOptions: + -movflags E..... MOV muxer flags (default 0) + rtphint E..... Add RTP hint tracks + empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) + frag_keyframe E..... Fragment at video keyframes + separate_moof E..... Write separate moof/mdat atoms for each track + frag_custom E..... Flush fragments on caller requests + isml E..... Create a live smooth streaming feed (for pushing to a publishing point) + faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file + omit_tfhd_offset E..... Omit the base data offset in tfhd atoms + -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) + -rtpflags E..... RTP muxer flags (default 0) + latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC + rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 + skip_rtcp E..... Don't send RTCP sender reports + h264_mode0 E..... Use mode 0 for H264 in RTP + send_bye E..... Send RTCP BYE packets when finishing + -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) + -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) + -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) + -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) + -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) + -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) + -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) + -use_editlist E..... use edit list (from -1 to 1) (default -1) + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ + if( av_dict_set( &m_pFormatOpts, "movflags", "frag_keyframe+empty_moov", 0 ) < 0 ){ + LOG_ERROR( "av_dict_set movflags!"); + } else { + LOG("MOV FLAG SET!"); + }; + + //default brand is "isom", which fails on some devices + if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){ + LOG_ERROR( "av_dict_set brand!" ); + }; + //m_pCodecCtx->max_b_frames = 1; + //m_pCodecCtx->level = 31; + + m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecCtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3–5 ref per P] + m_pCodecCtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0); + //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 ); + + LOG("End Options!"); + } else { + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + }; + + + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + + m_pVideoStrA->time_base = m_pCodecCtx->time_base; + m_pVideoStrB->time_base = m_pCodecCtx->time_base; + + //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); + + //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width; + //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height; + //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec ); + + //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width; + //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height; + //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx ); + //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata; + //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx ); + //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata; + //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + if ( avcodec_is_open( m_pCodecCtx ) == 0 ) { + LOG("output codec context is closed, opening"); + if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) { + LOG_ERROR("Error opening2 encoder"); + return false; + }; + } else { + LOG("output codec context is opened"); + }; + m_pConvertCtx = sws_getContext( + m_pMaster->m_sEmbedVideoData.width, + m_pMaster->m_sEmbedVideoData.height, + AV_PIX_FMT_BGR24, + m_pMaster->m_sEmbedVideoData.width, + m_pMaster->m_sEmbedVideoData.height, + VIDEO_OUTPUT_PIX_FMT, + SWS_FAST_BILINEAR, + NULL, + NULL, + NULL + ); + if ( m_pConvertCtx == NULL ) { + return false; + } + m_pAVFrame = av_frame_alloc(); + if ( m_pAVFrame == NULL ) { + return false; + }; + m_pOutBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN)); + if( m_pOutBuffer == NULL ) { + return false; + }; + m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width; + m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height; + m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT; + //avpicture_fill ((AVPicture *) picture, picture_buf, pix_fmt, width, height); + av_image_fill_arrays ( m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1 ); + //avpicture_fill((AVPicture *)m_pAVFrame, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height ); + + return init(); +}; + +//encoding thread + +void streamHandler::m_fThreadProc( void ){ + AVPacket mPacket; + int bGotPacket; + int rVal = 0; + + av_init_packet( &mPacket ); + while( m_bThreadStatus != TH_ENDED ){ + //At the begining All streams are closed --> try to Open + if( m_bThreadStatus < TH_WORKING ){ + if( !openSegmentA() ){ + m_bThreadStatus = TH_ENDED; + continue; + }; + if( !openSegmentB() ){ + m_bThreadStatus = TH_ENDED; + continue; + }; + m_bThreadStatus = TH_WORKING; + continue; + }; + + m_mCurrentOperationProtector.lock(); + switch ( m_bCOP ) { + case 0x01:{ + m_bSegAActive = false; + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); + + LOG("Stream A is Closed"); + //m_bThreadStatus = TH_ENDED; + //m_mCurrentOperationProtector.unlock(); + continue; + + break; + }; + case 0x02:{ + m_bSegBActive = false; + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); + + LOG("Stream B is Closed"); + //m_bThreadStatus = TH_ENDED; + //m_mCurrentOperationProtector.unlock(); + //continue; + + break; + }; + }; + m_bCOP = 0; + m_mCurrentOperationProtector.unlock(); + + m_mEncodingQueueProtector.lock(); + if ( m_qEncodingQueue.size() ) { + ENCODING_BUFFER *tData = m_qEncodingQueue.front(); + if( tData ){ + sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize ); + free( tData->data[0] ); + free( tData ); + m_qEncodingQueue.pop(); + + if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) { + m_pAVFrame->key_frame = 1; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; + }; + m_pAVFrame->pts = m_nGlobalFrameCounter + 1; + + rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + }; + }; + m_mEncodingQueueProtector.unlock(); + + if ( rVal == AVERROR(EAGAIN) ) { + mPacket.data = NULL; + mPacket.size = 0; + rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket ); + if ( !rVal ){ + if ( m_bSegAActive ) { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + if( av_write_frame( m_pFormatCtxA, &mPacket ) < 0 ){ + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output A!"); + continue; + }; + m_nSegAFrameCounter++; + }; + if ( m_bSegBActive ) { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + if( av_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output B!"); + continue; + }; + m_nSegBFrameCounter++; + }; + av_packet_unref( &mPacket ); + + m_mFrameCounterProtector.lock(); + m_nGlobalFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + }; + + // + //int ret = 0; + //do { + // if( ret == AVERROR(EAGAIN) ){ + // av_packet_unref( &mPacket ); + // ret = avcodec_receive_packet( m_pCodecCtx, &mPacket ); + // if( ret ) break; // deal with error + // av_write_frame( m_pFormatCtxA, &mPacket ); + // } //else if(ret) deal with error + // ret = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + //} while(ret); + + /* + avcodec_encode_video2( m_pCodecCtx, &mPacket, m_pAVFrame, &bGotPacket ); + if( bGotPacket ){ + //char bobo[64]; + //if( m_pCodecCtx->coded_frame->key_frame ) { + // mPacket.flags |= AV_PKT_FLAG_KEY; + // sprintf( bobo, "k-frame [%d]", m_nCurrentSegmentFrames ); + // LOG( bobo ); + //} else { + // sprintf( bobo, "n-frame [%d]", m_nCurrentSegmentFrames ); + // LOG( bobo ); + //}; + // write packet + if ( m_bSegAActive ) { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + //av_packet_rescale_ts( &mPacket, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket ) < 0 ) LOG_ERROR( "Trouble with Video Output!" ); + if( av_write_frame( m_pFormatCtxA, &mPacket ) < 0 ){ + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output A!"); + continue; + }; + m_nSegAFrameCounter++; + }; + if ( m_bSegBActive ) { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + //av_packet_rescale_ts( &mPacket, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket ) < 0 ) LOG_ERROR( "Trouble with Video Output!" ); + if( av_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output B!"); + continue; + }; + m_nSegBFrameCounter++; + }; + av_packet_unref( &mPacket ); + + m_mFrameCounterProtector.lock(); + m_nGlobalFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + */ + }; + LOG("Encoder Loop Ended!"); + if ( m_bSegAActive ) { + m_bSegAActive = false; + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); + }; + if ( m_bSegBActive ) { + m_bSegBActive = false; + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); + }; + LOG("Encoder Streams are Closed!"); +}; + + #undef LOG #undef LOG_ERROR #undef TLOG diff --git a/lib/rgoose/rgooseModuleEmbedVideo.h b/lib/rgoose/rgooseModuleEmbedVideo.h index 1b7f5de2..4583d374 100644 --- a/lib/rgoose/rgooseModuleEmbedVideo.h +++ b/lib/rgoose/rgooseModuleEmbedVideo.h @@ -5,14 +5,20 @@ #include "../components/base/basicThread.h" #include "../components/base/basicEventHeap.h" //#include "../data/media/video/videoAVLIBDestination.h" +#include "../components/base/basicMediaSource.h" #include "../components/base/basicMediaDestination.h" class argusModuleEmbedVideo; #define FILESTREAMBUFFERSZ 1048576 +#define EVE_ENABLE_VIDEO + //#define USE_SCALING_IN + +#ifdef EVE_ENABLE_VIDEO + /* Video CODECS */ #define VC_VPX 0 #define VC_X264 1 @@ -38,55 +44,62 @@ class argusModuleEmbedVideo; #define VP_VERYSLOW 5 #define VP_ULTRASLOW 6 -#define VIDEO_OUTPUT VO_MJPEG +#define VO_MJPEG 1 +#define VO_MPEG4 2 +#define VO_H264 3 +#define VO_H265 4 +#define VO_FLV 5 + +//#define VIDEO_OUTPUT VO_MJPEG //#define VIDEO_OUTPUT VO_MPEG4 -//#define VIDEO_OUTPUT VO_H264 +#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 30 +//#define VIDEO_OUTPUT_WIDTH 640 //1920 +//#define VIDEO_OUTPUT_HEIGHT 480 //1080 +//#define VIDEO_OUTPUT_FPS 10 +//#define VIDEO_OUTPUT_GOP 15 #if( LIBAVCODEC_VERSION_MAJOR < 54 ) - //#define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG - //#define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P + #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_YUVJ422P - #define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" - #define VIDEO_OUTPUT_BITRATE 4000000 - #define VIDEO_OUTPUT_CONTAINER "mjpeg" - /* - #endif - #if( VIDEO_OUTPUT == VO_MPEG4 ) - - #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 - #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #if VIDEO_OUTPUT == VO_MJPEG + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUVJ422P + #define VIDEO_OUTPUT_CONTAINER_LONG "mpeg" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "webm" + #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 100000000 - #define VIDEO_OUTPUT_CONTAINER "mp4" - //* - #endif - #if( VIDEO_OUTPUT == VO_H264 ) - //* / + #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 100000000 - #define VIDEO_OUTPUT_CONTAINER_LONG "matroska" - #define VIDEO_OUTPUT_CONTAINER "mkv" - /* - #endif - #if( VIDEO_OUTPUT == VO_FLV ) - #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 - #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P - #define VIDEO_OUTPUT_BITRATE 4000000 - #define VIDEO_OUTPUT_CONTAINER "flv" + #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" #endif - */ #endif +#endif //EVE_ENABLE_VIDEO + typedef struct S_buffer_data { uint8_t * buf; int size; @@ -98,6 +111,8 @@ typedef struct S_buffer_data { #define AVIO_BUFFER_SIZE 4096 #define BD_BUFFER_SIZE 1024 +class streamHandler; + typedef struct S_WEB_CLIENT_CTX{ int m_iSocketFID; int m_iEncoderPipe[2]; @@ -105,6 +120,7 @@ typedef struct S_WEB_CLIENT_CTX{ bool initDone; bool headerIsSent; uint32_t mediaStreamId; + streamHandler * m_pHandler; argusModuleEmbedVideo * ModulePtr; }WEB_CLIENT_CTX; @@ -120,6 +136,8 @@ typedef struct S_WEB_HANDLER{ }WEB_HANDLER; typedef vector vectorHANDLERS; + + //typedef vector vectorSTREAMS; typedef struct S_STREAM_CAP{ @@ -132,8 +150,101 @@ typedef vector compressedFRAME; typedef map mapSTREAMCAPS; typedef map mapSTREAMMAPS; +class argusModuleEmbedVideo; + +#define PRE_ALARM_TIME_MILSECONDS 2000 // 2 sec +#define POST_ALARM_TIME_MILSECONDS 2000 // 2 sec +#define ENCODING_SEGMENT_MILSECONDS 10000 // 10 sec +#define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute -class argusModuleEmbedVideo: public argusKernelModule, public basicMediaDestination, public basicThread { +#ifdef EVE_ENABLE_VIDEO + + typedef struct S_ENCODING_BUFFER{ + int linesize[2]; + int rows; + uint8_t * data[2]; + size_t size; + }ENCODING_BUFFER; + + typedef std::queue Q_ENCODING_BUFFER; + +#endif +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; + argusModuleEmbedVideo * m_pMaster; + MS_WORK_MODE m_eWM; + +#ifdef EVE_ENABLE_VIDEO + basicMutex m_mFrameCounterProtector; + uint32_t m_nPreAlarmFrames; + uint32_t m_nPostAlarmFrames; + uint32_t m_nGlobalFrameCounter; + uint32_t m_nVideoRegisteredDBID; + uint32_t m_nSegAFrameCounter; + uint32_t m_nSegBFrameCounter; + uint32_t m_nAlarmShiftFrames; + uint32_t m_nNoAlarmSegmentFrames; + uint32_t m_nHardLimitFrames; + uint8_t m_bActiveEncoderStream; + bool m_bActiveSegmentNoDelete; + bool m_bSegAActive; + bool m_bSegBActive; + basicMutex m_mCurrentOperationProtector; + uint8_t m_bCOP; + char m_cSegNameA[64]; + char m_cSegNameB[64]; + // encoding video stuff + AVCodec * m_pVideoCodec; + AVCodecContext * m_pCodecCtx; + SwsContext * m_pConvertCtx; + AVFrame * m_pAVFrame; + uint8_t * m_pOutBuffer; + // File Context 2 units + AVOutputFormat * m_pFormat; + AVFormatContext * m_pFormatCtxA; + AVFormatContext * m_pFormatCtxB; + AVStream * m_pVideoStrA; + AVStream * m_pVideoStrB; + //common output options + AVDictionary * m_pFormatOpts; + + basicMutex m_mEncodingQueueProtector; + Q_ENCODING_BUFFER m_qEncodingQueue; + + bool openSegmentA( void ); + void closeSegmentA( void ); + bool openSegmentB( void ); + void closeSegmentB( void ); + void closeAll(); + bool initVideoOutput(); + protected: + void m_fThreadProc( void ); +#endif //EVE_ENABLE_VIDEO + + public: + explicit streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M = MS_MODE_DECODE_FRAMES ); + virtual ~streamHandler(); + bool create( 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); +}; + +typedef map mapSTREAMHANDLERS; + +class argusModuleEmbedVideo: public argusKernelModule, /*public basicMediaDestination,*/ public basicThread { private: basicEventHeap * m_pEventHeap; static void * webClientProc( void *ptr ); @@ -145,6 +256,7 @@ class argusModuleEmbedVideo: public argusKernelModule, public basicMediaDestinat DBC_MODULE_EMBED_VIDEO_DATA m_sEmbedVideoData; mapSTREAMCAPS m_mapCAPTURES; mapSTREAMMAPS m_mapMATS; + mapSTREAMHANDLERS m_mapHANDLERS; uint8_t * n_pNoSignalData; uint32_t m_nNoSignalSize; cv::Mat m_mLogoPic; @@ -166,12 +278,17 @@ class argusModuleEmbedVideo: public argusKernelModule, public basicMediaDestinat virtual bool stopService( bool force = false ); virtual void dispatchEvent(EVENT_CONTAINER *Evt); virtual bool validate(); - /* from Media Destination */ + /* 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); /* Module Specific Functionality */ int getWidh( void ); int getHeight( void ); + bool registerStream( uint32_t streamID ); + bool unregisterStream( uint32_t streamID ); + + friend class streamHandler; + }; #endif diff --git a/lib/rgoose/rgooseModuleFactory.cpp b/lib/rgoose/rgooseModuleFactory.cpp index b0780514..135e6093 100644 --- a/lib/rgoose/rgooseModuleFactory.cpp +++ b/lib/rgoose/rgooseModuleFactory.cpp @@ -153,13 +153,25 @@ argusKernelModule *argusModuleFactory::createModule( int id ){ #ifdef DEBUG LOG("Creating OnVif Observer Module"); #endif - tVal = new argusModuleOnvifObserver( tData->module_id ); + if ( m_pDBC->isLocal() ) { + tVal = new argusModuleOnvifObserver(tData->module_id); +#ifdef DEBUG + } else { + LOG("Module is Disabled Since Remote Database!"); +#endif + }; break; case ARGUS_MODULE_EMBED_VIDEO: #ifdef DEBUG LOG("Creating Embed Video Module"); #endif - tVal = new argusModuleEmbedVideo( tData->module_id ); + if ( m_pDBC->isLocal() ){ + tVal = new argusModuleEmbedVideo( tData->module_id ); +#ifdef DEBUG + } else { + LOG("Module is Disabled Since Remote Database!"); +#endif + }; break; case ARGUS_MODULE_MODEM_MANAGER: #ifdef DEBUG diff --git a/lib/rgoose/rgooseModuleVideoRecorder.h b/lib/rgoose/rgooseModuleVideoRecorder.h new file mode 100644 index 00000000..b9cbaa81 --- /dev/null +++ b/lib/rgoose/rgooseModuleVideoRecorder.h @@ -0,0 +1,12 @@ +#ifndef __ARGUS_VIDEO_RECORDER_MODULE_HEADER__ +#define __ARGUS_VIDEO_RECORDER_MODULE_HEADER__ + +#include "rgooseModule.h" +#include + +class argusVideoRecorder: public argusKernelModule{ + public: + argusVideoRecorder(); +}; + +#endif diff --git a/lib/rgoose/rgooseNode2D.cpp b/lib/rgoose/rgooseNode2D.cpp index fd8d6ddd..8c15712c 100644 --- a/lib/rgoose/rgooseNode2D.cpp +++ b/lib/rgoose/rgooseNode2D.cpp @@ -187,7 +187,7 @@ bool ARGUS_2DSensor::startService() { LOG_ERROR("No DATA From Database!"); return false; }; - if( setDeviceID( m_sLRF_DATA.device_id ) ){ + if( setDeviceID( m_sLRF_DATA.device_id ) ){ if( !create() ){ LOG_ERROR("Protocol <<< Create >>> Failure!"); return false; @@ -197,6 +197,14 @@ bool ARGUS_2DSensor::startService() { // LOG_ERROR("Position <<< Create >>> Failure!"); // return false; //}; + switch( m_sNodeData.type ) { + case ARGUS_ALS_SENSOR: + case ARGUS_LFS_SENSOR: m_eSensorClass = EVT_CLASS_SENSOR_LFS; break; + + case ARGUS_PLS_200_SENSOR: + case ARGUS_PLS_360_SENSOR: + case ARGUS_NET_PLS_200: m_eSensorClass = EVT_CLASS_SENSOR_PLS_210; break; + }; systemAnchor * SA = systemAnchor::getInstance(); if( SA ){ @@ -1899,6 +1907,8 @@ CSTR ARGUS_2DSensor::generateSettingFile(){ return RetVal; }; +#include //For DBL_MAX + inline int DBL_CMP( const double& a, const double& b, const double quality = 1e-10 ){ if( fabs(a - b) <= fabs(quality) ) return 0; if( a > b ) return 1; diff --git a/lib/rgoose/rgooseNode3D.cpp b/lib/rgoose/rgooseNode3D.cpp index d1d8c809..f20c1cc5 100644 --- a/lib/rgoose/rgooseNode3D.cpp +++ b/lib/rgoose/rgooseNode3D.cpp @@ -38,35 +38,38 @@ bool argus3DLIDAR::startService(){ LOG_ERROR("No Database Connector Defined!"); return false; }; - systemAnchor *tSYS = systemAnchor::getInstance(); - if ( tSYS == NULL ) { - LOG_ERROR("Can not get System Anchor!"); - return false; - }; -#ifdef DEBUG - char tB[256]; - sprintf( tB, "Pos: x:%.3f y:%.3f z:%.3f", m_sDATA.x , m_sDATA.y, m_sDATA.z ); - LOG( tB ); -#endif - if( tSYS->beLocal() ){ - m_oPosition.setPositionXYZ( m_sDATA.x, m_sDATA.y, m_sDATA.z ); + systemAnchor * SA = systemAnchor::getInstance(); + if( SA ){ + LOG("SysAnchor OK"); + if ( SA->beLocal() ) { + LOG("SysAnchor beLocal!"); + m_oPosition.setPositionXYZ( m_sLRF_DATA.x, m_sLRF_DATA.y, m_sLRF_DATA.z, 0 ); //SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + } else { + LOG("SysAnchor is Global Position System!"); + C3D_DECART LD = SA->getXYZ(); + m_oPosition.setPositionXYZ( LD.x + m_sLRF_DATA.x, LD.y + m_sLRF_DATA.y, LD.z + m_sLRF_DATA.z, SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + }; } else { - int Zone = tSYS->getUTMZone(); - C3D_DECART tpp = tSYS->getXYZ(); - m_oPosition.setPositionXYZ( tpp.x + m_sDATA.x, tpp.y + m_sDATA.y, tpp.z + m_sDATA.z, Zone ); -#ifdef DEBUG - sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); - LOG( tB ); - sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); - LOG( tB ); -#endif + LOG("No SysAnchor!"); + m_oPosition.setPositionXYZ( m_sLRF_DATA.x , m_sLRF_DATA.y, m_sLRF_DATA.z ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); }; - + m_oPosition.updateMatrix(); + + char tB[128]; #ifdef DEBUG - sprintf( tB, "Orientation: x:%.3f y:%.3f z:%.3f", m_sDATA.x_rot , m_sDATA.y_rot, m_sDATA.z_rot ); + sprintf( tB, "Data Pos: %.4f %.4f %.4f", m_sLRF_DATA.x, m_sLRF_DATA.y, m_sLRF_DATA.z ); + LOG( tB ); + sprintf( tB, "Data Pos: %.4f %.4f %.4f", m_sLRF_DATA.x_rot, m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); LOG( tB ); #endif - m_oPosition.setOrientationDeg( m_sDATA.x_rot , m_sDATA.y_rot, m_sDATA.z_rot ); + sprintf( tB, "Sensor Position: %.4f %.4f %.4f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); + LOG( tB ); + sprintf( tB, "Sensor Orientation: %.4f %.4f %.4f", m_oPosition.getRotX_deg() , m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); + LOG( tB ); + // Check if Allredy Working if( m_bThreadStatus > TH_ARMED ){ if( m_bThreadStatus == TH_WORKING ) return true; diff --git a/lib/rgoose/rgooseNodePTZCamControl.cpp b/lib/rgoose/rgooseNodePTZCamControl.cpp index 217e7987..335baf4f 100644 --- a/lib/rgoose/rgooseNodePTZCamControl.cpp +++ b/lib/rgoose/rgooseNodePTZCamControl.cpp @@ -186,7 +186,8 @@ bool ARGUS_PTZCAM::validate(){ return false; }; }*/ - // Validate Stream + // Validate Stream - > moved to Video Encoder! + /* { if( m_sNodeData.aux_parameter ) { #ifdef DEBUG_EXTRA @@ -203,6 +204,7 @@ bool ARGUS_PTZCAM::validate(){ }; }; } + */ return true; }; diff --git a/lib/rgoose/rgooseNodeStaticCamControl.cpp b/lib/rgoose/rgooseNodeStaticCamControl.cpp index a7030c6e..97b8e04f 100644 --- a/lib/rgoose/rgooseNodeStaticCamControl.cpp +++ b/lib/rgoose/rgooseNodeStaticCamControl.cpp @@ -61,7 +61,7 @@ bool ARGUS_CAM::stopService(){ void ARGUS_CAM::dispatchEvent( EVENT_CONTAINER *E ){ if( E == NULL ) return; - if( !m_bSourceConnected ) return; + //if( !m_bSourceConnected ) return; //if( m_bBusy ) return; switch( E->m_eClass ) { case EVT_CLASS_SENSOR_CLD: @@ -160,7 +160,8 @@ bool ARGUS_CAM::validate(){ return false; }; }*/ - // Validate Stream + // Validate Stream -> Moved to Video Encooder + /* { if( m_sNodeData.aux_parameter ) { //LOG("VALIDATE Stream"); @@ -175,6 +176,7 @@ bool ARGUS_CAM::validate(){ }; }; } + */ return true; };