From e3798f99674885a2cc3b215cac7ca24b1175f4f1 Mon Sep 17 00:00:00 2001 From: Evgeny Gagua Date: Thu, 14 Sep 2023 07:38:39 -0700 Subject: [PATCH] Direct MJPEG Writing enabled --- Projects/la_mojo/build | 8 +- lib/App/common/kernelModuleEmbedVideo.cpp | 2149 +++++++++++---------- lib/App/common/kernelModuleEmbedVideo.h | 78 +- 3 files changed, 1165 insertions(+), 1070 deletions(-) diff --git a/Projects/la_mojo/build b/Projects/la_mojo/build index 0d3905e9..59699e61 100755 --- a/Projects/la_mojo/build +++ b/Projects/la_mojo/build @@ -1,11 +1,11 @@ #! /bin/sh -make clean -e "CFG=Debug" -make -e "CFG=Debug" -j6 +#make clean -e "CFG=Debug" +#make -e "CFG=Debug" -j6 -#make clean -e "CFG=Debug86" -#make -e "CFG=Debug86" -j4 +make clean -e "CFG=Debug86" +make -e "CFG=Debug86" -j4 #make clean -e "CFG=Release86" #make -e "CFG=Release86" -j4 diff --git a/lib/App/common/kernelModuleEmbedVideo.cpp b/lib/App/common/kernelModuleEmbedVideo.cpp index db69f436..10037af0 100644 --- a/lib/App/common/kernelModuleEmbedVideo.cpp +++ b/lib/App/common/kernelModuleEmbedVideo.cpp @@ -1194,9 +1194,14 @@ streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_p m_cSourceType = 'A'; memset( &m_sStreamSegmentInfo[0], 0, sizeof(VIDEO_SEGMENT_INFO)); memset( &m_sStreamSegmentInfo[1], 0, sizeof(VIDEO_SEGMENT_INFO)); -#ifdef OPENCV_VIDEO_OUTPUT - m_pEncoderA = NULL; - m_pEncoderB = NULL; +#ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD[0] = NULL; + m_pOutputFD[1] = NULL; +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + m_pEncoderA = NULL; + m_pEncoderB = NULL; + #endif #endif #endif //EVE_ENABLE_VIDEO }; @@ -1843,14 +1848,22 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ tData->flag_sa = SkeepA; tData->flag_sb = SkeepB; #endif - #ifdef OPENCV_VIDEO_OUTPUT + #ifdef DIRECT_MJPEG_COMPOSING + tData->size = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].size(); + //tData->data = (uint8_t *)malloc( tData->size ); + //if ( tData->data ) { + // memcpy( tData->data, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(), tData->size ); + tData->data = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(); + if ( tData->data ) { + #else + #ifdef OPENCV_VIDEO_OUTPUT tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols; tData->size = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize()*tData->rows; tData->data = (uint8_t *)malloc( tData->size ); if ( tData->data ) { memcpy( tData->data, m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size ); - #else //OPENCV_VIDEO_OUTPUT + #else //OPENCV_VIDEO_OUTPUT 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; @@ -1859,7 +1872,8 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ 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 ); - #endif //OPENCV_VIDEO_OUTPUT + #endif //OPENCV_VIDEO_OUTPUT + #endif //!DIRECT_MJPEG_COMPOSING m_mEncodingQueueProtector.lock(); m_qEncodingQueue.push( tData ); m_mEncodingQueueProtector.unlock(); @@ -1914,80 +1928,84 @@ void streamHandler::closeAll(){ }; #else //OPENCV_VIDEO_OUTPUT - #ifdef SEPARATED_VIDEO_ENCODERS - if( ( m_pCodecACtx != NULL || m_pCodecBCtx != NULL ) && (m_bSegAActive || m_bSegBActive )) { - if( m_pCodecACtx != NULL ) { - avcodec_send_frame(m_pCodecACtx, NULL); - int ret = 0; - AVPacket *avp = av_packet_alloc(); - if ( avp ) { - do { + #ifdef DIRECT_MJPEG_COMPOSING + + #else // ! DIRECT_MJPEG_COMPOSING + #ifdef SEPARATED_VIDEO_ENCODERS + if( ( m_pCodecACtx != NULL || m_pCodecBCtx != NULL ) && (m_bSegAActive || m_bSegBActive )) { + if( m_pCodecACtx != NULL ) { + avcodec_send_frame(m_pCodecACtx, NULL); + int ret = 0; + AVPacket *avp = av_packet_alloc(); + if ( avp ) { + do { + av_packet_unref( avp ); + ret = avcodec_receive_packet( m_pCodecACtx, avp ); + if ( !ret ) { + if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp ); + }; + } while ( !ret ); av_packet_unref( avp ); - ret = avcodec_receive_packet( m_pCodecACtx, avp ); - if ( !ret ) { - if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp ); - }; - } while ( !ret ); - av_packet_unref( avp ); - av_packet_free( &avp ); + av_packet_free( &avp ); + }; + }; + if( m_pCodecBCtx != NULL ) { + avcodec_send_frame(m_pCodecBCtx, NULL); + int ret = 0; + AVPacket *avp = av_packet_alloc(); + if ( avp ) { + do { + av_packet_unref( avp ); + ret = avcodec_receive_packet( m_pCodecBCtx, avp ); + if ( !ret ) { + 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; }; }; - if( m_pCodecBCtx != NULL ) { - avcodec_send_frame(m_pCodecBCtx, NULL); + #else // !SEPARATED_VIDEO_ENCODERS + if( m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive )) { + 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_pCodecBCtx, 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; + }; }; - 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; - }; - }; - #else // ! SEPARATED_VIDEO_ENCODERS - if( m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive )) { - 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; - }; - }; - #endif // SEPARATED_VIDEO_ENCODERS + #endif // !SEPARATED_VIDEO_ENCODERS + #endif // !DIRECT_MJPEG_COMPOSING //if( m_pFormat != NULL ) { //av_free( m_pFormat ); //}; @@ -2017,124 +2035,128 @@ bool streamHandler::openSegmentA( void ){ m_sStreamSegmentInfo[0].eventFrames.clear(); m_sStreamSegmentInfo[0].dataSize = 0; m_sStreamSegmentInfo[0].db_id = 0; -#ifdef OPENCV_VIDEO_OUTPUT - if ( m_pEncoderA ) { - //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); - int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - m_bAFrameSkeepDivider = m_bWebFrameSkeepDivider; - m_bAOutputFPS = m_bInitialOutputFPS / m_bAFrameSkeepDivider; - double fps = m_bAOutputFPS; -#else - double fps = m_sStreamData.fps; -#endif - cv::String mn( m_sStreamSegmentInfo[0].scratchPath ); - cv::Size fz( m_sStreamData.width, m_sStreamData.height ); - //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) - if( !m_pEncoderA->open( mn, fourcc, fps, fz ) ){ - LOG_ERROR("Cannot Open Output Segment A!"); +#ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD[0] = fopen( m_sStreamSegmentInfo[0].scratchPath, "wb+" ); +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if ( m_pEncoderA ) { + //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + m_bAFrameSkeepDivider = m_bWebFrameSkeepDivider; + m_bAOutputFPS = m_bInitialOutputFPS / m_bAFrameSkeepDivider; + double fps = m_bAOutputFPS; + #else + double fps = m_sStreamData.fps; + #endif + cv::String mn( m_sStreamSegmentInfo[0].scratchPath ); + cv::Size fz( m_sStreamData.width, m_sStreamData.height ); + //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if( !m_pEncoderA->open( mn, fourcc, fps, fz ) ){ + LOG_ERROR("Cannot Open Output Segment A!"); + return false; + #ifdef DEBUG + } else { + char tB[256]; + sprintf( tB,"VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps ); + LOG( tB ); + #endif + }; + m_bSegAActive = true; + m_bSegADelete = true; + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + } else { + LOG_ERROR("No Encoder(A) Object!"); return false; - #ifdef DEBUG + }; + #else// !OPENCV_VIDEO_OUTPUT + //Check if Encoder is Ready + if ( m_pFormat == NULL ) return false; + + #ifdef SEPARATED_VIDEO_ENCODERS + if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX A alloc error!"); + return false; + } else { + av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoACodec ); + if ( m_pVideoStrA == NULL){ + avformat_free_context( m_pFormatCtxA ); + return false; + #ifdef DEBUG_EXTRA } else { - char tB[256]; - sprintf( tB,"VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps ); - LOG( tB ); + LOG("VideoStream A is Created"); + #endif + }; + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; + m_pVideoStrA->time_base = m_pCodecACtx->time_base; + avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecACtx ); + #ifdef DEBUG_EXTRA + LOG("Opening Stream A"); + LOG(m_cSegNameA); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration ); + LOG( tB ); #endif + //if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, 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_mFrameCounterProtector.lock(); + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; m_bSegAActive = true; m_bSegADelete = true; + //m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1; + if (m_pVideoStrA->nb_frames) { + m_pVideoStrA->nb_frames = 0; + m_pVideoStrA->start_time = 0; + m_pVideoStrA->first_dts = 0; + m_pFormatCtxA->start_time = 0; + }; + #ifdef DEBUG_EXTRA + LOG("Opening Stream A"); + LOG(m_cSegNameA); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration ); + LOG( tB ); + #endif + 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_mFrameCounterProtector.lock(); m_nSegAFrameCounter = 0; m_nSegAShiftFrames = 0; - } else { - LOG_ERROR("No Encoder(A) Object!"); - return false; - }; -#else - //Check if Encoder is Ready - if ( m_pFormat == NULL ) return false; - - #ifdef SEPARATED_VIDEO_ENCODERS - if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { - LOG_ERROR("Format CTX A alloc error!"); - return false; - } else { - av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); - m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; - }; - - m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoACodec ); - if ( m_pVideoStrA == NULL){ - avformat_free_context( m_pFormatCtxA ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("VideoStream A is Created"); - #endif - }; - const AVRational dst_fps = { m_sStreamData.fps, 1 }; - m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; - m_pVideoStrA->time_base = m_pCodecACtx->time_base; - avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecACtx ); - #ifdef DEBUG_EXTRA - LOG("Opening Stream A"); - LOG(m_cSegNameA); - char tB[128]; - sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts ); - LOG( tB ); - sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration ); - LOG( tB ); - #endif - //if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { - if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, 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_mFrameCounterProtector.lock(); - m_nSegAFrameCounter = 0; - m_nSegAShiftFrames = 0; - m_bSegAActive = true; - m_bSegADelete = true; - //m_mFrameCounterProtector.unlock(); - #else // SEPARATED_VIDEO_ENCODERS - m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1; - if (m_pVideoStrA->nb_frames) { - m_pVideoStrA->nb_frames = 0; - m_pVideoStrA->start_time = 0; - m_pVideoStrA->first_dts = 0; - m_pFormatCtxA->start_time = 0; - }; - #ifdef DEBUG_EXTRA - LOG("Opening Stream A"); - LOG(m_cSegNameA); - char tB[128]; - sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts ); - LOG( tB ); - sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration ); - LOG( tB ); - #endif - 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_mFrameCounterProtector.lock(); - m_nSegAFrameCounter = 0; - m_nSegAShiftFrames = 0; - m_bSegAActive = true; - m_bSegADelete = true; - //m_mFrameCounterProtector.unlock(); - #endif // SEPARATED_VIDEO_ENCODERS - #ifdef DEBUG_EXTRA - LOG("Stream A Opened"); - #endif -#endif //OPENCV_VIDEO_OUTPUT + m_bSegAActive = true; + m_bSegADelete = true; + //m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream A Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING }; }; return m_bSegAActive; @@ -2163,119 +2185,122 @@ bool streamHandler::openSegmentB( void ){ m_sStreamSegmentInfo[1].dataSize = 0; m_sStreamSegmentInfo[1].db_id = 0; - -#ifdef OPENCV_VIDEO_OUTPUT - if ( m_pEncoderB ) { - //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); - int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - m_bBFrameSkeepDivider = m_bWebFrameSkeepDivider; - m_bBOutputFPS = m_bInitialOutputFPS / m_bBFrameSkeepDivider; - double fps = m_bBOutputFPS; -#else - double fps = m_sStreamData.fps; -#endif - cv::String mn( m_sStreamSegmentInfo[1].scratchPath ); - cv::Size fz( m_sStreamData.width, m_sStreamData.height ); - //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) - if( !m_pEncoderB->open( mn, fourcc, fps, fz ) ){ - LOG_ERROR("Cannot Open Output Segment B!"); +#ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD[1] = fopen( m_sStreamSegmentInfo[1].scratchPath, "wb+" ); +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if ( m_pEncoderB ) { + //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + m_bBFrameSkeepDivider = m_bWebFrameSkeepDivider; + m_bBOutputFPS = m_bInitialOutputFPS / m_bBFrameSkeepDivider; + double fps = m_bBOutputFPS; + #else + double fps = m_sStreamData.fps; + #endif + cv::String mn( m_sStreamSegmentInfo[1].scratchPath ); + cv::Size fz( m_sStreamData.width, m_sStreamData.height ); + //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if( !m_pEncoderB->open( mn, fourcc, fps, fz ) ){ + LOG_ERROR("Cannot Open Output Segment B!"); + return false; + #ifdef DEBUG + } else { + char tB[256]; + sprintf( tB,"VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps ); + LOG( tB ); + #endif + }; + m_bSegBActive = true; + m_bSegBDelete = true; + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + } else { + LOG_ERROR("No Encoder(B) Object!"); + return false; + }; + #else // !OPENCV + //Check if Encoder is Ready + if ( m_pFormat == NULL ) return false; + #ifdef SEPARATED_VIDEO_ENCODERS + if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX B alloc error!"); return false; - #ifdef DEBUG } else { - char tB[256]; - sprintf( tB,"VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps ); - LOG( tB ); - #endif + av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoBCodec ); + if ( m_pVideoStrB == NULL){ + avformat_free_context( m_pFormatCtxB ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("VideoStream B is Created"); + #endif }; + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + m_pVideoStrB->time_base = m_pCodecBCtx->time_base; + avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecBCtx ); + #ifdef DEBUG_EXTRA + LOG("Opening Stream B"); + LOG( m_cSegNameB ); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration ); + LOG( tB ); + #endif + + //if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ + if ( avio_open( &m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE ) < 0 ){ + LOG_ERROR("Could not open output file."); + avformat_free_context( m_pFormatCtxB ); + return false; + }; + if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + avio_close( m_pFormatCtxB->pb ); + avformat_free_context( m_pFormatCtxB ); + return false; + }; + //m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; m_bSegBActive = true; m_bSegBDelete = true; + //m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1; + if (m_pVideoStrB->nb_frames) { + m_pVideoStrB->nb_frames = 0; + m_pVideoStrB->start_time = 0; + m_pVideoStrB->first_dts = 0; + m_pFormatCtxB->start_time = 0; + }; + 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_mFrameCounterProtector.lock(); m_nSegBFrameCounter = 0; m_nSegBShiftFrames = 0; - } else { - LOG_ERROR("No Encoder(B) Object!"); - return false; - }; -#else - //Check if Encoder is Ready - if ( m_pFormat == NULL ) return false; - #ifdef SEPARATED_VIDEO_ENCODERS - if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { - LOG_ERROR("Format CTX B alloc error!"); - return false; - } else { - av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); - m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; - }; - - m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoBCodec ); - if ( m_pVideoStrB == NULL){ - avformat_free_context( m_pFormatCtxB ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("VideoStream B is Created"); - #endif - }; - const AVRational dst_fps = { m_sStreamData.fps, 1 }; - m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; - m_pVideoStrB->time_base = m_pCodecBCtx->time_base; - avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecBCtx ); - #ifdef DEBUG_EXTRA - LOG("Opening Stream B"); - LOG( m_cSegNameB ); - char tB[128]; - sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts ); - LOG( tB ); - sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration ); - LOG( tB ); - #endif - - //if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ - if ( avio_open( &m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE ) < 0 ){ - LOG_ERROR("Could not open output file."); - avformat_free_context( m_pFormatCtxB ); - return false; - }; - if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){ - LOG_ERROR("Error occurred when writing header to output file."); - avio_close( m_pFormatCtxB->pb ); - avformat_free_context( m_pFormatCtxB ); - return false; - }; - //m_mFrameCounterProtector.lock(); - m_nSegBFrameCounter = 0; - m_nSegBShiftFrames = 0; - m_bSegBActive = true; - m_bSegBDelete = true; - //m_mFrameCounterProtector.unlock(); - #else // SEPARATED_VIDEO_ENCODERS - m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1; - if (m_pVideoStrB->nb_frames) { - m_pVideoStrB->nb_frames = 0; - m_pVideoStrB->start_time = 0; - m_pVideoStrB->first_dts = 0; - m_pFormatCtxB->start_time = 0; - }; - 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_mFrameCounterProtector.lock(); - m_nSegBFrameCounter = 0; - m_nSegBShiftFrames = 0; - m_bSegBActive = true; - m_bSegBDelete = true; - //m_mFrameCounterProtector.unlock(); - #endif // SEPARATED_VIDEO_ENCODERS - #ifdef DEBUG_EXTRA - LOG("Stream B Opened"); - #endif -#endif //OPENCV_VIDEO_OUTPUT + m_bSegBActive = true; + m_bSegBDelete = true; + //m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream B Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING }; }; return m_bSegBActive; @@ -2304,675 +2329,677 @@ bool streamHandler::initVideoOutput(){ m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; #endif -#ifdef OPENCV_VIDEO_OUTPUT - m_pEncoderA = new cv::VideoWriter(); - if ( m_pEncoderA == NULL ) { - LOG_ERROR("Encoder A Create Failure!"); - return false; - }; - - //m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); - //m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); +#ifndef DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + m_pEncoderA = new cv::VideoWriter(); + if ( m_pEncoderA == NULL ) { + LOG_ERROR("Encoder A Create Failure!"); + return false; + }; - m_pEncoderB = new cv::VideoWriter(); - if ( m_pEncoderA == NULL ) { - LOG_ERROR("Encoder B Create Failure!"); - return false; - }; + //m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); + //m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); - //m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); - //m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); + m_pEncoderB = new cv::VideoWriter(); + if ( m_pEncoderA == NULL ) { + LOG_ERROR("Encoder B Create Failure!"); + return false; + }; -#else - if( !initLibAV() ) return false; + //m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); + //m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); - m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); + #else + if( !initLibAV() ) return false; - if ( m_pFormat == NULL ) { - LOG_ERROR("Out VideoFormat Not Found!"); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("Output video Format"); - LOG( VIDEO_OUTPUT_CONTAINER ); - #endif - }; + m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); - #ifdef SEPARATED_VIDEO_ENCODERS - /* Stream A */ - m_pVideoACodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); - if( m_pVideoACodec == NULL ){ - LOG_ERROR("Encoder Video Codec Not Found!"); - return false; + if ( m_pFormat == NULL ) { + LOG_ERROR("Out VideoFormat Not Found!"); + return false; #ifdef DEBUG_EXTRA - } else { - LOG("Video Encoder A Created"); - #endif - }; - m_pCodecACtx = avcodec_alloc_context3( m_pVideoACodec ); - if ( m_pCodecACtx == NULL){ - LOG_ERROR("Video Encoder A Context Memory Allocation Error!"); - av_free( m_pVideoACodec ); - avformat_free_context( m_pFormatCtxA ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("Video Encoder Context A Allocated"); - #endif - }; - /* Stream B */ - m_pVideoBCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); - if( m_pVideoBCodec == NULL ){ - LOG_ERROR("Out VideoCodec Not Found!"); - av_free( m_pVideoACodec ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("Video Encoder B Created"); - #endif - }; - m_pCodecBCtx = avcodec_alloc_context3( m_pVideoBCodec ); - if ( m_pCodecBCtx == NULL){ - LOG_ERROR("Video Encoder B Context Memory Allocation Error!"); - av_free( m_pVideoACodec ); - av_free( m_pVideoBCodec ); - avformat_free_context( m_pFormatCtxA ); - avformat_free_context( m_pFormatCtxB ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("Video Encoder Context B Allocated"); - #endif - }; - - m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC; - m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO; - m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; - m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE; - m_pCodecACtx->max_b_frames=1; - m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width; - m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height; - m_pCodecACtx->time_base.num = 1; - m_pCodecACtx->time_base.den = m_sStreamData.fps; - m_pCodecACtx->framerate.num = m_sStreamData.fps; - m_pCodecACtx->framerate.den = 1; - - m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC; - m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO; - m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; - m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE; - m_pCodecBCtx->max_b_frames=1; - m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width; - m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height; - m_pCodecBCtx->time_base.num = 1; - m_pCodecBCtx->time_base.den = m_sStreamData.fps; - m_pCodecBCtx->framerate.num = m_sStreamData.fps; - m_pCodecBCtx->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_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); + } else { + LOG("Output video Format"); + LOG( VIDEO_OUTPUT_CONTAINER ); #endif + }; - #if (LIBAVCODEC_VERSION_MAJOR > 54) - ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); - #endif - m_pFormatOpts = NULL; + #ifdef SEPARATED_VIDEO_ENCODERS + /* Stream A */ + m_pVideoACodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); + if( m_pVideoACodec == NULL ){ + LOG_ERROR("Encoder Video Codec Not Found!"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Video Encoder A Created"); + #endif + }; + m_pCodecACtx = avcodec_alloc_context3( m_pVideoACodec ); + if ( m_pCodecACtx == NULL){ + LOG_ERROR("Video Encoder A Context Memory Allocation Error!"); + av_free( m_pVideoACodec ); + avformat_free_context( m_pFormatCtxA ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Video Encoder Context A Allocated"); + #endif + }; + /* Stream B */ + m_pVideoBCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); + if( m_pVideoBCodec == NULL ){ + LOG_ERROR("Out VideoCodec Not Found!"); + av_free( m_pVideoACodec ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Video Encoder B Created"); + #endif + }; + m_pCodecBCtx = avcodec_alloc_context3( m_pVideoBCodec ); + if ( m_pCodecBCtx == NULL){ + LOG_ERROR("Video Encoder B Context Memory Allocation Error!"); + av_free( m_pVideoACodec ); + av_free( m_pVideoBCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Video Encoder Context B Allocated"); + #endif + }; + + m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE; + m_pCodecACtx->max_b_frames=1; + m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecACtx->time_base.num = 1; + m_pCodecACtx->time_base.den = m_sStreamData.fps; + m_pCodecACtx->framerate.num = m_sStreamData.fps; + m_pCodecACtx->framerate.den = 1; + + m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + m_pCodecBCtx->max_b_frames=1; + m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecBCtx->time_base.num = 1; + m_pCodecBCtx->time_base.den = m_sStreamData.fps; + m_pCodecBCtx->framerate.num = m_sStreamData.fps; + m_pCodecBCtx->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_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); + #endif + + #if (LIBAVCODEC_VERSION_MAJOR > 54) + ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->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_pCodecACtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecACtx->codec_id == AV_CODEC_ID_H265 ) ){ + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + //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 + delay_moov ?? + -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", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){ + LOG_ERROR( "av_dict_set movflags!"); + #ifdef DEBUG_EXTRA + } else { + LOG("MOV FLAG SET!"); + #endif + }; - // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + //}; - if( ( m_pCodecACtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecACtx->codec_id == AV_CODEC_ID_H265 ) ){ - #ifdef DEBUG_EXTRA - LOG("Begin Options!"); - #endif - //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 - delay_moov ?? - -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", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){ - LOG_ERROR( "av_dict_set movflags!"); - #ifdef DEBUG_EXTRA + //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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->priv_data, "b-pyramid", "0", 0 ); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif } else { - LOG("MOV FLAG SET!"); - #endif + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; }; - //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ - // LOG_ERROR( "av_dict_set live!" ); - //}; - - //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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->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_pCodecACtx->priv_data, "b-pyramid", "0", 0 ); - #ifdef DEBUG_EXTRA - LOG("End Options!"); - #endif - } else { - if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; - }; + if( ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H265 ) ){ + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + //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 + delay_moov ?? + -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) + + + */ + //m_pCodecCtx->max_b_frames = 1; + //m_pCodecCtx->level = 31; + + m_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->priv_data, "b-pyramid", "0", 0 ); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif + } else { + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + }; - if( ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H265 ) ){ - #ifdef DEBUG_EXTRA - LOG("Begin Options!"); - #endif - //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 - delay_moov ?? - -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) - - - */ - //m_pCodecCtx->max_b_frames = 1; - //m_pCodecCtx->level = 31; - - m_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->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 ); + + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + #ifdef DEBUG_EXTRA + char TB[129]; + sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den ); + LOG(TB); + sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den ); + LOG(TB); + #endif + + ////m_pVideoStrA->time_base = m_pCodecACtx->time_base; + ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base; - /// 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_pCodecBCtx->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_pCodecBCtx->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_pCodecBCtx->priv_data, "b-pyramid", "0", 0 ); - #ifdef DEBUG_EXTRA - LOG("End Options!"); - #endif - } else { - if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; - }; - - - - - const AVRational dst_fps = { m_sStreamData.fps, 1 }; - - #ifdef DEBUG_EXTRA - char TB[129]; - sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den ); - LOG(TB); - sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den ); - LOG(TB); - #endif - ////m_pVideoStrA->time_base = m_pCodecACtx->time_base; - ////m_pVideoStrB->time_base = m_pCodecBCtx->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_pVideoStrA->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_pCodecACtx ); + //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_pCodecBCtx ); + //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_pCodecACtx ) == 0 ) { + LOG("output codec context is closed, opening"); + if ( avcodec_open2( m_pCodecACtx, m_pVideoACodec, NULL) < 0 ) { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is opened"); + #endif + }; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is already opened"); + #endif + }; - //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); + if ( avcodec_is_open( m_pCodecBCtx ) == 0 ) { + LOG("output codec context is closed, opening"); + if ( avcodec_open2( m_pCodecBCtx, m_pVideoBCodec, NULL) < 0 ) { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is opened"); + #endif + }; - //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_pVideoStrA->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_pCodecACtx ); - //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_pCodecBCtx ); - //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_pCodecACtx ) == 0 ) { - LOG("output codec context is closed, opening"); - if ( avcodec_open2( m_pCodecACtx, m_pVideoACodec, NULL) < 0 ) { - LOG_ERROR("Error opening2 encoder"); + #ifdef DEBUG + } else { + LOG("output codec context is already opened"); + #endif + }; + #else // SEPARATED_VIDEO_ENCODERS + if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX A alloc error!"); return false; - #ifdef DEBUG_EXTRA } else { - LOG("output codec context is opened"); - #endif + av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; }; - - #ifdef DEBUG_EXTRA - } else { - LOG("output codec context is already opened"); - #endif - }; - if ( avcodec_is_open( m_pCodecBCtx ) == 0 ) { - LOG("output codec context is closed, opening"); - if ( avcodec_open2( m_pCodecBCtx, m_pVideoBCodec, NULL) < 0 ) { - LOG_ERROR("Error opening2 encoder"); + 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 ); return false; - #ifdef DEBUG_EXTRA } else { - LOG("output codec context is opened"); - #endif + 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 ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Out Video Codec Found"); + #endif }; - - #ifdef DEBUG - } else { - LOG("output codec context is already opened"); - #endif - }; - #else // SEPARATED_VIDEO_ENCODERS - if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { - LOG_ERROR("Format CTX A alloc error!"); - 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 ); - 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 ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("Out Video Codec Found"); - #endif - }; - - 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 ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("Out Codec Context3 Allocated"); - #endif - }; - 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_close_input ( &m_pFormatCtxA ); - //avformat_close_input ( &m_pFormatCtxB ); - avformat_free_context( m_pFormatCtxA ); - avformat_free_context( m_pFormatCtxB ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("VideoStream A is Created"); - #endif - }; - 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_close_input ( &m_pFormatCtxA ); - //avformat_close_input ( &m_pFormatCtxB ); - avformat_free_context( m_pFormatCtxA ); - avformat_free_context( m_pFormatCtxB ); - return false; - #ifdef DEBUG_EXTRA - } else { - LOG("VideoStream B is Created"); - #endif - }; - 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 + 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 ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Out Codec Context3 Allocated"); + #endif + }; + 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_close_input ( &m_pFormatCtxA ); + //avformat_close_input ( &m_pFormatCtxB ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("VideoStream A is Created"); + #endif + }; - //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; + 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_close_input ( &m_pFormatCtxA ); + //avformat_close_input ( &m_pFormatCtxB ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("VideoStream B is Created"); + #endif + }; + 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 ) ){ + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + //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 + delay_moov ?? + -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", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){ + LOG_ERROR( "av_dict_set movflags!"); + #ifdef DEBUG_EXTRA + } else { + LOG("MOV FLAG SET!"); + #endif + }; - // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + //}; - if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){ - #ifdef DEBUG_EXTRA - LOG("Begin Options!"); - #endif - //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 - delay_moov ?? - -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", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){ - LOG_ERROR( "av_dict_set movflags!"); - #ifdef DEBUG_EXTRA + //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 ); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif } else { - LOG("MOV FLAG SET!"); - #endif + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; }; - //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ - // LOG_ERROR( "av_dict_set live!" ); - //}; - - //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 ); + + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + #ifdef DEBUG_EXTRA + char TB[129]; + sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den ); + LOG(TB); + #endif + + m_pVideoStrA->time_base = m_pCodecCtx->time_base; + m_pVideoStrB->time_base = m_pCodecCtx->time_base; - /// 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 ); - #ifdef DEBUG_EXTRA - LOG("End Options!"); - #endif - } else { - if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; - }; - - - - const AVRational dst_fps = { m_sStreamData.fps, 1 }; - - #ifdef DEBUG_EXTRA - char TB[129]; - sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den ); - LOG(TB); - #endif - - 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 ); + //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; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is opened"); + #endif + }; - //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; - #ifdef DEBUG_EXTRA + #ifdef DEBUG_EXTRA } else { - LOG("output codec context is opened"); - #endif + LOG("output codec context is already opened"); + #endif }; - - #ifdef DEBUG_EXTRA - } else { - LOG("output codec context is already opened"); - #endif - }; - #endif // SEPARATED_VIDEO_ENCODERS - 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; - //av_frame_get_buffer( m_pAVFrame, 0 ); - 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 ); - - //av_frame_make_writable( m_pAVFrame ); -#endif //OPENCV_VIDEO_OUTPUT + #endif // SEPARATED_VIDEO_ENCODERS + 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; + //av_frame_get_buffer( m_pAVFrame, 0 ); + 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 ); + + //av_frame_make_writable( m_pAVFrame ); + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING return init(); }; @@ -3056,78 +3083,102 @@ void streamHandler::m_fThreadProc( void ){ bool bSkeepA = tData->flag_sa; bool bSkeepB = tData->flag_sb; #endif -#ifdef OPENCV_VIDEO_OUTPUT +#ifdef DIRECT_MJPEG_COMPOSING + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + if( !bSkeepA ) + #endif + if( m_bSegAActive ) if( m_pOutputFD[0] ){ + fwrite( tData->data, 1, tData->size, m_pOutputFD[0] ); + m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + if( !bSkeepB ) + #endif + if( m_bSegBActive ) if( m_pOutputFD[1] ){ + fwrite( tData->data, 1, tData->size, m_pOutputFD[1] ); + m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + // Don't free tData->data since is pointer on static data + //free( tData->data ); + free( tData ); +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT - cv::Mat image( tData->rows, tData->cols, CV_8UC3 ); - memcpy( image.data, tData->data, tData->size ); - free( tData->data ); - free( tData ); -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - if( !bSkeepA ){ -#endif - if (m_bSegAActive) { - if ( m_pEncoderA->isOpened() ) { - m_pEncoderA->write( image ); - m_mFrameCounterProtector.lock(); - m_nSegAFrameCounter++; - m_mFrameCounterProtector.unlock(); + cv::Mat image( tData->rows, tData->cols, CV_8UC3 ); + memcpy( image.data, tData->data, tData->size ); + free( tData->data ); + free( tData ); + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + if( !bSkeepA ){ + #endif + if (m_bSegAActive) { + if ( m_pEncoderA->isOpened() ) { + m_pEncoderA->write( image ); + m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; }; + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS }; -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - }; - if( !bSkeepB ){ -#endif - if ( m_bSegBActive ) { - if ( m_pEncoderB->isOpened() ) { - m_pEncoderB->write( image ); - m_mFrameCounterProtector.lock(); - m_nSegBFrameCounter++; - m_mFrameCounterProtector.unlock(); + if( !bSkeepB ){ + #endif + if ( m_bSegBActive ) { + if ( m_pEncoderB->isOpened() ) { + m_pEncoderB->write( image ); + m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; }; + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS }; -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - }; -#endif -#else // !OPENCV_VIDEO_OUTPUT - //av_frame_make_writable( m_pAVFrame ); - //m_qEncodingQueue.pop(); - //m_mEncodingQueueProtector.unlock(); - sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize ); - free( tData->data[0] ); - free( tData ); - /* - - - AV_PICTURE_TYPE_NONE Undefined. - AV_PICTURE_TYPE_I Intra. - AV_PICTURE_TYPE_P Predicted. - AV_PICTURE_TYPE_B Bi-dir predicted. - AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4. - AV_PICTURE_TYPE_SI Switching Intra. - AV_PICTURE_TYPE_SP Switching Predicted. - AV_PICTURE_TYPE_BI BI type. - - - */ - if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) { - m_pAVFrame->key_frame = 1; - m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; - } else { - m_pAVFrame->key_frame = 0; - m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE; - }; - m_pAVFrame->pts = m_nGlobalFrameCounter + 1; - #ifdef SEPARATED_VIDEO_ENCODERS - //if( m_bSegAActive ) { - rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame ); - //}; - //if( m_bSegBActive ) { - // rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame ); - //}; - #else // SEPARATED_VIDEO_ENCODERS - rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); - #endif // SEPARATED_VIDEO_ENCODERS -#endif // OPENCV_VIDEO_OUTPUT + #endif + #else // !OPENCV_VIDEO_OUTPUT + //av_frame_make_writable( m_pAVFrame ); + //m_qEncodingQueue.pop(); + //m_mEncodingQueueProtector.unlock(); + sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize ); + free( tData->data[0] ); + free( tData ); + /* + + + AV_PICTURE_TYPE_NONE Undefined. + AV_PICTURE_TYPE_I Intra. + AV_PICTURE_TYPE_P Predicted. + AV_PICTURE_TYPE_B Bi-dir predicted. + AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4. + AV_PICTURE_TYPE_SI Switching Intra. + AV_PICTURE_TYPE_SP Switching Predicted. + AV_PICTURE_TYPE_BI BI type. + + + */ + if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) { + m_pAVFrame->key_frame = 1; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; + } else { + m_pAVFrame->key_frame = 0; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE; + }; + m_pAVFrame->pts = m_nGlobalFrameCounter + 1; + #ifdef SEPARATED_VIDEO_ENCODERS + //if( m_bSegAActive ) { + rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame ); + //}; + //if( m_bSegBActive ) { + // rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame ); + //}; + #else // SEPARATED_VIDEO_ENCODERS + rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + #endif // SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING m_mFrameCounterProtector.lock(); m_nGlobalFrameCounter++; m_mFrameCounterProtector.unlock(); @@ -3143,18 +3194,25 @@ void streamHandler::m_fThreadProc( void ){ #endif m_bSegAActive = false; if ( !m_bSegADelete ) { -#ifdef OPENCV_VIDEO_OUTPUT - if ( m_pEncoderA->isOpened() ) { - m_pEncoderA->release(); -#ifdef DEBUG - } else { - LOG(" Encoder A is NOT Opened!"); -#endif +#ifdef DIRECT_MJPEG_COMPOSING + if ( m_pOutputFD[0] ) { + fclose( m_pOutputFD[0] ); + m_pOutputFD[0] = NULL; }; -#else - av_write_trailer( m_pFormatCtxA ); - avio_close( m_pFormatCtxA->pb ); -#endif //OPENCV_VIDEO_OUTPUT +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if ( m_pEncoderA->isOpened() ) { + m_pEncoderA->release(); + #ifdef DEBUG + } else { + LOG(" Encoder A is NOT Opened!"); + #endif + }; + #else + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); + #endif //OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0] ); if ( bEVT ) { basicEventHeap::getInstance()->broadcast( bEVT ); @@ -3163,20 +3221,27 @@ void streamHandler::m_fThreadProc( void ){ LOG("Stream A is Saved"); #endif } else { -#ifdef OPENCV_VIDEO_OUTPUT - if ( m_pEncoderA->isOpened() ) { - m_pEncoderA->release(); -#ifdef DEBUG - } else { - LOG(" Encoder A is NOT Opened!"); -#endif +#ifdef DIRECT_MJPEG_COMPOSING + if ( m_pOutputFD[0] ) { + fclose( m_pOutputFD[0] ); + m_pOutputFD[0] = NULL; }; -#else - #ifdef EVE_DONT_DELETE_SEGMENTS - av_write_trailer( m_pFormatCtxA ); +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if ( m_pEncoderA->isOpened() ) { + m_pEncoderA->release(); + #ifdef DEBUG + } else { + LOG(" Encoder A is NOT Opened!"); #endif - avio_close( m_pFormatCtxA->pb ); -#endif //OPENCV_VIDEO_OUTPUT + }; + #else // !OPENCV + #ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxA ); + #endif + avio_close( m_pFormatCtxA->pb ); + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING #ifndef EVE_DONT_DELETE_SEGMENTS unlink( m_sStreamSegmentInfo[0].scratchPath ); #endif @@ -3184,19 +3249,20 @@ void streamHandler::m_fThreadProc( void ){ LOG("Stream A is Closed!"); #endif }; -#ifdef OPENCV_VIDEO_OUTPUT -#else - #ifdef SEPARATED_VIDEO_ENCODERS - #ifdef DEBUG_EXTRA - LOG("Del FCTX"); - #endif - avformat_free_context( m_pFormatCtxA ); - m_pVideoStrA = NULL; - #ifdef DEBUG_EXTRA - LOG("Del FCTX DONE"); - #endif - #endif // SEPARATED_VIDEO_ENCODERS -#endif +#ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Del FCTX"); + #endif + avformat_free_context( m_pFormatCtxA ); + m_pVideoStrA = NULL; + #ifdef DEBUG_EXTRA + LOG("Del FCTX DONE"); + #endif + #endif // SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV +#endif // !DIRECT_MJPEG_COMPOSING break; }; case 0x02:{ @@ -3206,18 +3272,25 @@ void streamHandler::m_fThreadProc( void ){ #endif m_bSegBActive = false; if ( !m_bSegBDelete ) { -#ifdef OPENCV_VIDEO_OUTPUT +#ifdef DIRECT_MJPEG_COMPOSING + if ( m_pOutputFD[1] ) { + fclose( m_pOutputFD[1] ); + m_pOutputFD[1] = NULL; + }; +#else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderB->isOpened() ) { m_pEncoderB->release(); -#ifdef DEBUG + #ifdef DEBUG } else { LOG(" Encoder B is NOT Opened!"); -#endif + #endif }; -#else + #else // !OpenCV av_write_trailer( m_pFormatCtxB ); avio_close( m_pFormatCtxB->pb ); -#endif //OPENCV_VIDEO_OUTPUT + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1] ); if ( bEVT ) { basicEventHeap::getInstance()->broadcast( bEVT ); @@ -3227,20 +3300,27 @@ void streamHandler::m_fThreadProc( void ){ #endif } else { -#ifdef OPENCV_VIDEO_OUTPUT +#ifdef DIRECT_MJPEG_COMPOSING + if ( m_pOutputFD[1] ) { + fclose( m_pOutputFD[1] ); + m_pOutputFD[1] = NULL; + }; +#else + #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderB->isOpened() ) { m_pEncoderB->release(); -#ifdef DEBUG + #ifdef DEBUG } else { LOG(" Encoder B is NOT Opened!"); -#endif + #endif }; -#else - #ifdef EVE_DONT_DELETE_SEGMENTS + #else // !OPenCV + #ifdef EVE_DONT_DELETE_SEGMENTS av_write_trailer( m_pFormatCtxB ); - #endif + #endif avio_close( m_pFormatCtxB->pb ); -#endif // OPENCV_VIDEO_OUTPUT + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING #ifndef EVE_DONT_DELETE_SEGMENTS unlink( m_sStreamSegmentInfo[1].scratchPath ); #endif @@ -3248,23 +3328,23 @@ void streamHandler::m_fThreadProc( void ){ LOG("Stream B is Closed!"); #endif }; -#ifdef OPENCV_VIDEO_OUTPUT -#else - #ifdef SEPARATED_VIDEO_ENCODERS +#ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS avformat_free_context( m_pFormatCtxB ); m_pVideoStrB = NULL; - #endif // SEPARATED_VIDEO_ENCODERS -#endif + #endif // SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV +#endif // !DIRECT_MJPEG_COMPOSING break; }; }; m_bCOP = 0; m_mCurrentOperationProtector.unlock(); //}; -#ifdef OPENCV_VIDEO_OUTPUT - -#else // !OPENCV_VIDEO_OUTPUT - #ifdef SEPARATED_VIDEO_ENCODERS +#ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS do { mPacket.data = NULL; mPacket.size = 0; @@ -3320,7 +3400,7 @@ void streamHandler::m_fThreadProc( void ){ av_packet_unref( &mPacket ); }; } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED ); - #else // ! SEPARATED_VIDEO_ENCODERS + #else // ! SEPARATED_VIDEO_ENCODERS do { mPacket.data = NULL; mPacket.size = 0; @@ -3370,8 +3450,9 @@ void streamHandler::m_fThreadProc( void ){ av_packet_unref( &mPacket ); }; } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED ); - #endif // ! SEPARATED_VIDEO_ENCODERS -#endif // !OPENCV_VIDEO_OUTPUT + #endif // ! SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING SLEEP( 10 ); }; #ifdef DEBUG_EXTRA diff --git a/lib/App/common/kernelModuleEmbedVideo.h b/lib/App/common/kernelModuleEmbedVideo.h index ffcb9c32..2940fae7 100644 --- a/lib/App/common/kernelModuleEmbedVideo.h +++ b/lib/App/common/kernelModuleEmbedVideo.h @@ -60,7 +60,7 @@ class kernelModuleEmbedVideo; #define VO_FLV 5 #define VO_DIRECT_MJPG 6 - //#define DIRECT_MJPEG_COMPOSING + #define DIRECT_MJPEG_COMPOSING #ifdef DIRECT_MJPEG_COMPOSING @@ -205,25 +205,36 @@ typedef map mapSTREAMMAPS; #endif #ifdef EVE_ENABLE_VIDEO - #ifdef OPENCV_VIDEO_OUTPUT - typedef struct S_ENCODING_BUFFER{ -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - bool flag_sa; - bool flag_sb; -#endif - int cols; - int rows; - uint8_t * data; - size_t size; - }ENCODING_BUFFER; - #else + #ifdef DIRECT_MJPEG_COMPOSING typedef struct S_ENCODING_BUFFER{ - int linesize[2]; - int rows; - uint8_t * data[2]; - size_t size; - }ENCODING_BUFFER; - #endif //OPENCV_VIDEO_OUTPUT + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + bool flag_sa; + bool flag_sb; + #endif + uint8_t * data; + size_t size; + }ENCODING_BUFFER; + #else //!DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + typedef struct S_ENCODING_BUFFER{ + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + bool flag_sa; + bool flag_sb; + #endif + int cols; + int rows; + uint8_t * data; + size_t size; + }ENCODING_BUFFER; + #else + typedef struct S_ENCODING_BUFFER{ + int linesize[2]; + int rows; + uint8_t * data[2]; + size_t size; + }ENCODING_BUFFER; + #endif //OPENCV_VIDEO_OUTPUT + #endif //!DIRECT_MJPEG_COMPOSING typedef std::queue Q_ENCODING_BUFFER; #endif @@ -283,11 +294,8 @@ class streamHandler: uint32_t m_nHardLimitFrames; #endif - VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; + basicMutex m_mFrameCounterProtector; - - - uint64_t m_nGlobalFrameCounter; uint64_t m_nValidatorFrameCounter; //uint32_t m_nVideoRegisteredDBID; @@ -297,6 +305,19 @@ class streamHandler: uint32_t m_nSegBShiftFrames; uint32_t m_nSegASkippedFrames; uint32_t m_nSegBSkippedFrames; + + uint8_t m_bActiveEncoderStream; + bool m_bSegAActive; + bool m_bSegADelete; + bool m_bSegBActive; + bool m_bSegBDelete; + basicMutex m_mCurrentOperationProtector; + uint8_t m_bCOP; + VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; + +#ifdef DIRECT_MJPEG_COMPOSING + FILE * m_pOutputFD[2]; +#else // !DIRECT_MJPEG_COMPOSING #ifdef OPENCV_VIDEO_OUTPUT cv::VideoWriter * m_pEncoderA; cv::VideoWriter * m_pEncoderB; @@ -325,14 +346,7 @@ class streamHandler: // Common Pix Converter ( for both streams ) SwsContext * m_pConvertCtx; #endif //OPENCV_VIDEO_OUTPUT - - uint8_t m_bActiveEncoderStream; - bool m_bSegAActive; - bool m_bSegADelete; - bool m_bSegBActive; - bool m_bSegBDelete; - basicMutex m_mCurrentOperationProtector; - uint8_t m_bCOP; + //char m_cSegNameA[128]; //char m_cSegMD5A[33]; //char m_cSegNameB[128]; @@ -346,7 +360,7 @@ class streamHandler: AVStream * m_pVideoStrB; //common output options AVDictionary * m_pFormatOpts; - +#endif // !DIRECT_MJPEG_COMPOSING basicMutex m_mEncodingQueueProtector; Q_ENCODING_BUFFER m_qEncodingQueue;