From e740dd705f363aff7ad3f0c803b9d3abb708662b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Charette?= Date: Mon, 9 Feb 2026 13:42:02 -0800 Subject: [PATCH 1/4] added a few comments about memory leaks detected using Valgrind (not yet fixed) --- Projects/la_mojo/build | 4 + lib/App/common/SQLite_dataBinder.cpp | 107 ++++++++++++----------- lib/App/common/deviceNodeSensor.cpp | 71 +++++++-------- lib/App/mojo/rgooseModuleEmbedVideo.cpp | 111 ++++++++++++------------ prereqvisites.txt | 20 ++--- scripts/initial.sh | 65 ++++++++++++++ 6 files changed, 220 insertions(+), 158 deletions(-) create mode 100644 scripts/initial.sh diff --git a/Projects/la_mojo/build b/Projects/la_mojo/build index 8d62327c..8b4d16d0 100755 --- a/Projects/la_mojo/build +++ b/Projects/la_mojo/build @@ -6,9 +6,13 @@ make clean -e "CFG=Debug86" make -e "CFG=Debug86" -j$(nproc) +cd Debug86 +#strip ./mojo_d +cd .. #make clean -e "CFG=Release86" #make -e "CFG=Release86" -j$(nproc) #cd Release86 #strip ./mojo #cd .. + diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp index 337ba6c7..45407f39 100644 --- a/lib/App/common/SQLite_dataBinder.cpp +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -74,8 +74,8 @@ bool sqliteDBC::checkRDFDir( CSTR basePath, REPORT_DIRINFO &RDF, bool recreate ) } else return false; }; return true; -}; -*/ +}; +*/ sqliteDBC::sqliteDBC( config_setting_t * Settings ):dataBinder(){ m_pLog = basicLogCollection::getInstance(); @@ -115,8 +115,8 @@ bool sqliteDBC::connect( void ){ m_bRepIsConnected = false; m_bStaIsConnected = false; m_bLastEventWasClosed = false; - - + + //Apply New Config #ifdef DEBUG LOG( "Reading DB Settings ... " ); @@ -175,7 +175,7 @@ bool sqliteDBC::connect( void ){ sprintf( m_pDbMemory, "%s/%s", DB_SHMEM_POINT, tBuff ); basicSettingsProvider::getInstance()->validate(); - // Kill Connection if any + // Kill Connection if any if ( m_pDataStorage ) delete( m_pDataStorage ); if ( m_pDataMemory ) delete( m_pDataMemory ); if ( m_pDataReports ) delete( m_pDataReports ); @@ -245,7 +245,7 @@ bool sqliteDBC::connect( void ){ #ifdef DEBUG LOG( m_pDbStat ); LOG("DB Statistics Opened"); -#endif +#endif m_pDataStatistics->SilentQuery("PRAGMA journal_mode=WAL"); m_bStaIsConnected = true; } else { @@ -270,7 +270,7 @@ bool sqliteDBC::connect( void ){ chmod( m_pDbStat, DB_FILE_MODE ); m_pDataStatistics->SilentQuery("PRAGMA journal_mode=WAL"); m_pDataStatistics->SilentQuery("CREATE TABLE IF NOT EXISTS \"days\" (\"year\" INTEGER,\"month\" INTEGER,\"day\" INTEGER,\"evt_count\" INTEGER DEFAULT 0,\"session_count\" INTEGER DEFAULT 0,\"videos_count\" INTEGER DEFAULT 0,\"session_closed\" INTEGER DEFAULT 0, CONSTRAINT \"date_uni\" UNIQUE(\"year\",\"month\",\"day\") );"); - m_bStaIsConnected = true; + m_bStaIsConnected = true; } else { LOG_ERROR("Cannot Connect to DB Statistics"); delete( m_pDataStorage ); @@ -337,7 +337,7 @@ bool sqliteDBC::connect( void ){ sprintf( m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sPRepInfo.YEAR, m_sPRepInfo.MONTH, m_sPRepInfo.DAY ); LOG( m_pDbReport ); if( fileExist( m_pDbReport ) ){ - SQLite_Connector *tDBC = new SQLite_Connector(); + SQLite_Connector *tDBC = new SQLite_Connector(); if ( tDBC ) { if( tDBC->Connect( m_pDbReport, 0, true) ) { char tQBuf[CTEXT]; @@ -398,7 +398,7 @@ bool sqliteDBC::connect( void ){ if( !checkRDFDir( m_pDbReportBase, m_sCRepInfo, true, getUserUid(web_access_user), getUserGid(web_access_group) ) ) { LOG_ERROR("Cannot Open Report!!"); return false; - }; + }; sprintf( m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); #ifdef DEBUG LOG( m_pDbReport ); @@ -409,7 +409,7 @@ bool sqliteDBC::connect( void ){ #endif chown( m_pDbReport, getUserUid(web_access_user), getUserGid(web_access_group) ); chmod( m_pDbReport, DB_FILE_MODE ); - //Recreate Table in any case + //Recreate Table in any case //if ( m_sCRepInfo.ts != m_sPRepInfo.ts || create_tables ) { // Created New Report ?? m_pDataReports->SilentQuery("CREATE TABLE IF NOT EXISTS \"events\" ( \"id\" INTEGER NOT NULL, \"node_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT NULL, \"lrf_id\" INTEGER, \"range_digital\" INTEGER, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, \"lat\" REAL, \"lon\" REAL, \"alt\" REAL, \"ref_id\" INTEGER, \"ref_uuid\" TEXT, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); @@ -427,7 +427,7 @@ bool sqliteDBC::connect( void ){ return false; }; }; - + return ( m_bRepIsConnected && m_bMemIsConnected && m_bStoIsConnected && m_bStaIsConnected ); }; @@ -512,7 +512,7 @@ DBC_PUSHED_CMD *sqliteDBC::getNodePushedCMD( uint32_t NodeID ){ }; #ifdef DEBUG_ALL } else { - + LOG("No Rows Fetched!"); #endif }; @@ -644,10 +644,10 @@ bool sqliteDBC::updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ){ }; -/******************************************************************** +/******************************************************************** + * * + * Slow DB Functions * * * - * Slow DB Functions * - * * ********************************************************************/ bool sqliteDBC::addLRFDraw( uint32_t node_id, CSTR uniq_id, uint8_t lrf_id, uint8_t type ){ if ( m_bStoIsConnected ){ @@ -676,7 +676,7 @@ bool sqliteDBC::addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *t fwrite( &sisi, 4, 1, fd ); fwrite( th_data, 4, sisi, fd ); fclose( fd ); - bool rV = addLRFDraw( DBID, uid, lrf, type ); + bool rV = addLRFDraw( DBID, uid, lrf, type ); free ( uid ); return rV; }; @@ -711,7 +711,7 @@ void sqliteDBC::updateStats( bool evt, bool video, uint8_t ses_status ){ REPORT_DIRINFO tRR = {0}; fillRDF( time( NULL ), tRR ); if( tRR.ts > m_sCRepInfo.ts ) { - //New Day Report + //New Day Report if ( m_bRepIsConnected ) { m_bRepIsConnected = false; LOG("Disconnect Report!"); @@ -748,7 +748,7 @@ void sqliteDBC::updateStats( bool evt, bool video, uint8_t ses_status ){ LOG( tQBuf ); #endif m_pDataStatistics->SilentQuery( tQBuf ); - + break; }; case SESSION_END:{ @@ -757,7 +757,7 @@ void sqliteDBC::updateStats( bool evt, bool video, uint8_t ses_status ){ #ifdef DEBUG_ALL LOG( tQBuf ); #endif - m_pDataStatistics->SilentQuery( tQBuf ); + m_pDataStatistics->SilentQuery( tQBuf ); break; }; case SESSION_DROP:{ @@ -779,7 +779,7 @@ bool sqliteDBC::dropSession(){ char tQBuf[1024]; AAssoc *result; #ifdef REMOVE_ONLY_SESSION_MARKS - sprintf( tQBuf, "SELECT `ts`, `ts_ms` FROM `events` WHERE `evt_type`=%d ORDER BY `ts` DESC,`ts_ms` DESC LIMIT 1", EVT_LRF_START_SESSION ); + sprintf( tQBuf, "SELECT `ts`, `ts_ms` FROM `events` WHERE `evt_type`=%d ORDER BY `ts` DESC,`ts_ms` DESC LIMIT 1", EVT_LRF_START_SESSION ); #else sprintf( tQBuf, "SELECT `ts`, `ts_ms` FROM `events` WHERE `evt_type`=%d ORDER BY `ts` DESC,`ts_ms` DESC LIMIT 1", EVT_LRF_START_SESSION ); #endif @@ -1098,7 +1098,7 @@ uint32_t sqliteDBC::addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t w camID, name, tM5, width, height, path, fps, width, height, fps ); #ifdef DEBUG_ALL LOG(tQBuf); -#endif +#endif RetVal = (uint32_t) m_pDataStorage->QueryID( tQBuf ); if( RetVal == 0 ){ RetVal = getMediaStreamID( camID, tM5 ); @@ -1111,7 +1111,7 @@ uint32_t sqliteDBC::addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t w uint32_t sqliteDBC::addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ uint32_t RetVal = 0; if( m_bStoIsConnected ) { - char tQBuf[MAX_PATH_LEN]; + char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `networks`(`nif_id`,`type`,`address`,`gateway`,`mask`,`broadcast`) VALUES (%d,%d,'%s','%s','%s','%s') ON CONFLICT(`nif_id`,`type`) DO UPDATE SET `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s'", NIF_ID, net_type, @@ -1131,7 +1131,7 @@ uint32_t sqliteDBC::addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CST // On Update IF data no need to return ID //if( RetVal == 0 ) { // RetVal = getNetworkInterfaceID( tKey ); - //}; + //}; }; return RetVal; }; @@ -1183,7 +1183,7 @@ uint32_t sqliteDBC::addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUT // On Update IF data no need to return ID if( RetVal == 0 ) { RetVal = getNetworkInfrastructureID( NIF_ID ); - }; + }; }; return RetVal; }; @@ -1311,7 +1311,7 @@ bool sqliteDBC::cleanLRFMask( uint32_t maskID, bool deleteMask ){ bool sqliteDBC::cleanLRFWidthTable( uint32_t sensorID ){ if( m_bStoIsConnected ) { - char tQBuf[MAX_PATH_LEN]; + char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "DELETE FROM `lrf_detection_width_tables` WHERE `aux_id`=%d", sensorID ); #ifdef DEBUG_ALL LOG(tQBuf); @@ -1435,11 +1435,11 @@ bool sqliteDBC::addLRFWidthTable( uint32_t sensorID, PWIDTH_TABLE ptr ){ bool sqliteDBC::addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ){ bool rVal = false; - if( ptr != NULL ){ + if( ptr != NULL ){ if( m_bRepIsConnected ){ char tQBuf[MAX_PATH_LEN]; uint32_t pic_id; - sprintf( tQBuf, "%s/%s/%s/%s/%s.%s", + sprintf( tQBuf, "%s/%s/%s/%s/%s.%s", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY, ptr->md5, ext ); #ifdef DEBUG_ALL LOG(tQBuf); @@ -1552,7 +1552,7 @@ DBC_MODULE_EMBED_VIDEO_DATA *sqliteDBC::getEmbedVideoData( uint32_t ID ){ tPtr = (DBC_MODULE_EMBED_VIDEO_DATA*)malloc(sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); if( tPtr!= NULL ) { Assoc::iterator it; - memset(tPtr,0,sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); + memset(tPtr,0,sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); cArr = result->at(0); it = cArr->find("output_mode"); if( it != cArr->end() ){ @@ -1985,7 +1985,7 @@ DBC_LRF_INI *sqliteDBC::getINIData( uint32_t lrfID ){ it = cArr->find("SAVE_FIRST_TH"); if( it != cArr->end() ){ tVal->_SAVE_FIRST_TH = (bool) atoi( it->second.c_str() ); - }; + }; }; }; }; @@ -1994,7 +1994,7 @@ DBC_LRF_INI *sqliteDBC::getINIData( uint32_t lrfID ){ return tVal; }; -bool sqliteDBC::getEventSessionStatus( uint32_t nodeID ){ +bool sqliteDBC::getEventSessionStatus( uint32_t nodeID ){ bool rv = false; if( m_bRepIsConnected ){ char tQBuf[CTEXT]; @@ -2024,7 +2024,7 @@ bool sqliteDBC::getEventSessionStatus( uint32_t nodeID ){ /* * The Last TS is from the current report (as latest) -*/ +*/ uint32_t sqliteDBC::getLastEventTS(){ uint32_t rv = 0; if( m_bRepIsConnected ){ @@ -2091,7 +2091,7 @@ uint32_t sqliteDBC::getFirstEventTS(){ return rv; }; -bool sqliteDBC::deleteReportDate( uint32_t ts ){ +bool sqliteDBC::deleteReportDate( uint32_t ts ){ if( ts ){ REPORT_DIRINFO tRDF = {0}; fillRDF( ts, tRDF ); @@ -2192,7 +2192,7 @@ DBC_LRF_DATA *sqliteDBC::getLRFData( uint32_t ID ){ it = cArr->find("filter_id"); if( it != cArr->end() ){ tVal->filter_id = atoi( it->second.c_str() ); - }; + }; it = cArr->find("enabled_lrf"); if( it != cArr->end() ){ tVal->enabled_lrf = atoi( it->second.c_str() ); @@ -2265,7 +2265,7 @@ PLGS_2D_PARAMETERS sqliteDBC::getLRFDetectionProfile( uint32_t lrfID, uint8_t pr char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `lrf_detection_profiles` WHERE `aux_id`=%d AND `profile_id`=%d AND `master`=%d", lrfID, profileID,((master)?1:0) ); - + #ifdef DEBUG_ALL LOG(tQBuf); #endif @@ -2471,7 +2471,7 @@ DBC_LRF_UPLOAD_DATA *sqliteDBC::getLRFUploadData( uint32_t upID ){ memset( RetVal, 0, sizeof(DBC_LRF_UPLOAD_DATA)); Assoc::iterator it; RetVal->id = upID; - cArr = result->at(0); + cArr = result->at(0); it = cArr->find("md5"); if( it != cArr->end() ){ strncpy( RetVal->md5, it->second.c_str(), 32 ); @@ -2552,7 +2552,7 @@ uint32_t sqliteDBC::getNodeAuxParam( uint32_t NodeID ){ if( result->size() > 0 ) { Assoc *cArr; Assoc::iterator it; - cArr = result->at(0); + cArr = result->at(0); it = cArr->find("aux_parameter"); if( it != cArr->end() ){ retVal = atoi( it->second.c_str() ); @@ -2582,7 +2582,7 @@ DBC_NODE_DATA *sqliteDBC::getNodeData( uint32_t ID ){ memset( tVal, 0, sizeof(DBC_NODE_DATA)); Assoc::iterator it; tVal->node_id = ID; - cArr = result->at(0); + cArr = result->at(0); it = cArr->find("type"); if( it != cArr->end() ){ tVal->type = /*(NODE_TYPE)*/ atoi( it->second.c_str() ); @@ -2629,7 +2629,7 @@ uint32_t sqliteDBC::getNodeIdByTypeAndAux( uint8_t type, uint32_t aux_id ){ if( result->size() > 0 ) { Assoc *cArr; Assoc::iterator it; - cArr = result->at(0); + cArr = result->at(0); it = cArr->find("id"); if( it != cArr->end() ){ retVal = atoi( it->second.c_str() ); @@ -2655,7 +2655,7 @@ CSTR sqliteDBC::getNodeName( uint32_t NodeID ){ if( result->size() > 0 ) { Assoc *cArr; Assoc::iterator it; - cArr = result->at(0); + cArr = result->at(0); it = cArr->find("name"); if( it != cArr->end() ){ retVal = strdup( it->second.c_str() ); @@ -2663,7 +2663,7 @@ CSTR sqliteDBC::getNodeName( uint32_t NodeID ){ }; }; deleteResult( result ); - }; + }; return retVal; }; @@ -2862,7 +2862,7 @@ REPORT_DIRINFO *sqliteDBC::getReportDirInfo( uint32_t id ){ cArr = result->at(0); it = cArr->find("year"); if( it != cArr->end() ){ - strncpy( tVal->YEAR, it->second.c_str(), 5 ); + strncpy( tVal->YEAR, it->second.c_str(), 5 ); }; it = cArr->find("month"); if( it != cArr->end() ){ @@ -2870,7 +2870,7 @@ REPORT_DIRINFO *sqliteDBC::getReportDirInfo( uint32_t id ){ }; it = cArr->find("day"); if( it != cArr->end() ){ - strncpy( tVal->DAY, it->second.c_str(), 3 ); + strncpy( tVal->DAY, it->second.c_str(), 3 ); }; }; }; @@ -2893,6 +2893,7 @@ DBC_RESOURCE_DATA *sqliteDBC::getResourceData( uint32_t ResourceID ){ if( result!= NULL ) { if( result->size() > 0 ) { Assoc *cArr; + /// @todo Valgrind tells us that tVal is lost and never freed tVal = (DBC_RESOURCE_DATA*) malloc(sizeof(DBC_RESOURCE_DATA)); if( tVal != NULL ) { Assoc::iterator it; @@ -3499,7 +3500,7 @@ DBC_INT_LIST *sqliteDBC::listMediaStreams( uint32_t SiteId, uint8_t listMode ){ char tQBuf[CTEXT]; AAssoc *result; switch( listMode ){ - case LIST_VALID_RECORDS: + case LIST_VALID_RECORDS: sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13,14,15) AND `ms`.`valid`=1 AND `nd`.`online`=1" ); break; case LIST_INVALID_RECORDS: @@ -3560,7 +3561,7 @@ DBC_INT_LIST *sqliteDBC::listModules(){ }; DBC_INT_LIST *sqliteDBC::listNewModules( DBC_INT_LIST * old_ids ){ - DBC_INT_LIST * tVal = NULL; + DBC_INT_LIST * tVal = NULL; if( m_bStoIsConnected ){ char tParam[CTEXT]; //memset( tParam, 0, CTEXT ); @@ -3601,7 +3602,7 @@ DBC_INT_LIST *sqliteDBC::listNewModules( DBC_INT_LIST * old_ids ){ }; DBC_INT_LIST *sqliteDBC::listNewNodes( DBC_INT_LIST * old_ids ){ - DBC_INT_LIST * tVal = NULL; + DBC_INT_LIST * tVal = NULL; if( m_bStoIsConnected ){ char tParam[CTEXT]; //memset( tParam, 0, CTEXT ); @@ -3878,7 +3879,7 @@ bool sqliteDBC::pushMemCMD( uint32_t NODE_ID, uint8_t CMD, CSTR DATA ){ void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ){ if( m_bStoIsConnected ){ m_nSiteID = SiteID; - + char tQBuf[MAX_PATH_LEN]; #ifdef DEFAULT_SERVER_ID sprintf( tQBuf, "INSERT INTO `servers`(`id`,`site_id`,`identity`,`version_string`) VALUES (%d,%d,'%s','%s') ON CONFLICT(`id`) DO UPDATE SET `identity`='%s',`version_string`='%s'", @@ -3913,7 +3914,7 @@ void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_ LOG(tQBuf); #endif m_nServerNodeID = ( uint32_t ) m_pDataStorage->QueryID( tQBuf ); - + if( m_nServerNodeID== 0 ){ m_nServerNodeID = getServerNode( m_nServerID ); }; @@ -3942,7 +3943,7 @@ void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_ //LOG(tQBuf); #endif //m_pDataStorage->SilentQuery( tQBuf ); - + //sprintf(tQBuf,"UPDATE `media_streams` SET `valid`=1 WHERE `source_id` IN ( SELECT `id` FROM `cameras` WHERE `online`=1 )" ); #ifdef DEBUG_ALL //LOG(tQBuf); @@ -3954,7 +3955,7 @@ void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_ // LOG(tQBuf); #endif // m_pDataStorage->SilentQuery( tQBuf ); - + //cleanResources( tServerNodeID ); setNodeOnline( m_nServerNodeID ); }; @@ -3995,7 +3996,7 @@ bool sqliteDBC::setLRFMaskStatus( uint32_t maskID, bool status ){ } else { sprintf( tQBuf, "UPDATE `lrf_masks` SET `status`='D' WHERE `id`=%d", maskID ); }; - + #ifdef DEBUG_ALL LOG(tQBuf); #endif @@ -4222,7 +4223,7 @@ bool sqliteDBC::getAppDebugMode(){ result = m_pDataStorage->Query( tQBuf ); if( result!= NULL ) { if( result->size() > 0 ) { - Assoc *cArr; + Assoc *cArr; Assoc::iterator it; cArr = result->at(0); it = cArr->find("work_mode"); @@ -4422,7 +4423,7 @@ DBC_CAM_DATA *sqliteDBC::getCamData( uint32_t ID ){ it = cArr->find("zoom"); if( it != cArr->end() ){ tVal->zoom = atof( it->second.c_str() ); - }; + }; it = cArr->find("max_range"); if( it != cArr->end() ){ tVal->max_range = atof( it->second.c_str() ); @@ -4852,7 +4853,7 @@ bool sqliteDBC::updateLRFDryContact( uint32_t lrfID, bool bAuto, bool bNO, uint1 if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_sensors` SET `dc_auto`=%d, `dc_no`=%d, `dc_window`=%d WHERE `id`=%d", bAuto, bNO, wWindow, lrfID ); - + #ifdef DEBUG_ALL LOG(tQBuf); #endif diff --git a/lib/App/common/deviceNodeSensor.cpp b/lib/App/common/deviceNodeSensor.cpp index c44acf5c..66a7f292 100644 --- a/lib/App/common/deviceNodeSensor.cpp +++ b/lib/App/common/deviceNodeSensor.cpp @@ -10,7 +10,7 @@ /* USER.INI - + AUTORESET_ENABLE=0 AUTORESET_INTERLEAVE=2000 AUTORESET_TIMEOUT=-5536 @@ -24,9 +24,9 @@ SWITCHER_COMMAND_TIMEOUT=500 SWITCHER_AUTO_MODE=0 SWITCHER_AUTO_ENTER_TIMEOUT=60 SWITCHER_AUTO_SWITCH_TIMEOUT=3 - - - + + + */ /* "ADDRESS", @@ -39,8 +39,8 @@ SWITCHER_AUTO_SWITCH_TIMEOUT=3 "RELAY_DELAY", "VOLTAGE_CONTROL", "MASTER_DISABLED", - "SLAVE_DISABLED", - + "SLAVE_DISABLED", + */ /* @@ -58,8 +58,8 @@ typedef struct S_DBC_LRF_INI{ uint16_t _JUST_MOVING_DISTANCE; uint16_t _FREEZ_FIRST_TH; uint16_t _SAVE_FIRST_TH; -}DBC_LRF_INI; - +}DBC_LRF_INI; + */ #define __INI_FILE_ENTRIES_CNT__ 13 @@ -188,7 +188,7 @@ deviceNodeSensor::deviceNodeSensor( uint32_t id ):deviceNode( id ),m_oPosition() case ARGUS_3D_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_3D; break; default: m_eEventClass = EVT_CLASS_SYSTEM; break; }; - setWM( LRF_WM_INIT ); + setWM( LRF_WM_INIT ); memset( &m_sLRF_DATA, 0, sizeof(DBC_LRF_DATA)); if( m_pDBC ){ DBC_LRF_DATA *tDATA = m_pDBC->getLRFData( m_sNodeData.aux_id ); @@ -203,7 +203,7 @@ deviceNodeSensor::deviceNodeSensor( uint32_t id ):deviceNode( id ),m_oPosition() #endif }; }; - + //m_pTargetFilter = NULL; systemAnchor *SA = systemAnchor::getInstance(); if( SA ){ @@ -233,9 +233,9 @@ deviceNodeSensor::deviceNodeSensor( uint32_t id ):deviceNode( id ),m_oPosition() LOG("Finish Construct!"); }; -deviceNodeSensor::deviceNodeSensor( DBC_NODE_DATA *Data ):deviceNode( Data ),m_oPosition(){ - m_nCommErrorsCounter = 0; - m_ePPMODE = STG_INIT; +deviceNodeSensor::deviceNodeSensor( DBC_NODE_DATA *Data ):deviceNode( Data ),m_oPosition(){ + m_nCommErrorsCounter = 0; + m_ePPMODE = STG_INIT; m_bValidationSkipCounter = DAFAULT_VALIDATION_SKIP_COUNTER; m_nCommErrorsStatTO = COMMUNICATION_ERROR_STATISTIC_HARVEST_INTERVAL_IN_SECONDS; m_pEventHeap = basicEventHeap::getInstance(); @@ -273,12 +273,12 @@ bool deviceNodeSensor::filterTargetData( TARGET_DATA *ptr ){ */ bool deviceNodeSensor::reloadDeviceNodeFromDB(){ - if( m_pDBC ){ + if( m_pDBC ){ DBC_LRF_DATA *tDATA = m_pDBC->getLRFData(m_sNodeData.aux_id); if( tDATA != NULL ) { memcpy( &m_sLRF_DATA, tDATA, sizeof(DBC_LRF_DATA)); free( tDATA ); - }; + }; } else return false; systemAnchor *SA = systemAnchor::getInstance(); if( SA ){ @@ -294,6 +294,7 @@ bool deviceNodeSensor::reloadDeviceNodeFromDB(){ m_oPosition.setPositionXYZ( m_sLRF_DATA.x , m_sLRF_DATA.y, m_sLRF_DATA.z ); m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); }; + /// @todo Valgrind tells us something in this next call to updateMatrix() is leaked m_oPosition.updateMatrix(); #ifdef DEBUG_EXTRA @@ -365,9 +366,9 @@ uint8_t *deviceNodeSensor::create2dDraw( uint32_t *out_size, uint32_t *th_data, const cv::Point * ppz[1]; int npz[1]; - + float rst; - + int rpt; uint16_t RANGE = 0; @@ -383,7 +384,7 @@ uint8_t *deviceNodeSensor::create2dDraw( uint32_t *out_size, uint32_t *th_data, }; float ca = 0.0 - ( S + i * stp ); - if( RANGE > 0 ){ + if( RANGE > 0 ){ pts[psize+i].x = x0 + maxR * cosf( ca ); pts[psize+i].y = y0 + maxR * sinf( ca ); if( RANGE > max_digital ){ @@ -394,7 +395,7 @@ uint8_t *deviceNodeSensor::create2dDraw( uint32_t *out_size, uint32_t *th_data, pts[i].x = x0 + cr * cosf( ca ); pts[i].y = y0 + cr * sinf( ca ); }; - } else { + } else { ptt[rpt].x = pts[psize+i].x = pts[i].x = x0 + maxR * cosf( ca ); ptt[rpt].y = pts[psize+i].y = pts[i].y = y0 + maxR * sinf( ca ); rpt++; @@ -519,8 +520,8 @@ bool deviceNodeSensor::handleDeviceDraw( uint8_t kID, void *th_data, size_t th_s case ARGUS_PLS_200_SENSOR: case ARGUS_PLS_360_SENSOR: case ARGUS_NET_PLS_200:{ - /* - 2D Sensors does not need Image to be created + /* + 2D Sensors does not need Image to be created #ifdef DEBUG_EXTRA LOG("DEV DRAW"); #endif @@ -553,8 +554,8 @@ bool deviceNodeSensor::handleDeviceDraw( uint8_t kID, void *th_data, size_t th_s }; #ifdef DEBUG_EXTRA LOG(" DD FINISH!"); - #endif - */ + #endif + */ break; }; case ARGUS_3D_SENSOR:{ @@ -626,7 +627,7 @@ bool deviceNodeSensor::handleDeviceDraw( uint8_t kID, void *th_data, size_t th_s //int RetVal = stbi_write_png( filename, 1024, 512, cSpace, tMemory, 1024 * cSpace ); vector compression_params; compression_params.push_back( cv::IMWRITE_PNG_COMPRESSION ); - compression_params.push_back(9); + compression_params.push_back(9); if(! cv::imwrite( filename, tImage, compression_params ) ){ tImage.release(); free( uid ); @@ -759,10 +760,10 @@ bool argus3DLIDAR::saveTHPicture( thresholdNode *ptr, CSTR uid, bool master, boo uint8_t *cPixel = NULL; int cSpace; - + int x, y; tMemory = stbi_load( "data/assets/images/empty_3d.png", &x, &y, &cSpace, STBI_default ); - + if( tMemory == NULL ){ LOG_ERROR("Draw Memory Alloc Eror!"); return false; @@ -952,7 +953,7 @@ void deviceNodeSensor::startWaitDeviceOnline( LRF_WORK_MODE wm, LRF_WORK_STAGE s m_SP_STAGE = stg; setWM( LRF_WM_WAIT_ONLINE_SPECIAL ); }; -uint8_t deviceNodeSensor::getSensStatus(){ +uint8_t deviceNodeSensor::getSensStatus(){ return m_sLRF_DATA.data_status; }; void deviceNodeSensor::updateDataStatus( uint8_t ds, uint8_t ns ){ @@ -1025,23 +1026,23 @@ void deviceNodeSensor::waitStateFunction( LRF_WORK_STAGE boboStage ){ }; void deviceNodeSensor::poolStateFunction(){ - goNextStage(); + goNextStage(); transactionResetResult(); }; bool deviceNodeSensor::initWModeFunction( uint8_t wm ){ if( getOWM() != wm ) { setWM( wm ); - setWM( wm ); + setWM( wm ); setStage( LRF_WS_INIT ); transactionResetResult(); - m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; + m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; return true; }; return false; }; -void deviceNodeSensor::m_fThreadProc( void ){ +void deviceNodeSensor::m_fThreadProc( void ){ time_t tTimeT_Current; time_t tTimeT_Old = time( NULL ); m_bThreadStatus = TH_WORKING; @@ -1063,19 +1064,19 @@ void deviceNodeSensor::m_fThreadProc( void ){ }; proceedDBCommands(); }; - + if( getWM() > LRF_WM_CONNECTION ){ if( !validateCommunicationRessource() ){ setWM( LRF_WM_CONNECTION ); DELAY_10MS( 200 ); }; - }; + }; switch( getWM() ) { case LRF_WM_INIT: reloadDeviceNodeFromDB(); setWM( LRF_WM_CONNECTION ); break; case LRF_WM_CONNECTION: connectMode(); break; case LRF_WM_HANDSHAKE: handshakeMode(); break; case LRF_WM_SYNC_UP: readMode(); break; - case LRF_WM_SYNC_DOWN: syncMode(); break; + case LRF_WM_SYNC_DOWN: syncMode(); break; case LRF_WM_BORDER: drawMode(); break; case LRF_WM_FULL_BORDER: fullDrawMode(); break; case LRF_WM_FILE: getfileMode(); break; @@ -1129,7 +1130,7 @@ LRF_WORK_STAGE deviceNodeSensor::getPrevStage(){ bool deviceNodeSensor::generateIniFile( uint8_t i ){ if ( m_pDBC == NULL ) return false; DBC_LRF_INI *tData = m_pDBC->getINIData( m_sNodeData.aux_id ); - if ( tData ) { + if ( tData ) { } else { LOG("No Data From DB! ---> Set Defaults!"); tData = (DBC_LRF_INI *) malloc( sizeof(DBC_LRF_INI)); diff --git a/lib/App/mojo/rgooseModuleEmbedVideo.cpp b/lib/App/mojo/rgooseModuleEmbedVideo.cpp index b2484bde..7575146d 100644 --- a/lib/App/mojo/rgooseModuleEmbedVideo.cpp +++ b/lib/App/mojo/rgooseModuleEmbedVideo.cpp @@ -89,7 +89,7 @@ argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelMo sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port ); LOG( tB ); sprintf( tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height ); - LOG( tB ); + 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"); @@ -113,7 +113,7 @@ argusModuleEmbedVideo::~argusModuleEmbedVideo(){ m_bEnabled = false; waitThreadEnd( true ); if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes -#ifdef DEBUG +#ifdef DEBUG char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); LOG( tB ); @@ -158,7 +158,7 @@ static const char * ht_no_signal = "HTTP/1.1 200 OK\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; @@ -183,7 +183,7 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ pfd->fd = CTX->m_iSocketFID; pfd->events = POLLIN | POLLHUP; - + while( CTX->bValid ) { if( !CTX->initDone ){ int RetVal; @@ -305,7 +305,7 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ TLOG_ERROR("Pipe Communication Error[1]!"); CTX->bValid = false; continue; - }; + }; if( msgSize < FILESTREAMBUFFERSZ ) { retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); } else { @@ -321,7 +321,7 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ TLOG_ERROR("Pipe Communication Error[2]!"); CTX->bValid = false; continue; - }; + }; */ /**************/ CTX->ModulePtr->m_mEncodedProtector.lock(); @@ -364,7 +364,7 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ #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)); @@ -495,10 +495,10 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ #ifdef DEBUG_EXTRA LOG("Web Handler Ripped!"); #endif - } else idx++; + } else idx++; }; - - }; + + }; // validate active streams ? SLEEP( 50 ); @@ -546,8 +546,8 @@ bool argusModuleEmbedVideo::startService(){ 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::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 ); @@ -624,11 +624,11 @@ bool argusModuleEmbedVideo::startService(){ bool argusModuleEmbedVideo::stopService( bool force ){ m_bEnabled = false; m_bDetached = uninit(); -#ifdef DEBUG +#ifdef DEBUG LOG("Service Thread ended!"); #endif if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes -#ifdef DEBUG +#ifdef DEBUG char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); LOG( tB ); @@ -636,12 +636,12 @@ bool argusModuleEmbedVideo::stopService( bool force ){ #endif for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) { if( force ) { -#ifdef DEBUG +#ifdef DEBUG LOG("Force Client Handler to Stop!"); #endif pthread_cancel( (*index)->m_hThreadHandle ); } else { -#ifdef DEBUG +#ifdef DEBUG LOG("Waiting Client Handler to End!"); #endif pthread_join( (*index)->m_hThreadHandle, NULL ); @@ -1137,7 +1137,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ m_pMaster->m_sEmbedVideoData.width, CV_8UC3 ); - cv::rectangle( + cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point( 0, 0 ), cv::Point( @@ -1224,11 +1224,11 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ 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_face, m_pMaster->m_sEmbedVideoData.label_font_scale, m_pMaster->m_sEmbedVideoData.label_font_thickness, &baseline @@ -1248,12 +1248,12 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ 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, + (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, @@ -1272,9 +1272,9 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) { if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { shift_y = 15; - cv::rectangle( + cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], - cv::Point( + cv::Point( m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y ), @@ -1413,13 +1413,13 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ #ifdef EVE_ENABLE_VIDEO // encode Video Stream - + //m_nPreAlarmFrames //m_nPostAlarmFrames //m_nNoAlarmSegmentFrames //m_nSegmentLimitFrames - //m_nHardLimitFrames + //m_nHardLimitFrames if ( m_bSegAActive || m_bSegBActive ) { m_mFrameCounterProtector.lock(); @@ -1442,7 +1442,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ LOG("Swap Active!(A)"); swapActiveStreams(); break; - }; + }; } while ( 0 ); }; @@ -1464,12 +1464,13 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ 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(); @@ -1745,12 +1746,12 @@ bool streamHandler::initVideoOutput(){ 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 @@ -1764,9 +1765,9 @@ bool streamHandler::initVideoOutput(){ #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 @@ -1793,9 +1794,9 @@ bool streamHandler::initVideoOutput(){ -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) - - + -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!"); @@ -1832,8 +1833,8 @@ bool streamHandler::initVideoOutput(){ 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); @@ -1853,11 +1854,11 @@ bool streamHandler::initVideoOutput(){ 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 ); @@ -1866,10 +1867,10 @@ bool streamHandler::initVideoOutput(){ 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; @@ -1915,10 +1916,10 @@ bool streamHandler::initVideoOutput(){ m_pConvertCtx = sws_getContext( m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, - AV_PIX_FMT_BGR24, + AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, - m_pMaster->m_sEmbedVideoData.height, - VIDEO_OUTPUT_PIX_FMT, + m_pMaster->m_sEmbedVideoData.height, + VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, @@ -1954,7 +1955,7 @@ void streamHandler::m_fThreadProc( void ){ int rVal = 0; char tB[128]; - av_init_packet( &mPacket ); + av_init_packet( &mPacket ); while( m_bThreadStatus != TH_ENDED ){ //At the begining All streams are closed --> try to Open if( m_bThreadStatus < TH_WORKING ){ @@ -1968,7 +1969,7 @@ void streamHandler::m_fThreadProc( void ){ //}; m_bThreadStatus = TH_WORKING; continue; - }; + }; m_mEncodingQueueProtector.lock(); if ( m_qEncodingQueue.size() ) { @@ -1980,8 +1981,8 @@ void streamHandler::m_fThreadProc( void ){ free( tData ); m_qEncodingQueue.pop(); /* - - + + AV_PICTURE_TYPE_NONE Undefined. AV_PICTURE_TYPE_I Intra. AV_PICTURE_TYPE_P Predicted. @@ -1990,8 +1991,8 @@ void streamHandler::m_fThreadProc( void ){ 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; @@ -2016,7 +2017,7 @@ void streamHandler::m_fThreadProc( void ){ m_mCurrentOperationProtector.lock(); switch ( m_bCOP ) { case 0x01:{ - m_bSegAActive = false; + m_bSegAActive = false; if ( !m_bSegADelete ) { av_write_trailer( m_pFormatCtxA ); avio_close( m_pFormatCtxA->pb ); @@ -2034,7 +2035,7 @@ void streamHandler::m_fThreadProc( void ){ #ifdef DEBUG LOG("Stream A is Deleted!"); #endif - }; + }; break; }; case 0x02:{ @@ -2141,7 +2142,7 @@ void streamHandler::swapActiveStreams( void ){ } else { m_bActiveEncoderStream = 0; m_nVideoRegisteredDBID = 0; - // No need to continue Stream B if no Events + // No need to continue Stream B if no Events if ( m_bSegBDelete ) closeSegmentB(); }; //m_mFrameCounterProtector.unlock(); @@ -2193,7 +2194,7 @@ bool streamHandler::triggerCamMove( void ){ }; bool streamHandler::validate( void ){ - if ( m_pSource ) + if ( m_pSource ) #ifdef EVE_ENABLE_VIDEO if( m_bThreadStatus < TH_ENDED ) #endif diff --git a/prereqvisites.txt b/prereqvisites.txt index a0761ba6..ce35b243 100644 --- a/prereqvisites.txt +++ b/prereqvisites.txt @@ -1,15 +1,5 @@ -libconfig-dev -libavcodec-dev -libavformat-dev -libavdevice-dev -libcurl4-openssl-dev -default-libmysqlclient-dev -libi2c-dev -libssl-dev -libv4l-dev -libhidapi-dev -libgphoto2-dev - - -sudo apt-get install openssl libssl-dev -apt-get install libmodbus-dev \ No newline at end of file + +# no longer needed: libhidapi-dev libgphoto2-dev + +apt-get install libconfig-dev libavcodec-dev libavformat-dev libavdevice-dev libcurl4-openssl-dev default-libmysqlclient-dev libi2c-dev libssl-dev libv4l-dev openssl libssl-dev + diff --git a/scripts/initial.sh b/scripts/initial.sh new file mode 100644 index 00000000..80c02e57 --- /dev/null +++ b/scripts/initial.sh @@ -0,0 +1,65 @@ +#!/usr/bash + +#disable eth0 renaming!! +#nano /etc/default/grubCOPY +#Look for GRUB_CMDLINE_LINUX line and add net.ifnames=0 biosdevname=0. +#grub-mkconfig -o /boot/grub/grub.cfg +#update nano /etc/network/interfaces + +systemctl stop apparmor +systemctl disable apparmor +apt remove --assume-yes --purge apparmor +rm -R /etc/apparmor.d +apt update +apt install net-tools --assume-yes +apt install mc --assume-yes +apt install samba smbclient cifs-utils --assume-yes +apt install hostapd --assume-yes +?? apt install dhcpcd5 --assume-yes +apt install dnsmasq --assume-yes +apt install rsync --assume-yes +#add /sbin/ to a root path at /etc/profile +if [ "$(id -u)" -eq 0 ]; then + PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +else + PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games" +fi +export PATH + +apt install build-essential --assume-yes +apt install curl --assume-yes +apt install nginx --assume-yes +apt install php php-fpm --assume-yes +apt install php-curl --assume-yes +apt install php-simplexml --assume-yes +apt install php-sqlite3 --assume-yes +apt install v4l-utils --assume-yes +# php-fpm.conf change Upload limit to 16M +# add user www-data to video group +# set security.limit_extensions in /etc/php ... fmp/pool/web.comf +apt install libconfig9 --assume-yes +apt install libconfig-dev +apt install libopencv-dev +apt install libavdevice-dev +apt install libssl-dev +apt install libcurl4-openssl-dev +apt install libsqlite3-dev +apt install libhidapi-dev +#add as source deb http://www.deb-multimedia.org bullseye main +apt-get update -oAcquire::AllowInsecureRepositories=true +apt-get install deb-multimedia-keyring +apt-get install liblivemedia-dev + +#copy /usr/include/groupsock/* to /usr/include +#copy /usr/include/UsageEnvironment/* to .. +#copy /usr/include/BasicUsageEnvironment/* to .. +apt install sqlite3 + + +############################################# END MINIMAL SUPPORT + +apt install librdkafka-dev +apt install default-libmysqlclient-dev +apt install libv4l-dev +## add to fstab option "barrier=1" + From 4eda7aab94ac5010669bcdcf8c89858a2a22e764 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Charette?= Date: Mon, 9 Feb 2026 14:25:36 -0800 Subject: [PATCH 2/4] bug #4: when reporting available memory, consider linux kernel file cache as 'available' --- lib/App/common/hardwareManager.cpp | 67 +++++++++++++++--------------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/lib/App/common/hardwareManager.cpp b/lib/App/common/hardwareManager.cpp index 6b352810..d4d053d5 100644 --- a/lib/App/common/hardwareManager.cpp +++ b/lib/App/common/hardwareManager.cpp @@ -66,7 +66,7 @@ hardwareManager::hardwareManager( bool cold_start ){ m_nSiteID = 0; #ifdef MEMORY_CONSUMPTION_LIMIT m_bCacheCleanCounter = 3; -#endif +#endif memset( &m_sSYS_INFO, 0, sizeof(DBC_SYS_INFO) ); strncpy( m_sSYS_INFO.SW_INFO, _BUILD_STRING_, 128 ); config_setting_t * m_pSettings = basicSettingsProvider::getInstance()->getSubNode( NULL, "HARDWARE" ); @@ -106,7 +106,7 @@ hardwareManager::hardwareManager( bool cold_start ){ fclose( fd ); fd = NULL; }; -#else +#else FILE *fd = NULL; #endif @@ -142,14 +142,14 @@ hardwareManager::hardwareManager( bool cold_start ){ }; }; }; - }; + }; m_sSYS_INFO.HW_INFO[127] = (char)0; trim( m_sSYS_INFO.HW_INFO ); fclose( fd ); fd = NULL; }; -#ifdef USE_MYSQL +#ifdef USE_MYSQL m_pDBC = mysqlDBC::getInstance(); #else m_pDBC = sqliteDBC::getInstance(); @@ -197,12 +197,12 @@ void hardwareManager::unloadResources( void ){ if( m_vResources.size() ) { for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { switch( (*idx)->getHardwareType() ) { - case HARDWARE_UART: + case HARDWARE_UART: case HARDWARE_IP_UART: delete( ( hardwareResourceSerialProvider*)(*idx) ); break; case HARDWARE_NIF_LOOPBACK: case HARDWARE_NIF_ETHERNET: case HARDWARE_NIF_WIFI: - case HARDWARE_NIF_VIRTUAL: + case HARDWARE_NIF_VIRTUAL: case HARDWARE_NIF_TUNEL: delete( ( hardwareResourceNetwork*)(*idx) ); break; }; }; @@ -244,7 +244,7 @@ void hardwareManager::loadResources( void ){ case HARDWARE_NIF_LOOPBACK: case HARDWARE_NIF_ETHERNET: case HARDWARE_NIF_WIFI: - case HARDWARE_NIF_VIRTUAL: + case HARDWARE_NIF_VIRTUAL: case HARDWARE_NIF_TUNEL:{ #ifdef DEBUG LOG("Construct NetIF"); @@ -503,7 +503,7 @@ PARSE_RESULT_NET_INTERFACES *hardwareManager::parse_neconfig( CSTR if_name ){ if(strstr((*idx), "allow-hotplug")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->hot_plug = true; if(strstr((*idx), "iface")!= NULL ) if( strstr( tB, if_name )!= NULL ){ if (strstr( tB, "static") != NULL) tVal->if_static = true; - cConfig = true; + cConfig = true; } else cConfig = false; if(strstr((*idx), "address")!= NULL ) if( cConfig ){ idx++; @@ -512,7 +512,7 @@ PARSE_RESULT_NET_INTERFACES *hardwareManager::parse_neconfig( CSTR if_name ){ strncpy( tVal->address, (*idx), sh ); tVal->address[sh]=(char)0; int8_t bm = atoi( (*idx) + sh + 1 ); - union{ + union{ uint32_t mm; uint8_t nm[4]; } nmu = {0}; @@ -564,7 +564,7 @@ PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){ fd = fopen("/etc/dnsmasq.conf","r"); if ( fd ) { char tB[1024]; - char expBuf[1024]; + char expBuf[1024]; while (!feof(fd)) { fgets((CSTR)tB, 1024, fd); trim((CSTR)tB); @@ -577,7 +577,7 @@ PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){ if( strstr(CA->at(0), "interface")!= NULL ) { if( strstr( tB, if_name)!= NULL ) { cConfig = true; - tVal->dhcp_enabled = true; + tVal->dhcp_enabled = true; }; }; if( cConfig ){ @@ -611,7 +611,7 @@ PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){ sprintf( tName, "iwconfig %s", if_name ); fd = popen( tName, "r" ); if ( fd ) { - char tB[1024]; + char tB[1024]; while (!feof(fd)) { fgets((CSTR)tB, 1024, fd ); trim( tB ); @@ -625,7 +625,7 @@ PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){ fd = fopen("/etc/hostapd/hostapd.conf", "r"); if ( fd ) { char tB[1024]; - char expBuf[1024]; + char expBuf[1024]; while (!feof(fd)) { fgets((CSTR)tB, 1024, fd); trim( tB ); @@ -658,7 +658,7 @@ PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){ fd = fopen("/etc/rc.local","r"); if ( fd ) { char tB[1024]; - char expBuf[1024]; + char expBuf[1024]; while (!feof(fd)) { fgets((CSTR)tB, 1024, fd); trim((CSTR)tB); @@ -737,7 +737,7 @@ void hardwareManager::enumerateNIFS( void ){ LOG("Enumerating Network Interfaces"); #endif struct ifaddrs * ifa; - + for( ifa = ifaddr; ifa; ifa = ifa->ifa_next ){ char addr[INET6_ADDRSTRLEN]; char mask[INET6_ADDRSTRLEN]; @@ -857,7 +857,7 @@ void hardwareManager::enumerateNIFS( void ){ sprintf( tBuffer, "NIF(%s) added as [%d]", device, nif_id ); LOG( tBuffer ); #endif - if ( nif_type == NIF_WIFI ){ + if ( nif_type == NIF_WIFI ){ if( nif_id == 0 ){ LOG_ERROR("Error Adding NIF in DB!"); continue; @@ -950,8 +950,8 @@ void hardwareManager::enumerateNIFS( void ){ LOG("NIF Already added (regular Mode)!"); #endif }; - - + + m_pDBC->addResource( /*m_nServerNodeID,*/ res_type, device, nif_id ); if( ifa->ifa_addr->sa_family == AF_INET ){ net_type = NETWORK_IPV4; @@ -963,7 +963,7 @@ void hardwareManager::enumerateNIFS( void ){ (uint8_t)ifa->ifa_netmask->sa_data[3], (uint8_t)ifa->ifa_netmask->sa_data[4], (uint8_t)ifa->ifa_netmask->sa_data[5] - ); + ); sprintf( bc, "%d.%d.%d.%d", (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2], (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3], @@ -1036,8 +1036,8 @@ void hardwareManager::enumerateNIFS( void ){ void hardwareManager::enumerateHardware( void ){ char tBuffer[CTEXT]; DIR * dFD = NULL; - struct dirent * pDR = NULL; - + struct dirent * pDR = NULL; + //ToDo: Check Ability to work without Kernel and DBC //if( m_pKernel == NULL ) return; if( m_pDBC == NULL ) return; @@ -1234,7 +1234,7 @@ uint32_t hardwareManager::createResourceVIDEO( CSTR devName ){ struct stat st; sprintf( dev_name, "/dev/%s", devName ); - + if (-1 == stat( dev_name, &st )) { sprintf( tBuffer, "Cannot identify '%s': %d, %s\\n", dev_name, errno, strerror(errno)); LOG_ERROR( tBuffer ); @@ -1408,7 +1408,7 @@ bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){ if ( ptr == NULL) return false; struct sysinfo SI; struct statvfs DI; - + ptr->CPU_CORES = get_nprocs(); if( sysinfo( &SI ) == 0 ){ @@ -1417,7 +1417,8 @@ bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){ ptr->cpu5 = SI.loads[1] * f_load; ptr->cpu15 = SI.loads[2] * f_load; ptr->T_MEM = SI.totalram * SI.mem_unit; - ptr->C_MEM = ( SI.totalram - SI.freeram ) * SI.mem_unit; + // "freeram" is obvious, and "bufferram" is memory temporarily used by the kernel to cache some files + ptr->C_MEM = ( SI.totalram - SI.freeram - SI.bufferram ) * SI.mem_unit; ptr->mem = 100.0f * (float)ptr->C_MEM / (float)ptr->T_MEM; #ifdef DEBUG_EXTRA char tB[128]; @@ -1428,16 +1429,16 @@ bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){ if ( ptr->mem > 80.0f ) { LOG_ERROR( "Try to free some caches!" ); /* - + To free pagecache: - # echo 1 > /proc/sys/vm/drop_caches - + # echo 1 > /proc/sys/vm/drop_caches + To free dentries and inodes: - # echo 2 > /proc/sys/vm/drop_caches - + # echo 2 > /proc/sys/vm/drop_caches + To free pagecache, dentries and inodes: - # echo 3 > /proc/sys/vm/drop_caches - + # echo 3 > /proc/sys/vm/drop_caches + */ //system( "echo 1 > /proc/sys/vm/drop_caches" ); if( m_bCacheCleanCounter ) { @@ -1452,7 +1453,7 @@ bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){ LOG_ERROR("Error while getting System Info!"); }; //const uint32_t MB = 1 << 10;//(1024 * 1024);// * 1024; - + if( statvfs("/", &DI) == 0 ){ ptr->T_DISK = ( DI.f_blocks * (unsigned long long) DI.f_frsize ) >> 10;// / MB; //cDISK = ( DI.f_bavail * (unsigned long long) DI.f_bsize ) >> 10;// / MB; @@ -1486,7 +1487,7 @@ bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){ } else break; }; }; - + return m_pDBC->updateServerUtilisation( ptr ); }; From c0dd7679b8dce96c17845f1fccdd4f02bbb69f28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Charette?= Date: Mon, 9 Feb 2026 20:24:09 -0800 Subject: [PATCH 3/4] add -g3 flag to get full debug information --- Projects/la_mojo/la_mojo.vpj | 8 ++++---- Projects/la_mojo/makefile | 32 ++++++++++++++++---------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Projects/la_mojo/la_mojo.vpj b/Projects/la_mojo/la_mojo.vpj index 16982da8..8fdba8a5 100644 --- a/Projects/la_mojo/la_mojo.vpj +++ b/Projects/la_mojo/la_mojo.vpj @@ -26,7 +26,7 @@ SaveOption="SaveCurrent" RunFromDir="%rw"> - + - + Date: Mon, 9 Feb 2026 20:24:39 -0800 Subject: [PATCH 4/4] added several comments with Valgrind information on memory leaks --- lib/App/common/SQLite_dataBinder.cpp | 16 ++ lib/App/common/hardwareManager.cpp | 35 +++ lib/App/common/kernelModuleEmbedVideo.cpp | 291 ++++++++++++---------- lib/alg/generic/md5.cpp | 18 ++ lib/components/base/basicPosition.cpp | 21 +- lib/data/media/video/videoAVLIBSource.cpp | 142 +++++++---- 6 files changed, 327 insertions(+), 196 deletions(-) diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp index 45407f39..39ed9d19 100644 --- a/lib/App/common/SQLite_dataBinder.cpp +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -2950,6 +2950,22 @@ uint32_t sqliteDBC::getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID return RetVal; }; DBC_SITE_DATA *sqliteDBC::getSiteData( uint32_t ID ){ + + /** @todo Valgrind is reporting an important memory leak in this method. + * See these details: + * + * ~~~~ + ==00:00:04:04.218 26021== 28,304 bytes in 122 blocks are definitely lost in loss record 3,966 of 3,972 + ==00:00:04:04.218 26021== at 0x483877F: malloc (vg_replace_malloc.c:307) + ==00:00:04:04.218 26021== by 0x23452A: sqliteDBC::getSiteData(unsigned int) (SQLite_dataBinder.cpp:2981) + ==00:00:04:04.218 26021== by 0x1DA681: mojoKernel::validateReports() (mojoKernel.cpp:1347) + ==00:00:04:04.218 26021== by 0x1D7D16: mojoKernel::m_fThreadProc() (mojoKernel.cpp:511) + ==00:00:04:04.218 26021== by 0x131B54: basicThread::m_fThreadEntryPoint(void*) (basicThread.cpp:62) + ==00:00:04:04.218 26021== by 0x49B7EA6: start_thread (pthread_create.c:477) + ==00:00:04:04.218 26021== by 0x7874ADE: clone (clone.S:95) + * ~~~~ + */ + DBC_SITE_DATA * tVal = NULL; if( m_bStoIsConnected ){ char tQBuf[CTEXT]; diff --git a/lib/App/common/hardwareManager.cpp b/lib/App/common/hardwareManager.cpp index d4d053d5..cb9ea20b 100644 --- a/lib/App/common/hardwareManager.cpp +++ b/lib/App/common/hardwareManager.cpp @@ -215,6 +215,41 @@ void hardwareManager::unloadResources( void ){ }; void hardwareManager::loadResources( void ){ + + /** @todo Valgrind is showing several memory leaks from this function. + * + * ~~~~ + ==00:00:04:04.207 26021== 513 (480 direct, 33 indirect) bytes in 1 blocks are definitely lost in loss record 3,863 of 3,972 + ==00:00:04:04.207 26021== at 0x4838DEF: operator new(unsigned long) (vg_replace_malloc.c:342) + ==00:00:04:04.207 26021== by 0x16D0EF: hardwareManager::loadResources() (hardwareManager.cpp:318) + ==00:00:04:04.207 26021== by 0x16C9CE: hardwareManager::hardwareManager(bool) (hardwareManager.cpp:174) + ==00:00:04:04.207 26021== by 0x16C470: hardwareManager::getInstance(bool) (hardwareManager.cpp:55) + ==00:00:04:04.207 26021== by 0x1D6E89: mojoKernel::create() (mojoKernel.cpp:264) + ==00:00:04:04.207 26021== by 0x1D5C60: main (mojoBackend.cpp:476) + ==00:00:04:04.207 26021== by 0x779CD79: __libc_start_main (libc-start.c:308) + ==00:00:04:04.207 26021== by 0x124CF9: _start (in /home/stephane/src/argus/Projects/la_mojo/Debug86/mojo_d) + ==00:00:04:04.207 26021== by 0x1FFF000497: ??? + ==00:00:04:04.207 26021== by 0x1B: ??? + * ~~~~ + * + * And: + * + * ~~~~ + ==00:00:04:04.198 26021== 240 bytes in 3 blocks are definitely lost in loss record 3,796 of 3,972 + ==00:00:04:04.198 26021== at 0x483877F: malloc (vg_replace_malloc.c:307) + ==00:00:04:04.198 26021== by 0x233EAA: sqliteDBC::getResourceData(unsigned int) (SQLite_dataBinder.cpp:2897) + ==00:00:04:04.198 26021== by 0x16CD43: hardwareManager::loadResources() (hardwareManager.cpp:260) + ==00:00:04:04.198 26021== by 0x16C9CE: hardwareManager::hardwareManager(bool) (hardwareManager.cpp:174) + ==00:00:04:04.198 26021== by 0x16C470: hardwareManager::getInstance(bool) (hardwareManager.cpp:55) + ==00:00:04:04.198 26021== by 0x1D6E89: mojoKernel::create() (mojoKernel.cpp:264) + ==00:00:04:04.198 26021== by 0x1D5C60: main (mojoBackend.cpp:476) + ==00:00:04:04.198 26021== by 0x779CD79: __libc_start_main (libc-start.c:308) + ==00:00:04:04.198 26021== by 0x124CF9: _start (in /home/stephane/src/argus/Projects/la_mojo/Debug86/mojo_d) + ==00:00:04:04.198 26021== by 0x1FFF000497: ??? + ==00:00:04:04.198 26021== by 0x1B: ??? + * ~~~~ + */ + if( m_pDBC == NULL ) return; DBC_INT_LIST *tVal; tVal = m_pDBC->listResources( );//load whole site resources diff --git a/lib/App/common/kernelModuleEmbedVideo.cpp b/lib/App/common/kernelModuleEmbedVideo.cpp index 09e670be..14a2faea 100644 --- a/lib/App/common/kernelModuleEmbedVideo.cpp +++ b/lib/App/common/kernelModuleEmbedVideo.cpp @@ -147,7 +147,7 @@ kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){ //Sanity check LOG("Sanity check in Destructor!"); - waitThreadAEnd( true ); + waitThreadAEnd( true ); if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes #ifdef DEBUG char tB[200]; @@ -177,7 +177,7 @@ kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){ LOG("No More Viewers Left"); #endif - + #ifdef DEBUG_EXTRA LOG("Deleting CAPS"); #endif @@ -209,7 +209,7 @@ static const char * ht_head = "HTTP/1.1 200 OK\r\n" "Pragma: no-cache\r\n" "Expires: 0\r\n" "MIME-version: 1.0\r\n" - "Connection: close\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" @@ -245,7 +245,7 @@ uint8_t kernelModuleEmbedVideo::getMediaMode( void ){ }; void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ - + WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; kernelModuleEmbedVideo * MODULE = CTX->ModulePtr; @@ -274,7 +274,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ pfd->fd = CTX->m_iSocketFID; pfd->events = POLLIN | POLLHUP; - + while( CTX->bValid && w ) { if( !CTX->initDone ){ int RetVal; @@ -332,7 +332,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ if( strncmp( cGetURI, "/video_feed", 11 ) == 0 ) { uint32_t tStreamID = 0; CSTR tP; -#ifdef HAVE_SMAL_PREVIEW_STREAMS +#ifdef HAVE_SMAL_PREVIEW_STREAMS if( tP = strstr( cGetURI, "/preview" ) ) CTX->bPreviewMode = true; #endif if( tP = strstr( cGetURI, "?" ) ) { @@ -409,7 +409,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ TLOG_ERROR("Pipe Communication Error[1]!"); CTX->bValid = false; continue; - }; + }; if( msgSize < FILESTREAMBUFFERSZ ) { retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); } else { @@ -425,7 +425,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ TLOG_ERROR("Pipe Communication Error[2]!"); CTX->bValid = false; continue; - }; + }; */ /**************/ CTX->ModulePtr->m_mEncodedProtector.lock(); @@ -517,7 +517,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ close( CTX->m_iEncoderPipe[0] ); shutdown( CTX->m_iSocketFID, SHUT_RDWR); SLEEP( 3 ); - close( CTX->m_iSocketFID ); + close( CTX->m_iSocketFID ); CTX->bValid = false; #ifdef DEBUG_EXTRA TLOG("WEB Client Handler Ended!"); @@ -528,7 +528,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ void *kernelModuleEmbedVideo::viewClientProc( void *ptr ){ - + WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; kernelModuleEmbedVideo * MODULE = CTX->ModulePtr; @@ -571,7 +571,7 @@ void *kernelModuleEmbedVideo::viewClientProc( void *ptr ){ pfd->fd = CTX->m_iSocketFID; pfd->events = POLLIN | POLLHUP; - + while( CTX->bValid && w ) { if( !CTX->initDone ){ int RetVal; @@ -626,7 +626,7 @@ void *kernelModuleEmbedVideo::viewClientProc( void *ptr ){ #endif }; - if( ( strncmp( cGetURI, "/stream", 7 ) == 0 ) || ( strncmp( cGetURI, "/video_view", 11 ) == 0 ) ) { + if( ( strncmp( cGetURI, "/stream", 7 ) == 0 ) || ( strncmp( cGetURI, "/video_view", 11 ) == 0 ) ) { CSTR tP; if( tP = strstr( cGetURI, "?" ) ) { CSTR tB; @@ -771,7 +771,7 @@ void *kernelModuleEmbedVideo::viewClientProc( void *ptr ){ }; }; #ifdef DEBUG_EXTRA - TLOG("Shut Down Socket"); + TLOG("Shut Down Socket"); #endif shutdown( CTX->m_iSocketFID, SHUT_RDWR); #ifdef DEBUG_EXTRA @@ -894,13 +894,13 @@ void kernelModuleEmbedVideo::m_fThreadAProc( void ){ close( (*idx)->CTX->m_iEncoderPipe[1] ); free( (*idx)->CTX ); free( (*idx) ); - m_vHandlersPool.erase(idx); + m_vHandlersPool.erase(idx); #ifdef DEBUG_EXTRA LOG("Web Handler Ripped!"); #endif } else idx++; - }; - }; + }; + }; m_mWebHandlersProtector.unlock(); // validate active streams ? @@ -1018,8 +1018,8 @@ void kernelModuleEmbedVideo::m_fThreadBProc( void ){ #endif } else idx++; }; - - }; + + }; m_mViewHandlersProtector.unlock(); // validate active streams ? @@ -1068,8 +1068,8 @@ bool kernelModuleEmbedVideo::startService(){ 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::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 ); @@ -1210,7 +1210,7 @@ bool kernelModuleEmbedVideo::stopService( bool force ){ m_bEnabled = false; //Stop Conveyor m_bDetached = uninit(); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_EXTRA LOG("StopService!"); #endif @@ -1230,7 +1230,7 @@ bool kernelModuleEmbedVideo::stopService( bool force ){ m_mStreamHandlersProtector.unlock(); if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes -#ifdef DEBUG_EXTRA +#ifdef DEBUG_EXTRA char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); LOG( tB ); @@ -1238,12 +1238,12 @@ bool kernelModuleEmbedVideo::stopService( bool force ){ #endif for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index != m_vHandlersPool.end(); index++ ) { if( force ) { -#ifdef DEBUG_EXTRA +#ifdef DEBUG_EXTRA LOG("Force Client Handler to Stop!"); #endif pthread_cancel( (*index)->m_hThreadHandle ); } else { -#ifdef DEBUG_EXTRA +#ifdef DEBUG_EXTRA LOG("Waiting Client Handler to End!"); #endif pthread_join( (*index)->m_hThreadHandle, NULL ); @@ -1357,7 +1357,7 @@ bool kernelModuleEmbedVideo::validate(){ LOG("No Camera Defined/Enabled In the system!"); #endif }; - if ( RetVal ) { + if ( RetVal ) { DBC_INT_LIST tInvalidList; m_mStreamHandlersProtector.lock(); for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) { @@ -1407,7 +1407,7 @@ bool kernelModuleEmbedVideo::validate(){ #endif }; }; - if ( RetVal ) { + if ( RetVal ) { DBC_INT_LIST tInvalidList; m_mStreamHandlersProtector.lock(); for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) { @@ -1496,7 +1496,7 @@ bool kernelModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){ #ifdef DEBUG_EXTRA LOG("Mutex Locked!"); #endif - mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( sid ); + mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( sid ); if( hnd != m_mapHANDLERS.end() ) #ifdef DEBUG_EXTRA { @@ -1575,8 +1575,8 @@ bool kernelModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){ LOG("No apropriate Stream Found!"); #endif }; - }; - //*/ + }; + //*/ #ifdef DEBUG_EXTRA } else { LOG("No Pic Mode!"); @@ -1694,7 +1694,7 @@ bool kernelModuleEmbedVideo::registerStream( uint32_t streamID, uint8_t flip_mod try { m_mStreamHandlersProtector.lock(); streamHandler * tData = m_mapHANDLERS.at( streamID ); - //If SH allready exists + //If SH allready exists if( tData!= NULL ){ m_mStreamHandlersProtector.unlock(); return true; @@ -1780,7 +1780,7 @@ bool kernelModuleEmbedVideo::unregisterStream( uint32_t streamID ){ #endif -streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M, uint8_t flip_mode ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() +streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M, uint8_t flip_mode ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() #ifdef EVE_ENABLE_VIDEO ,basicThread() #endif @@ -1798,7 +1798,7 @@ streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M, uint8 m_bAFrameSkeepDividerCounter = 0; m_bAOutputFPS = VIDEO_OUTPUT_FPS; - m_bBFrameSkeepDivider = 1; + m_bBFrameSkeepDivider = 1; m_bBFrameSkeepDividerCounter = 0; m_bBOutputFPS = VIDEO_OUTPUT_FPS; #endif @@ -1807,7 +1807,7 @@ streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M, uint8 m_bInitialOutputFPS = m_bCurrentOutputFPS = VIDEO_OUTPUT_FPS; #endif -#ifdef EVE_ENABLE_VIDEO +#ifdef EVE_ENABLE_VIDEO #ifdef EVE_ENABLE_EASE_OUTPUT_FPS m_nAPreAlarmFrames = 0; m_nAPostAlarmFrames = 0; @@ -1832,7 +1832,7 @@ streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M, uint8 m_nSegAShiftFrames = 0; m_nSegBShiftFrames = 0; m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; - + m_bActiveEncoderStream = 0; m_bSegAActive = false; m_bSegADelete = true; @@ -1882,7 +1882,7 @@ bool streamHandler::create( dataBinder *ptr, uint32_t stremID ){ m_sSourceDesc.mediaStreamId = stremID; - m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; + m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; uint32_t tNID = m_pDBC->getNodeIdByTypeAndAux( tCAM->type, m_sStreamData.source_id ); //ToDo: Check Camera Addition // Just Work around to handle Wrong tyoe 12 instead of 13 @@ -1890,7 +1890,7 @@ bool streamHandler::create( dataBinder *ptr, uint32_t stremID ){ tNID = m_pDBC->getNodeIdByTypeAndAux( 13, m_sStreamData.source_id ); }; if (tNID) { - CSTR tNAM = m_pDBC->getNodeName( tNID ); + CSTR tNAM = m_pDBC->getNodeName( tNID ); if ( tNAM!= NULL ) { strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); m_sSourceDesc.mediaName[127] = (char)0; @@ -1925,7 +1925,7 @@ bool streamHandler::create( dataBinder *ptr, uint32_t stremID ){ #endif int tW = m_pMaster->getWidh(); int tH = m_pMaster->getHeight(); - int pix = -1; + 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 ){ @@ -1942,7 +1942,7 @@ bool streamHandler::create( dataBinder *ptr, uint32_t stremID ){ //export PATH=/usr/sbin:$PATH if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) { sprintf( tMRL, m_sStreamData.mrl ); - pix = atoi( m_sStreamData.c_type ); + pix = atoi( m_sStreamData.c_type ); } 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 ); }; @@ -1998,10 +1998,25 @@ bool streamHandler::pushFrame( AVFrame *Frame, void* src){ }; bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ + + /** @todo Valgrind is reporting an important memory leak in this method. The @p malloc() call on line 2568 (and others, such as 2576). + * The details are as follows: + * + * ~~~~ + = =00:00:04:04.219 26021== 8,805,208 (4,416 direct, 8,800,792 *indirect) bytes in 184 blocks are definitely lost in loss record 3,972 of 3,972 + ==00:00:04:04.219 26021== at 0x483877F: malloc (vg_replace_malloc.c:307) + ==00:00:04:04.219 26021== by 0x1B0FF9: streamHandler::pushFrame(cv::Mat&, void*) (kernelModuleEmbedVideo.cpp:2568) + ==00:00:04:04.219 26021== by 0x2490CB: videoAVLIBSource::m_fThreadProc() (videoAVLIBSource.cpp:874) + ==00:00:04:04.219 26021== by 0x131B54: basicThread::m_fThreadEntryPoint(void*) (basicThread.cpp:62) + ==00:00:04:04.219 26021== by 0x49B7EA6: start_thread (pthread_create.c:477) + ==00:00:04:04.219 26021== by 0x7874ADE: clone (clone.S:95) + * ~~~~ + */ + bool SkeepW, SkeepA, SkeepB; if( m_pMaster == NULL ) return false; MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; - char tBuffer[128]; + char tBuffer[128]; if( tMD ) { float mK, oK; cv::Rect ROI; @@ -2018,7 +2033,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ m_pMaster->m_sEmbedVideoData.width, CV_8UC3 ); - cv::rectangle( + cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point( 0, 0 ), cv::Point( @@ -2030,12 +2045,12 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ ); }; -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS SkeepW = !((m_bWebFrameSkeepDividerCounter % m_bWebFrameSkeepDivider) == 0 ); m_bWebFrameSkeepDividerCounter = ( ++m_bWebFrameSkeepDividerCounter ) % m_bWebFrameSkeepDivider; - #ifdef EVE_ENABLE_VIDEO - SkeepA = !((m_bAFrameSkeepDividerCounter % m_bAFrameSkeepDivider) == 0 ); - //m_bAFrameSkeepDividerCounter++; + #ifdef EVE_ENABLE_VIDEO + SkeepA = !((m_bAFrameSkeepDividerCounter % m_bAFrameSkeepDivider) == 0 ); + //m_bAFrameSkeepDividerCounter++; m_bAFrameSkeepDividerCounter = ( ++m_bAFrameSkeepDividerCounter ) % m_bAFrameSkeepDivider; SkeepB = !((m_bBFrameSkeepDividerCounter % m_bBFrameSkeepDivider) == 0 ); //m_bBFrameSkeepDividerCounter++; @@ -2168,20 +2183,20 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ //LOG("Q"); #endif -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS - #ifdef EVE_ENABLE_VIDEO +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + #ifdef EVE_ENABLE_VIDEO if( SkeepW && SkeepA && SkeepB ) { m_pMaster->m_mPictureProtector.unlock(); return true; }; - #else + #else if( SkeepW ){ m_pMaster->m_mPictureProtector.unlock(); return true; }; #endif #endif - + if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) { cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], @@ -2212,12 +2227,12 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ char tsb[64]; //if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ if( strftime( tsb, sizeof(tsb), "%F %T", tmp )!=0 ){ - + //sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); sprintf( tBuffer, ">>>%s>%s>", 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_face, m_pMaster->m_sEmbedVideoData.label_font_scale, m_pMaster->m_sEmbedVideoData.label_font_thickness, &baseline @@ -2237,12 +2252,12 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ 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, + (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, @@ -2262,9 +2277,9 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) { if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { shift_y = 15; - cv::rectangle( + cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], - cv::Point( + cv::Point( m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y ), @@ -2413,7 +2428,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId].clear(); cv::imencode( ".jpg", dst, m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId], compression_params ); -#endif +#endif m_pMaster->m_mEncodedProtector.unlock(); #ifdef EVE_ENABLE_EASE_OUTPUT_FPS }; @@ -2426,12 +2441,12 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ return true; }; // encode Video Stream - + //m_nPreAlarmFrames //m_nPostAlarmFrames //m_nNoAlarmSegmentFrames //m_nSegmentLimitFrames - //m_nHardLimitFrames + //m_nHardLimitFrames if ( m_bSegAActive || m_bSegBActive ) { m_mFrameCounterProtector.lock(); @@ -2461,7 +2476,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ #endif swapActiveStreams(); //break; - }; + }; // } while ( 0 ); #else //do { @@ -2487,7 +2502,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ #endif swapActiveStreams(); //break; - }; + }; // } while ( 0 ); #endif// !EVE_ENABLE_EASE_OUTPUT_FPS }; @@ -2517,7 +2532,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ #endif swapActiveStreams(); // break; - }; + }; //} while ( 0 ); #else // !EVE_ENABLE_EASE_OUTPUT_FPS // do { @@ -2543,7 +2558,7 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ #endif swapActiveStreams(); // break; - }; + }; //} while ( 0 ); #endif // !EVE_ENABLE_EASE_OUTPUT_FPS }; @@ -2621,7 +2636,7 @@ void streamHandler::closeSegmentB( void ){ void streamHandler::closeAll(){ waitThreadEnd( true ); #ifdef OPENCV_VIDEO_OUTPUT - + if( m_pEncoderA ){ if ( m_pEncoderA->isOpened() ) { m_pEncoderA->release(); @@ -2724,7 +2739,7 @@ void streamHandler::closeAll(){ //if( m_pFormat != NULL ) { //av_free( m_pFormat ); //}; -#endif // OPENCV_VIDEO_OUTPUT +#endif // OPENCV_VIDEO_OUTPUT }; bool streamHandler::openSegmentA( void ){ @@ -2875,7 +2890,7 @@ bool streamHandler::openSegmentA( void ){ m_bSegAActive = true; m_bSegADelete = true; //m_mFrameCounterProtector.unlock(); - #endif // SEPARATED_VIDEO_ENCODERS + #endif // SEPARATED_VIDEO_ENCODERS #ifdef DEBUG_EXTRA LOG("Stream A Opened"); #endif @@ -2988,7 +3003,7 @@ bool streamHandler::openSegmentB( void ){ sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration ); LOG( tB ); #endif - + //if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ if ( avio_open( &m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE ) < 0 ){ LOG_ERROR("Could not open output file."); @@ -3083,7 +3098,7 @@ bool streamHandler::initVideoOutput(){ m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 10.0 ); m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 ); - #else + #else if( !initLibAV() ) return false; m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); @@ -3144,7 +3159,7 @@ bool streamHandler::initVideoOutput(){ LOG("Video Encoder Context B Allocated"); #endif }; - + m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC; m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO; m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; @@ -3168,12 +3183,12 @@ bool streamHandler::initVideoOutput(){ m_pCodecBCtx->time_base.den = m_sStreamData.fps; m_pCodecBCtx->framerate.num = m_sStreamData.fps; m_pCodecBCtx->framerate.den = 1; - + //https://pastebin.com/yG37YhWW //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec //G@ avcodec encode NALU mp4 - + #if (LIBAVCODEC_VERSION_MAJOR > 54) ////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); #endif @@ -3191,9 +3206,9 @@ bool streamHandler::initVideoOutput(){ #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 @@ -3220,9 +3235,9 @@ bool streamHandler::initVideoOutput(){ -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) - - + -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!"); @@ -3250,7 +3265,7 @@ bool streamHandler::initVideoOutput(){ m_pCodecACtx->max_b_frames = 5; /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. - /// [use 3–5 ref per P] + /// [use 3„1¤75 ref per P] m_pCodecACtx->refs = 3; /// Compression efficiency (slower -> better quality + higher cpu%) @@ -3259,8 +3274,8 @@ bool streamHandler::initVideoOutput(){ av_opt_set( m_pCodecACtx->priv_data, "preset", "ultrafast", 0); //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); - - + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding av_opt_set( m_pCodecACtx->priv_data, "crf", "32", 0); @@ -3287,9 +3302,9 @@ bool streamHandler::initVideoOutput(){ #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 @@ -3316,10 +3331,10 @@ bool streamHandler::initVideoOutput(){ -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) - - - */ + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ //m_pCodecCtx->max_b_frames = 1; //m_pCodecCtx->level = 31; @@ -3330,7 +3345,7 @@ bool streamHandler::initVideoOutput(){ m_pCodecBCtx->max_b_frames = 5; /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. - /// [use 3–5 ref per P] + /// [use 3„1¤75 ref per P] m_pCodecBCtx->refs = 3; /// Compression efficiency (slower -> better quality + higher cpu%) @@ -3339,8 +3354,8 @@ bool streamHandler::initVideoOutput(){ av_opt_set( m_pCodecBCtx->priv_data, "preset", "ultrafast", 0); //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); - - + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding av_opt_set( m_pCodecBCtx->priv_data, "crf", "32", 0); @@ -3360,11 +3375,11 @@ bool streamHandler::initVideoOutput(){ if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; }; - - - + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; - + #ifdef DEBUG_EXTRA char TB[129]; sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den ); @@ -3375,16 +3390,16 @@ bool streamHandler::initVideoOutput(){ ////m_pVideoStrA->time_base = m_pCodecACtx->time_base; ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base; - + //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); - + //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width; //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height; //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); - //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = - ////dst_fps; + //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = + ////dst_fps; //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec ); @@ -3392,20 +3407,20 @@ bool streamHandler::initVideoOutput(){ //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; + //// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = + ////dst_fps; //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; - //// avcodec_parameters_from_context( m_pVideoStrA->codecpar, - ////m_pCodecACtx ); + //// avcodec_parameters_from_context( m_pVideoStrA->codecpar, + ////m_pCodecACtx ); //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT; //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata; //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size; - //// avcodec_parameters_from_context( m_pVideoStrB->codecpar, - ////m_pCodecBCtx ); + //// avcodec_parameters_from_context( m_pVideoStrB->codecpar, + ////m_pCodecBCtx ); //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT; //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata; //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size; @@ -3420,7 +3435,7 @@ bool streamHandler::initVideoOutput(){ LOG("output codec context is opened"); #endif }; - + #ifdef DEBUG_EXTRA } else { LOG("output codec context is already opened"); @@ -3437,7 +3452,7 @@ bool streamHandler::initVideoOutput(){ LOG("output codec context is opened"); #endif }; - + #ifdef DEBUG_EXTRA } else { LOG("output codec context is already opened"); @@ -3504,7 +3519,7 @@ bool streamHandler::initVideoOutput(){ 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 ); @@ -3533,12 +3548,12 @@ bool streamHandler::initVideoOutput(){ 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 @@ -3552,9 +3567,9 @@ bool streamHandler::initVideoOutput(){ #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 @@ -3581,9 +3596,9 @@ bool streamHandler::initVideoOutput(){ -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) - - + -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!"); @@ -3611,7 +3626,7 @@ bool streamHandler::initVideoOutput(){ 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] + /// [use 3„1¤75 ref per P] m_pCodecCtx->refs = 3; /// Compression efficiency (slower -> better quality + higher cpu%) @@ -3620,8 +3635,8 @@ bool streamHandler::initVideoOutput(){ 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); @@ -3641,11 +3656,11 @@ bool streamHandler::initVideoOutput(){ if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; }; - - - + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; - + #ifdef DEBUG_EXTRA char TB[129]; sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den ); @@ -3654,10 +3669,10 @@ bool streamHandler::initVideoOutput(){ 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; @@ -3695,7 +3710,7 @@ bool streamHandler::initVideoOutput(){ LOG("output codec context is opened"); #endif }; - + #ifdef DEBUG_EXTRA } else { LOG("output codec context is already opened"); @@ -3705,10 +3720,10 @@ bool streamHandler::initVideoOutput(){ m_pConvertCtx = sws_getContext( m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, - AV_PIX_FMT_BGR24, + AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, - m_pMaster->m_sEmbedVideoData.height, - VIDEO_OUTPUT_PIX_FMT, + m_pMaster->m_sEmbedVideoData.height, + VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, @@ -3739,7 +3754,7 @@ bool streamHandler::initVideoOutput(){ //encoding thread -void streamHandler::m_fThreadProc( void ){ +void streamHandler::m_fThreadProc( void ){ char tB[128]; //#ifdef EVE_ENABLE_EASE_OUTPUT_FPS size_t nQueueSize; @@ -3772,7 +3787,7 @@ void streamHandler::m_fThreadProc( void ){ nQueueSize = m_qEncodingQueue.size(); m_mEncodingQueueProtector.unlock(); -#ifdef EVE_ENABLE_EASE_OUTPUT_FPS +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS if ( nQueueSize > EVE_EASE_FPS_QUEUE_SIZE_MAXIMUM ) { //Just in case allredy applied to a streams if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){ @@ -3848,7 +3863,7 @@ void streamHandler::m_fThreadProc( void ){ cv::Mat image( tData->rows, tData->cols, CV_8UC3 ); memcpy( image.data, tData->data, tData->size ); free( tData->data ); - free( tData ); + free( tData ); #ifdef EVE_ENABLE_EASE_OUTPUT_FPS if( !bSkeepA ) #endif @@ -3873,10 +3888,10 @@ void streamHandler::m_fThreadProc( void ){ //m_mEncodingQueueProtector.unlock(); sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize ); free( tData->data[0] ); - free( tData ); + free( tData ); /* - - + + AV_PICTURE_TYPE_NONE Undefined. AV_PICTURE_TYPE_I Intra. AV_PICTURE_TYPE_P Predicted. @@ -3885,8 +3900,8 @@ void streamHandler::m_fThreadProc( void ){ 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; @@ -3907,8 +3922,8 @@ void streamHandler::m_fThreadProc( void ){ m_mFrameCounterProtector.lock(); m_nGlobalFrameCounter++; m_mFrameCounterProtector.unlock(); - } else m_mEncodingQueueProtector.unlock(); - }; + } else m_mEncodingQueueProtector.unlock(); + }; // Test Commands! m_mCurrentOperationProtector.lock(); switch ( m_bCOP ) { @@ -3917,7 +3932,7 @@ void streamHandler::m_fThreadProc( void ){ LOG("Actual Closing Video Stream A!"); LOG( m_sStreamSegmentInfo[0].scratchPath ); #endif - m_bSegAActive = false; + m_bSegAActive = false; if ( !m_bSegADelete ) { #ifdef DIRECT_MJPEG_COMPOSING if ( m_pOutputFD[0] ) { @@ -4022,7 +4037,7 @@ void streamHandler::m_fThreadProc( void ){ } else LOG_ERROR( "Event Creation failure!"); #ifdef DEBUG_EXTRA LOG("Stream B is Saved"); - + #endif } else { #ifdef DIRECT_MJPEG_COMPOSING @@ -4192,7 +4207,7 @@ void streamHandler::swapActiveStreams( void ){ if ( m_bSegADelete ) closeSegmentA(); } else { if ( m_bSegBDelete ) closeSegmentB(); - }; + }; //m_mFrameCounterProtector.unlock(); }; @@ -4207,13 +4222,13 @@ bool streamHandler::triggerEvent( uint32_t eid, uint32_t &dbid, uint32_t &frame #ifdef EVE_ENABLE_VIDEO m_mFrameCounterProtector.lock(); // To Mark Events Frames - m_bEvtMarkerCounter = 255; + m_bEvtMarkerCounter = 255; PF_TIMESTAMP ts; getPFTS( &ts ); /* if ( m_nVideoRegisteredDBID == 0 ) { LOG("New Event!"); - + if ( !m_bActiveEncoderStream ) { // Stream A is Active m_nVideoRegisteredDBID = m_pDBC->addVideoRecord( m_sStreamData.id, diff --git a/lib/alg/generic/md5.cpp b/lib/alg/generic/md5.cpp index 164e7ea9..ed68f131 100644 --- a/lib/alg/generic/md5.cpp +++ b/lib/alg/generic/md5.cpp @@ -81,6 +81,24 @@ char* PrintMD5(u_char md5Digest[16]) strncat(chBuffer, chEach, sizeof(chEach)); }; #ifdef __linux__ + /** @todo Valgrind tells us this @p strdup() called from @ref videoAVLIBSource is never freed. + * + * ~~~~ + = =00:00:04:04.006 26021== 33 bytes in 1 blocks are definitely* lost in loss record 2,412 of 3,972 + ==00:00:04:04.006 26021== at 0x483877F: malloc (vg_replace_malloc.c:307) + ==00:00:04:04.006 26021== by 0x7802C3A: strdup (strdup.c:42) [now line 102 since I've inserted this comment] + ==00:00:04:04.006 26021== by 0x1D20BD: PrintMD5(unsigned char*) (md5.cpp:84) + ==00:00:04:04.006 26021== by 0x1D212A: MD5String(char*) (md5.cpp:100) + ==00:00:04:04.006 26021== by 0x2476EA: videoAVLIBSource::_open(char*, bool, float, int, int, int, int, int) (videoAVLIBSource.cpp:388) + ==00:00:04:04.006 26021== by 0x1AE949: streamHandler::create(dataBinder*, unsigned int) (kernelModuleEmbedVideo.cpp:1949) + ==00:00:04:04.006 26021== by 0x1ADA24: kernelModuleEmbedVideo::registerStream(unsigned int, unsigned char) (kernelModuleEmbedVideo.cpp:1731) + ==00:00:04:04.006 26021== by 0x1AC2A9: kernelModuleEmbedVideo::validate() (kernelModuleEmbedVideo.cpp:1347) + ==00:00:04:04.006 26021== by 0x1BB1E7: kernelModuleFactory::m_fThreadProc() (kernelModuleFactory.cpp:397) + ==00:00:04:04.006 26021== by 0x131B54: basicThread::m_fThreadEntryPoint(void*) (basicThread.cpp:62) + ==00:00:04:04.006 26021== by 0x49B7EA6: start_thread (pthread_create.c:477) + ==00:00:04:04.006 26021== by 0x7874ADE: clone (clone.S:95) + * ~~~~ + */ return strdup(chBuffer); #else return _strdup(chBuffer); diff --git a/lib/components/base/basicPosition.cpp b/lib/components/base/basicPosition.cpp index ed5badbb..f4eb165a 100644 --- a/lib/components/base/basicPosition.cpp +++ b/lib/components/base/basicPosition.cpp @@ -205,6 +205,21 @@ void basicPosition::setPositionDeg(float Lat, float Lon, float Alt, float h_lat, updateMatrix(); }; void basicPosition::updateMatrix( void ){ + + /** @todo Valgrind is showing several memory leaks from this function. + * + * ~~~~ + ==00:00:04:04.173 26021== 176 bytes in 2 blocks are definitely lost in loss record 3,541 of 3,972 + ==00:00:04:04.173 26021== at 0x4838DEF: operator new(unsigned long) (vg_replace_malloc.c:342) + ==00:00:04:04.173 26021== by 0x130F5C: basicPosition::updateMatrix() (basicPosition.cpp:232) + ==00:00:04:04.173 26021== by 0x167C58: deviceNodeSensor::reloadDeviceNodeFromDB() (deviceNodeSensor.cpp:298) + ==00:00:04:04.173 26021== by 0x169DE2: deviceNodeSensor::m_fThreadProc() (deviceNodeSensor.cpp:1075) + ==00:00:04:04.173 26021== by 0x131B54: basicThread::m_fThreadEntryPoint(void*) (basicThread.cpp:62) + ==00:00:04:04.173 26021== by 0x49B7EA6: start_thread (pthread_create.c:477) + ==00:00:04:04.173 26021== by 0x7874ADE: clone (clone.S:95) + * ~~~~ + */ + //Tait-Bryan angles //X1Y2Z3 // C2C3 -C2S3 S2 @@ -217,7 +232,7 @@ void basicPosition::updateMatrix( void ){ m_pTransform = new transform_3( x, y, z, rot_x, rot_y, rot_z ); /* float X, Z, Y; - + X = rot_x; Y = rot_y; Z = rot_z; @@ -229,7 +244,7 @@ void basicPosition::updateMatrix( void ){ m_sMatrix.AB = -sinf(Z); m_sMatrix.AC = sinf(Y); m_sMatrix.AD = x; - + //m_sMatrix.BA = sinf(P)*cosf(Y) + cosf(P)*cosf(R)*sinf(Y); //m_sMatrix.BB = -sinf(P)*sinf(Y) + cosf(P)*cosf(R)*cosf(Y); //m_sMatrix.BC = -cosf(P)*sinf(R); @@ -237,7 +252,7 @@ void basicPosition::updateMatrix( void ){ m_sMatrix.BB = cosf(Z)*cosf(X); m_sMatrix.BC = -sinf(X); m_sMatrix.BD = y; - + //m_sMatrix.CA = sinf(R)*sinf(Y); //m_sMatrix.CB = sinf(R)*cosf(Y); //m_sMatrix.CC = cosf(R); diff --git a/lib/data/media/video/videoAVLIBSource.cpp b/lib/data/media/video/videoAVLIBSource.cpp index f9d1e373..bc031957 100644 --- a/lib/data/media/video/videoAVLIBSource.cpp +++ b/lib/data/media/video/videoAVLIBSource.cpp @@ -12,13 +12,13 @@ #define LOG_ERROR( X ) m_pLog->Log( "LIBAV_SRC", this, _LOG_ERROR, X ); #endif -static int interrupt_cb( void *ctx ){ +static int interrupt_cb( void *ctx ){ basicLogCollection::getInstance()->Log( "LibAV_CB", NULL, "INTERUPT!" ); - // do something + // do something return 0; -} +} -static const AVIOInterruptCB int_cb = { interrupt_cb, NULL }; +static const AVIOInterruptCB int_cb = { interrupt_cb, NULL }; //https://ffmpeg.org/doxygen/3.4/ffplay_8c_source.html#l02732 videoAVLIBSource::videoAVLIBSource( void *opaque ): basicMediaSource(), basicThread() { @@ -40,11 +40,11 @@ videoAVLIBSource::videoAVLIBSource( void *opaque ): basicMediaSource(), basicThr return; }; m_eMediaStatus = m_pVideoState->m_bStatus = MS_UNDEFINED; - + m_pVideoState->m_iVideoStreamID = -1; #ifndef _NOAUDIO_ m_pVideoState->m_iAudioStreamID = -1; -#endif +#endif m_pVideoState->m_bStatus = MS_INIT; }; @@ -69,7 +69,7 @@ videoAVLIBSource::videoAVLIBSource( char *Source, void *opaque ) : basicMediaSou m_eMediaStatus = m_pVideoState->m_bStatus = MS_UNDEFINED; m_pVideoState->m_pFormatCtx = avformat_alloc_context(); - + if (m_pVideoState->m_pFormatCtx == NULL){ LOG_ERROR("Video Format Context Memory Allocation Error"); return; @@ -77,9 +77,9 @@ videoAVLIBSource::videoAVLIBSource( char *Source, void *opaque ) : basicMediaSou m_pVideoState->m_iVideoStreamID = -1; #ifndef _NOAUDIO_ m_pVideoState->m_iAudioStreamID = -1; -#endif +#endif m_pVideoState->m_bStatus = MS_INIT; - + _open( Source ); }; @@ -93,7 +93,7 @@ videoAVLIBSource::~videoAVLIBSource(){ }; bool videoAVLIBSource::setOutputSize( int Width, int Height ){ - if( m_pVideoState ){ + if( m_pVideoState ){ if( m_pVideoState->m_bStatus == MS_INIT ) { if( Width && Height ) { m_bSizeIsAutomatic = false; @@ -107,7 +107,7 @@ bool videoAVLIBSource::setOutputSize( int Width, int Height ){ }; bool videoAVLIBSource::setProportionalByWidth(int Width){ - if( m_pVideoState ){ + if( m_pVideoState ){ if( m_pVideoState->m_bStatus == MS_INIT ) { if( Width > 0 ) { m_bSizeIsAutomatic = true; @@ -120,7 +120,7 @@ bool videoAVLIBSource::setProportionalByWidth(int Width){ }; bool videoAVLIBSource::setProportionalByHeight(int Height){ - if( m_pVideoState ){ + if( m_pVideoState ){ if( m_pVideoState->m_bStatus == MS_INIT ) { if( Height > 0 ) { m_bSizeIsAutomatic = true; @@ -157,7 +157,7 @@ bool videoAVLIBSource::_close(void){ m_pVideoState->m_iVideoStreamID = -1; }; - if( m_pVideoState->m_bStatus > MS_INIT ){ + if( m_pVideoState->m_bStatus > MS_INIT ){ #if ( LIBAVCODEC_VERSION_MAJOR < 58 ) // && ( LIBAVCODEC_VERSION_MINOR < 50 ) #ifndef _NOAUDIO_ @@ -181,7 +181,7 @@ bool videoAVLIBSource::_close(void){ avcodec_close(m_pVideoState->m_pCodecCtx); avcodec_free_context(&m_pVideoState->m_pCodecCtx); }; -#endif +#endif m_eMediaStatus = m_pVideoState->m_bStatus = MS_INIT; }; @@ -217,7 +217,7 @@ bool videoAVLIBSource::_restart( void ){ switch( m_bSrcType ){ case AVLIB_SOURCE_DDSHOW:{ AVInputFormat *iformat = av_find_input_format("dshow"); - if( ( RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, iformat, &m_pVideoState->m_pFormatOpts) ) != 0 ){ + if( ( RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, iformat, &m_pVideoState->m_pFormatOpts) ) != 0 ){ char tB[1024]; //av_free( iformat ); char tBuffer[1024]; @@ -248,7 +248,7 @@ bool videoAVLIBSource::_restart( void ){ LOG("DataStream Opened"); #endif m_eMediaStatus = m_pVideoState->m_bStatus = MS_OPENED; - + if( avformat_find_stream_info( m_pVideoState->m_pFormatCtx, NULL )<0 ){ char tB[1024]; sprintf( tB, "Couldn't find stream information: %s", m_pVideoState->m_pFileName ); @@ -257,7 +257,7 @@ bool videoAVLIBSource::_restart( void ){ }; #if ( LIBAVCODEC_VERSION_MAJOR < 58 ) // && ( LIBAVCODEC_VERSION_MINOR < 50 ) - for( unsigned int i=0; i < m_pVideoState->m_pFormatCtx->nb_streams; i++ ){ + for( unsigned int i=0; i < m_pVideoState->m_pFormatCtx->nb_streams; i++ ){ //if( m_pVideoState->m_pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){ if( m_pVideoState->m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ){ LOG( "VIDEO stream detected." ); @@ -324,17 +324,17 @@ bool videoAVLIBSource::_restart( void ){ }; #endif - + if( m_pVideoState->m_pVideoCodec == NULL ){ char tB[1024]; //sprintf(Buffer, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, m_pVideoState->m_pFileName); sprintf( tB, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, m_pVideoState->m_pFileName ); LOG_ERROR( tB ); return false; - }; + }; /* - End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2()) - and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE). + End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2()) + and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE). Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool. */ m_pVideoState->m_pCodecCtx->thread_count = 4; @@ -354,10 +354,10 @@ bool videoAVLIBSource::_restart( void ){ }; /* we do not send complete frames */ - //if( m_pVideoState->m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_pVideoState->m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED; + //if( m_pVideoState->m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_pVideoState->m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED; #ifndef _NOAUDIO_ - m_pVideoState->m_pAudioCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iAudioStreamID]->codec; + m_pVideoState->m_pAudioCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iAudioStreamID]->codec; m_pVideoState->m_pAudioCodec = avcodec_find_decoder( m_pVideoState->m_pAudioCtx->codec_id ); if( !m_pVideoState->m_pAudioCodec ){ LOG_ERROR( "Unsupported Audio codec!" ); @@ -376,7 +376,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i if (URI == NULL) return false; if (m_pVideoState == NULL) return false; if (m_bThreadStatus > TH_PRE_INIT ) return false; - m_pVideoState->m_pFormatCtx = avformat_alloc_context(); + m_pVideoState->m_pFormatCtx = avformat_alloc_context(); if (m_pVideoState->m_pFormatCtx == NULL){ LOG_ERROR("Video Format Context Memory Allocation Error"); return false; @@ -428,10 +428,10 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i //if (!fileExist(Buffer)) av_dict_set(&m_pVideoState->m_pFormatOpts, "video_device_load", Buffer, 0); }; //av_dict_set(&m_pVideoState->m_pFormatOpts, "crossbar_video_input_pin_number", "1", 0); - + //av_dict_set(&m_pVideoState->m_pFormatOpts, "show_audio_crossbar_connection_dialog", "true", 0); //av_dict_set(&m_pVideoState->m_pFormatOpts, "show_video_crossbar_connection_dialog", "true", 0); - + //AVInputFormat * is Internal Const in CoDec Lib AVInputFormat *iformat = av_find_input_format("dshow"); //av_dict_set(&options, "pixel_format", "bgr24", 0); @@ -489,10 +489,10 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i av_dict_set(&opts, "rtsp_transport", "tcp", 0); av_dict_set(&opts, "rtsp_flags", "prefer_tcp", 0); av_dict_set_int(&opts, "buffer_size", BUFSIZE, 0); - + pFormatCtx->flags |= AVFMT_FLAG_NONBLOCK; pFormatCtx->flags |= AVFMT_FLAG_DISCARD_CORRUPT; - pFormatCtx->flags |= AVFMT_FLAG_NOBUFFER; + pFormatCtx->flags |= AVFMT_FLAG_NOBUFFER; */ } else { #ifdef DEBUG @@ -502,8 +502,8 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i m_bSizeIsAutomatic = false; sprintf(tChar, "%dx%d", width, height); av_dict_set(&m_pVideoState->m_pFormatOpts, "video_size", tChar, 0); - switch ( inputPin ) { - case 0: LOG("PIX YUYV"); av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "yuv420p", 0); break; + switch ( inputPin ) { + case 0: LOG("PIX YUYV"); av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "yuv420p", 0); break; case 1: LOG("PIX MJPG"); av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "mjpeg", 0); break; default: av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "rgb24", 0); break; }; @@ -512,7 +512,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; av_dict_set(&m_pVideoState->m_pFormatOpts, "fflags", "nobuffer", 0); }; - av_dict_set(&m_pVideoState->m_pFormatOpts, "max_delay", "100", 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "max_delay", "100", 0); //av_dict_set(&options, "analyzeduration", "1000000", 0); if( framerate != -1 ){ sprintf(tChar, "%0.2f", framerate); @@ -520,9 +520,9 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i av_dict_set(&m_pVideoState->m_pFormatOpts, "framerate", tChar, 0); //av_dict_set(&options, "frame_rate", tChar, 0); }; - + //av_dict_set(&options, "timeout", "8000", 0); - int RetVal = 0; + int RetVal = 0; //LOG("Before Open1"); if( ( RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts) ) != 0 ){ av_dict_free( &m_pVideoState->m_pFormatOpts); @@ -547,7 +547,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i LOG("DataStream Opened"); #endif m_eMediaStatus = m_pVideoState->m_bStatus = MS_OPENED; - + if( avformat_find_stream_info( m_pVideoState->m_pFormatCtx, NULL )<0 ){ sprintf(Buffer, "Couldn't find stream information: %s", URI); LOG_ERROR(Buffer); @@ -555,7 +555,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; #if ( LIBAVCODEC_VERSION_MAJOR < 58 ) // && ( LIBAVCODEC_VERSION_MINOR < 50 ) - for( unsigned int i=0; i < m_pVideoState->m_pFormatCtx->nb_streams; i++ ){ + for( unsigned int i=0; i < m_pVideoState->m_pFormatCtx->nb_streams; i++ ){ //if( m_pVideoState->m_pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){ if( m_pVideoState->m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ){ LOG( "VIDEO stream detected." ); @@ -591,8 +591,8 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; //ToDo: Bind Audio Codec # endif - - + + #else # ifdef DEBUG_EXTRA LOG("YABABA-2!"); @@ -624,16 +624,16 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; #endif - + if( m_pVideoState->m_pVideoCodec == NULL ){ //sprintf(Buffer, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, URI); sprintf(Buffer, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, URI); LOG_ERROR( Buffer ); return false; - }; + }; /* - End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2()) - and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE). + End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2()) + and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE). Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool. */ m_pVideoState->m_pCodecCtx->thread_count = 4; @@ -652,10 +652,10 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; /* we do not send complete frames */ - if( m_pVideoState->m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_pVideoState->m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED; + if( m_pVideoState->m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_pVideoState->m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED; #ifndef _NOAUDIO_ - m_pVideoState->m_pAudioCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iAudioStreamID]->codec; + m_pVideoState->m_pAudioCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iAudioStreamID]->codec; m_pVideoState->m_pAudioCodec = avcodec_find_decoder( m_pVideoState->m_pAudioCtx->codec_id ); if( !m_pVideoState->m_pAudioCodec ){ LOG_ERROR( "Unsupported Audio codec!" ); @@ -708,7 +708,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; }; }; - + #ifdef DEBUG_EXTRA sprintf( tB, "Using Size [%dx%d]", m_nOutWidth, m_nOutHeight ); LOG( tB ); @@ -720,7 +720,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i AV_PIX_FMT_BGR24, SWS_BICUBIC ); LOG( tB ); -#endif +#endif m_pVideoState->m_pSwsCtx = sws_getContext( m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, @@ -747,7 +747,7 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i }; void videoAVLIBSource::m_fThreadProc( void ){ - AVPacket * pPacket = NULL; + AVPacket * pPacket = NULL; cv::Mat mRGB( m_nOutHeight, m_nOutWidth, CV_8UC3, cv::Scalar( 255, 0, 255 ) ); AVFrame * pFrame = NULL; AVFrame * pFrameBGR = NULL; @@ -755,6 +755,38 @@ void videoAVLIBSource::m_fThreadProc( void ){ int dec_ret; char tB[256]; + /** @todo Valgrind is reporting several important memory leaks in this method. + * + * The first one has to do with @p av_frame_alloc(): + * + * ~~~~ + ==00:00:04:04.219 26021== 2,074,168 (536 direct, 2,073,632 indirect) bytes in 1 blocks are definitely lost in loss record 3,970 of 3,972 + ==00:00:04:04.219 26021== at 0x483AEB8: memalign (vg_replace_malloc.c:906) + ==00:00:04:04.219 26021== by 0x483AFCE: posix_memalign (vg_replace_malloc.c:1070) + ==00:00:04:04.219 26021== by 0x66E2244: av_malloc (in /usr/lib/x86_64-linux-gnu/libavutil.so.56.70.100) + ==00:00:04:04.219 26021== by 0x66E25FD: av_mallocz (in /usr/lib/x86_64-linux-gnu/libavutil.so.56.70.100) + ==00:00:04:04.219 26021== by 0x66BF6BF: av_frame_alloc (in /usr/lib/x86_64-linux-gnu/libavutil.so.56.70.100) + ==00:00:04:04.219 26021== by 0x248B0E: videoAVLIBSource::m_fThreadProc() (videoAVLIBSource.cpp:802) + ==00:00:04:04.219 26021== by 0x131B54: basicThread::m_fThreadEntryPoint(void*) (basicThread.cpp:62) + ==00:00:04:04.219 26021== by 0x49B7EA6: start_thread (pthread_create.c:477) + ==00:00:04:04.219 26021== by 0x7874ADE: clone (clone.S:95) + * ~~~~ + * + * The next one has to do with @p av_image_alloc(): + * + * ~~~~ + ==00:00:04:04.219 26021== 2,073,632 bytes in 1 blocks are indirectly lost in loss record 3,969 of 3,972 + ==00:00:04:04.219 26021== at 0x483AEB8: memalign (vg_replace_malloc.c:906) + ==00:00:04:04.219 26021== by 0x483AFCE: posix_memalign (vg_replace_malloc.c:1070) + ==00:00:04:04.219 26021== by 0x66E2244: av_malloc (in /usr/lib/x86_64-linux-gnu/libavutil.so.56.70.100) + ==00:00:04:04.219 26021== by 0x66DCEB5: av_image_alloc (in /usr/lib/x86_64-linux-gnu/libavutil.so.56.70.100) + ==00:00:04:04.219 26021== by 0x248BCB: videoAVLIBSource::m_fThreadProc() (videoAVLIBSource.cpp:807) + ==00:00:04:04.219 26021== by 0x131B54: basicThread::m_fThreadEntryPoint(void*) (basicThread.cpp:62) + ==00:00:04:04.219 26021== by 0x49B7EA6: start_thread (pthread_create.c:477) + ==00:00:04:04.219 26021== by 0x7874ADE: clone (clone.S:95) + * ~~~~ + */ + m_bThreadStatus = TH_WORKING; pPacket = (AVPacket *) av_malloc( sizeof(AVPacket) ); if ( pPacket == NULL ) { @@ -785,11 +817,11 @@ void videoAVLIBSource::m_fThreadProc( void ){ // LOG_ERROR("Error allocating BGR AVFrame Buffer!"); //} else { // av_image_fill_arrays ( pFrameBGR->data, pFrameBGR->linesize, pBGRbuffer, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, BUFFER_ALIGN ); - // + // // pFrameBGR->width = m_nWidth; // pFrameBGR->height = m_nHeight; // m_pVideoState->m_bStatus = MS_ALOCATED; - + #ifdef DEBUG LOG("Video Reader Thread Started."); #endif @@ -797,7 +829,7 @@ void videoAVLIBSource::m_fThreadProc( void ){ }; }; }; - + //cv::setBreakOnError( true ); m_eMediaStatus = m_pVideoState->m_bStatus = MS_STOPED; while( m_pMediaDestination == NULL && m_bThreadStatus == TH_WORKING ){ @@ -895,16 +927,16 @@ void videoAVLIBSource::m_fThreadProc( void ){ av_free( pBGRbuffer ); }; m_bThreadStatus = TH_ENDED; - m_eMediaStatus = m_pVideoState->m_bStatus = MS_STOPED; + m_eMediaStatus = m_pVideoState->m_bStatus = MS_STOPED; #ifdef DEBUG LOG("Video Structures Cleared!"); #endif }; -/* - -JPEG2000 isn't jpeg. To encode JPEG images, use AV_CODEC_ID_MJPEG. MJPEG stands for "motion JPEG", which is how a sequence of JPEG pictures making up a video stream is typically called. - +/* + +JPEG2000 isn't jpeg. To encode JPEG images, use AV_CODEC_ID_MJPEG. MJPEG stands for "motion JPEG", which is how a sequence of JPEG pictures making up a video stream is typically called. + int save_frame_as_jpeg( AVCodecContext *pCodecCtx, AVFrame *pFrame, int FrameNo) { AVCodec *jpegCodec = avcodec_find_encoder(AV_CODEC_ID_JPEG2000); if (!jpegCodec) { @@ -949,7 +981,7 @@ MediaStateStatus videoAVLIBSource::getStatus( void ){ return MS_UNDEFINED; }; -bool videoAVLIBSource::isFinished( void ){ +bool videoAVLIBSource::isFinished( void ){ if( m_pVideoState ) if( m_pVideoState->m_bStatus < MS_CLOSING ) return false; return true; };