#include "rgooseModuleEmbedVideo.h" //#include "rgooseHardwareResourceNetworkProvider.h" #include "mojoKernel.h" #include "../alg/generic/base64.h" #include "../data/media/video/videoAVLIBSource.h" #include "../data/media/video/videoLive555AVLibSource.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* MIN() */ #include #include #define STORAGE_DIR_MODE 0x1FF #define STORAGE_FILE_MODE 0x1B6 #define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X ) #ifdef DEBUG #define LOG_ERROR( X ) {\ char _tBfrErrMSG2w34[256];\ sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ } #else #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X ); #endif #define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X ) #ifdef DEBUG #define TLOG_ERROR( X ) {\ char _tBfrErrMSG2w34[256];\ sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34 );\ } #else #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ); #endif enum { WEBRTC_REQ_SIGNIN = 0, WEBRTC_REQ_WAIT = 1, WEBRTC_REQ_SIGNOUT = 2, WEBRTC_REQ_MESSAGE = 3 }; static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_out", "/message" }; //buffer_data bd[1]={0}; argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicThread(){ m_pEventHeap = basicEventHeap::getInstance(); if( m_pDBC ){ DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); if( tDATA ) { memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); free( tDATA ); } else { memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); m_sEmbedVideoData.port = 8972; }; } else { LOG_ERROR( "DB Error!" ); }; n_pNoSignalData = NULL; m_nNoSignalSize = 0; char tBuff[1024]; sprintf( m_pBaseSavePath, "%s/data/reports", getcwd(tBuff, 1024) ); #ifdef DEBUG char tB[64]; sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port ); LOG( tB ); sprintf( tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height ); LOG( tB ); if( m_sEmbedVideoData.show_ts ) LOG("Show TimeStamp"); if( m_sEmbedVideoData.show_label ) LOG("Show Label"); if( m_sEmbedVideoData.show_logo ) LOG("Show Logo"); #endif if( m_sEmbedVideoData.show_logo ){ LOG( m_sEmbedVideoData.logo_md5 ); char tPath[MAX_PATH]; sprintf( tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 ); if( !fileExist( tPath ) ){ LOG_ERROR("Logo File Missed!"); m_sEmbedVideoData.show_logo = false; } #ifdef DEBUG else LOG("Logo File is OK"); #endif ; }; }; argusModuleEmbedVideo::~argusModuleEmbedVideo(){ m_bEnabled = false; waitThreadEnd( true ); if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes #ifdef DEBUG char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); LOG( tB ); #endif for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) pthread_cancel( (*index)->m_hThreadHandle ); m_vHandlersPool.clear(); }; #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); }; static const char * ht_head = "HTTP/1.1 200 OK\r\n" "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n" "MIME-version: 1.0\r\n" "Connection: close\r\n" //"Keep-Alive: timeout=5, max=1\r\n" //"Connection: Keep-Alive\r\n" //"Content-Type: video/mp4\r\n" "Content-Transfer-Encoding: BINARY\r\n" //"Transfer-Encoding: chunked\r\n" "Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n" "\r\n"; static const char * ht_abort = "HTTP/1.1 404 OK\r\n" "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n" "Connection: close\r\n\r\n"; static const char * ht_no_signal = "HTTP/1.1 200 OK\r\n" "MIME-version: 1.0\r\n" "Connection: close\r\n" "Content-Transfer-Encoding: BINARY\r\n" //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n" "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n"; void *argusModuleEmbedVideo::webClientProc( void *ptr ){ WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; argusModuleEmbedVideo * MODULE = CTX->ModulePtr; uint32_t msgSize; uint8_t tBuf[FILESTREAMBUFFERSZ]; int retVal; if( CTX ) { char mesg[1024]; size_t RecvSize; struct pollfd pfd[1]; char cGetURI[1024]; bool m_bDeflatePerMessage = false; bool m_pInit; #ifdef DEBUG_EXTRA pid_t pid = gettid(); char pidBuf[16]; sprintf( pidBuf, "pid:%d", pid); TLOG( pidBuf ); #endif pfd->fd = CTX->m_iSocketFID; pfd->events = POLLIN | POLLHUP; while( CTX->bValid ) { if( !CTX->initDone ){ int RetVal; char * reqline[256]; RetVal = poll( pfd, 1, 1000 ); if( RetVal <= 0 ){ if ( EINTR == errno ) continue; TLOG_ERROR("Unrecoverable error"); CTX->bValid = false; continue; }; memset( mesg, 0, sizeof(mesg) ); RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 ); if ( RetVal <= 0 ) { sprintf( mesg, "web recv() error: %s", strerror(errno)); TLOG_ERROR( mesg ); CTX->bValid = false; continue; }; #ifdef DEBUG_EXTRA TLOG( mesg ); #endif uint32_t index = 0; reqline[index] = strtok( mesg, "\n" ); if( strncmp( reqline[index], "GET", 3 ) == 0 ) { char * pPartURI; char * pPartPROTO; pPartURI = strstr( reqline[index], " " ); if( pPartURI != NULL ) { pPartURI++; pPartPROTO = strstr( pPartURI, " " ); pPartPROTO++; int URILen = pPartPROTO - pPartURI; strncpy( cGetURI, pPartURI, URILen ); cGetURI[URILen] = (char)0; if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) { TLOG_ERROR("No HTTP version supplied in request!"); if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){ sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno)); TLOG_ERROR(mesg); }; CTX->bValid = false; continue; }; }; #ifdef DEBUG_EXTRA TLOG( cGetURI ); #endif }; if( strncmp( cGetURI, "/stream", 7 ) == 0 ) { uint32_t tStreamID = 0; CSTR tP; if( tP = strstr( cGetURI, "?" ) ) { CSTR tB; tP++; if( tB = strstr( tP, "id=" ) ) { tStreamID = atoi( tB+3 ); }; }; if( tStreamID ) { #ifdef DEBUG_EXTRA char tB[64]; sprintf(tB,"StremID: %d", tStreamID ); TLOG( tB ); #endif if( CTX->ModulePtr->registerForMediaStream( tStreamID, CTX ) ){ // Send Header if( send( CTX->m_iSocketFID, ht_head, strlen(ht_head), 0 ) < 0 ){ #ifdef DEBUG_EXTRA sprintf( mesg, "Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg); #endif CTX->bValid = false; }; CTX->initDone = true; continue; } #ifdef DEBUG_EXTRA else { TLOG("Stream id Not Online"); } #endif ; } #ifdef DEBUG_EXTRA else TLOG("No Stream ID") #endif ; }; if( CTX->ModulePtr->n_pNoSignalData ) { //Send Dummy Picture sprintf( mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize ); send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 ); send( CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0 ); send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 ); #ifdef DEBUG_EXTRA TLOG("Sent No Signal Image!"); #endif } else { // Send 404 Header send( CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0 ); #ifdef DEBUG_EXTRA TLOG("Aborted!"); #endif }; CTX->bValid = false; continue; } else { /* retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); if( retVal == -1 ){ if( errno == EAGAIN || errno == EWOULDBLOCK ){ continue; }; TLOG_ERROR("Pipe Communication Error[1]!"); CTX->bValid = false; continue; }; if( msgSize < FILESTREAMBUFFERSZ ) { retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); } else { TLOG_ERROR("Data too Big in Pipe Transfer!"); CTX->bValid = false; continue; }; if( retVal == -1 ){ //free( tBuf ); if( errno == EAGAIN || errno == EWOULDBLOCK ){ continue; }; TLOG_ERROR("Pipe Communication Error[2]!"); CTX->bValid = false; continue; }; */ /**************/ CTX->ModulePtr->m_mEncodedProtector.lock(); if( CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size() ) { msgSize = CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size(); if( msgSize < FILESTREAMBUFFERSZ ) { memcpy( tBuf, CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].data(), msgSize ); CTX->ModulePtr->m_mEncodedProtector.unlock(); } else { CTX->ModulePtr->m_mEncodedProtector.unlock(); TLOG_ERROR("Data too Big in Pipe Transfer!"); CTX->bValid = false; continue; }; } else { CTX->ModulePtr->m_mEncodedProtector.unlock(); if( CTX->ModulePtr->n_pNoSignalData ){ msgSize = CTX->ModulePtr->m_nNoSignalSize; memcpy( tBuf, CTX->ModulePtr->n_pNoSignalData, msgSize ); } else { TLOG_ERROR("Data too Big in Pipe Transfer!"); CTX->bValid = false; continue; }; }; /*********/ sprintf( mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize ); if( send( CTX->m_iSocketFID, mesg, strlen( mesg ), 0 )< 0 ){ #ifdef DEBUG_EXTRA sprintf( mesg, "[1]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg); #endif CTX->bValid = false; continue; }; if( send( CTX->m_iSocketFID, tBuf, msgSize, 0 ) < 0 ){ #ifdef DEBUG_EXTRA sprintf( mesg, "[2]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg); #endif CTX->bValid = false; continue; }; if( send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 )< 0 ){ #ifdef DEBUG_EXTRA sprintf( mesg, "[3]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg); #endif CTX->bValid = false; continue; }; SLEEP( 80 ); }; }; }; CTX->bValid = false; #ifdef DEBUG_EXTRA TLOG("WEB Client Handler Ended!"); #endif close( CTX->m_iEncoderPipe[0] ); shutdown( CTX->m_iSocketFID, SHUT_RDWR); close( CTX->m_iSocketFID ); //pthread_exit( NULL ); return NULL; }; void argusModuleEmbedVideo::m_fThreadProc( void ){ if( !m_bEnabled ) { #ifdef DEBUG LOG("Module is Disabled!"); #endif return; }; #ifdef DEBUG LOG("Module Started!"); #endif struct pollfd pfd[1]; pfd->fd = m_nSocketDescriptor; pfd->events = POLLIN | POLLHUP; m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ) { if( !m_bEnabled ) { m_bThreadStatus = TH_ENDED; continue; }; int RetVal = poll( pfd, 1, 1000 ); if( RetVal < 0 ){ if( EINTR == errno ) continue; LOG_ERROR("Unrecoverable error"); m_bThreadStatus = TH_ENDED; continue; }; // Handle Connections if( RetVal != 0 ){ if ( pfd[0].revents & POLLIN ) { #ifdef DEBUG_EXTRA LOG("Handle New Client"); #endif int tSID = accept( pfd[0].fd, NULL, NULL); if( tSID < 0 ){ char tBuf[CTEXT]; sprintf(tBuf, "Accept() error: %s", strerror(errno)); LOG_ERROR(tBuf); } else { #ifdef DEBUG_EXTRA LOG("Accept OK"); #endif WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); if( tCTX ) { #ifdef DEBUG_EXTRA LOG("CTX OK"); #endif WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); if( tHANDLER ) { #ifdef DEBUG_EXTRA LOG("HANDLER OK"); #endif memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) ); memset( tHANDLER, 0, sizeof(WEB_HANDLER) ); tCTX->m_iSocketFID = tSID; tCTX->m_iEncoderPipe[0] = -1; tCTX->m_iEncoderPipe[1] = -1; tCTX->mediaStreamId = 0; tCTX->bValid = true; tCTX->ModulePtr = this; #ifdef DEBUG_EXTRA LOG("Before Thread Create"); #endif int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX ); if( RetVal == -1 ) { free(tCTX); free(tHANDLER); LOG_ERROR("Thread Creation Faled."); shutdown( tSID, SHUT_RDWR ); close( tSID ); } else { tHANDLER->CTX = tCTX; m_mHandlersProtector.lock(); m_vHandlersPool.push_back( tHANDLER ); m_mHandlersProtector.unlock(); #ifdef DEBUG_EXTRA LOG("Handler Pushed to a Pool"); #endif }; } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click free(tCTX); LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); shutdown( tSID, SHUT_RDWR ); close( tSID ); }; } else { LOG_ERROR("CL_CTX Mem Allocation Failure!"); shutdown( tSID, SHUT_RDWR ); close( tSID ); }; }; }; }; // Handle Dead Clients if( m_vHandlersPool.size() ) { for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); ) { if( !( (*idx)->CTX->bValid ) ) { pthread_join( (*idx)->m_hThreadHandle, NULL ); //close( (*idx)->CTX->m_iEncoderPipe[0] ); close( (*idx)->CTX->m_iEncoderPipe[1] ); free( (*idx)->CTX ); free( (*idx) ); m_mHandlersProtector.lock(); m_vHandlersPool.erase(idx); m_mHandlersProtector.unlock(); #ifdef DEBUG_EXTRA LOG("Web Handler Ripped!"); #endif } else idx++; }; }; // validate active streams ? SLEEP( 50 ); }; }; #define ENABLE_SOCKOPT(sd, level, opt) \ do { \ int val = 1; \ if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ warn("Failed enabling %s for web service", #opt); \ } while (0); bool argusModuleEmbedVideo::startService(){ m_bEnabled = true; //Create NoSignal Image cv::Mat tMat( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 ); cv::rectangle( tMat, cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::Scalar( 255, 0, 0 ), cv::FILLED ); cv::putText( tMat, "NO SIGNAL", cv::Point( 10, 30 ), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar( 0, 255, 255 ), 3 ); if( m_sEmbedVideoData.show_logo ) { int a_x, a_y; if( m_sEmbedVideoData.logo_x < 0 ) { a_x = m_sEmbedVideoData.width + m_sEmbedVideoData.logo_x - m_sEmbedVideoData.logo_w; if( a_x < 0 ) a_x = 0; } else a_x = m_sEmbedVideoData.logo_x; if( ( a_x + m_sEmbedVideoData.logo_w ) > m_sEmbedVideoData.width ) a_x = m_sEmbedVideoData.width - m_sEmbedVideoData.logo_w; if( m_sEmbedVideoData.logo_y < 0 ) { a_y = m_sEmbedVideoData.height + m_sEmbedVideoData.logo_y - m_sEmbedVideoData.logo_h; if( a_y < 0 ) a_y = 0; } else a_y = m_sEmbedVideoData.logo_y; if( ( a_y + m_sEmbedVideoData.logo_h ) > m_sEmbedVideoData.height ) a_y = m_sEmbedVideoData.height - m_sEmbedVideoData.logo_h; if( ( a_x > -1 ) && ( a_y > -1 ) ) { char tName[256]; m_sEmbedVideoData.logo_x = a_x; m_sEmbedVideoData.logo_y = a_y; sprintf( tName, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 ); cv::Mat T = cv::imread( tName, cv::IMREAD_UNCHANGED ); if( T.cols > 0 ) { cv::Mat mask; vector layers; #ifdef DEBUG LOG("Logo Loaded OK"); #endif cv::split( T, layers); // seperate channels cv::Mat rgb[3] = { layers[0], layers[1], layers[2] }; mask = layers[3]; // png's alpha channel used as mask cv::merge( rgb, 3, T ); // put together the RGB channels, now transp insn't transparent cv::resize( T, m_mLogoPic, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC ); cv::resize( mask, m_mLogoMask, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC ); cv::Rect roi(cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h )); cv::Mat destinationROI = tMat( roi ); m_mLogoPic.copyTo( destinationROI, m_mLogoMask ); //m_sEmbedVideoData.show_logo = false; } else { LOG("Logo Disabled - No Picture is Loaded"); m_sEmbedVideoData.show_logo = false; }; } else { LOG("Logo Disabled - Wrong Coords"); m_sEmbedVideoData.show_logo = false; }; LOG("Logo Draw OK"); }; try{ vector compression_params; //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); //compression_params.push_back(9); compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); compression_params.push_back( m_sEmbedVideoData.compression_quality ); vector buf; cv::imencode( ".jpg", tMat, buf, compression_params ); m_nNoSignalSize = buf.size(); n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize ); if( n_pNoSignalData ) { memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize ); } else m_nNoSignalSize =0; buf.clear(); } catch (cv::Exception & e) { LOG_ERROR(e.msg.c_str()); }; // Socket struct sockaddr sa; struct sockaddr_in *sin; memset(&sa, 0, sizeof(struct sockaddr)); sa.sa_family = AF_INET; sin = (struct sockaddr_in *)&sa; sin->sin_addr.s_addr = htonl( INADDR_ANY ); sin->sin_port = htons( m_sEmbedVideoData.port ); m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); if( m_nSocketDescriptor == -1 ){ LOG_ERROR("Failed creating ACC socket"); return false; }; ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR); #ifdef SO_REUSEPORT ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT); #endif if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){ LOG_ERROR("Failed binding Socket"); close( m_nSocketDescriptor ); return false; } else { LOG("Bind Socessfull"); }; if( listen( m_nSocketDescriptor, 10) != 0 ){ LOG_ERROR("Failed setting web listen backlog"); close( m_nSocketDescriptor ); return false; } else { LOG("Listen OK"); }; LOG("Start Thread"); m_bEnabled = init(); return m_bEnabled; }; bool argusModuleEmbedVideo::stopService( bool force ){ m_bEnabled = false; m_bDetached = uninit(); #ifdef DEBUG LOG("Service Thread ended!"); #endif if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes #ifdef DEBUG char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); LOG( tB ); #endif for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) { if( force ) { #ifdef DEBUG LOG("Force Client Handler to Stop!"); #endif pthread_cancel( (*index)->m_hThreadHandle ); } else { #ifdef DEBUG LOG("Waiting Client Handler to End!"); #endif pthread_join( (*index)->m_hThreadHandle, NULL ); } }; m_vHandlersPool.clear(); }; #ifdef DEBUG LOG("No More Client Handlers!"); #endif if( m_mapCAPTURES.size() ){ m_mapCAPTURES.clear(); //for( mapSTREAMCAPS::iterator idx = m_mapCAPTURES.begin(); idx < m_mapCAPTURES.end(); idx++ ) { //}; }; if( m_mapMATS.size() ){ m_mapMATS.clear(); //for( mapSTREAMMAPS::iterator idx = m_mapMATS.begin(); idx < m_mapMATS.end(); idx++ ) { //}; }; if ( n_pNoSignalData ) { free( n_pNoSignalData ); n_pNoSignalData = NULL; m_nNoSignalSize = 0; }; return m_bDetached; }; bool argusModuleEmbedVideo::reloadSettings(){ LOG("Reload Service"); if( m_pDBC ){ DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); if( tDATA ) { if( stopService() ){ LOG("Stoped!"); memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); free( tDATA ); LOG("Starting..."); return startService(); } else { free( tDATA ); }; }; }; return false; }; bool argusModuleEmbedVideo::validate(){ bool RetVal = true; if( m_pDBC ){ DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); if( tDATA ) { if( memcmp( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0 ){ free( tDATA ); LOG("Module Settings Changed!"); return reloadSettings(); }; free( tDATA ); } else { RetVal = false; }; if ( RetVal ) { DBC_INT_LIST *tList = m_pDBC->listMediaStreams(0, LIST_VALID_RECORDS); if ( tList != NULL ) { for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ){ if( !registerStream( *idx ) ){ RetVal = false; break; }; }; delete ( tList ); }; }; 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; }; return RetVal; }; bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){ if( CTX ){ if( id ){ //Check if its Valid! DBC_MEDIA_STREAM_DATA *tSD = m_pDBC->getMediaStreamData( id ); if( tSD ) { //if( !tSD->valid ) { // free( tSD ); // return false; //}; free( tSD ); //if( pipe( CTX->m_iEncoderPipe ) == -1 ){ // CTX->bValid = false; // return false; //}; CTX->mediaStreamId = id; return true; }; }; } else LOG_ERROR("Client Context error!"); return false; }; void argusModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){ if( Evt ) { switch( Evt->m_eClass ) { case EVT_CLASS_IMAGE: case EVT_CLASS_VIDEO:{ switch( Evt->m_eType ) { case EVT_CAPTURE_START:{ #ifdef DEBUG LOG("Capture Event"); #endif if( Evt->m_ref_id && Evt->m_db_id ){ uint32_t tPicID = saveStreamPicture( Evt->m_ref_id ); if( tPicID ){ // //m_pDBC->addPictureEvent( Evt->m_db_id, tPicID ); } else { #ifdef DEBUG LOG_ERROR("No Picture is Saved!"); #endif }; } else { #ifdef DEBUG LOG_ERROR("No Stream ID or Event ID in Event Data!"); #endif }; break; }; }; break; }; case EVT_CLASS_CAMERA_CTRL:{ switch ( Evt->m_eType ) { case EVT_CAMERA_MOVE_TO:{ uint32_t sid = m_pDBC->getNodeAuxParam( Evt->m_nSourceNodeID ); if ( sid ) { mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(sid); if( hnd != m_mapHANDLERS.end() ){ (*hnd).second->triggerCamMove(); }; } break; }; case EVT_CAMERA_ON_POSITION:{ #ifdef DEBUG LOG("Cam On Position After Event -> Capture Picture"); #endif DBC_SNAPSHOT_DATA *tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData; if( tData ){ if( !saveStreamPicture( tData ) ) LOG_ERROR("Save Error!"); tData->assoc_event_ids.clear(); delete( tData ); Evt->m_pEvtData = NULL; } else LOG_ERROR("No Evt Data!"); break; }; }; break; }; }; }; }; //https://www.ps2-home.com/forum/viewtopic.php?t=98 //https://www.mikekohn.net/software/playstation2.php bool argusModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){ if( ptr == NULL ) return false; 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!"); #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 ){ 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 true; }; int argusModuleEmbedVideo::getWidh( void ){ if( m_sEmbedVideoData.width ) return m_sEmbedVideoData.width; return -1; }; int argusModuleEmbedVideo::getHeight( void ){ if( m_sEmbedVideoData.height ) return m_sEmbedVideoData.height; return -1; }; bool argusModuleEmbedVideo::generateSavePicPath( CSTR MD5, CSTR Output ){ if( MD5 == NULL ) return false; if( Output == NULL ) return false; if( !fileExist( m_pBaseSavePath ) ) { LOG_ERROR("No Base Picture Save Path Defined!"); return false; }; if( strlen(MD5) < 4 ) return false; char test[MAX_PATH]; sprintf( test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1] ); if( !fileExist( test ) ) { #ifdef __linux__ mkdir( test, STORAGE_DIR_MODE ); #else _mkdir( test ); #endif chown( test, "nobody", "nogroup" ); }; sprintf( test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3] ); if( !fileExist( test ) ) { #ifdef __linux__ mkdir( test, STORAGE_DIR_MODE ); #else _mkdir( test ); #endif chown( test, "nobody", "nogroup" ); }; sprintf( Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5 ); return true; }; bool argusModuleEmbedVideo::registerStream( uint32_t streamID ){ //Check if stream is not allready exists //for ( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ){ // if ( (*idx)->CTX->mediaStreamId == streamID ) return true; //}; try { streamHandler * tData = m_mapHANDLERS.at( streamID ); if( tData!= NULL ) return true; } catch (const std::out_of_range& oor ) { //std::cerr << "Out of Range error: " << oor.what() << '\n'; m_mapHANDLERS[streamID] = new streamHandler( this ); if ( m_mapHANDLERS[streamID] != NULL ) return m_mapHANDLERS[streamID]->create( streamID ); }; return false; }; bool argusModuleEmbedVideo::unregisterStream( uint32_t streamID ){ return true; }; #undef LOG #undef LOG_ERROR #define LOG( X ) streamHandler::m_pLog->Log( "MEV_STR", this, X ) #ifdef DEBUG #define LOG_ERROR( X ) {\ char _tBfrErrMSG2w34[256];\ sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ } #else #define LOG_ERROR( X ) streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, X ); #endif streamHandler::streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() { m_pLog = basicLogCollection::getInstance( ); memset( &m_sStreamData, 0, sizeof( DBC_MEDIA_STREAM_DATA ) ); m_pSource = NULL; m_bEvtMarkerCounter = 0; m_bCamMoveCounter = 0; #ifdef EVE_ENABLE_VIDEO m_nPreAlarmFrames = 0; m_nPostAlarmFrames = 0; m_nSegAFrameCounter = 0; m_nSegBFrameCounter = 0; m_nGlobalFrameCounter = 0; m_nVideoRegisteredDBID = 0; m_nSegAShiftFrames = 0; m_nSegBShiftFrames = 0; m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; m_nSegmentLimitFrames = 0; m_nHardLimitFrames = 0; m_bActiveEncoderStream = 0; m_bSegAActive = false; m_bSegADelete = true; m_bSegBActive = false; m_bSegBDelete = true; m_bCOP = 0; #endif //EVE_ENABLE_VIDEO }; streamHandler::~streamHandler(){ LOG("DESTRUCT!"); if ( m_sStreamData.id ) { if (m_pMaster != NULL) m_pMaster->unregisterStream(m_sStreamData.id); if ( m_pSource != NULL ) { switch( m_sStreamData.source_type[0] ) { case 'D': delete( ( videoLIVE555Source *) m_pSource ); break; case 'A': delete( ( videoAVLIBSource *) m_pSource ); break; }; }; #ifdef EVE_ENABLE_VIDEO closeAll(); #endif //EVE_ENABLE_VIDEO }; }; bool streamHandler::create( uint32_t stremID ){ if( stremID ) { DBC_MEDIA_STREAM_DATA *tData = mojoDBC::getInstance()->getMediaStreamData( stremID ); if ( tData ) { memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); free(tData); DBC_CAM_DATA *tCAM = mojoDBC::getInstance()->getCamData( m_sStreamData.source_id ); if( tCAM ){ CSTR tNAM = mojoDBC::getInstance()->getNodeName( tCAM->node_id ); m_sSourceDesc.mediaStreamId = stremID; m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; if ( tNAM!= NULL ) { strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); m_sSourceDesc.mediaName[127] = (char)0; free( tNAM ); } else { sprintf(m_sSourceDesc.mediaName, "No Name Cam"); }; switch( m_sStreamData.source_type[0] ) { case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break; case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break; }; if( m_pSource != NULL ) { char tMRL[1024]; #ifdef DEBUG LOG("Source OK"); #endif int tW = m_pMaster->getWidh(); int tH = m_pMaster->getHeight(); int pix = -1; bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 ); bool out_16_9 = (((tW*100) / tH ) > 140 ); //if( tW > 0 ){ // //m_pSource->setProportionalByWidth( tW ); // m_pSource->setSize( tW, tH ); //}; if( in_16_9 != out_16_9 ){ if( in_16_9 ){ tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000; } else { tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000; }; }; if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) { sprintf( tMRL, m_sStreamData.mrl ); } else { sprintf( tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl ); }; LOG( tMRL ); if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){ if( !m_pSource->attachDestination( this ) ){ delete( m_pSource ); m_pSource = NULL; } else { #ifdef DEBUG LOG("Source is Connected to Output."); #endif }; } else { LOG_ERROR("Can not Open Video Source!"); delete( m_pSource ); m_pSource = NULL; }; } else { LOG_ERROR("Video Source Stream Failure!"); }; free( tCAM ); } else { LOG_ERROR("Error Getting CAM Data!"); m_pSource = NULL; return false; }; }; }; if( m_pSource ){ #ifdef EVE_ENABLE_VIDEO return initVideoOutput(); #else return true; #endif // EVE_ENABLE_VIDEO }; return false; }; bool streamHandler::pushFrame( AVFrame *Frame, void* src){ if( m_pMaster == NULL ) return false; MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src; if( tMD ) { }; return true; }; bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ if( m_pMaster == NULL ) return false; MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; char tBuffer[128]; if( tMD ) { float mK, oK; cv::Rect ROI; m_pMaster->m_mPictureProtector.lock(); if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) { LOG("First Frame Enqueued"); sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId ); LOG( tBuffer ); m_pMaster->m_mapMATS[tMD->mediaStreamId].create( m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width, CV_8UC3 ); cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point( 0, 0 ), cv::Point( m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); }; #ifdef USE_SCALING_IN oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width); mK = ((float)Frame.rows )/ ((float)Frame.cols); //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) { ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; ROI.x = (int) 0; ROI.y = (int) 0; } else { if( mK < oK ) { ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK ); ROI.x = (int) 0; ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1; } else { ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK ); ROI.y = (int) 0; ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1; }; }; cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR ); #else if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){ Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] ); } else { //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows)); //src.copyTo(dst_roi); if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) { ROI.width = Frame.cols; ROI.height = Frame.rows; ROI.x = 0; ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1; cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); Frame.copyTo(mROI); } else { ROI.width = Frame.cols; ROI.height = Frame.rows; ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1; ROI.y = 0; cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); Frame.copyTo(mROI); }; }; #endif if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) { cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect( 10, 10, 20, 20 ), cv::Scalar( m_bCamMoveCounter, 0, 0 ), cv::FILLED ); m_bCamMoveCounter -=4; if ( m_bCamMoveCounter < 4 ) m_bCamMoveCounter = 0; } else { if ( m_bEvtMarkerCounter ) { m_bCamMoveCounter = 0; cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect( 10, 10, 20, 20 ), cv::Scalar( 0, 0, m_bEvtMarkerCounter ), cv::FILLED ); m_bEvtMarkerCounter -=4; if ( m_bEvtMarkerCounter < 4 ) m_bEvtMarkerCounter = 0; }; }; if (m_pMaster->m_sEmbedVideoData.show_label) { time_t t = time( NULL ); struct tm * tmp = gmtime( &t ); if( tmp ){ char tsb[64]; if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); int baseline=0; cv::Size textSize = cv::getTextSize( tBuffer, m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, m_pMaster->m_sEmbedVideoData.label_font_thickness, &baseline ); int x = m_pMaster->m_sEmbedVideoData.label_x; int y = m_pMaster->m_sEmbedVideoData.label_y; if( x < 0 ) { x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width; }; if( y < 0 ) { y = m_pMaster->m_sEmbedVideoData.height+y-baseline;// }; if( !m_pMaster->m_sEmbedVideoData.label_transperant ) { cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); }; cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( x, y ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, cv::Scalar( 0, 255, 0 ), m_pMaster->m_sEmbedVideoData.label_font_thickness, m_pMaster->m_sEmbedVideoData.label_line_type ); }; }; } else { if( m_pMaster->m_sEmbedVideoData.show_ts ){ time_t t = time( NULL ); struct tm * tmp = gmtime( &t ); if( tmp ){ if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){ uint8_t shift_x = 0; uint8_t shift_y = 15; if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) { if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { shift_y = 15; cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point( m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); } else { shift_y = 23; cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point( m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); }; cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type ); } else { if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { shift_y = 15; } else { shift_y = 23; }; cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type ); cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type ); cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1 ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type ); cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2 ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 0, 0 ), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type ); cv::putText( m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y ), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type ); } }; }; }; }; if( m_pMaster->m_sEmbedVideoData.show_logo ){ cv::Rect roi( cv::Point( m_pMaster->m_sEmbedVideoData.logo_x, m_pMaster->m_sEmbedVideoData.logo_y ), cv::Size( m_pMaster->m_sEmbedVideoData.logo_w, m_pMaster->m_sEmbedVideoData.logo_h ) ); cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi ); m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask ); }; vector compression_params; //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); //compression_params.push_back(9); compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality ); m_pMaster->m_mEncodedProtector.lock(); m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); m_pMaster->m_mEncodedProtector.unlock(); #ifdef EVE_ENABLE_VIDEO // encode Video Stream //m_nPreAlarmFrames //m_nPostAlarmFrames //m_nNoAlarmSegmentFrames //m_nSegmentLimitFrames //m_nHardLimitFrames if ( m_bSegAActive || m_bSegBActive ) { m_mFrameCounterProtector.lock(); 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 ) { 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(); /// @todo this tData pointer is never freed according to Valgrind ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER)); if ( tData ) { tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize(); tData->linesize[1] = 0; tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; tData->size = tData->linesize[0]*tData->rows; tData->data[1] = NULL; tData->data[0] = (uint8_t *)malloc( tData->size ); if ( tData->data[0] ) { memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size ); m_mEncodingQueueProtector.lock(); m_qEncodingQueue.push( tData ); m_mEncodingQueueProtector.unlock(); } else { LOG_ERROR("MAT_CPY malloc Error!"); free( tData ); }; } else LOG_ERROR("ENC_BUF malloc Error!"); }; #endif // EVE_ENABLE_VIDEO m_pMaster->m_mPictureProtector.unlock(); } else { LOG_ERROR("No PayLoad!"); }; return true; }; void streamHandler::closeSegmentA( void ){ m_mCurrentOperationProtector.lock(); if ( m_bCOP == 0 ) m_bCOP = 0x01; m_mCurrentOperationProtector.unlock(); LOG("Closing Stream A"); }; void streamHandler::closeSegmentB( void ){ m_mCurrentOperationProtector.lock(); if ( m_bCOP == 0 ) m_bCOP = 0x02; m_mCurrentOperationProtector.unlock(); LOG("Closing Stream B"); }; void streamHandler::closeAll(){ waitThreadEnd( true ); avcodec_send_frame( m_pCodecCtx, NULL ); int ret = 0; AVPacket *avp = av_packet_alloc(); if ( avp ) { do { av_packet_unref( avp ); ret = avcodec_receive_packet( m_pCodecCtx, avp ); if ( !ret ) { if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp ); if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp ); }; } while ( !ret ); av_packet_unref( avp ); av_packet_free( &avp ); }; if ( m_bSegAActive ) { av_write_trailer(m_pFormatCtxA); avformat_close_input( &m_pFormatCtxA ); m_bSegAActive = false; }; if ( m_bSegBActive ) { av_write_trailer(m_pFormatCtxB); avformat_close_input( &m_pFormatCtxB ); m_bSegBActive = false; }; }; bool streamHandler::openSegmentA( void ){ 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 }; }; return m_bSegAActive; }; bool streamHandler::openSegmentB( void ){ 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 }; }; return m_bSegBActive; }; bool streamHandler::initVideoOutput(){ m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000; m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; if( !initLibAV() ) return false; m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); if ( m_pFormat == NULL ) { LOG_ERROR("Out VideoFormat Not Found!"); return false; #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 ) { LOG_ERROR("Format CTX A alloc error!"); av_free( m_pFormat ); return false; } else { av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; }; if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { LOG_ERROR("Format CTX B alloc error!"); avformat_free_context( m_pFormatCtxA ); //av_free( m_pFormat ); return false; } else { av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; }; m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); if( m_pVideoCodec == NULL ){ LOG_ERROR("Out VideoCodec Not Found!"); avformat_free_context( m_pFormatCtxA ); avformat_free_context( m_pFormatCtxB ); //av_free( m_pFormat ); return false; #ifdef DEBUG } 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 ); //av_free( m_pFormat ); return false; #ifdef DEBUG } 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_free_context( m_pFormatCtxA ); avformat_free_context( m_pFormatCtxB ); //av_free( m_pFormat ); return false; #ifdef DEBUG } 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_free_context( m_pFormatCtxA ); 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; 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 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 } 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!" ); }; //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 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 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 ); //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 } else { LOG("output codec context is opened"); }; #endif #ifdef DEBUG } else { LOG("output codec context is already opened"); #endif }; 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 ); return init(); }; //encoding thread void streamHandler::m_fThreadProc( void ){ AVPacket mPacket; int bGotPacket; int rVal = 0; char tB[128]; av_init_packet( &mPacket ); while( m_bThreadStatus != TH_ENDED ){ //At the begining All streams are closed --> try to Open if( m_bThreadStatus < TH_WORKING ){ if( !openSegmentA() ){ m_bThreadStatus = TH_ENDED; continue; }; //if( !openSegmentB() ){ // m_bThreadStatus = TH_ENDED; // continue; //}; m_bThreadStatus = TH_WORKING; continue; }; m_mEncodingQueueProtector.lock(); if ( m_qEncodingQueue.size() ) { ENCODING_BUFFER *tData = m_qEncodingQueue.front(); 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(); }; do { mPacket.data = NULL; mPacket.size = 0; rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket ); 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_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; 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!"); av_strerror( rc, tB, 128 ); LOG_ERROR( tB ); break; //continue (changed since embed into do-while) }; }; if ( m_bSegBActive ) { mPacket.stream_index = m_pVideoStrB->index; mPacket.duration = 1; 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; 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!" ); av_strerror( rc, tB, 128 ); LOG_ERROR( tB ); break; //continue (changed since embed into do-while) }; }; av_packet_unref( &mPacket ); }; } 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 ); avio_close( m_pFormatCtxA->pb ); }; if ( m_bSegBActive ) { m_bSegBActive = false; 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(); // To Mark Events Frames m_bEvtMarkerCounter = 255; if ( m_nVideoRegisteredDBID == 0 ) { LOG("New Event!"); PF_TIMESTAMP ts; getPFTS( &ts ); if ( !m_bActiveEncoderStream ) { // Stream A is Active m_nVideoRegisteredDBID = mojoDBC::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 = mojoDBC::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::triggerCamMove( void ){ m_bCamMoveCounter = 255; 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 #undef TLOG #undef TLOG_ERROR