diff --git a/lib/components/base/basicFunctionality.cpp b/lib/components/base/basicFunctionality.cpp index a8c2e158..e15812cd 100644 --- a/lib/components/base/basicFunctionality.cpp +++ b/lib/components/base/basicFunctionality.cpp @@ -199,6 +199,10 @@ unsigned __int64 getTimeValue( void ){ return tMilliseconds; }; +static uint32_t UID_INCREMENTAL_VALUE = 0; + +#define UID_INCREMEMTAL (UID_INCREMENTAL_VALUE++) + CSTR getTimeStamp( void ){ CSTR RetVal = NULL; time_t rawtime; @@ -226,11 +230,39 @@ CSTR getTimeStamp( void ){ return RetVal; }; +CSTR getTimeStampI( void ){ + CSTR RetVal = NULL; + time_t rawtime; + uint32_t msec; + struct tm * ptm = NULL; + + time ( &rawtime ); + ptm = gmtime ( &rawtime ); + msec = getTimeValue() % 1000; + //2019-03-24T12:32:59.670Z + if( ptm != NULL ) { + RetVal = (CSTR) malloc( 128 ); + if( RetVal!=NULL ){ + sprintf( RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ %d", + (ptm->tm_year+1900), + (ptm->tm_mon+1), + ptm->tm_mday, + ptm->tm_hour, + ptm->tm_min, + ptm->tm_sec, + msec, + UID_INCREMEMTAL + ); + }; + }; + return RetVal; +}; + CSTR getUniqID_MD5( void ){ CSTR tVal = NULL; CSTR tMD5 = NULL; char buf[33]; - tVal = getTimeStamp(); + tVal = getTimeStampI(); buf[0] = (char)0; if( tVal ){ tMD5 = MD5String( tVal ); @@ -283,7 +315,7 @@ CSTR getUniqID_UUID( uint32_t SEED ){ buf[0] = (char)0; if( tVal ){ char tt[256]; - sprintf( tt, "%s %d", tVal ,SEED ); + sprintf( tt, "%s %d %d", tVal ,SEED, UID_INCREMEMTAL ); tMD5 = MD5String( tt ); if( tMD5 ) { memcpy( buf, tMD5, 8 ); diff --git a/lib/data/protocol/protocol.cpp b/lib/data/protocol/protocol.cpp index afe1a019..36d72e2a 100644 --- a/lib/data/protocol/protocol.cpp +++ b/lib/data/protocol/protocol.cpp @@ -78,7 +78,7 @@ bool protocolParser::create(void){ }; void protocolParser::setConnectionStatus( CONNECTION_STATUS cStatus ){ -#ifdef DEBUG +#ifdef DEBUG_EXTRA if (cStatus == CS_CONNECTED)LOG("Connection Status Changed - Connected!"); if (cStatus == CS_DISCONNECTED)LOG("Connection Status Changed - Disconnected!"); #endif diff --git a/lib/rgoose/rgooseDBConnector.cpp b/lib/rgoose/rgooseDBConnector.cpp index 6f535608..7544536a 100644 --- a/lib/rgoose/rgooseDBConnector.cpp +++ b/lib/rgoose/rgooseDBConnector.cpp @@ -4140,10 +4140,10 @@ bool argusDBC::addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th return rVal; }; -bool argusDBC::addVideoEvent( uint32_t evtID, uint32_t videoID ){ +bool argusDBC::addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t clen ){ if( m_bIsConnected ) { char tQBuf[MAX_PATH_LEN]; - sprintf( tQBuf, "INSERT INTO `events_2_videos` SET `evt_id`=%d, `video_id`=%d", evtID, videoID ); + sprintf( tQBuf, "INSERT INTO `events_2_videos` SET `evt_id`=%d, `video_id`=%d, `frame`=%d", evtID, videoID, clen ); #ifdef DEBUG_ALL LOG(tQBuf); #endif @@ -4167,11 +4167,11 @@ bool argusDBC::addPictureEvent( uint32_t evtID, uint32_t pictureoID ){ }; */ -uint32_t argusDBC::addVideoRecord( uint32_t streamID, CSTR md5, uint32_t partID ){ +uint32_t argusDBC::addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t ts, uint32_t tsms, uint32_t fps ){ uint32_t tID = 0; if( m_bIsConnected ) { char tQBuf[MAX_PATH_LEN]; - sprintf( tQBuf, "INSERT INTO `videos` SET `media_stream_id`=%d, `ts`=NOW(), `md5`='%s', `part_id`=%d ", streamID, md5, partID ); + sprintf( tQBuf, "INSERT INTO `videos` SET `media_stream_id`=%d, `uts`=%d, `uts_ms`=%d, `md5`='%s', `ext`='%s', `fps`=%d ", streamID, ts, tsms, md5, ext, fps ); #ifdef DEBUG_ALL LOG(tQBuf); #endif @@ -4557,6 +4557,10 @@ DBC_MODULE_EMBED_VIDEO_DATA *argusDBC::getEmbedVideoData( uint32_t ID ){ Assoc::iterator it; memset(tPtr,0,sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); cArr = result->at(0); + it = cArr->find("output_mode"); + if( it != cArr->end() ){ + tPtr->output_mode = atoi( it->second.c_str() ); + }; it = cArr->find("web_port"); if( it != cArr->end() ){ tPtr->port = atoi( it->second.c_str() ); diff --git a/lib/rgoose/rgooseDBConnector.h b/lib/rgoose/rgooseDBConnector.h index ddeede00..3fcf6625 100644 --- a/lib/rgoose/rgooseDBConnector.h +++ b/lib/rgoose/rgooseDBConnector.h @@ -55,12 +55,14 @@ class argusDBC{ uint32_t addLocalWiFi( uint32_t NIF_ID, ARGUS_WIFI_MODE mode, CSTR SSID, CSTR password, ARGUS_WIFI_ENCRIPTION encryption, uint32_t router_id=0 ); bool addNotification( uint32_t MSG_ID, uint8_t DIS_LVL = 0, uint32_t OBJ_ID=0 ); bool addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ); + //bool addPictureEvent( uint32_t evtID, uint32_t pictureoID ); uint32_t addResource( uint32_t NodeID, uint8_t type, CSTR devName, uint32_t auxID = 0 ); uint32_t addUploadFile( uint32_t NodeID, CSTR uid, CSTR fileName ); - bool addVideoEvent( uint32_t evtID, uint32_t videoID ); - uint32_t addVideoRecord( uint32_t streamID, CSTR md5, uint32_t partID ); + bool addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t clen ); + uint32_t addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t ts, uint32_t tsms, uint32_t fps ); + bool cleanResources( uint32_t ServerNodeID, bool all = false ); bool cleanLRFMask( uint32_t maskID, bool deleteMask = false ); bool cleanNodeEvents( uint32_t NodeID, bool all = false ); @@ -148,7 +150,8 @@ class argusDBC{ void deleteResource( uint32_t ResourceID ); void deleteSensor( uint32_t SensorID ); void deleteUART( uint32_t UARTID ); - + + void finalizeVideoRecord( uint32_t videoID, uint32_t clen ); void registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ); void unregisterServer( uint32_t ServerID, uint32_t NodeID ); diff --git a/lib/rgoose/rgooseHardwareManager.cpp b/lib/rgoose/rgooseHardwareManager.cpp index 845e1adb..25df9ce5 100644 --- a/lib/rgoose/rgooseHardwareManager.cpp +++ b/lib/rgoose/rgooseHardwareManager.cpp @@ -43,7 +43,7 @@ argusHardwareManager::argusHardwareManager( bool cold_start ){ m_nServerNodeID = 0; m_nServerID = 0; m_nSiteID = 0; - m_nMemoryLimitHeapSize = 524288000; // 50 MB //524288000; //500 MB ~ 1 Hour + m_nMemoryLimitHeapSize = 724288000; //524288000; //500 MB ~ 1 Hour m_pKernel = argusKernel::getInstance(); if( m_pKernel == NULL ){ LOG_ERROR( "Failure to get Kernel Instance!" ); @@ -226,6 +226,9 @@ bool argusHardwareManager::validate( void ){ #endif //https://www.ebay.com/itm/274974088159? RetVal = ( memStat < m_nMemoryLimitHeapSize ); + if ( !RetVal ) { + LOG_ERROR("Memory Consumption too BIG!"); + }; }; return RetVal; }; @@ -1073,10 +1076,11 @@ argusHardwareResource *argusHardwareManager::requestResource( ARGUS_HARDWARE_PRO if( m_vResources.size() ) { for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { +#ifdef DEBUG_EXTRA char tB[256]; sprintf( tB, "Check Resources RR[%d] RI[%d] ?? CR[%d] CI[%d]", type, id, (*idx)->getProviderType(), (*idx)->getDbId() ); LOG( tB ); - +#endif if( ((*idx)->getProviderType() == type ) && ( (*idx)->getDbId() == id ) ) { RetVal = (*idx); break; diff --git a/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp b/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp index b13a38a5..8d4f82d1 100644 --- a/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp +++ b/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp @@ -79,7 +79,11 @@ bool argusHardwareResourceSerialProvider::validate( void ){ switch( m_sUartData.type ) { case ARGUS_HARDWARE_UART:{ //HW port is valid - //BBm_bValid = true; + if( ( m_bThreadBStatus == TH_ENDED ) && ( m_bThreadAStatus == TH_ENDED ) ) { + LOG("IO Theads are Finished!"); + m_bValid = false; + closePort(); + }; break; }; case ARGUS_HARDWARE_IP_UART:{ @@ -89,7 +93,7 @@ bool argusHardwareResourceSerialProvider::validate( void ){ if( !m_bValid ){ LOG("No Ping"); closePort(); - } + }; }; break; }; @@ -762,9 +766,14 @@ void argusHardwareResourceSerialProvider::m_fThreadAProc(void){ if( m_nOutputBufferSize > 0 ){ index = 0; while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){ + char TT[64]; + sprintf( TT, "Have %d Bytes to send!", m_nOutputBufferSize ); + LOG( TT ); RetVal = sendBlock(m_pOutputBuffer + index, m_nOutputBufferSize - index); - if( RetVal > 0 ) index += RetVal; - if( RetVal == -1 ){ + if( RetVal > 0 ){ + index += RetVal; + } /*;*/ else { + //if( RetVal == -1 ){ setConnectionStatus( CS_DISCONNECTED ); m_nOutputBufferSize = 0; m_bThreadBStatus = TH_ENDED; diff --git a/lib/rgoose/rgooseModuleEmbedVideo.cpp b/lib/rgoose/rgooseModuleEmbedVideo.cpp index 7b140b98..afbf2e24 100644 --- a/lib/rgoose/rgooseModuleEmbedVideo.cpp +++ b/lib/rgoose/rgooseModuleEmbedVideo.cpp @@ -125,9 +125,13 @@ argusModuleEmbedVideo::~argusModuleEmbedVideo(){ #ifdef DEBUG LOG("No More Client Handlers!"); #endif + if( m_mapHANDLERS.size() ){ + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) delete( (*idx).second ); + m_mapHANDLERS.clear(); + }; if( m_mapCAPTURES.size() ) m_mapCAPTURES.clear(); if( m_mapMATS.size() ) m_mapMATS.clear(); - if(n_pNoSignalData) free(n_pNoSignalData); + if( n_pNoSignalData ) free(n_pNoSignalData); }; static const char * ht_head = "HTTP/1.1 200 OK\r\n" @@ -711,6 +715,13 @@ bool argusModuleEmbedVideo::validate(){ delete ( tList ); }; }; + if ( RetVal ) { + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) { + if ( !(*idx).second->validate() ) { + RetVal = false; + }; + }; + }; } else { LOG_ERROR( "DB Error!" ); RetVal = false; @@ -796,68 +807,88 @@ void argusModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){ //https://www.mikekohn.net/software/playstation2.php bool argusModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){ + if( ptr == NULL ) return false; - if( ptr->assoc_event_ids.size() ){ - if( m_mapCAPTURES.find( ptr->stream_id ) != m_mapCAPTURES.end() ){ - m_mPictureProtector.lock(); - ptr->data = (uint8_t *) malloc( m_mapCAPTURES[ptr->stream_id].size() ); - if( ptr->data ){ - ptr->data_size = m_mapCAPTURES[ptr->stream_id].size(); - memcpy( ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size ); - m_mPictureProtector.unlock(); - CSTR MD5 = MD5Binary( ptr->data, ptr->data_size ); - if( MD5 ){ - strncpy( ptr->md5, MD5, 32 ); - free( MD5 ); - if( !m_pDBC->addPicture( ptr, "jpg" ) ) LOG_ERROR("Database Error to consume capture!"); - } else LOG_ERROR("no MD5 Hash!"); - free( ptr->data ); - } else { - m_mPictureProtector.unlock(); - LOG_ERROR("No memory to allocate!"); - }; - } + + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){ + LOG("Saving Picture!"); + if( ptr->assoc_event_ids.size() ){ + if( m_mapCAPTURES.find( ptr->stream_id ) != m_mapCAPTURES.end() ){ + m_mPictureProtector.lock(); + ptr->data = (uint8_t *) malloc( m_mapCAPTURES[ptr->stream_id].size() ); + if( ptr->data ){ + ptr->data_size = m_mapCAPTURES[ptr->stream_id].size(); + memcpy( ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size ); + m_mPictureProtector.unlock(); + CSTR MD5 = MD5Binary( ptr->data, ptr->data_size ); + if( MD5 ){ + strncpy( ptr->md5, MD5, 32 ); + free( MD5 ); + if( !m_pDBC->addPicture( ptr, "jpg" ) ) LOG_ERROR("Database Error to consume capture!"); + } else LOG_ERROR("no MD5 Hash!"); + free( ptr->data ); + } else { + m_mPictureProtector.unlock(); + LOG_ERROR("No memory to allocate!"); + }; #ifdef DEBUG - else { - LOG("No apropriate Stream Found!"); - } + } else { + LOG("No apropriate Stream Found!"); #endif - ; + }; + }; + }; + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO ){ + LOG("Saving Video!"); + if( ptr->assoc_event_ids.size() ){ + mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( ptr->stream_id ); + if( hnd != m_mapHANDLERS.end() ){ + uint32_t db_id; + uint32_t cfrm; + if( (*hnd).second->triggerEvent( db_id, cfrm ) ){ + for( DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++ ){ + m_pDBC->addVideoEvent( (*idx), db_id, cfrm ); + }; + }; + }; + }; }; return true; }; bool argusModuleEmbedVideo::saveStreamPicture( uint32_t id ){ - uint32_t retVal = 0; - if( m_mapCAPTURES.find( id ) != m_mapCAPTURES.end() ){ - FILE *tFD; - m_mPictureProtector.lock(); - size_t tBufferSize = m_mapCAPTURES[id].size(); - uint8_t * tBuffer = (uint8_t *) malloc( tBufferSize ); - if( tBuffer ){ - memcpy( tBuffer, m_mapCAPTURES[id].data(), tBufferSize ); - m_mPictureProtector.unlock(); - CSTR MD5 = MD5Binary( tBuffer, tBufferSize ); - if( MD5 ){ - char tFileName[MAX_PATH]; - if( generateSavePicPath( MD5, tFileName ) ){ - FILE *fd = fopen( tFileName, "wb+" ); - if( fd ){ - fwrite(tBuffer, 1, tBufferSize, fd ); - fclose(fd); - chown( tFileName, "nobody", "nogroup" ); - //retVal = m_pDBC->addPicture( id, MD5, "jpg" ); - } else LOG_ERROR("Can not open picture file!"); - } else LOG_ERROR("Can not generate file name!"); - free(MD5); - } else LOG_ERROR("no MD5 Hash!"); - free(tBuffer); - } else { - m_mPictureProtector.unlock(); - LOG_ERROR("no memory to allocate!"); + if( !id ) return false; + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){ + if( m_mapCAPTURES.find(id) != m_mapCAPTURES.end() ){ + FILE * tFD; + m_mPictureProtector.lock(); + size_t tBufferSize = m_mapCAPTURES[id].size(); + uint8_t * tBuffer = (uint8_t *) malloc( tBufferSize ); + if( tBuffer ){ + memcpy( tBuffer, m_mapCAPTURES[id].data(), tBufferSize ); + m_mPictureProtector.unlock(); + CSTR MD5 = MD5Binary( tBuffer, tBufferSize ); + if( MD5 ){ + char tFileName[MAX_PATH]; + if( generateSavePicPath( MD5, tFileName ) ){ + FILE *fd = fopen( tFileName, "wb+" ); + if( fd ){ + fwrite(tBuffer, 1, tBufferSize, fd ); + fclose(fd); + chown( tFileName, "nobody", "nogroup" ); + //retVal = m_pDBC->addPicture( id, MD5, "jpg" ); + } else LOG_ERROR("Can not open picture file!"); + } else LOG_ERROR("Can not generate file name!"); + free(MD5); + } else LOG_ERROR("no MD5 Hash!"); + free(tBuffer); + } else { + m_mPictureProtector.unlock(); + LOG_ERROR("no memory to allocate!"); + }; }; - }; - return retVal; + } + return true; }; int argusModuleEmbedVideo::getWidh( void ){ @@ -948,13 +979,17 @@ streamHandler::streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pM m_nSegBFrameCounter = 0; m_nGlobalFrameCounter = 0; m_nVideoRegisteredDBID = 0; - m_nAlarmShiftFrames = 0; - m_nNoAlarmSegmentFrames = 0; + m_nSegAShiftFrames = 0; + m_nSegBShiftFrames = 0; + m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; + m_nSegmentLimitFrames = 0; m_nHardLimitFrames = 0; m_bActiveEncoderStream = 0; - m_bActiveSegmentNoDelete = false; m_bSegAActive = false; + m_bSegADelete = true; m_bSegBActive = false; + m_bSegBDelete = true; + m_bCOP = 0; #endif //EVE_ENABLE_VIDEO }; @@ -1349,38 +1384,56 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ //m_nPreAlarmFrames //m_nPostAlarmFrames //m_nNoAlarmSegmentFrames + //m_nSegmentLimitFrames //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_bSegAActive ){ + do { + //In Any Case Close Stream if it Long enough + if( m_nSegAFrameCounter > m_nHardLimitFrames ){ + LOG("HardLimit Reached!(A)"); + closeSegmentA(); + break; + }; + if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ + if ( !m_bSegBActive ){ + LOG("Start Alt!(A)"); + openSegmentB(); + }; + }; + if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){ + LOG("Swap Active!(A)"); + swapActiveStreams(); + break; + }; + } while ( 0 ); }; - if( m_bSegBActive ) { - if ( m_nSegBFrameCounter > m_nHardLimitFrames ) { - closeSegmentB(); - } else { - int vCNT = m_nSegBFrameCounter - m_nAlarmShiftFrames; - - }; - } else { + if( m_bSegBActive ) { + do { + //In Any Case Close Stream if it Long enough + if( m_nSegBFrameCounter > m_nHardLimitFrames ){ + LOG("HardLimit Reached!(B)"); + closeSegmentB(); + break; + }; + if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ + if ( !m_bSegAActive ){ + LOG("Start Alt!(B)"); + openSegmentA(); + }; + }; + if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){ + LOG("Swap Active!(B)"); + swapActiveStreams(); + break; + }; + } while ( 0 ); }; + m_mFrameCounterProtector.unlock(); ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER)); @@ -1397,88 +1450,11 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ m_qEncodingQueue.push( tData ); m_mEncodingQueueProtector.unlock(); } else { + LOG_ERROR("MAT_CPY malloc Error!"); 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); - //*/ - + } else LOG_ERROR("ENC_BUF malloc Error!"); }; - #endif // EVE_ENABLE_VIDEO m_pMaster->m_mPictureProtector.unlock(); } else { @@ -1531,41 +1507,93 @@ void streamHandler::closeAll(){ }; 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; + if( !m_bSegAActive ){ + CSTR tAM = getUniqID_MD5(); + if ( tAM ) { + sprintf( m_cSegNameA, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + strncpy( m_cSegMD5A, tAM, 32 ); + m_cSegMD5A[32] = (char)0; + free( tAM ); + #ifdef DEBUG + 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 + 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; + //}; + 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(); + #ifdef DEBUG + LOG("Stream A Opened"); + #endif }; - 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; + if( !m_bSegBActive ){ + CSTR tAM = getUniqID_MD5(); + if ( tAM ) { + sprintf( m_cSegNameB, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + strncpy( m_cSegMD5B, tAM, 32 ); + m_cSegMD5B[32] = (char)0; + free( tAM ); + #ifdef DEBUG + 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 + 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(); + #ifdef DEBUG + LOG("Stream B Opened"); + #endif }; - m_nSegBFrameCounter = 0; - m_bSegBActive = true; }; return m_bSegBActive; }; @@ -1573,7 +1601,7 @@ bool streamHandler::openSegmentB( void ){ 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_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000; m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; if( !initLibAV() ) return false; @@ -1583,9 +1611,11 @@ bool streamHandler::initVideoOutput(){ if ( m_pFormat == NULL ) { LOG_ERROR("Out VideoFormat Not Found!"); return false; +#ifdef DEBUG } else { LOG("Output video Format"); LOG( VIDEO_OUTPUT_CONTAINER ); +#endif }; if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { @@ -1600,7 +1630,7 @@ bool streamHandler::initVideoOutput(){ 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 ); + //av_free( m_pFormat ); return false; } else { av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); @@ -1612,10 +1642,12 @@ bool streamHandler::initVideoOutput(){ LOG_ERROR("Out VideoCodec Not Found!"); avformat_free_context( m_pFormatCtxA ); avformat_free_context( m_pFormatCtxB ); - av_free( m_pFormat ); + //av_free( m_pFormat ); return false; +#ifdef DEBUG } else { LOG("Out Video Codec Found"); +#endif }; m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec ); @@ -1624,10 +1656,12 @@ bool streamHandler::initVideoOutput(){ av_free( m_pVideoCodec ); avformat_free_context( m_pFormatCtxA ); avformat_free_context( m_pFormatCtxB ); - av_free( m_pFormat ); + //av_free( m_pFormat ); return false; +#ifdef DEBUG } else { LOG("Out Codec Context3 Allocated"); +#endif }; m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec ); @@ -1638,10 +1672,12 @@ bool streamHandler::initVideoOutput(){ av_free( m_pVideoCodec ); avformat_free_context( m_pFormatCtxA ); avformat_free_context( m_pFormatCtxB ); - av_free( m_pFormat ); + //av_free( m_pFormat ); return false; - }else{ +#ifdef DEBUG + } else { LOG("VideoStream A is Created"); +#endif }; m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec ); @@ -1654,8 +1690,10 @@ bool streamHandler::initVideoOutput(){ avformat_free_context( m_pFormatCtxB ); av_free( m_pFormat ); return false; +#ifdef DEBUG } else { LOG("VideoStream B is Created"); +#endif }; m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; @@ -1687,7 +1725,9 @@ bool streamHandler::initVideoOutput(){ // 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 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() @@ -1703,6 +1743,7 @@ bool streamHandler::initVideoOutput(){ 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 @@ -1722,12 +1763,18 @@ bool streamHandler::initVideoOutput(){ */ - if( av_dict_set( &m_pFormatOpts, "movflags", "frag_keyframe+empty_moov", 0 ) < 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 } else { LOG("MOV FLAG SET!"); +#endif }; + //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!" ); @@ -1765,8 +1812,9 @@ bool streamHandler::initVideoOutput(){ /// 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 LOG("End Options!"); +#endif } else { if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; }; @@ -1776,8 +1824,15 @@ bool streamHandler::initVideoOutput(){ const AVRational dst_fps = { m_sStreamData.fps, 1 }; +#ifdef DEBUG + 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 ); @@ -1813,9 +1868,15 @@ bool streamHandler::initVideoOutput(){ if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) { LOG_ERROR("Error opening2 encoder"); return false; +#ifdef DEBUG + } else { + LOG("output codec context is opened"); }; +#endif +#ifdef DEBUG } else { - LOG("output codec context is opened"); + LOG("output codec context is already opened"); +#endif }; m_pConvertCtx = sws_getContext( m_pMaster->m_sEmbedVideoData.width, @@ -1843,9 +1904,10 @@ bool streamHandler::initVideoOutput(){ 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_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 ); - //avpicture_fill((AVPicture *)m_pAVFrame, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height ); + + //av_frame_make_writable( m_pAVFrame ); return init(); }; @@ -1856,6 +1918,7 @@ void streamHandler::m_fThreadProc( void ){ AVPacket mPacket; int bGotPacket; int rVal = 0; + char tB[128]; av_init_packet( &mPacket ); while( m_bThreadStatus != TH_ENDED ){ @@ -1865,163 +1928,160 @@ void streamHandler::m_fThreadProc( void ){ m_bThreadStatus = TH_ENDED; continue; }; - if( !openSegmentB() ){ - 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 ){ + if( tData ){ + //av_frame_make_writable( m_pAVFrame ); 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(); - + /* + + + 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; rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + m_mFrameCounterProtector.lock(); + m_nGlobalFrameCounter++; + if ( m_bSegAActive ) m_nSegAFrameCounter++; + if ( m_bSegBActive ) m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); }; + m_mEncodingQueueProtector.unlock(); + } else { + m_mEncodingQueueProtector.unlock(); + // If No Encode Job -> Test Commands! + m_mCurrentOperationProtector.lock(); + switch ( m_bCOP ) { + case 0x01:{ + m_bSegAActive = false; + if ( !m_bSegADelete ) { + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); +#ifdef DEBUG + LOG("Stream A is Closed"); +#endif + } else { +#ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxA ); +#endif + avio_close( m_pFormatCtxA->pb ); +#ifndef EVE_DONT_DELETE_SEGMENTS + unlink( m_cSegNameA ); +#endif +#ifdef DEBUG + LOG("Stream A is Deleted!"); +#endif + }; + break; + }; + case 0x02:{ + m_bSegBActive = false; + if ( !m_bSegBDelete ) { + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); +#ifdef DEBUG + LOG("Stream B is Closed"); +#endif + } else { +#ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxB ); +#endif + avio_close( m_pFormatCtxB->pb ); +#ifndef EVE_DONT_DELETE_SEGMENTS + unlink( m_cSegNameB ); +#endif +#ifdef DEBUG + LOG("Stream B is Deleted!"); +#endif + }; + break; + }; + }; + m_bCOP = 0; + m_mCurrentOperationProtector.unlock(); }; - m_mEncodingQueueProtector.unlock(); - - if ( rVal == AVERROR(EAGAIN) ) { + do { mPacket.data = NULL; mPacket.size = 0; rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket ); - if ( !rVal ){ + if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){ + break; + } else if( rVal < 0 ){ + LOG_ERROR( "Error during encoding " ); + m_bThreadStatus = TH_ENDED; + break; + }; + 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.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //mPacket.pts = AV_NOPTS_VALUE; + //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); mPacket.dts = mPacket.pts; - if( av_write_frame( m_pFormatCtxA, &mPacket ) < 0 ){ + int rc = av_write_frame( m_pFormatCtxA, &mPacket ); + if( rc < 0 ){ + //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) { m_bThreadStatus = TH_ENDED; LOG_ERROR("Trouble with Video Output A!"); - continue; + av_strerror( rc, tB, 128 ); + LOG_ERROR( tB ); + break; //continue (changed since embed into do-while) }; - 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.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //mPacket.pts = AV_NOPTS_VALUE; + //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); mPacket.dts = mPacket.pts; - if( av_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + int rc = av_write_frame( m_pFormatCtxB, &mPacket); + if( rc < 0 ) { + //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { m_bThreadStatus = TH_ENDED; - LOG_ERROR("Trouble with Video Output B!"); - continue; + LOG_ERROR( "Trouble with Video Output B!" ); + av_strerror( rc, tB, 128 ); + LOG_ERROR( tB ); + break; //continue (changed since embed into do-while) }; - 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(); - }; - */ + } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED ); }; +#ifdef DEBUG LOG("Encoder Loop Ended!"); +#endif if ( m_bSegAActive ) { m_bSegAActive = false; av_write_trailer( m_pFormatCtxA ); @@ -2032,9 +2092,73 @@ void streamHandler::m_fThreadProc( void ){ av_write_trailer( m_pFormatCtxB ); avio_close( m_pFormatCtxB->pb ); }; +#ifdef DEBUG LOG("Encoder Streams are Closed!"); +#endif +}; + +void streamHandler::swapActiveStreams( void ){ + //m_mFrameCounterProtector.lock(); + if ( !m_bActiveEncoderStream ) { + m_bActiveEncoderStream = 1; + m_nVideoRegisteredDBID = 0; + // No need to continue Stream A if no Events + if ( m_bSegADelete ) closeSegmentA(); + } else { + m_bActiveEncoderStream = 0; + m_nVideoRegisteredDBID = 0; + // No need to continue Stream B if no Events + if ( m_bSegBDelete ) closeSegmentB(); + }; + //m_mFrameCounterProtector.unlock(); +}; + +bool streamHandler::triggerEvent( uint32_t &dbid, uint32_t &frame ){ + m_mFrameCounterProtector.lock(); + if ( m_nVideoRegisteredDBID == 0 ) { + LOG("New Event!"); + PF_TIMESTAMP ts; + getPFTS( &ts ); + if ( !m_bActiveEncoderStream ) { // Stream A is Active + m_nVideoRegisteredDBID = argusDBC::getInstance()->addVideoRecord( + m_sStreamData.id, + m_cSegMD5A, + VIDEO_OUTPUT_CONTAINER, + ts.seconds, + ts.milliseconds, + m_sStreamData.fps + ); + m_bSegADelete = false; + m_nSegAShiftFrames = frame = m_nSegAFrameCounter; + } else { // Stream B is Active + m_nVideoRegisteredDBID = argusDBC::getInstance()->addVideoRecord( + m_sStreamData.id, + m_cSegMD5B, + VIDEO_OUTPUT_CONTAINER, + ts.seconds, + ts.milliseconds, + m_sStreamData.fps + ); + m_bSegBDelete = false; + m_nSegBShiftFrames = frame = m_nSegBFrameCounter; + }; + }; + if ( m_nVideoRegisteredDBID == 0 ) return false; + dbid = m_nVideoRegisteredDBID; + LOG("Event Registered!"); + m_mFrameCounterProtector.unlock(); + return true; }; +bool streamHandler::validate( void ){ + if ( m_pSource ) +#ifdef EVE_ENABLE_VIDEO + if( m_bThreadStatus < TH_ENDED ) +#endif + return true; + + return false; +}; #undef LOG #undef LOG_ERROR diff --git a/lib/rgoose/rgooseModuleEmbedVideo.h b/lib/rgoose/rgooseModuleEmbedVideo.h index 4583d374..47715ccf 100644 --- a/lib/rgoose/rgooseModuleEmbedVideo.h +++ b/lib/rgoose/rgooseModuleEmbedVideo.h @@ -14,11 +14,15 @@ class argusModuleEmbedVideo; #define EVE_ENABLE_VIDEO + + //#define USE_SCALING_IN #ifdef EVE_ENABLE_VIDEO +//#define EVE_DONT_DELETE_SEGMENTS + /* Video CODECS */ #define VC_VPX 0 #define VC_X264 1 @@ -143,9 +147,14 @@ typedef vector vectorHANDLERS; typedef struct S_STREAM_CAP{ uint32_t stream_id; uint32_t buffer_size; - uint8_t picture_buffer; + uint8_t picture_buffer; }STREAM_CAP; +typedef struct S_VIDEO_EVT{ + uint32_t dbid; + uint32_t frame; +}VIDEO_EVT; + typedef vector compressedFRAME; typedef map mapSTREAMCAPS; typedef map mapSTREAMMAPS; @@ -154,8 +163,13 @@ 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_MILSECONDS 50000 // 50 sec #define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute +//#define ENCODING_SEGMENT_LIMIT_MILSECONDS 900000 // 15 minute + +#define EVE_OUTPUT_PICTURES 1 +#define EVE_OUTPUT_VIDEO 2 +#define EVE_OUTPUT_PIC_AND_VID 3 #ifdef EVE_ENABLE_VIDEO @@ -193,17 +207,23 @@ class streamHandler: uint32_t m_nVideoRegisteredDBID; uint32_t m_nSegAFrameCounter; uint32_t m_nSegBFrameCounter; - uint32_t m_nAlarmShiftFrames; - uint32_t m_nNoAlarmSegmentFrames; + uint32_t m_nSegAShiftFrames; + uint32_t m_nSegBShiftFrames; + uint32_t m_nSegASkippedFrames; + uint32_t m_nSegBSkippedFrames; + uint32_t m_nSegmentLimitFrames; uint32_t m_nHardLimitFrames; uint8_t m_bActiveEncoderStream; - bool m_bActiveSegmentNoDelete; bool m_bSegAActive; + bool m_bSegADelete; bool m_bSegBActive; + bool m_bSegBDelete; basicMutex m_mCurrentOperationProtector; uint8_t m_bCOP; - char m_cSegNameA[64]; - char m_cSegNameB[64]; + char m_cSegNameA[128]; + char m_cSegMD5A[33]; + char m_cSegNameB[128]; + char m_cSegMD5B[33]; // encoding video stuff AVCodec * m_pVideoCodec; AVCodecContext * m_pCodecCtx; @@ -226,6 +246,7 @@ class streamHandler: void closeSegmentA( void ); bool openSegmentB( void ); void closeSegmentB( void ); + void swapActiveStreams( void ); void closeAll(); bool initVideoOutput(); protected: @@ -240,6 +261,8 @@ class streamHandler: virtual bool pushFrame( AVFrame *Frame, void* src = NULL); //virtual void pushFrame( cv::Mat* Frame, void* src = NULL); virtual bool pushFrame( cv::Mat &Frame, void* src = NULL); + bool triggerEvent( uint32_t &dbid, uint32_t &frame ); + bool validate( void ); }; typedef map mapSTREAMHANDLERS; diff --git a/lib/rgoose/rgooseModuleZLMedia.cpp b/lib/rgoose/rgooseModuleZLMedia.cpp index 224c9e94..0ac25770 100644 --- a/lib/rgoose/rgooseModuleZLMedia.cpp +++ b/lib/rgoose/rgooseModuleZLMedia.cpp @@ -330,7 +330,7 @@ bool argusModuleZLMedia::startRecord( uint32_t evt_id, uint32_t chan, CSTR evtID }; if( tRecord != NULL ) { tRecord->m_pMutex->lock(); - m_pDBC->addVideoEvent( evt_id, tRecord->m_uVideoID ); + //m_pDBC->addVideoEvent( evt_id, tRecord->m_uVideoID ); tRecord->m_uTimer += ZLM_10TH_SEC_RECORD_LENGTH; tRecord->m_pMutex->unlock(); return true; @@ -359,8 +359,8 @@ bool argusModuleZLMedia::startRecord( uint32_t evt_id, uint32_t chan, CSTR evtID tRecord->m_uTimer = ZLM_10TH_SEC_RECORD_LENGTH; tRecord->m_uSkeep = ZLM_10TH_SEC_RECORD_SKEEP; tRecord->m_pMutex = new basicMutex(); - tRecord->m_uVideoID = m_pDBC->addVideoRecord( tRecord->m_uStreamID, tRecord->m_sDstName, tRecord->m_uPartNumber ); - m_pDBC->addVideoEvent( evt_id, tRecord->m_uVideoID ); + //tRecord->m_uVideoID = m_pDBC->addVideoRecord( tRecord->m_uStreamID, tRecord->m_sDstName, tRecord->m_uPartNumber ); + //m_pDBC->addVideoEvent( evt_id, tRecord->m_uVideoID ); if(tRecord->m_pMutex!=NULL) { int RetVal = pthread_create( &tRecord->m_hThreadHandle, NULL, m_fRecorder, ( void * ) tRecord ); if( RetVal == -1 ) { @@ -451,7 +451,7 @@ void *argusModuleZLMedia::m_fRecorder( void *ptr ){ cFN = tFN; MS->m_pMutex->lock(); MS->m_uPartNumber++; - MS->m_uVideoID = m_pDBC->addVideoRecord( MS->m_uStreamID, MS->m_sDstName, MS->m_uPartNumber ); + //MS->m_uVideoID = m_pDBC->addVideoRecord( MS->m_uStreamID, MS->m_sDstName, MS->m_uPartNumber ); MS->m_pMutex->unlock(); } else free( tFN ); SLEEP( 100 ); diff --git a/lib/rgoose/rgooseNode2D.cpp b/lib/rgoose/rgooseNode2D.cpp index 8c15712c..169c6e17 100644 --- a/lib/rgoose/rgooseNode2D.cpp +++ b/lib/rgoose/rgooseNode2D.cpp @@ -251,9 +251,13 @@ bool ARGUS_2DSensor::startService() { bool ARGUS_2DSensor::stopService() { m_mWMProtector.unlock(); + LOG( "Kiling Thread"); waitThreadEnd( true ); + LOG( "Thread is Dead!"); m_pDBC->setNodeOffline( m_sNodeData.node_id ); + LOG( "Start Clenup Structs!"); cleanupDeviceStructures(); + LOG( "Clenup Structs Done!"); return true; }; @@ -438,11 +442,10 @@ bool ARGUS_2DSensor::validate(){ void ARGUS_2DSensor::m_fThreadProc( void ){ m_bThreadStatus = TH_WORKING; - while (m_bThreadStatus < TH_ENDED) { + while( m_bThreadStatus < TH_ENDED ){ if( getConnectionStatus() != CS_CONNECTED ) m_bWM = ANODE_WM_2D_CREATE_PORT; - switch( getWM() ) { // Physical Connection Channel case ANODE_WM_2D_CREATE_PORT:{ @@ -471,15 +474,13 @@ void ARGUS_2DSensor::m_fThreadProc( void ){ break; }; }; - } #ifdef DEBUG_EXTRA - else { + } else { char tB[256]; sprintf( tB, "HWM Has No UART PORT[%d]!", m_sLRF_DATA.uart_id ); LOG( tB ); - } #endif - ; + }; } else { LOG_ERROR("Can not access Hardware Manager"); }; @@ -501,7 +502,9 @@ void ARGUS_2DSensor::m_fThreadProc( void ){ LOG_ERROR("Fall Back to Disconnected!"); } else { // Cleanup Current data; + LOG("BCS"); cleanupDeviceStructures(); + LOG("ACS"); setWM( ANODE_WM_2D_WAIT_CONNECT ); }; break; @@ -806,6 +809,7 @@ void ARGUS_2DSensor::m_fThreadProc( void ){ m_bOpRetryCnt = 10; m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; m_bWM = ANODE_WM_2D_WAIT_CHECK_REPLAY; + // going directly through -> ANODE_WM_2D_WAIT_CHECK_REPLAY case ANODE_WM_2D_WAIT_CHECK_REPLAY:{ if(( --m_bTimeOutCounter )==0 ){ #ifdef DEBUG_EXTRA @@ -1643,8 +1647,8 @@ bool ARGUS_2DSensor::packetHandler( protocolPackage *Package ){ }; }; #ifdef DEBUG_EXTRA - rasterizeShadow(); - makeShadowPic("shadow.png"); + //rasterizeShadow(); + //makeShadowPic("shadow.png"); #endif setWM(ANODE_WM_2D_PING); }; @@ -2154,7 +2158,7 @@ bool ARGUS_2DSensor::rasterizeShadow(){ return true; }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG_EXTRA_ void ARGUS_2DSensor::makeShadowPic( CSTR picname ){ cv::Scalar zone_colors[6] = { cv::Scalar(0, 0, 255), cv::Scalar(255, 20, 255), diff --git a/lib/rgoose/rgooseTypes.h b/lib/rgoose/rgooseTypes.h index 089d3ff1..540ee7a5 100644 --- a/lib/rgoose/rgooseTypes.h +++ b/lib/rgoose/rgooseTypes.h @@ -299,6 +299,7 @@ typedef struct S_DBC_MODULE_DATA{ }DBC_MODULE_DATA; typedef struct S_DBC_MODULE_EMBED_VIDEO_DATA{ + uint8_t output_mode; uint16_t port; bool show_ts; bool show_label;