diff --git a/Linux_Workspace.vpw b/Linux_Workspace.vpw index cf345146..035f4c4e 100644 --- a/Linux_Workspace.vpw +++ b/Linux_Workspace.vpw @@ -8,6 +8,8 @@ + + diff --git a/Projects/LRF_Server/build b/Projects/LRF_Server/build old mode 100755 new mode 100644 diff --git a/Projects/MEKOROT/MEKOROT.vcxproj b/Projects/MEKOROT/MEKOROT.vcxproj index 0d52e042..6966673e 100644 --- a/Projects/MEKOROT/MEKOROT.vcxproj +++ b/Projects/MEKOROT/MEKOROT.vcxproj @@ -115,7 +115,7 @@ Console true - opencv_core440d.lib;opencv_imgproc440d.lib;libcurl_a_debug.lib;libeay32.lib;ssleay32.lib;%(AdditionalDependencies) + opencv_core440d.lib;opencv_imgproc440d.lib;opencv_imgcodecs440d.lib;libcurl_a_debug.lib;libeay32.lib;ssleay32.lib;%(AdditionalDependencies) @@ -155,10 +155,11 @@ true true true - opencv_core440.lib;opencv_imgproc440.lib;libcurl_a.lib;libeay32.lib;ssleay32.lib;%(AdditionalDependencies) + opencv_core440.lib;opencv_imgproc440.lib;opencv_imgcodecs440.lib;libcurl_a.lib;libeay32.lib;ssleay32.lib;%(AdditionalDependencies) + @@ -235,10 +236,10 @@ + - - + diff --git a/Projects/MEKOROT/MEKOROT.vcxproj.filters b/Projects/MEKOROT/MEKOROT.vcxproj.filters index 5779a6fd..f4c03b7f 100644 --- a/Projects/MEKOROT/MEKOROT.vcxproj.filters +++ b/Projects/MEKOROT/MEKOROT.vcxproj.filters @@ -120,12 +120,6 @@ Source Files - - Source Files - - - Source Files - Source Files @@ -303,6 +297,15 @@ Source Files + + Source Files + + + Source Files + + + Source Files + diff --git a/Projects/MEKOROT/MEKOROT_Kernel.cpp b/Projects/MEKOROT/MEKOROT_Kernel.cpp index e909186f..20c08981 100644 --- a/Projects/MEKOROT/MEKOROT_Kernel.cpp +++ b/Projects/MEKOROT/MEKOROT_Kernel.cpp @@ -12,7 +12,7 @@ bool getconchar(KEY_EVENT_RECORD& krec) { return false; // console not found }; if (!GetNumberOfConsoleInputEvents(h, &NOF)) return false; - if( NOF ) for(int i=0;igetSubNode(ptr, (CSTR)"KERNEL"); m_bStage = MEKOROT_KRNL_STG_INIT; @@ -108,7 +108,7 @@ bool mekorotKernel::init(void){ LOG_ERROR("Failure while adding setting!"); return false; }; - config_setting_set_int(pSetting, m_nRestartTimer); + config_setting_set_int(pSetting, (uint32_t)m_nRestartTimer); }; }; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_SERIAL_SPEED_TAG); @@ -135,6 +135,7 @@ bool mekorotKernel::init(void){ }; config_setting_set_int(pSetting, m_bDeviceID[0]); }; + if( m_bDeviceID[0] < 0 ) m_bDeviceFlags[0] = true; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_1_ID_TAG); if (pSetting != NULL) { m_bDeviceID[1] = config_setting_get_int(pSetting); @@ -147,6 +148,7 @@ bool mekorotKernel::init(void){ }; config_setting_set_int(pSetting, m_bDeviceID[1]); }; + if (m_bDeviceID[1] < 0) m_bDeviceFlags[1] = true; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_2_ID_TAG); if (pSetting != NULL) { m_bDeviceID[2] = config_setting_get_int(pSetting); @@ -159,6 +161,7 @@ bool mekorotKernel::init(void){ }; config_setting_set_int(pSetting, m_bDeviceID[2]); }; + if (m_bDeviceID[2] < 0) m_bDeviceFlags[2] = true; if (!config_setting_lookup_string(m_pSettings, KNL_SETTINGS_STORAGE_BASE, (const char**)&m_pStorageBase)) { m_pStorageBase = (CSTR)"storage"; pSetting = config_setting_add(m_pSettings, KNL_SETTINGS_STORAGE_BASE, CONFIG_TYPE_STRING); @@ -210,8 +213,8 @@ bool mekorotKernel::init(void){ if (m_pVideoFrame != NULL) { memset(m_pVideoFrame, 0, sizeof(m_pVideoFrame)); config_setting_t* tRec; - config_setting_t* ttRec; - int tIID, tWIDTH, tHEIGHT, tSCALEW, tSCALEH; + //config_setting_t* ttRec; + int /*tIID,*/ tWIDTH, tHEIGHT, tSCALEW, tSCALEH; bool tSCALED; double tFPS; m_nVideoInputs = mCount; @@ -234,6 +237,7 @@ bool mekorotKernel::init(void){ m_pVideoInputs[index] = NULL; LOG_ERROR("Source Open Failure."); } else { + LOG("Video SOURCE OPENED OK!"); if (tSCALED) { if (m_nWidth < tSCALEW) m_nWidth = tSCALEW; if (m_nHeight < tSCALEH) m_nHeight = tSCALEH; @@ -241,6 +245,7 @@ bool mekorotKernel::init(void){ if (m_nWidth < tWIDTH) m_nWidth = tWIDTH; if (m_nHeight < tHEIGHT) m_nHeight = tHEIGHT; }; + LOG("Make Video FRAME!"); m_pVideoFrame[index] = new cv::Mat(tHEIGHT, tWIDTH, CV_8UC3); if (m_pMatProtector == NULL) { m_pMatProtector = new basicMutex(); @@ -268,7 +273,7 @@ bool mekorotKernel::init(void){ for (int index = 0; (index < m_nZoomTableCount) && (index < MAX_ZOOM_TABLE_COUNT); index++) { tRec = config_setting_get_elem(pSetting, index); if (tRec != NULL) { - m_pZoomTable[index] = config_setting_get_float(tRec); + m_pZoomTable[index] = (float)config_setting_get_float(tRec); #ifdef DEBUG char tBuff[64]; sprintf(tBuff, "Value[%d]=%0.2f", index, m_pZoomTable[index]); @@ -335,7 +340,7 @@ bool mekorotKernel::init(void){ pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_LEFT_PAN_TAG); if (pSetting != NULL) { - m_fLeftZeroPan = config_setting_get_float(pSetting); + m_fLeftZeroPan = (float)config_setting_get_float(pSetting); } else { pSetting = config_setting_add(m_pSettings, MEKOROT_KRNL_DEVICE_LEFT_PAN_TAG, CONFIG_TYPE_FLOAT); basicSettingsProvider::getInstance()->compromise(); @@ -347,7 +352,7 @@ bool mekorotKernel::init(void){ }; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_RIGHT_PAN_TAG); if (pSetting != NULL) { - m_fRightZeroPan = config_setting_get_float(pSetting); + m_fRightZeroPan = (float)config_setting_get_float(pSetting); } else { pSetting = config_setting_add(m_pSettings, MEKOROT_KRNL_DEVICE_RIGHT_PAN_TAG, CONFIG_TYPE_FLOAT); basicSettingsProvider::getInstance()->compromise(); @@ -359,7 +364,7 @@ bool mekorotKernel::init(void){ }; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_HORIZONT_TILT_TAG); if (pSetting != NULL) { - m_fHorizontalZeroTilt = config_setting_get_float(pSetting); + m_fHorizontalZeroTilt = (float)config_setting_get_float(pSetting); } else { pSetting = config_setting_add(m_pSettings, MEKOROT_KRNL_DEVICE_HORIZONT_TILT_TAG, CONFIG_TYPE_FLOAT); basicSettingsProvider::getInstance()->compromise(); @@ -371,7 +376,7 @@ bool mekorotKernel::init(void){ }; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_HOME_PAN_TAG); if (pSetting != NULL) { - m_fHomePan = config_setting_get_float(pSetting); + m_fHomePan = (float)config_setting_get_float(pSetting); } else { pSetting = config_setting_add(m_pSettings, MEKOROT_KRNL_DEVICE_HOME_PAN_TAG, CONFIG_TYPE_FLOAT); basicSettingsProvider::getInstance()->compromise(); @@ -384,7 +389,7 @@ bool mekorotKernel::init(void){ }; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_HOME_TILT_TAG); if (pSetting != NULL) { - m_fHomeTilt = config_setting_get_float(pSetting); + m_fHomeTilt = (float)config_setting_get_float(pSetting); } else { pSetting = config_setting_add(m_pSettings, MEKOROT_KRNL_DEVICE_HOME_TILT_TAG, CONFIG_TYPE_FLOAT); basicSettingsProvider::getInstance()->compromise(); @@ -396,7 +401,7 @@ bool mekorotKernel::init(void){ }; pSetting = config_setting_get_member(m_pSettings, MEKOROT_KRNL_DEVICE_HOME_ZOOM_TAG); if (pSetting != NULL) { - m_fHomeZoom = config_setting_get_float(pSetting); + m_fHomeZoom = (float)config_setting_get_float(pSetting); } else { pSetting = config_setting_add(m_pSettings, MEKOROT_KRNL_DEVICE_HOME_ZOOM_TAG, CONFIG_TYPE_FLOAT); basicSettingsProvider::getInstance()->compromise(); @@ -480,6 +485,65 @@ bool mekorotKernel::keyboard_proc(void) { }; break; }; + case 49: { + if( m_bUsePTZ ){ + LOG("Left Horizontal"); + treat_alarm( MEKOROT_DEV_LEFT, 1440, 100, 1000 ); + }; + break; + }; + case 50: { + if (m_bUsePTZ) { + LOG("Left Max Up (45)"); + treat_alarm(MEKOROT_DEV_LEFT, 0, 100, 1000); + }; + break; + }; + case 51: { + if (m_bUsePTZ) { + LOG("Right Horizontal"); + treat_alarm(MEKOROT_DEV_RIGHT, 0, 100, 1000); + }; + break; + }; + case 52: { + if (m_bUsePTZ) { + LOG("Right Max Up (45)"); + treat_alarm(MEKOROT_DEV_RIGHT, 720, 100, 1000); + }; + break; + }; + case 56: { + if (m_bUsePTZ) { + LOG("Horizontal Left (97.5)"); + treat_alarm(MEKOROT_DEV_CENTER, 1625, 100, 1000); + }; + break; + }; + case 57: { + if (m_bUsePTZ) { + LOG("Horizontal Center"); + treat_alarm(MEKOROT_DEV_CENTER, 812, 100, 1000); + }; + break; + }; + case 48: { + if (m_bUsePTZ) { + LOG("Horizontal Zero (0)"); + treat_alarm(MEKOROT_DEV_CENTER, 0, 100, 1000); + }; + break; + }; + case 187: { + LOG("187"); + move_cam( m_fHomePan, 1.0, 0.0); + break; + }; + case 189: { + LOG("189"); + move_cam( m_fHomePan, 0.0, 0.0); + break; + }; case 36: case 72: { //PTZ 'h' or 'home' = Stop @@ -517,7 +581,7 @@ void mekorotKernel::m_fThreadProc(void){ #ifdef DEBUG // Each 5 sec print statuses if ((cTS - dTS ) > 5000) { - char tBuff[64]; + //char tBuff[64]; //sprintf(tBuff, "Stage: %d OP: %d", m_bStage, m_nOperation ); //LOG(tBuff); dTS = cTS; @@ -546,7 +610,7 @@ void mekorotKernel::m_fThreadProc(void){ if (m_nOperation & MEKOROT_KRNL_OP_OP_MATRIX) { switch (m_nOperation) { case MEKOROT_KRNL_OP_PING_DEV0: { - if (m_bDeviceID[0] != -1) { + if (m_bDeviceID[0] > 0 ) { if (setDeviceID(m_bDeviceID[0])) { if (!getVoltage()) { LOG_ERROR("Get Voltage FAILURE!"); @@ -560,11 +624,13 @@ void mekorotKernel::m_fThreadProc(void){ } else { LOG_ERROR("Set DevID FAILURE!"); }; + } else { + m_nOperation = MEKOROT_KRNL_OP_PING_DEV1; }; break; }; case MEKOROT_KRNL_OP_PING_DEV1: { - if (m_bDeviceID[1] != -1) { + if (m_bDeviceID[1] > 0 ) { if (setDeviceID(m_bDeviceID[1])) { if (!getVoltage()) { LOG_ERROR("Get Voltage FAILURE!"); @@ -578,11 +644,13 @@ void mekorotKernel::m_fThreadProc(void){ } else { LOG_ERROR("Set DevID FAILURE!"); }; + } else { + m_nOperation = MEKOROT_KRNL_OP_PING_DEV2; }; break; }; case MEKOROT_KRNL_OP_PING_DEV2: { - if (m_bDeviceID[2] != -1) { + if (m_bDeviceID[2] > 0 ) { if (setDeviceID(m_bDeviceID[2])) { if (!getVoltage()) { LOG_ERROR("Get Voltage FAILURE!"); @@ -596,6 +664,9 @@ void mekorotKernel::m_fThreadProc(void){ } else { LOG_ERROR("Set DevID FAILURE!"); }; + } else { + m_nOperation = MEKOROT_KRNL_OP_PING_DEV0; + //LOG_ERROR("No Devices Assigned!"); }; break; }; @@ -604,7 +675,7 @@ void mekorotKernel::m_fThreadProc(void){ unsigned long long cTS;//must be checket logics cTS = getMilliseconds(); if ((cTS - m_bOperationTO) > 1000) { - LOG_ERROR("FAILED TO COMMUNICATE WITH SENSOR"); + //LOG_ERROR("FAILED TO COMMUNICATE WITH SENSOR"); m_bOperationTO = cTS; if( m_nOperation > 1 ) m_nOperation = m_nOperation >> 1; }; @@ -612,10 +683,12 @@ void mekorotKernel::m_fThreadProc(void){ break; }; case MEKOROT_KRNL_STG_WORKING: { - if (m_nOperation & MEKOROT_KRNL_OP_OP_MATRIX) { + LOG("*"); + if( m_nOperation & MEKOROT_KRNL_OP_OP_MATRIX) { switch (m_nOperation) { case MEKOROT_KRNL_OP_QSTG_DEV0: { - if (m_bDeviceFlags[0]) { + if( m_bDeviceFlags[0] && ( m_bDeviceID[0] > 0 ) ){ + LOG("Ping 0"); if (setDeviceID(m_bDeviceID[0])) { if (!getState2()) { LOG_ERROR("Get STATE2 FAILURE!"); @@ -637,7 +710,8 @@ void mekorotKernel::m_fThreadProc(void){ // In Case Device is Offline - Skip to next Device }; case MEKOROT_KRNL_OP_QSTG_DEV1: { - if (m_bDeviceFlags[1]) { + if (m_bDeviceFlags[1] && (m_bDeviceID[1] > 0)) { + LOG("Ping 1"); if (setDeviceID(m_bDeviceID[1])) { if (!getState2()) { LOG_ERROR("Get STATE2 FAILURE!"); @@ -659,7 +733,8 @@ void mekorotKernel::m_fThreadProc(void){ // In Case Device is Offline - Skip to next Device }; case MEKOROT_KRNL_OP_QSTG_DEV2: { - if (m_bDeviceFlags[2]) { + if (m_bDeviceFlags[2] && (m_bDeviceID[2] > 0)) { + LOG("Ping 2"); if (setDeviceID(m_bDeviceID[2])) { if (!getState2()) { LOG_ERROR("Get STATE2 FAILURE!"); @@ -680,8 +755,10 @@ void mekorotKernel::m_fThreadProc(void){ }; // Loop Query m_nOperation = MEKOROT_KRNL_OP_QSTG_DEV0; + break; }; default: { + LOG("Ping Z"); m_bStage = MEKOROT_KRNL_STG_PING_DEVICES; m_nOperation = MEKOROT_KRNL_OP_PING_DEV0; LOG_ERROR("Conveyor Error! Falling down to Pinging sensors ..."); @@ -697,21 +774,27 @@ void mekorotKernel::m_fThreadProc(void){ }; }; }; - +#include void mekorotKernel::reg_event( uint8_t devID, float az, float el, float ra, CSTR path ) { FILE* fd; fd = fopen(m_sFSReportName, "a+"); - if (fd) { + if( fd ){ m_nInitialFSID++; - uint32_t ts = (uint32_t)time(NULL); - fprintf(fd, "%d,%d,%d,%0.2f,%0.2f,%0.2f,%s\n", - m_nInitialFSID, - ts, - devID, - az, el, ra, path - ); + //uint32_t ts = (uint32_t)time(NULL); + CSTR tSTR = getTStr(); + if (tSTR) { + fprintf(fd, "%d,%s,%0.2f,%0.2f,%0.2f,%s\n", + //m_nInitialFSID, + devID, + + //ts, + tSTR, + az, el, ra, path + ); + free(tSTR); + }; fclose(fd); - chmod(m_sFSReportName, STORAGE_FILE_MODE ); + _chmod(m_sFSReportName, STORAGE_FILE_MODE ); }; }; //https://www.ebay.com/itm/Nvidia-Tesla-M2090-6GB-GDDR5-PCIe-Accelerator-Video-Graphics-Card-775NK/123590917738 @@ -723,8 +806,9 @@ bool mekorotKernel::packetHandler(protocolPackage* Package) { if( Package == NULL ) return true; if( Package->m_nSize < 4 ) return true; cDeviceID = Package->m_pData[2]; - for (uint8_t idx = 0; idx < 3; idx++) { - if (cDeviceID == m_bDeviceID[idx]) cDeviceIDX = idx; + for (uint8_t idx = 0; idx < 3; idx++) if (cDeviceID == m_bDeviceID[idx]){ + cDeviceIDX = idx; + break; }; if (cDeviceIDX == 255) { LOG_ERROR("Package from not registered device!"); @@ -739,9 +823,10 @@ bool mekorotKernel::packetHandler(protocolPackage* Package) { LOG(tBuff); #endif m_bDeviceFlags[cDeviceIDX] = true; - if ( m_bDeviceFlags[0] && m_bDeviceFlags[0] && m_bDeviceFlags[0] ) { + if( m_bDeviceFlags[0] && m_bDeviceFlags[1] && m_bDeviceFlags[2] ){ m_nOperation = MEKOROT_KRNL_OP_QSTG_DEV0; m_bStage = MEKOROT_KRNL_STG_WORKING; + LOG("Switching To Work LOOP!"); return true; }; }; @@ -777,23 +862,24 @@ bool mekorotKernel::packetHandler(protocolPackage* Package) { }; void mekorotKernel::treat_alarm(uint8_t devID, uint16_t az, uint16_t ra, uint32_t wd) { float rAz, rEl, rZoom; - uint16_t tAz, tRa; + uint16_t tAz/*, tRa*/; + char tB[120]; switch (devID) { case MEKOROT_DEV_LEFT: { - tAz = ( 6000 + az + m_nLeftZeroShift ) % 6000; - rEl = ((float)tAz * 2.f ) / 6000.f - 1.f; + tAz = ( 6000 + az + m_nLeftZeroShift ) % 3000; + rEl = ((float)tAz * 2.f ) / 3000.f - 1.f; rAz = m_fLeftZeroPan; break; }; case MEKOROT_DEV_CENTER: { tAz = (6000 + az + m_nCenterZeroShift) % 6000; - rAz = 1.f - ((float)tAz * 2.f) / 6000.f; + rAz = ((float)tAz * 2.f) / 6000.f - 1.f; rEl = m_fHorizontalZeroTilt; break; }; case MEKOROT_DEV_RIGHT: { - tAz = (6000 + az + m_nRightZeroShift) % 6000; - rEl = 1.f - ((float)tAz * 2.f) / 6000.f; + tAz = (6000 + az + m_nRightZeroShift) % 3000; + rEl = 1.f - ((float)tAz * 2.f) / 3000.f; rAz = m_fRightZeroPan; break; }; @@ -802,15 +888,18 @@ void mekorotKernel::treat_alarm(uint8_t devID, uint16_t az, uint16_t ra, uint32_ rAz = 0.f; }; }; - if (m_nZoomTableCount > 1) { + sprintf(tB, "tAZ: %d rEL: %0.3f rAz: %0.3f", tAz, rEl, rAz); + LOG(tB); + if( m_nZoomTableCount > 1 ){ int idx = (ra * m_nZoomTableCount) / 4000; rZoom = m_pZoomTable[idx]; } else { rZoom = m_pZoomTable[0]; }; - alarm(); - reg_event(devID, rAz, rEl, rZoom, m_pVideoOutput->getOutputName()); move_cam( rAz, rEl, rZoom ); + SLEEP( 100 ); + alarm(); + reg_event(devID, rAz, rEl, rZoom, m_sOutputPicture);//m_pVideoOutput->getOutputName() ); }; void mekorotKernel::move_cam(float az, float el, float zoom){ @@ -831,8 +920,8 @@ void mekorotKernel::move_cam(float az, float el, float zoom){ //DH-SD52C225U-HNI //1/2.8” //FL=4.8mm~120mm - float SensorSize = 9.0714285714285714285714285714286; - float FN = ((120.0 - 4.8) * m_fCamTargetZoom) + 4.8; + float SensorSize = 9.0714285714285714285714285714286f; + float FN = ((120.0f - 4.8f) * m_fCamTargetZoom) + 4.8f; /* The calculator below converts between the focal length f and the field of view (FOV) of a rectilinear lens. The formula that it implements is FOV = 2 arctan (x / (2 f)), where x is the diagonal of the film. @@ -840,7 +929,7 @@ void mekorotKernel::move_cam(float az, float el, float zoom){ and even smaller across the vertical dimension. */ //tFov = 57.295779513082320876798154814105 * ( 2.f * atanf( SensorSize / (2.f * FN )) ) / 2.0; - tFov = 0.31830988618379067153776752674503 * atanf( SensorSize / (2.f * FN)) / 2.; //(+-) 1/4 FOV - Ok to see both targets at same frame + tFov = 0.31830988618379067153776752674503f * atanf( SensorSize / (2.f * FN)) / 2.f; //(+-) 1/4 FOV - Ok to see both targets at same frame #ifdef DEBUG sprintf(tBuff, "Half FOV[%0.2f]: %0.2f", m_fCamTargetZoom, tFov ); LOG(tBuff); @@ -859,7 +948,11 @@ void mekorotKernel::move_cam(float az, float el, float zoom){ m_pPTZCTRL->goAbsolute(m_fCamTargetPan, m_fCamTargetTilt, m_fCamTargetZoom ); }; }; - +#define SIZE_IDX 1 +#define DEV_ID_IDX 2 +#define CMD_IDX 3 +#define SUB_CMD_IDX 4 +#define DATA_BEGIN_IDX 5 bool mekorotKernel::react(uint8_t devID, protocolPackage* Package){ char tBuf[128]; switch( Package->m_pData[CMD_IDX] ) { @@ -932,36 +1025,38 @@ bool mekorotKernel::react(uint8_t devID, protocolPackage* Package){ return true; }; -void mekorotKernel::pushFrame(cv::Mat* Frame, void* src) { - if (src == NULL) { - return; - }; - if (m_nFrameCounter == 0) m_lStartTS = getMilliseconds(); - m_nFrameCounter++; - for (int index = 0; index < m_nVideoInputs; index++) { - if (src == m_pVideoInputs[index]) { - Frame->copyTo((*m_pVideoFrame[index])); - m_nCLoopMask &= ~(1 << index); - break; - }; - }; +void mekorotKernel::pushFrame(cv::Mat &Frame, void* src) { + //if (src == NULL) { + // return; + //}; + //if (m_nFrameCounter == 0) m_lStartTS = getMilliseconds(); + //m_nFrameCounter++; + //for (int index = 0; index < m_nVideoInputs; index++) { + // if (src == m_pVideoInputs[index]) { + // Frame->copyTo((*m_pVideoFrame[index])); + // m_nCLoopMask &= ~(1 << index); + // break; + // }; + //}; //If we get all frames; if (m_pFinalFrame != NULL) { - if ((m_nCLoopMask & m_nCLoopCheck) == 0) { + //if ((m_nCLoopMask & m_nCLoopCheck) == 0) { int cx, cy; cx = 0; cy = 15; m_pMatProtector->lock(); //rectangle( (*m_pFinalFrame), Point(0,0), Point(m_nWidth, m_nHeight), Scalar(0,0,0), CV_FILLED ); - for (int index = 0; index < m_nVideoInputs; index++) { - if (m_bHorizontal) { - m_pVideoFrame[index]->copyTo((*m_pFinalFrame)(cv::Rect(cx, cy, m_pVideoFrame[index]->cols, m_pVideoFrame[index]->rows))); - cx += m_pVideoFrame[index]->cols; - } - else { - m_pVideoFrame[index]->copyTo((*m_pFinalFrame)(cv::Rect(cx, cy, m_pVideoFrame[index]->cols, m_pVideoFrame[index]->rows))); - cy += m_pVideoFrame[index]->rows; - }; - }; + //for (int index = 0; index < m_nVideoInputs; index++) { + // if (m_bHorizontal) { + // m_pVideoFrame[index]->copyTo((*m_pFinalFrame)(cv::Rect(cx, cy, m_pVideoFrame[index]->cols, m_pVideoFrame[index]->rows))); + // cx += m_pVideoFrame[index]->cols; + // } + // else { + // m_pVideoFrame[index]->copyTo((*m_pFinalFrame)(cv::Rect(cx, cy, m_pVideoFrame[index]->cols, m_pVideoFrame[index]->rows))); + // cy += m_pVideoFrame[index]->rows; + // }; + //}; + Frame.copyTo((*m_pFinalFrame)); + int X, W = 260; X = (m_pFinalFrame->cols - W) >> 1; //rectangle( (*m_pFinalFrame), Point( X, 10 ), Point( X+W, 25 ), Scalar( 0, 0, 0 ), CV_FILLED ); @@ -976,9 +1071,9 @@ void mekorotKernel::pushFrame(cv::Mat* Frame, void* src) { }; char DateStr[200]; - sprintf(DateStr, "TS:%010lu", tMilliseconds); + sprintf(DateStr, "TS:%010llu", tMilliseconds); putText((*m_pFinalFrame), DateStr, Point(X, 12), FONT_HERSHEY_SIMPLEX, .4, Scalar(0, 255, 255), 1); - sprintf(DateStr, "FID:%06lu", m_nFrameCounter); + sprintf(DateStr, "FID:%06u", m_nFrameCounter); putText((*m_pFinalFrame), DateStr, Point(X + 110, 12), FONT_HERSHEY_SIMPLEX, .4, Scalar(0, 255, 0), 1); sprintf(DateStr, "FPS:%03.2f", fps); putText((*m_pFinalFrame), DateStr, Point(X + 190, 12), FONT_HERSHEY_SIMPLEX, .4, Scalar(255, 0, 255), 1); @@ -990,12 +1085,14 @@ void mekorotKernel::pushFrame(cv::Mat* Frame, void* src) { rectangle((*m_pFinalFrame), Point(X + 260, 3), Point(X + 275, 12), Scalar(0, 255, 0), cv::FILLED); }; //if( m_bAssembleMP4 ) { - m_pVideoOutput->pushFrame(m_pFinalFrame); + + //m_pVideoOutput->pushFrame(m_pFinalFrame); + //}; m_pMatProtector->unlock(); // Assemble Final Frame; m_nCLoopMask = 0xFFFFFFFF; - }; + //}; }; }; @@ -1009,8 +1106,9 @@ bool mekorotKernel::copyFrame(cv::Mat& Frame) { }; void mekorotKernel::alarm(void) { + /* #ifdef DEBUG - LOG("Get VO Status!"); + //LOG("Get VO Status!"); #endif if (!m_pVideoOutput->getRecordStatus()) { m_nAlarmCnt++; @@ -1019,18 +1117,52 @@ void mekorotKernel::alarm(void) { //sprintf( Buffer, "%s_%02d.%s", m_sSeriesName, m_nAlarmCnt, VIDEO_OUTPUT_CONTAINER ); sprintf(Buffer, "%s_%02d.%s", m_pStorageProvider->getNewFileName(), m_nAlarmCnt, VIDEO_OUTPUT_CONTAINER); #ifdef DEBUG - LOG("Begin VO!"); + //LOG("Begin VO!"); #endif m_bRecordIsSaving = m_pVideoOutput->beginOutput(Buffer); } else { #ifdef DEBUG - LOG("Cont VO!"); + //LOG("Cont VO!"); #endif m_bRecordIsSaving = m_pVideoOutput->continueOutput(); }; m_bRecordIsActive = m_bRecordIsSaving; //m_bEventRegistered = false; + */ + + //char Buffer[1024]; + m_pMatProtector->lock(); + m_nAlarmCnt++; + sprintf( m_sOutputPicture, "%s_%02d.%s", m_pStorageProvider->getNewFileName(), m_nAlarmCnt, PICTURE_OUTPUT_CONTAINER); + try { + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); + compression_params.push_back( 90 ); + /* + vector buf; + cv::imencode( Buffer, *m_pFinalFrame, buf, compression_params ); + m_nNoSignalSize = buf.size(); + n_pNoSignalData = (uint8_t*)malloc(m_nNoSignalSize); + if (n_pNoSignalData) { + memcpy(n_pNoSignalData, buf.data(), m_nNoSignalSize); + } + else m_nNoSignalSize = 0; + buf.clear(); + */ + cv::imwrite( m_sOutputPicture, *m_pFinalFrame, compression_params); + } catch (cv::Exception & e) { + LOG_ERROR(e.msg.c_str()); + }; + m_pMatProtector->unlock(); }; +#undef SIZE_IDX +#undef DEV_ID_IDX +#undef CMD_IDX +#undef SUB_CMD_IDX +#undef DATA_BEGIN_IDX + #undef LOG #undef LOG_ERROR diff --git a/Projects/MEKOROT/MEKOROT_Kernel.h b/Projects/MEKOROT/MEKOROT_Kernel.h index 3aec2862..11b4a117 100644 --- a/Projects/MEKOROT/MEKOROT_Kernel.h +++ b/Projects/MEKOROT/MEKOROT_Kernel.h @@ -19,7 +19,8 @@ #include "../../lib/data/media/lapsedVideoRecorder.h" #include "../../lib/data/media/videoNode.h" #include "../../lib/data/media/video/videoAVLIBSource.h" -#include "../../lib/data/protocol/protocolLGS.h" +//#include "../../lib/data/protocol/protocolLGS.h" +#include "../../lib/data/protocol/protocolLGS2D.h" #include "../../lib/data/protocol/protocolPTZ_ONVIF.h" #include "../../lib/data/storage/storageProvider.h" #include "../../lib/hardware/uart/serialPort.h" @@ -85,7 +86,7 @@ #define KERNEL_QUICK_SLEEP_TIME 50 // msec #define MAX_ZOOM_TABLE_COUNT 32 -class mekorotKernel: public basicEngine, public basicThread, public basicMediaDestination, public protocolLGS_CLIENT { +class mekorotKernel: public basicEngine, public basicThread, public basicMediaDestination, public protocolLGS_2D{ private: basicLogCollection *m_pLog; config_setting_t *m_pSettings; @@ -114,6 +115,7 @@ class mekorotKernel: public basicEngine, public basicThread, public basicMediaDe basicMutex * m_pMatProtector; cv::Mat * m_pFinalFrame; cv::Mat ** m_pVideoFrame; + char m_sOutputPicture[1024]; bool m_bHorizontal; bool m_bRecordIsActive; @@ -159,8 +161,8 @@ class mekorotKernel: public basicEngine, public basicThread, public basicMediaDe explicit mekorotKernel( config_setting_t *ptr=NULL ); virtual ~mekorotKernel(); virtual bool init(void); - virtual void pushFrame(cv::Mat* Frame, void* src = NULL); - bool copyFrame(cv::Mat& Frame); + virtual void pushFrame(cv::Mat &Frame, void* src = NULL); + bool copyFrame(cv::Mat &Frame); }; #endif \ No newline at end of file diff --git a/Projects/MEKOROT/mekorot.conf b/Projects/MEKOROT/mekorot.conf index a11417a2..93362c32 100644 --- a/Projects/MEKOROT/mekorot.conf +++ b/Projects/MEKOROT/mekorot.conf @@ -5,33 +5,33 @@ GENERAL : }; KERNEL : { - SERIAL_LINE = "\\\\.\\COM5"; + SERIAL_LINE = "\\\\.\\COM2"; SERIAL_SPEED = 19200; - DEVICE_LEFT_ID = 1; - DEVICE_CENTER_ID = 2; - DEVICE_RIGHT_ID = 3; + DEVICE_LEFT_ID = -1; + DEVICE_CENTER_ID = -2; + DEVICE_RIGHT_ID = -3; VIDEO : { INPUT_0 : { - SOURCE = "artsp://admin:4GetMyID@192.168.200.102:554/cam/realmonitor?channel=1&subtype=1&unicast=true&proto=Onvif"; + SOURCE = "rtsp://admin:4GetMyID@192.168.200.106:554/cam/realmonitor?channel=1&subtype=1&unicast=true&proto=Onvif"; PROFILE = "MediaProfile001"; - WIDTH = 704; - HEIGHT = 576; + WIDTH = 1920; + HEIGHT = 1080; }; }; STORAGE = "storage"; ONVIF_USER = "admin"; ONVIF_PASSWORD = "4GetMyID"; - ONVIF_DEVICE_URI = "http://192.168.200.102/onvif/device_service"; - LEFT_PAN = 0.5; - RIGHT_PAN = -0.5; + ONVIF_DEVICE_URI = "http://192.168.200.106/onvif/device_service"; + LEFT_PAN = 0.83; + RIGHT_PAN = 0.29; HORIZONTAL_TILT = 1.0; HOOME_TILT = 1.0; HOOME_ZOOM = 0.0; - HOOME_PAN = 0.0; - LEFT_ZSIFT = 0; - HORIZONTAL_ZSHIFT = 0; + HOOME_PAN = 0.56; + LEFT_ZSIFT = 1400; + HORIZONTAL_ZSHIFT = 3800; RIGHT_ZSHIFT = 0; RECORD_FRAMES = 50; ZOOM_TABLE : diff --git a/Projects/Pathfinder/build b/Projects/Pathfinder/build old mode 100755 new mode 100644 diff --git a/Projects/argus/argus.vpj b/Projects/argus/argus.vpj index 9ff67ef7..0d487bda 100644 --- a/Projects/argus/argus.vpj +++ b/Projects/argus/argus.vpj @@ -25,7 +25,7 @@ SaveOption="SaveCurrent" RunFromDir="%rw"> - + - + + @@ -140,7 +141,7 @@ Version="1" OutputFile="%bdargus" CompilerConfigName="Latest Version" - Defines='"/D__STDC_CONSTANT_MACROS" "/D_CLIENT_APPLICATION_"'> + Defines='"/D__STDC_CONSTANT_MACROS" "/D_CLIENT_APPLICATION_" "/D_OPENCV_"'> - + + + @@ -343,6 +346,7 @@ + @@ -422,6 +426,7 @@ + @@ -429,6 +434,8 @@ + + diff --git a/Projects/argus/argus.vpj.bk b/Projects/argus/argus.vpj.bk new file mode 100644 index 00000000..74748c3f --- /dev/null +++ b/Projects/argus/argus.vpj.bk @@ -0,0 +1,462 @@ + + + + Defines='"/DDEBUG" "/D__STDC_CONSTANT_MACROS" "/D_CLIENT_APPLICATION_" "/D_OPENCV_"'> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Defines='"/D__STDC_CONSTANT_MACROS" "/D_CLIENT_APPLICATION_" "/D_OPENCV_"'> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Projects/argus/build b/Projects/argus/build old mode 100755 new mode 100644 diff --git a/Projects/argus/debug b/Projects/argus/debug index e26d955d..f003f201 100644 --- a/Projects/argus/debug +++ b/Projects/argus/debug @@ -1 +1,26 @@ -(gdb) set follow-fork-mode child \ No newline at end of file +(gdb) set follow-fork-mode child + +Web NEt Manager... +Add the user to netdev group : The members of this group can manage network interfaces through the network-manager and wicd: + +Add user: +adduser user_name_here netdev + +Reload dbus: +/etc/init.d/dbus reload + + + +push /// +Android + +https://phpadvices.com/send-push-notification-to-android-using-php-and-firebase/ +https://www.tutsmake.com/php-send-push-notification-to-android-ios-using-google-fcm/ +https://thefuturelens.com/send-notification-using-php/ +https://help.pushwoosh.com/hc/en-us/community/posts/360000793786-Get-Device-Token + +IOS +https://michael.wright.uk/sending-ios-push-notifications-with-php/ +https://stackoverflow.com/questions/14102349/how-to-get-device-tokens + +https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential \ No newline at end of file diff --git a/Projects/argus/makefile b/Projects/argus/makefile index 16547782..05ffe460 100644 --- a/Projects/argus/makefile +++ b/Projects/argus/makefile @@ -24,8 +24,8 @@ CFG_INC= CFG_LIB=-lpthread -lmysqlclient -lssl -lcurl -lm -lcrypto -lconfig \ -lz -lv4l1 -lv4l2 -lhidapi-libusb `pkg-config libavcodec libavdevice \ libavfilter libavformat libavutil libpostproc libswresample \ - libswscale --libs` -lssl -latomic `pkg-config --libs opencv4 \ - rdkafka++` + libswscale --libs` -latomic `pkg-config --libs openssl libssl \ + opencv4 rdkafka++` CFG_OBJ= COMMON_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/basicCameraInfo.o $(OUTDIR)/basicDualThread.o \ @@ -68,9 +68,10 @@ COMMON_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/rgooseModuleUSBRelay.o $(OUTDIR)/rgooseModuleZLMedia.o \ $(OUTDIR)/rgooseNode.o $(OUTDIR)/rgooseNode2D.o \ $(OUTDIR)/rgooseNode3D.o $(OUTDIR)/rgooseNodeFactory.o \ - $(OUTDIR)/rgooseNodePTZCamControl.o $(OUTDIR)/rgooseServerModule.o \ - $(OUTDIR)/rgooseTargetFilter.o $(OUTDIR)/serialPort.o \ - $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/rgooseNodePTZCamControl.o \ + $(OUTDIR)/rgooseNodeStaticCamControl.o \ + $(OUTDIR)/rgooseServerModule.o $(OUTDIR)/rgooseTargetFilter.o \ + $(OUTDIR)/serialPort.o $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ $(OUTDIR)/servletChannelWS.o $(OUTDIR)/servletClientHandlerWS.o \ $(OUTDIR)/servletWS.o $(OUTDIR)/ssdpAnnouncer.o \ $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ @@ -118,9 +119,10 @@ ALL_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/rgooseModuleUSBRelay.o $(OUTDIR)/rgooseModuleZLMedia.o \ $(OUTDIR)/rgooseNode.o $(OUTDIR)/rgooseNode2D.o \ $(OUTDIR)/rgooseNode3D.o $(OUTDIR)/rgooseNodeFactory.o \ - $(OUTDIR)/rgooseNodePTZCamControl.o $(OUTDIR)/rgooseServerModule.o \ - $(OUTDIR)/rgooseTargetFilter.o $(OUTDIR)/serialPort.o \ - $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/rgooseNodePTZCamControl.o \ + $(OUTDIR)/rgooseNodeStaticCamControl.o \ + $(OUTDIR)/rgooseServerModule.o $(OUTDIR)/rgooseTargetFilter.o \ + $(OUTDIR)/serialPort.o $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ $(OUTDIR)/servletChannelWS.o $(OUTDIR)/servletClientHandlerWS.o \ $(OUTDIR)/servletWS.o $(OUTDIR)/ssdpAnnouncer.o \ $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ @@ -129,10 +131,10 @@ ALL_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ -lmysqlclient -lssl -lcurl -lm -lcrypto -lconfig -lz -lv4l1 -lv4l2 \ -lhidapi-libusb `pkg-config libavcodec libavdevice libavfilter \ libavformat libavutil libpostproc libswresample libswscale --libs` \ - -lssl -latomic `pkg-config --libs opencv4 rdkafka++` + -latomic `pkg-config --libs openssl libssl opencv4 rdkafka++` -COMPILE=g++ -c -x c++ "-DDEBUG" "-D__STDC_CONSTANT_MACROS" "-D_CLIENT_APPLICATION_" "-D_OPENCV_" -g -ggdb -std=c++11 -Wno-write-strings -I../../lib/include `pkg-config opencv4 libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< -LINK=g++ -g -ggdb -o "$(OUTFILE)" $(ALL_OBJ) +COMPILE=g++ -c -x c++ "-DDEBUG" "-D__STDC_CONSTANT_MACROS" "-D_CLIENT_APPLICATION_" "-D_OPENCV_" -O0 -g3 -ggdb -std=c++11 -Wno-write-strings -I../../lib/include `pkg-config opencv4 libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< +LINK=g++ -O0 -g3 -ggdb -o "$(OUTFILE)" $(ALL_OBJ) # Pattern rules $(OUTDIR)/%.o : ../../lib/data/transport/%.cpp @@ -223,7 +225,8 @@ CFG_INC= CFG_LIB=-lpthread -lmysqlclient -lssl -lcurl -lm -lcrypto -lconfig \ -lz -lv4l1 -lv4l2 -lhidapi-libusb `pkg-config libavcodec libavdevice \ libavfilter libavformat libavutil libpostproc libswresample \ - libswscale --libs` -lssl -latomic `pkg-config --libs rdkafka++` + libswscale --libs` -latomic `pkg-config --libs openssl libssl \ + opencv4 rdkafka++` CFG_OBJ= COMMON_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/basicCameraInfo.o $(OUTDIR)/basicDualThread.o \ @@ -266,9 +269,10 @@ COMMON_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/rgooseModuleUSBRelay.o $(OUTDIR)/rgooseModuleZLMedia.o \ $(OUTDIR)/rgooseNode.o $(OUTDIR)/rgooseNode2D.o \ $(OUTDIR)/rgooseNode3D.o $(OUTDIR)/rgooseNodeFactory.o \ - $(OUTDIR)/rgooseNodePTZCamControl.o $(OUTDIR)/rgooseServerModule.o \ - $(OUTDIR)/rgooseTargetFilter.o $(OUTDIR)/serialPort.o \ - $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/rgooseNodePTZCamControl.o \ + $(OUTDIR)/rgooseNodeStaticCamControl.o \ + $(OUTDIR)/rgooseServerModule.o $(OUTDIR)/rgooseTargetFilter.o \ + $(OUTDIR)/serialPort.o $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ $(OUTDIR)/servletChannelWS.o $(OUTDIR)/servletClientHandlerWS.o \ $(OUTDIR)/servletWS.o $(OUTDIR)/ssdpAnnouncer.o \ $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ @@ -316,9 +320,10 @@ ALL_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ $(OUTDIR)/rgooseModuleUSBRelay.o $(OUTDIR)/rgooseModuleZLMedia.o \ $(OUTDIR)/rgooseNode.o $(OUTDIR)/rgooseNode2D.o \ $(OUTDIR)/rgooseNode3D.o $(OUTDIR)/rgooseNodeFactory.o \ - $(OUTDIR)/rgooseNodePTZCamControl.o $(OUTDIR)/rgooseServerModule.o \ - $(OUTDIR)/rgooseTargetFilter.o $(OUTDIR)/serialPort.o \ - $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/rgooseNodePTZCamControl.o \ + $(OUTDIR)/rgooseNodeStaticCamControl.o \ + $(OUTDIR)/rgooseServerModule.o $(OUTDIR)/rgooseTargetFilter.o \ + $(OUTDIR)/serialPort.o $(OUTDIR)/serialSOL.o $(OUTDIR)/serverPort.o \ $(OUTDIR)/servletChannelWS.o $(OUTDIR)/servletClientHandlerWS.o \ $(OUTDIR)/servletWS.o $(OUTDIR)/ssdpAnnouncer.o \ $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ @@ -327,9 +332,9 @@ ALL_OBJ=$(OUTDIR)/ArgusBackend.o $(OUTDIR)/base64.o \ -lmysqlclient -lssl -lcurl -lm -lcrypto -lconfig -lz -lv4l1 -lv4l2 \ -lhidapi-libusb `pkg-config libavcodec libavdevice libavfilter \ libavformat libavutil libpostproc libswresample libswscale --libs` \ - -lssl -latomic `pkg-config --libs rdkafka++` + -latomic `pkg-config --libs openssl libssl opencv4 rdkafka++` -COMPILE=g++ -c -x c++ "-D__STDC_CONSTANT_MACROS" "-D_CLIENT_APPLICATION_" -O3 -std=c++11 -Wno-write-strings -I../../lib/include `pkg-config libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< +COMPILE=g++ -c -x c++ "-D__STDC_CONSTANT_MACROS" "-D_CLIENT_APPLICATION_" "-D_OPENCV_" -O3 -std=c++11 -Wno-write-strings -I../../lib/include `pkg-config libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< LINK=g++ -O3 -o "$(OUTFILE)" $(ALL_OBJ) # Pattern rules diff --git a/Projects/argus/test_mem b/Projects/argus/test_mem new file mode 100644 index 00000000..0e42ed9c --- /dev/null +++ b/Projects/argus/test_mem @@ -0,0 +1,6 @@ +cd ./Debug +valgrind --leak-check=full \ + --track-origins=yes \ + --verbose \ + --log-file=valgrind-out.txt \ + ./argus diff --git a/Projects/custom_cam/popo b/Projects/custom_cam/popo old mode 100755 new mode 100644 diff --git a/Projects/custom_cam/runtest b/Projects/custom_cam/runtest old mode 100755 new mode 100644 diff --git a/Projects/custom_cam/start_params b/Projects/custom_cam/start_params old mode 100755 new mode 100644 diff --git a/Projects/img_mill/build b/Projects/img_mill/build old mode 100755 new mode 100644 diff --git a/Projects/libONVIF/LibONVIF.vpj b/Projects/libONVIF/LibONVIF.vpj index 6eb28891..76fd908e 100644 --- a/Projects/libONVIF/LibONVIF.vpj +++ b/Projects/libONVIF/LibONVIF.vpj @@ -104,30 +104,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -239,52 +213,52 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Projects/unit_tests/ut_basic_object/ut_basic_object.vpw b/Projects/unit_tests/ut_basic_object/ut_basic_object.vpw new file mode 100644 index 00000000..30ca270f --- /dev/null +++ b/Projects/unit_tests/ut_basic_object/ut_basic_object.vpw @@ -0,0 +1,6 @@ + + + + + + diff --git a/lib/App/argus/ArgusBackend.cpp b/lib/App/argus/ArgusBackend.cpp index 6eaed682..fce58408 100644 --- a/lib/App/argus/ArgusBackend.cpp +++ b/lib/App/argus/ArgusBackend.cpp @@ -22,7 +22,6 @@ bool gSignal_Handler_Enabled = true; #define LOG_ERROR( X ) m_pLog->Log( "main", 0, _LOG_ERROR, X ) argusKernel * Kernel = NULL; -//LRF_HardwareManager * HWManager = NULL; basicLogCollection * m_pLog = NULL; networkServer * NetworkManager = NULL; @@ -71,19 +70,17 @@ int main (int argc, char *argv[]){ MySQL_Connector * DBC = NULL; basicSettingsProvider * SETTINGS = NULL; - bool WBG; // Working Background - bool SSE; // Server Statistics Engine - bool NDC; // No Default Configuration + bool WBG = true; // Working Background + bool SSE = true; // Server Statistics Engine + bool NDC = true; // No Default Configuration + bool COLD_START = true; CSTR FLE_NAME; CSTR DCF_NAME; CSTR SSP_NAME; objectFileLoggingService * FLE = NULL; objectConsoleLoggingService * CLE = NULL; // default init - WBG = true; FLE_NAME = (CSTR) DEFAULT_SERVER_LOG_FILE; - SSE = true; - NDC = true; DCF_NAME = (CSTR) DEFAULT_SERVER_CONFIG_PATH; SSP_NAME = (CSTR) DEFAULT_SERVER_SOCKET_PATH; gsSOFT_INFO.SW_BUILD_DATE = UNIX_TIMESTAMP; @@ -174,7 +171,28 @@ int main (int argc, char *argv[]){ } else { SETTINGS = basicSettingsProvider::getInstance(); }; - + if ( fileExist( gsCFG_PID_FILE ) ){ + COLD_START = false; + //check if process already running + FILE *tFD = fopen( gsCFG_PID_FILE, "r" ); + if( tFD ) { + pid_t pid; + char tBuff[256]; + //fscanf( tFD, "%d\n", pid ); + fread( tBuff, 1, 255, tFD ); + pid = atoi( tBuff ); + printf("Old Process PID: %d\n", pid ); + if( kill( pid, 0 )==0 ){ + printf("Process Already Running --> exiting!\n"); + delete( FLE ); + fclose( tFD ); + exit(12); + } else { + printf("No Running Process --> Hot Restart Detected!\n"); + }; + fclose( tFD ); + }; + }; // Demonizing or not if( WBG ){ printf( "Dr Frucht Systems LRF Server ver. %s\n", VERSION_NUMBER ); @@ -227,7 +245,7 @@ int main (int argc, char *argv[]){ uint8_t m_bKernelExitCode = 0; do{ - Kernel = argusKernel::getInstance(); + Kernel = argusKernel::getInstance( COLD_START ); if( Kernel == NULL ) { // Aborting Work LOG_ERROR( "++++ Kernel failed to born ++++" ); diff --git a/lib/alg/generic/Transform.cpp b/lib/alg/generic/Transform.cpp index 2ffa60aa..f2b51f84 100644 --- a/lib/alg/generic/Transform.cpp +++ b/lib/alg/generic/Transform.cpp @@ -118,7 +118,7 @@ void translate2world(S_TRANS_MATRIX tMat, C3D_DECART local, C3D_DECART &world){ void translate2local(S_TRANS_MATRIX mat, C3D_DECART world, C3D_DECART &local){ S_TRANS_MATRIX tMat; - transform_3 *trHelper; + //transform_3 *trHelper; transponeMatrix(mat, tMat); local.x = world.x * tMat.AA + world.y * tMat.AB + world.z * tMat.AC + tMat.AD; local.y = world.x * tMat.BA + world.y * tMat.BB + world.z * tMat.BC + tMat.BD; @@ -142,9 +142,9 @@ void transponeMatrix(S_TRANS_MATRIX in, S_TRANS_MATRIX &out){ -const C3D_FLOAT transform_3::PI_M = 3.141592653589793; -const C3D_FLOAT transform_3::DTOR = 0.017453292519943; -const C3D_FLOAT transform_3::RTOD = 57.29577951308232; +const C3D_FLOAT transform_3::PI_M = 3.141592653589793f; +const C3D_FLOAT transform_3::DTOR = 0.017453292519943f; +const C3D_FLOAT transform_3::RTOD = 57.29577951308232f; vector_3::vector_3(C3D_FLOAT a0, C3D_FLOAT a1, C3D_FLOAT a2) { @@ -189,7 +189,7 @@ vector_3 matrix_3::operator * (const vector_3& vector) const for(uint8_t ii = 0; ii < 3; ++ii) for(uint8_t jj = 0; jj < 3; ++jj) - result[ii] += elem_[ii][jj] * vector[jj]; + result[ii] += (float)elem_[ii][jj] * vector[jj]; return result; } @@ -200,7 +200,7 @@ vector_3 operator * (const vector_3& vector, const matrix_3& matrix) for(uint8_t ii = 0; ii < 3; ++ii) for(uint8_t jj = 0; jj < 3; ++jj) - result[ii] += matrix.elem_[jj][ii] * vector[jj]; + result[ii] += (float)matrix.elem_[jj][ii] * vector[jj]; return result; } diff --git a/lib/alg/generic/heapDebug.cpp b/lib/alg/generic/heapDebug.cpp index 183f720b..85199bb6 100644 --- a/lib/alg/generic/heapDebug.cpp +++ b/lib/alg/generic/heapDebug.cpp @@ -1,6 +1,6 @@ #include "heapDebug.h" -#ifndef DEBUG +#if !defined( DEBUG ) && !defined( MEM_DEBUG_LOG ) size_t getPeakRSS( ){ return 0; }; size_t getCurrentRSS( ){ return 0; }; #else diff --git a/lib/alg/generic/heapDebug.h b/lib/alg/generic/heapDebug.h index 583752d0..74f88ead 100644 --- a/lib/alg/generic/heapDebug.h +++ b/lib/alg/generic/heapDebug.h @@ -4,7 +4,7 @@ * License: Creative Commons Attribution 3.0 Unported License * http://creativecommons.org/licenses/by/3.0/deed.en_US */ -#ifndef DEBUG +#if !defined( DEBUG ) && !defined( MEM_DEBUG_LOG ) #include size_t getPeakRSS( ); size_t getCurrentRSS( ); diff --git a/lib/alg/generic/md5.cpp b/lib/alg/generic/md5.cpp index 6dc68225..b3428fd5 100644 --- a/lib/alg/generic/md5.cpp +++ b/lib/alg/generic/md5.cpp @@ -91,10 +91,10 @@ char* PrintMD5(u_char md5Digest[16]) // the results as a char*. char* MD5String(char* szString) { - int nLen = strlen(szString); + size_t nLen = strlen(szString); md5 alg; - alg.Update((unsigned char*)szString, (unsigned int)nLen); + alg.Update((unsigned char*)szString, nLen ); alg.Finalize(); return PrintMD5(alg.Digest()); @@ -105,9 +105,9 @@ char* MD5String(char* szString) // returning the results as a char*. Returns NULL if it fails. char* MD5File(char* szFilename) { - FILE* file; - md5 alg; - int nLen; + FILE * file; + md5 alg; + size_t nLen; unsigned char chBuffer[1024]; try @@ -151,9 +151,10 @@ void md5::Init() // MD5 block update operation. Continues an MD5 message-digest // operation, processing another message block, and updating the // context. -void md5::Update(u_char* chInput, u_int4 nInputLen) +void md5::Update(u_char* chInput, size_t IL) { u_int4 i, index, partLen; + u_int4 nInputLen = (u_int4)IL; // Compute number of bytes mod 64 index = (unsigned int)((m_Count[0] >> 3) & 0x3F); diff --git a/lib/alg/generic/md5.h b/lib/alg/generic/md5.h index 9b575ba7..07c39293 100644 --- a/lib/alg/generic/md5.h +++ b/lib/alg/generic/md5.h @@ -49,7 +49,7 @@ class md5{ public: md5() { Init(); } void Init(); - void Update(u_char* chInput, u_int4 nInputLen); + void Update(u_char* chInput, size_t InputLen); void Finalize(); u_char* Digest() { return m_Digest; } diff --git a/lib/alg/generic/utm.cpp b/lib/alg/generic/utm.cpp index dc71954d..196c9d72 100644 --- a/lib/alg/generic/utm.cpp +++ b/lib/alg/generic/utm.cpp @@ -29,14 +29,14 @@ coordConverter::~coordConverter(){ // DegToRad // Converts degrees to radians. FLOAT_UTM coordConverter::DegToRad(FLOAT_UTM deg) { - return (deg / 180.0 * PI_UTM); + return (FLOAT_UTM)(deg / 180.0 * PI_UTM); }; // RadToDeg // Converts radians to degrees. FLOAT_UTM coordConverter::RadToDeg(FLOAT_UTM rad) { - return (rad / PI_UTM * 180.0); + return (FLOAT_UTM)(rad / PI_UTM * 180.0f); }; // ArcLengthOfMeridian @@ -60,29 +60,29 @@ FLOAT_UTM coordConverter::ArcLengthOfMeridian(FLOAT_UTM phi) { FLOAT_UTM result; /* Precalculate n */ - n = (sm_a - sm_b) / (sm_a + sm_b); + n = (FLOAT_UTM)(sm_a - sm_b) / (sm_a + sm_b); /* Precalculate alpha */ - alpha = ((sm_a + sm_b) / 2.0) + alpha = (FLOAT_UTM)((sm_a + sm_b) / 2.0) * (1.0 + (POW_UTM(n, 2.0) / 4.0) + (POW_UTM(n, 4.0) / 64.0)); /* Precalculate beta */ - beta = (-3.0 * n / 2.0) + (9.0 * POW_UTM(n, 3.0) / 16.0) + beta = (FLOAT_UTM)(-3.0 * n / 2.0) + (9.0 * POW_UTM(n, 3.0) / 16.0) + (-3.0 * POW_UTM(n, 5.0) / 32.0); /* Precalculate gamma */ - gamma = (15.0 * POW_UTM(n, 2.0) / 16.0) + gamma = (FLOAT_UTM)(15.0 * POW_UTM(n, 2.0) / 16.0) + (-15.0 * POW_UTM(n, 4.0) / 32.0); /* Precalculate delta */ - delta = (-35.0 * POW_UTM(n, 3.0) / 48.0) + delta = (FLOAT_UTM)(-35.0 * POW_UTM(n, 3.0) / 48.0) + (105.0 * POW_UTM(n, 5.0) / 256.0); /* Precalculate epsilon */ - epsilon = (315.0 * POW_UTM(n, 4.0) / 512.0); + epsilon = (FLOAT_UTM)(315.0 * POW_UTM(n, 4.0) / 512.0); /* Now calculate the sum of the series and return */ - result = alpha + result = (FLOAT_UTM) alpha * (phi + (beta * SIN_UTM(2.0 * phi)) + (gamma * SIN_UTM(4.0 * phi)) + (delta * SIN_UTM(6.0 * phi)) @@ -129,36 +129,36 @@ FLOAT_UTM coordConverter::FootpointLatitude(FLOAT_UTM y) { FLOAT_UTM result; /* Precalculate n (Eq. 10.18) */ - n = (sm_a - sm_b) / (sm_a + sm_b); + n = (FLOAT_UTM)(sm_a - sm_b) / (sm_a + sm_b); /* Precalculate alpha_ (Eq. 10.22) */ /* (Same as alpha in Eq. 10.17) */ - alpha_ = ((sm_a + sm_b) / 2.0) + alpha_ = (FLOAT_UTM)((sm_a + sm_b) / 2.0) * (1 + (POW_UTM(n, 2.0) / 4) + (POW_UTM(n, 4.0) / 64)); /* Precalculate y_ (Eq. 10.23) */ y_ = y / alpha_; /* Precalculate beta_ (Eq. 10.22) */ - beta_ = (3.0 * n / 2.0) + (-27.0 * POW_UTM(n, 3.0) / 32.0) + beta_ = (FLOAT_UTM)(3.0 * n / 2.0) + (-27.0 * POW_UTM(n, 3.0) / 32.0) + (269.0 * POW_UTM(n, 5.0) / 512.0); /* Precalculate gamma_ (Eq. 10.22) */ - gamma_ = (21.0 * POW_UTM(n, 2.0) / 16.0) + gamma_ = (FLOAT_UTM)(21.0 * POW_UTM(n, 2.0) / 16.0) + (-55.0 * POW_UTM(n, 4.0) / 32.0); /* Precalculate delta_ (Eq. 10.22) */ - delta_ = (151.0 * POW_UTM(n, 3.0) / 96.0) + delta_ = (FLOAT_UTM)(151.0 * POW_UTM(n, 3.0) / 96.0) + (-417.0 * POW_UTM(n, 5.0) / 128.0); /* Precalculate epsilon_ (Eq. 10.22) */ - epsilon_ = (1097.0 * POW_UTM(n, 4.0) / 512.0); + epsilon_ = (FLOAT_UTM)(1097.0 * POW_UTM(n, 4.0) / 512.0); /* Now calculate the sum of the series (Eq. 10.21) */ - result = y_ + (beta_ * SIN_UTM(2.0 * y_)) + result = (FLOAT_UTM)(y_ + (beta_ * SIN_UTM(2.0 * y_)) + (gamma_ * SIN_UTM(4.0 * y_)) + (delta_ * SIN_UTM(6.0 * y_)) - + (epsilon_ * SIN_UTM(8.0 * y_)); + + (epsilon_ * SIN_UTM(8.0 * y_))); return result; }; @@ -190,13 +190,13 @@ void coordConverter::MapLatLonToXY(FLOAT_UTM phi, FLOAT_UTM lambda, FLOAT_UTM la //FLOAT tmp; // Unused /* Precalculate ep2 */ - ep2 = (POW_UTM(sm_a, 2.0) - POW_UTM(sm_b, 2.0)) / POW_UTM(sm_b, 2.0); + ep2 = (FLOAT_UTM)(POW_UTM(sm_a, 2.0) - POW_UTM(sm_b, 2.0)) / POW_UTM(sm_b, 2.0); /* Precalculate nu2 */ - nu2 = ep2 * POW_UTM(COS_UTM(phi), 2.0); + nu2 = (FLOAT_UTM)ep2 * POW_UTM(COS_UTM(phi), 2.0); /* Precalculate N */ - N = POW_UTM(sm_a, 2.0) / (sm_b * SQRT_UTM(1 + nu2)); + N = (FLOAT_UTM)POW_UTM(sm_a, 2.0) / (sm_b * SQRT_UTM(1 + nu2)); /* Precalculate t */ t = TAN_UTM(phi); @@ -204,38 +204,38 @@ void coordConverter::MapLatLonToXY(FLOAT_UTM phi, FLOAT_UTM lambda, FLOAT_UTM la //tmp = (t2 * t2 * t2) - POW(t, 6.0); // Unused /* Precalculate l */ - l = lambda - lambda0; + l = (FLOAT_UTM) lambda - lambda0; /* Precalculate coefficients for l**n in the equations below so a normal human being can read the expressions for easting and northing -- l**1 and l**2 have coefficients of 1.0 */ - l3coef = 1.0 - t2 + nu2; + l3coef = (FLOAT_UTM)(1.0 - t2 + nu2); - l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2); + l4coef = (FLOAT_UTM)(5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2)); - l5coef = 5.0 - 18.0 * t2 + (t2 * t2) + 14.0 * nu2 - - 58.0 * t2 * nu2; + l5coef = (FLOAT_UTM)(5.0 - 18.0 * t2 + (t2 * t2) + 14.0 * nu2 + - 58.0 * t2 * nu2); - l6coef = 61.0 - 58.0 * t2 + (t2 * t2) + 270.0 * nu2 - - 330.0 * t2 * nu2; + l6coef = (FLOAT_UTM)(61.0 - 58.0 * t2 + (t2 * t2) + 270.0 * nu2 + - 330.0 * t2 * nu2); - l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2 * t2) - (t2 * t2 * t2); + l7coef = (FLOAT_UTM)(61.0 - 479.0 * t2 + 179.0 * (t2 * t2) - (t2 * t2 * t2)); - l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2 * t2) - (t2 * t2 * t2); + l8coef = (FLOAT_UTM)(1385.0 - 3111.0 * t2 + 543.0 * (t2 * t2) - (t2 * t2 * t2)); /* Calculate easting (x) */ - x = N * COS_UTM(phi) * l + x = (FLOAT_UTM)( N * COS_UTM(phi) * l + (N / 6.0 * POW_UTM(COS_UTM(phi), 3.0) * l3coef * POW_UTM(l, 3.0)) + (N / 120.0 * POW_UTM(COS_UTM(phi), 5.0) * l5coef * POW_UTM(l, 5.0)) - + (N / 5040.0 * POW_UTM(COS_UTM(phi), 7.0) * l7coef * POW_UTM(l, 7.0)); + + (N / 5040.0 * POW_UTM(COS_UTM(phi), 7.0) * l7coef * POW_UTM(l, 7.0))); /* Calculate northing (y) */ - y = ArcLengthOfMeridian (phi) + y = (FLOAT_UTM) ( ArcLengthOfMeridian (phi) + (t / 2.0 * N * POW_UTM(COS_UTM(phi), 2.0) * POW_UTM(l, 2.0)) + (t / 24.0 * N * POW_UTM(COS_UTM(phi), 4.0) * l4coef * POW_UTM(l, 4.0)) + (t / 720.0 * N * POW_UTM(COS_UTM(phi), 6.0) * l6coef * POW_UTM(l, 6.0)) - + (t / 40320.0 * N * POW_UTM(COS_UTM(phi), 8.0) * l8coef * POW_UTM(l, 8.0)); + + (t / 40320.0 * N * POW_UTM(COS_UTM(phi), 8.0) * l8coef * POW_UTM(l, 8.0))); return; }; diff --git a/lib/alg/generic/utm.h b/lib/alg/generic/utm.h index 416dd793..619257ce 100644 --- a/lib/alg/generic/utm.h +++ b/lib/alg/generic/utm.h @@ -37,6 +37,12 @@ #define SQRT_UTM sqrt #define FLOOR_UTM floor #define PI_UTM 3.14159265358979 + + /* Ellipsoid model constants (actual values here are for WGS84) */ + #define sm_a 6378137.0 + #define sm_b 6356752.314 + #define sm_EccSquared 6.69437999013e-03 + #define UTMScaleFactor 0.9996 #else #ifdef FLOAT_32 #define FLOAT_UTM float @@ -47,6 +53,12 @@ #define SQRT_UTM sqrtf #define FLOOR_UTM floorf #define PI_UTM 3.14159265358979f + + /* Ellipsoid model constants (actual values here are for WGS84) */ + #define sm_a 6378137.0f + #define sm_b 6356752.314f + #define sm_EccSquared 0.00669437999013f + #define UTMScaleFactor 0.9996f #endif #endif @@ -55,12 +67,6 @@ -/* Ellipsoid model constants (actual values here are for WGS84) */ -#define sm_a 6378137.0 -#define sm_b 6356752.314 -#define sm_EccSquared 6.69437999013e-03 - -#define UTMScaleFactor 0.9996 class coordConverter{ private: diff --git a/lib/alg/lgs/mask.h b/lib/alg/lgs/mask.h index 16fd2ab3..2836d0c6 100644 --- a/lib/alg/lgs/mask.h +++ b/lib/alg/lgs/mask.h @@ -24,7 +24,7 @@ typedef struct{ uint8_t color[3]; simplePoint *points; - uint16_t count; + uint8_t count; } simplePolygone; typedef std::vector vectorMasking; typedef std::vector vectorQPoly; @@ -35,7 +35,7 @@ typedef struct{ uint8_t color[3]; QPoint *points; - uint16_t count; + uint8_t count; } simplePolygone; typedef std::vector vectorMasking; diff --git a/lib/components/base/basicCamera.cpp b/lib/components/base/basicCamera.cpp index b2032a07..bdf55fb1 100644 --- a/lib/components/base/basicCamera.cpp +++ b/lib/components/base/basicCamera.cpp @@ -60,22 +60,22 @@ bool basicCamera::create(void){ /*Location*/ pSetting = config_setting_get_member(m_pSettings, TAG_POSITION_LAT); if (pSetting == NULL) return false; - m_sSourceInfo.lat = config_setting_get_float(pSetting); + m_sSourceInfo.lat = (float)config_setting_get_float(pSetting); pSetting = config_setting_get_member(m_pSettings, TAG_POSITION_LON); if (pSetting == NULL) return false; - m_sSourceInfo.lon = config_setting_get_float(pSetting); + m_sSourceInfo.lon = (float)config_setting_get_float(pSetting); pSetting = config_setting_get_member(m_pSettings, TAG_POSITION_ALT); if (pSetting == NULL) return false; - m_sSourceInfo.alt = config_setting_get_float(pSetting); + m_sSourceInfo.alt = (float)config_setting_get_float(pSetting); pSetting = config_setting_get_member(m_pSettings, TAG_POSITION_ROLL); if (pSetting == NULL) return false; - m_sSourceInfo.h_lat = config_setting_get_float(pSetting); + m_sSourceInfo.h_lat = (float)config_setting_get_float(pSetting); pSetting = config_setting_get_member(m_pSettings, TAG_POSITION_PITCH); if (pSetting == NULL) return false; - m_sSourceInfo.h_lon = config_setting_get_float(pSetting); + m_sSourceInfo.h_lon = (float)config_setting_get_float(pSetting); pSetting = config_setting_get_member(m_pSettings, TAG_POSITION_YAW); if (pSetting == NULL) return false; - m_sSourceInfo.h_alt = config_setting_get_float(pSetting); + m_sSourceInfo.h_alt = (float)config_setting_get_float(pSetting); setPositionDeg(m_sSourceInfo.lat, m_sSourceInfo.lon, m_sSourceInfo.alt, m_sSourceInfo.h_lat, m_sSourceInfo.h_lon, m_sSourceInfo.h_alt); return true; }; @@ -312,31 +312,39 @@ void basicCamera::updateSettings(void){ if (basicSettingsProvider::getInstance()->isCompromised()) basicSettingsProvider::getInstance()->validate(); }; -void basicCamera::dispatchEvent( basicEvent *Evt ){ - if( Evt->m_eClass == EVT_CLASS_SENSOR ) { - switch (Evt->m_eType){ - case EVT_TARGET_1D: - case EVT_TARGET_2D_WHITE: - case EVT_TARGET_2D_BLACK: - case EVT_TARGET_3D_WHITE: - case EVT_TARGET_3D_BLACK: - case EVT_ALARM: - CLIENT_EVENT *tData; - tData = ( CLIENT_EVENT *) Evt->m_pEvtData; - // Basic Camera Reaction - Start Record - - break; - default: - break; +void basicCamera::dispatchEvent(EVENT_CONTAINER *Evt ){ + switch (Evt->m_eClass) { + case EVT_CLASS_SENSOR_LGS: + case EVT_CLASS_SENSOR_LFS: + case EVT_CLASS_SENSOR_MND: + case EVT_CLASS_SENSOR_PLS_210: + case EVT_CLASS_SENSOR_PLS_360: + case EVT_CLASS_SENSOR_ALS: + case EVT_CLASS_SENSOR_3D: { + switch (Evt->m_eType) { + case EVT_TARGET_1D: + case EVT_TARGET_2D_WHITE: + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_3D_WHITE: + case EVT_TARGET_3D_BLACK: + case EVT_ALARM: + CLIENT_EVENT* tData; + tData = (CLIENT_EVENT*)Evt->m_pEvtData; + // Basic Camera Reaction - Start Record + + break; + default: + break; + }; + break; }; - } else - if (Evt->m_eClass == EVT_CLASS_VIDEO){ - switch (Evt->m_eType){ - case EVT_COMMAND: - basicCameraCommand *pData; - pData = (basicCameraCommand *)Evt->m_pEvtData; - // Basic Camera Commands - switch( pData->m_cCode ){ + case EVT_CLASS_VIDEO: { + switch (Evt->m_eType) { + case EVT_COMMAND: + basicCameraCommand* pData; + pData = (basicCameraCommand*)Evt->m_pEvtData; + // Basic Camera Commands + switch (pData->m_cCode) { case CMD_CAMERA_START_RECORD: m_pVideoNode->startRecord(); break; @@ -345,10 +353,12 @@ void basicCamera::dispatchEvent( basicEvent *Evt ){ break; default: break; - }; - break; - default: - break; + }; + break; + default: + break; + }; + break; }; }; }; diff --git a/lib/components/base/basicCamera.h b/lib/components/base/basicCamera.h index a5ebea2b..a84adf10 100644 --- a/lib/components/base/basicCamera.h +++ b/lib/components/base/basicCamera.h @@ -112,7 +112,7 @@ public: explicit basicCamera(config_setting_t *Settings = NULL); // Destructor virtual ~basicCamera(); - virtual void dispatchEvent( basicEvent *Evt ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt ); osdLabel *getLabel(uint8_t id){ if (id < m_vOSD.size()) return &(m_vOSD.at(id)); return NULL; }; uint8_t getLabelCount(void){ return ( uint8_t ) m_vOSD.size(); }; processStatus getProcessStatus( void ){ return m_iStatus; }; diff --git a/lib/components/base/basicCameraPTZ.cpp b/lib/components/base/basicCameraPTZ.cpp index 33564139..f151015d 100644 --- a/lib/components/base/basicCameraPTZ.cpp +++ b/lib/components/base/basicCameraPTZ.cpp @@ -147,7 +147,7 @@ bool basicCameraPTZ::create(SOURCE_INFO *SI){ return true; }; -void basicCameraPTZ::dispatchEvent( basicEvent *Evt ){ +void basicCameraPTZ::dispatchEvent( EVENT_CONTAINER *Evt ){ basicCamera::dispatchEvent( Evt ); }; diff --git a/lib/components/base/basicCameraPTZ.h b/lib/components/base/basicCameraPTZ.h index 1c3a463c..5ea7cffe 100644 --- a/lib/components/base/basicCameraPTZ.h +++ b/lib/components/base/basicCameraPTZ.h @@ -78,7 +78,7 @@ // Destructor virtual ~basicCameraPTZ(); - virtual void dispatchEvent( basicEvent *Evt ); + virtual void dispatchEvent( EVENT_CONTAINER *Evt ); virtual void cmdBeginPanLeft(float Speed = 0.f){}; virtual void cmdBeginPanRight(float Speed = 0.f){}; virtual void cmdEndManualPan( void ){}; diff --git a/lib/components/base/basicDualThread.cpp b/lib/components/base/basicDualThread.cpp index 8324f247..9c1ffe75 100644 --- a/lib/components/base/basicDualThread.cpp +++ b/lib/components/base/basicDualThread.cpp @@ -6,7 +6,9 @@ #define SLOG_ERROR( X ) m_pLog->Log( "basicDualThreadS", mThis, _LOG_ERROR, X ) bool basicDualThread::init( void ){ - //LOG("Init Object"); +#ifdef DEBUG + LOG("Init Dual Thread"); +#endif if (m_bThreadAStatus == TH_PRE_INIT) { m_bThreadAStatus = TH_ARMED; #if defined( __linux__ ) || defined(WIN_PTHREAD) diff --git a/lib/components/base/basicFunctionality.cpp b/lib/components/base/basicFunctionality.cpp index 944b11f1..64ceb8e2 100644 --- a/lib/components/base/basicFunctionality.cpp +++ b/lib/components/base/basicFunctionality.cpp @@ -1,7 +1,7 @@ #include "basicFunctionality.h" #include "../../alg/generic/md5.h" -#include +//#include #ifdef DEBUG #include "basicLogCollection.h" @@ -35,6 +35,7 @@ }; #endif +#ifdef __linux__ int fileCopy( const char* source, const char* destination ){ int input, output; if ((input = open(source, O_RDONLY)) == -1) return -1; @@ -57,6 +58,7 @@ int fileCopy( const char* source, const char* destination ){ close(output); return result; }; +#endif bool fileExist(const char *strFilename) { struct stat stFileInfo; @@ -277,6 +279,10 @@ CSTR trim( CSTR val ){ return val; }; +// orig - input String to Search In +// rep - token to search +// with - replacement for token +// in case with is NULL - cutting off the token // You must free the result if result is non-NULL. CSTR strReplace( CSTR orig, CSTR rep, CSTR with ){ char *result; // the return string @@ -288,13 +294,12 @@ CSTR strReplace( CSTR orig, CSTR rep, CSTR with ){ int count; // number of replacements // sanity checks and initialization - if (!orig || !rep) - return NULL; + if (!orig || !rep) return NULL; + len_rep = strlen(rep); - if (len_rep == 0) - return NULL; // empty rep causes infinite loop during count - if (!with) - with = ""; + + if (len_rep == 0) return NULL; // empty rep causes infinite loop during count + if (!with) with =(CSTR)""; // In case With not suplied - just cut off Token len_with = strlen(with); // count the number of replacements needed diff --git a/lib/components/base/basicFunctionality.h b/lib/components/base/basicFunctionality.h index 04155e7c..da164d90 100644 --- a/lib/components/base/basicFunctionality.h +++ b/lib/components/base/basicFunctionality.h @@ -6,15 +6,17 @@ #include #include #include -#include + #if defined(__APPLE__) || defined(__FreeBSD__) #include #else - #include + #ifdef __linux__ + #include + #endif #endif -#include "basicTypes.h" #ifdef __linux__ + #include #include #include #include @@ -36,7 +38,7 @@ #include #include #endif - +#include "basicTypes.h" int fileCopy( const char* source, const char* destination ); bool fileExist( const char *strFilename ); diff --git a/lib/components/base/basicLogCollection.cpp b/lib/components/base/basicLogCollection.cpp index 423fc037..6f3c2ea3 100644 --- a/lib/components/base/basicLogCollection.cpp +++ b/lib/components/base/basicLogCollection.cpp @@ -1,5 +1,9 @@ #include "basicLogCollection.h" +#ifdef MEM_DEBUG_LOG + #include "../../alg/generic/heapDebug.h" +#endif + basicLogCollection* basicLogCollection::_instance = 0; /** @@ -45,13 +49,28 @@ void basicLogCollection::Log( const char *Mod, void *ptr, const char *Msg ){ }; void basicLogCollection::Log( const char *Mod, void *ptr, _LOG_LEVEL Level, CSTR Msg ){ + +#ifdef MEM_DEBUG_LOG + size_t memStat; + char MEM_MSG[256]; + memStat = getCurrentRSS(); + sprintf( MEM_MSG, "MemStat: %d\n", memStat ); + broadcast( MEM_MSG ); +#endif + if( Level <= m_bMaxLevel ){ - char temp[CLOG]; - if( strlen( Msg ) < ( CLOG - 120 ) ) { + char temp[MAX_LOG_MSG_SIZE]; + if( strlen( Msg ) < ( MAX_LOG_MSG_SIZE - 120 ) ) { time_t LocalTime; - tm *gmt_time; time( &LocalTime ); +#ifndef __linux__ + tm* gmt_time = NULL; gmt_time = gmtime( &LocalTime ); +#else + tm gmtt; + tm* gmt_time = &gmtt; + if( gmtime_r( &LocalTime, &gmtt ) == NULL ) return; +#endif switch( m_bLogSettings ) { case _LOG_SIMPLE: sprintf( temp, "%s: %s\n", Mod, Msg ); break; case _LOG_TIME:{ @@ -74,10 +93,12 @@ void basicLogCollection::Log( const char *Mod, void *ptr, _LOG_LEVEL Level, CSTR break; }; }; + broadcast( (CSTR) temp ); } else { - sprintf( temp, "Log Message Too Long Buffer is Overflowed" ); + sprintf( temp, "Log Message Too Long Buffer is Overflowed Splitting!" ); + broadcast( (CSTR) temp ); }; - broadcast( (CSTR) temp ); + }; }; diff --git a/lib/components/base/basicLogCollection.h b/lib/components/base/basicLogCollection.h index 15cc5a2f..d3c329a9 100644 --- a/lib/components/base/basicLogCollection.h +++ b/lib/components/base/basicLogCollection.h @@ -1,6 +1,8 @@ #ifndef __BASICLOGCOLLECTION_H_INCL__ #define __BASICLOGCOLLECTION_H_INCL__ +#include + #include "basicLoggingService.h" #include "basicMutex.h" diff --git a/lib/components/base/basicLogCollection_.cpp b/lib/components/base/basicLogCollection_.cpp new file mode 100644 index 00000000..4fd7ca07 --- /dev/null +++ b/lib/components/base/basicLogCollection_.cpp @@ -0,0 +1,106 @@ +#include "basicLogCollection.h" + +#ifdef MEM_DEBUG_LOG + #include "../../alg/generic/heapDebug.h" +#endif + +basicLogCollection * basicLogCollection::_instance = NULL; +CSTR basicLogCollection::m_pBroadcastBuffer = NULL; +/** + * Returns the single instance of the object. + */ +basicLogCollection* basicLogCollection::getInstance( _LOG_SETTINGS val ) { + // check if the instance has been created yet + if( NULL == _instance ){ + // if not, then create it + _instance = new basicLogCollection( val ); + }; + // return the single instance + return _instance; +}; + +void basicLogCollection::addHandler( basicLoggingService *handler ){ + if( m_pRing != NULL ){ + m_mLogMutex.lock(); + m_pRing->add( handler ); + m_mLogMutex.unlock(); + } +}; + +void basicLogCollection::broadcast( CSTR Msg ){ + basicLoggingService *mService = NULL; + LoggersIterator *mpIterator = NULL; + m_mLogMutex.lock(); + mpIterator = m_pRing->begin(); + while( mpIterator != NULL ){ + mService = m_pRing->getAtCursor( mpIterator ); + mService->logMessage( Msg ); + mpIterator = mpIterator->next; + }; + m_mLogMutex.unlock(); +}; + +void basicLogCollection::setLogLevel( _LOG_LEVEL level ){ + m_bMaxLevel = level; +}; + +void basicLogCollection::Log( const char *Mod, void *ptr, CSTR Msg ){ + Log( Mod, ptr, m_bMaxLevel, Msg ); +}; + +void basicLogCollection::Log( const char *Mod, void *ptr, const char *Msg ){ + Log( Mod, ptr, m_bMaxLevel, Msg ); +}; + +void basicLogCollection::Log( const char *Mod, void *ptr, _LOG_LEVEL Level, CSTR Msg ){ + +#ifdef MEM_DEBUG_LOG + size_t memStat = getCurrentRSS(); + sprintf( m_pBroadcastBuffer, "MemStat: %d\n", memStat ); + broadcast( m_pBroadcastBuffer ); +#endif + + if( Level <= m_bMaxLevel ){ + if( strlen( Msg ) < ( MAX_LOG_MSG_SIZE - 120 ) ) { + time_t LocalTime; + time( &LocalTime ); +#ifndef __linux__ + tm* gmt_time = NULL; + gmt_time = gmtime( &LocalTime ); +#else + tm gmtt; + tm* gmt_time = &gmtt; + if( gmtime_r( &LocalTime, &gmtt ) == NULL ) return; +#endif + switch( m_bLogSettings ) { + case _LOG_SIMPLE: sprintf( m_pBroadcastBuffer, "%s: %s\n", Mod, Msg ); break; + case _LOG_TIME:{ + sprintf( m_pBroadcastBuffer, "%04d-%02d-%02d %02d:%02d:%02d %s: %s\n", 1900+gmt_time->tm_year, 1+gmt_time->tm_mon, gmt_time->tm_mday, gmt_time->tm_hour, gmt_time->tm_min, gmt_time->tm_sec, Mod, Msg ); + break; + }; + case _LOG_PTR: sprintf( m_pBroadcastBuffer, "%p %s: %s\n", ptr, Mod, Msg ); break; + case _LOG_TIME_PTR: { + sprintf( m_pBroadcastBuffer, "%04d-%02d-%02d %02d:%02d:%02d %p %s: %s\n", 1900+gmt_time->tm_year, 1+gmt_time->tm_mon, gmt_time->tm_mday, gmt_time->tm_hour, gmt_time->tm_min, gmt_time->tm_sec, ptr, Mod, Msg ); + break; + }; + case _LOG_LVL: sprintf( m_pBroadcastBuffer, "%02X %s: %s\n", Level, Mod, Msg ); break; + case _LOG_LVL_TIME:{ + sprintf( m_pBroadcastBuffer, "%02X %04d-%02d-%02d %02d:%02d:%02d %s: %s\n", Level, 1900+gmt_time->tm_year, 1+gmt_time->tm_mon, gmt_time->tm_mday, gmt_time->tm_hour, gmt_time->tm_min, gmt_time->tm_sec, Mod, Msg ); + break; + }; + case _LOG_LVL_PTR: sprintf( m_pBroadcastBuffer, "%02X %p %s: %s\n", Level, ptr, Mod, Msg ); break; + case _LOG_LVL_TIME_PTR:{ + sprintf( m_pBroadcastBuffer, "%02X %04d-%02d-%02d %02d:%02d:%02d %p %s: %s\n", Level, 1900+gmt_time->tm_year, 1+gmt_time->tm_mon, gmt_time->tm_mday, gmt_time->tm_hour, gmt_time->tm_min, gmt_time->tm_sec, ptr, Mod, Msg ); + break; + }; + }; + } else { + sprintf( m_pBroadcastBuffer, "Log Message Too Long Buffer is Overflowed Splitting!\n" ); + }; + broadcast( (CSTR) m_pBroadcastBuffer ); + }; +}; + +void basicLogCollection::Log( const char *Mod, void *ptr, _LOG_LEVEL Level, const char *Msg ){ + Log( Mod, ptr, Level,(CSTR) Msg ); +}; diff --git a/lib/components/base/basicLogCollection_.h b/lib/components/base/basicLogCollection_.h new file mode 100644 index 00000000..f8880941 --- /dev/null +++ b/lib/components/base/basicLogCollection_.h @@ -0,0 +1,123 @@ +#ifndef __BASICLOGCOLLECTION_H_INCL__ +#define __BASICLOGCOLLECTION_H_INCL__ + +#include + +#include "basicLoggingService.h" +#include "basicMutex.h" + +typedef enum EE_LOG_LEVEL{ + _LOG_NONE = 0, + _LOG_CRITICAL = 1, + _LOG_ERROR, + _LOG_DEBUG, + _LOG_VERBOSE, + _LOG_ALL +} _LOG_LEVEL; + +typedef enum EE_LOG_SETTINGS{ + _LOG_SIMPLE = 0, + _LOG_TIME = 1, + _LOG_PTR = 2, + _LOG_TIME_PTR = 3, + _LOG_LVL = 4, + _LOG_LVL_TIME = 5, + _LOG_LVL_PTR = 6, + _LOG_LVL_TIME_PTR = 7 +} _LOG_SETTINGS; + +#define _DEFAULT_LOG_LEVEL_ _LOG_DEBUG +#define _WORKING_LOG_LEVEL_ _LOG_ALL +#define _DEFAULT_LOG_SETTINGS _LOG_TIME_PTR + +/** + * @Description Singleton class to handle logging + * + * @author Gagua + */ +class basicLogCollection { + private: + basicMutex m_mLogMutex; + LoggersRing *m_pRing; + _LOG_LEVEL m_bMaxLevel; + _LOG_SETTINGS m_bLogSettings; + static CSTR m_pBroadcastBuffer; + void broadcast( CSTR Msg ); + public: + // Method to fetch singleton instance. + static basicLogCollection* getInstance( _LOG_SETTINGS val = _DEFAULT_LOG_SETTINGS ); + // Destructor + virtual ~basicLogCollection(); + + void addHandler( basicLoggingService *handler ); + + void setLogLevel( _LOG_LEVEL level ); + + void Log( const char *Mod, void *ptr, CSTR Msg ); + void Log( const char *Mod, void *ptr, const char *Msg ); + void Log( const char *Mod, void *ptr, _LOG_LEVEL Level, CSTR Msg ); + void Log( const char *Mod, void *ptr, _LOG_LEVEL Level, const char *Msg ); + protected: + // Constructor - protected so users cannot call it. + explicit basicLogCollection( _LOG_SETTINGS val ); + + private: + // private static member referencing the single instance of the object + // TODO: Replace basicLogCollection with the type of object you want to + // return the single instance of + static basicLogCollection* _instance; + + // Copy constructor + // Declared but not defined to prevent auto-generated + // copy constructor. Refer to "Effective C++" by Meyers + basicLogCollection(const basicLogCollection& src); + + // Assignment operator + // Declared but not defined to prevent auto-generated + // assignment operator. Refer to "Effective C++" by Meyers + basicLogCollection& operator=(const basicLogCollection& src); + +}; + +// Constructor implementation +inline basicLogCollection::basicLogCollection( _LOG_SETTINGS val ):m_mLogMutex(){ + m_pBroadcastBuffer = (CSTR) malloc( MAX_LOG_MSG_SIZE ); + if( m_pBroadcastBuffer!= NULL ) { + m_pRing = new LoggersRing();//4); // Maximum 4 Logginig Engines; + if( m_pRing != NULL ) { + m_bLogSettings = val; + memset( m_pBroadcastBuffer, 0, MAX_LOG_MSG_SIZE ); + m_bMaxLevel = _DEFAULT_LOG_LEVEL_; + } else { + printf( "Error Creating MemRing for LogCollection!"); + }; + } else { + m_pRing = NULL; + }; +}; + +// Destructor implementation +inline basicLogCollection::~basicLogCollection(){ + if( m_pRing != NULL ) delete m_pRing; + if( m_pBroadcastBuffer != NULL ) free(m_pBroadcastBuffer ); +}; + +// TODO: Uncomment the copy constructor when you need it. +//inline basicLogCollection::basicLogCollection(const basicLogCollection& src) +//{ +// // TODO: copy +//} + +// TODO: Uncomment the assignment operator when you need it. +//inline basicLogCollection& basicLogCollection::operator=(const basicLogCollection& rhs) +//{ +// if (this == &rhs) { +// return *this; +// } +// +// // TODO: assignment +// +// return *this; +//} + +#endif // __BASICLOGCOLLECTION_H_INCL__ diff --git a/lib/components/base/basicLoggingService.h b/lib/components/base/basicLoggingService.h index d4356c92..af31f966 100644 --- a/lib/components/base/basicLoggingService.h +++ b/lib/components/base/basicLoggingService.h @@ -3,6 +3,9 @@ #include "basicRing.h" + +#define MAX_LOG_MSG_SIZE 4096 + /** * TODO: Add class description * diff --git a/lib/components/base/basicThread.cpp b/lib/components/base/basicThread.cpp index bc28a3bd..1ac00d43 100644 --- a/lib/components/base/basicThread.cpp +++ b/lib/components/base/basicThread.cpp @@ -7,6 +7,9 @@ #define SLOG_ERROR( X ) mThis->m_pLog->Log( "BasicThreadS", mThis, _LOG_ERROR, X ) bool basicThread::init( void ){ +#ifdef DEBUG + LOG("Init Single Thread"); +#endif if (m_bThreadStatus == TH_PRE_INIT) { m_bThreadStatus = TH_ARMED; #if defined( __linux__ ) || defined(WIN_PTHREAD) @@ -47,9 +50,7 @@ void basicThread::m_fThreadProc( void ){ basicThread *mThis; mThis = ( basicThread * ) ptr; if( mThis->m_bThreadStatus == TH_ARMED ) { - SLOG("Proc Start!"); mThis->m_fThreadProc(); - SLOG("Proc Exited!"); } else { SLOG_ERROR("Thread is not ARMED!"); }; @@ -63,19 +64,15 @@ void basicThread::m_fThreadProc( void ){ }; void basicThread::waitThreadEnd(bool forced){ - LOG("ENDING"); if( m_bThreadStatus > TH_WORKING || m_bThreadStatus < TH_ARMED ) return; - LOG("WAITING"); if( forced ) m_bThreadStatus = TH_ENDED; while (m_bThreadStatus != TH_EXIT) SLEEP(1);//DEFAULT_THREAD_SLEEP_TIME); - LOG("DONE -> RIPING"); #if defined( __linux__ ) || defined(WIN_PTHREAD) pthread_join(m_sThreadHandler, NULL); #else WaitForSingleObject(m_hThreadHandle, 2000); CloseHandle(m_hThreadHandle); #endif - LOG("FINISH"); }; bool basicThread::uninit( void ){ if( m_bThreadStatus == TH_PRE_INIT ) return true; diff --git a/lib/components/base/basicVideoAnalyzer.h b/lib/components/base/basicVideoAnalyzer.h index 037f9fd5..b610c028 100644 --- a/lib/components/base/basicVideoAnalyzer.h +++ b/lib/components/base/basicVideoAnalyzer.h @@ -75,7 +75,7 @@ class basicVideoAnalyzer : public basicThread, public basicMediaDestination, pub Mat m_oWorkingMat; virtual bool m_fImageAnalyzer( Mat &Picture ){ return false;}; - virtual basicEvent *createVAEvent(bool Status){ return NULL; }; + virtual EVENT_CONTAINER * createVAEvent(bool Status){ return NULL; }; public: basicVideoAnalyzer(); ~basicVideoAnalyzer(); diff --git a/lib/components/object/objectConsoleLoggingService.cpp b/lib/components/object/objectConsoleLoggingService.cpp index 0875bbb5..bf060c76 100644 --- a/lib/components/object/objectConsoleLoggingService.cpp +++ b/lib/components/object/objectConsoleLoggingService.cpp @@ -10,10 +10,6 @@ void objectConsoleLoggingService::logMessage( CSTR Msg ){ void objectConsoleLoggingService::logMessage( const char *Msg ){ if ( m_bLogging ){ - time_t LocalTime; - tm *gmt_time; - time( &LocalTime ); - gmt_time = gmtime( &LocalTime ); - printf( "%04d-%02d-%02d %02d:%02d:%02d %s\n", 1900+gmt_time->tm_year, 1+gmt_time->tm_mon, gmt_time->tm_mday, gmt_time->tm_hour, gmt_time->tm_min, gmt_time->tm_sec, Msg ); + printf( Msg ); }; }; diff --git a/lib/components/object/objectFileLoggingService.cpp b/lib/components/object/objectFileLoggingService.cpp index 487e7fb7..d40631e4 100644 --- a/lib/components/object/objectFileLoggingService.cpp +++ b/lib/components/object/objectFileLoggingService.cpp @@ -21,7 +21,7 @@ void objectFileLoggingService::logMessage( const char *Msg ){ FILE *FD; FD = fopen( m_pFileName , "a+"); if( FD != NULL ) { - fwrite( Msg, strlen(Msg), 1, FD ); + fwrite( Msg, 1, strlen(Msg), FD ); fclose(FD); } else { printf( "Totally Lost\n" ); diff --git a/lib/data/curl/curlRequest.cpp b/lib/data/curl/curlRequest.cpp index 6256cd46..6c59f4fc 100644 --- a/lib/data/curl/curlRequest.cpp +++ b/lib/data/curl/curlRequest.cpp @@ -3,101 +3,191 @@ #define LOG( X ) m_pLog->Log( "curlRequest", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "curlRequest", this, _LOG_ERROR, X ) //Thread Logging -#define SLOG( X ) mThis->m_pLog->Log( "curlRequestsManagerS", mThis, X ) -#define SLOG_ERROR( X ) mThis->m_pLog->Log( "curlRequestsManagerS", mThis, _LOG_ERROR, X ) +#define SLOG( X ) basicLogCollection::getInstance()->Log( "curlRequest_T", NULL, X ) +#define SLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "curlRequest_T", NULL, _LOG_ERROR, X ) curlRequest::curlRequest(CSTR URL, CSTR cntType ){ m_pLog = basicLogCollection::getInstance(); + m_pCURL = NULL; m_pBaseObject = NULL; m_pBaseParam = NULL; m_pPostData = NULL; m_pSignalFunc = NULL; m_pMemoryBuffer = NULL; + m_HeaderList = NULL; m_nMemorySize = 0; + m_bRequestComplete = false; m_pURL = (CSTR)malloc(strlen(URL)+1); - sprintf(m_pURL, "%s", URL); - m_pHost = NULL; - m_pPath = NULL; - //LOG(m_pURL); - m_bRequestComplete = false; - m_pCURL = curl_easy_init(); - if( m_pCURL != NULL){ - struct curl_slist *sList = NULL; - if( cntType != NULL ) { - sprintf( m_cContentType, "Content-Type: %s", cntType ); - sList = curl_slist_append( sList, m_cContentType ); - }; - sList = curl_slist_append( sList, "Connection: Keep-Alive" ); - if( sList != NULL ) { - curl_easy_setopt(m_pCURL, CURLOPT_HTTPHEADER, sList ); - }; - curl_easy_setopt(m_pCURL, CURLOPT_NOSIGNAL, 1); - curl_easy_setopt(m_pCURL, CURLOPT_URL, m_pURL); - curl_easy_setopt(m_pCURL, CURLOPT_WRITEFUNCTION, m_fWriteMemoryHandler); - curl_easy_setopt(m_pCURL, CURLOPT_WRITEDATA, this); - curl_easy_setopt(m_pCURL, CURLOPT_USERAGENT, "Mozilla/5.0 (PC; U; Intel; Linux; en) AppleWebKit/420+ (KHTML, like Gecko)"); - }; + if( cntType != NULL ) sprintf( m_cContentType, "Content-Type: %s", cntType ); + if( m_pURL ) { + sprintf( m_pURL, "%s", URL ); +#ifdef DEBUG_EXTRA + LOG(m_pURL); +#endif + init_CURL(); + }; }; curlRequest::curlRequest(CSTR Host, CSTR Path, CSTR cntType ){ m_pLog = basicLogCollection::getInstance(); + m_pCURL = NULL; m_pBaseObject = NULL; m_pBaseParam = NULL; m_pSignalFunc = NULL; m_pMemoryBuffer = NULL; + m_HeaderList = NULL; m_nMemorySize = 0; + m_bRequestComplete = false; + if( cntType != NULL ) sprintf( m_cContentType, "Content-Type: %s", cntType ); m_pURL = (CSTR)malloc(strlen(Host) + 1 + strlen(Path)); - sprintf(m_pURL, "%s%s", Host, Path ); - m_pHost = (CSTR)malloc(strlen(Host)+1); - sprintf(m_pHost, "%s", Host); - m_pPath = (CSTR)malloc(strlen(Path)+1); - sprintf(m_pPath, "%s", Path); - //LOG(m_pURL); - m_bRequestComplete = false; - m_pCURL = curl_easy_init(); - if (m_pCURL != NULL){ - struct curl_slist *sList = NULL; - if( cntType != NULL ) { - sprintf( m_cContentType, "Content-Type: %s", cntType ); - sList = curl_slist_append( sList, m_cContentType ); - }; - sList = curl_slist_append( sList, "Connection: Keep-Alive" ); - if( sList != NULL ) { - curl_easy_setopt(m_pCURL, CURLOPT_HTTPHEADER, sList ); - }; - curl_easy_setopt(m_pCURL, CURLOPT_NOSIGNAL, 1); - curl_easy_setopt(m_pCURL, CURLOPT_URL, m_pURL); - curl_easy_setopt(m_pCURL, CURLOPT_WRITEFUNCTION, m_fWriteMemoryHandler); - curl_easy_setopt(m_pCURL, CURLOPT_WRITEDATA, this); - curl_easy_setopt(m_pCURL, CURLOPT_USERAGENT, "Mozilla/5.0 (PC; U; Intel; Linux; en) AppleWebKit/420+ (KHTML, like Gecko)"); - }; -} - -void curlRequest::setPOST( CSTR postDATA, int size ){ - if (m_pCURL != NULL){ - if( size > 0 ){ - m_pPostData = (CSTR) malloc( size+1 ); - if( m_pPostData == NULL ) return; - memcpy( m_pPostData, postDATA, size ); - m_pPostData[size] = (char)0; - } else { - m_pPostData = (CSTR) malloc(strlen(postDATA)+1); - if( m_pPostData == NULL ) return; - sprintf( m_pPostData, "%s", postDATA ); - }; - curl_easy_setopt(m_pCURL, CURLOPT_POSTFIELDS, m_pPostData ); - }; -}; + if( m_pURL ) { + sprintf( m_pURL, "%s%s", Host, Path ); +#ifdef DEBUG_EXTRA + LOG(m_pURL); +#endif + init_CURL(); + }; +}; curlRequest::~curlRequest(){ - //LOG("Destructor"); - curl_easy_cleanup(m_pCURL); - if( m_pPostData ) free(m_pPostData ); - if (m_pMemoryBuffer) free(m_pMemoryBuffer); +#ifdef DEBUG + +#endif + curl_easy_cleanup(m_pCURL); + if( m_pURL ) free(m_pURL); + if( m_pPostData ) free(m_pPostData); + if( m_pMemoryBuffer ) free(m_pMemoryBuffer); +}; + +#ifdef DEBUG +int curlRequest::debug_callback( CURL *handle, curl_infotype type, char *data, size_t size, void *userptr ){ + FILE *tdFD = fopen("CURL_DEBUG.TXT","ab+"); + if( tdFD ) { + switch( type ) { + case CURLINFO_TEXT: + fprintf( tdFD, "== Info: %s\n", data ); + break; + case CURLINFO_HEADER_IN: + fprintf( tdFD, "<= Recpt header\n"); + fwrite( data, 1, size, tdFD ); + fprintf( tdFD, "\n" ); + break; + case CURLINFO_HEADER_OUT: + fprintf( tdFD, "=> Send header\n"); + fwrite( data, 1, size, tdFD ); + fprintf( tdFD, "\n" ); + break; + case CURLINFO_DATA_IN: + fprintf( tdFD, "<= Recpt Data\n" ); + fwrite( data, 1, size, tdFD ); + fprintf( tdFD, "\n" ); + break; + case CURLINFO_DATA_OUT: + fprintf( tdFD, "=> Send Data\n"); + fwrite( data, 1, size, tdFD ); + fprintf( tdFD, "\n" ); + break; + case CURLINFO_SSL_DATA_IN: + fprintf( tdFD, "<= Recpt SSL Data\n" ); + fwrite( data, 1, size, tdFD ); + fprintf( tdFD, "\n" ); + break; + case CURLINFO_SSL_DATA_OUT: + fprintf( tdFD, "=> Send SSL Data\n"); + fwrite( data, 1, size, tdFD ); + fprintf( tdFD, "\n" ); + break; + case CURLINFO_END: + fprintf( tdFD, "End\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n" ); + break; + default: + fprintf( tdFD, "~~~~~~~~~ UNKNOWN ~~~~~~~~~~~~\n%s\n", data ); + }; + fclose( tdFD ); + }; + return 0; +}; +#endif + +void curlRequest::init_CURL(){ + m_pCURL = curl_easy_init(); + if( m_pCURL != NULL ){ + m_HeaderList = curl_slist_append( m_HeaderList, m_cContentType ); + //m_HeaderList = curl_slist_append( m_HeaderList, "Connection: Keep-Alive" ); + //m_HeaderList = curl_slist_append( m_HeaderList, "Connection: Close" ); + + curl_easy_setopt( m_pCURL, CURLOPT_HTTPHEADER, m_HeaderList ); + + curl_easy_setopt( m_pCURL, CURLOPT_CONNECTTIMEOUT, 20 ); + curl_easy_setopt( m_pCURL, CURLOPT_TIMEOUT, 20 ); + curl_easy_setopt( m_pCURL, CURLOPT_SSL_VERIFYPEER, 0 ); + curl_easy_setopt( m_pCURL, CURLOPT_SSL_VERIFYHOST, 0 ); +#ifdef DEBUG + curl_easy_setopt( m_pCURL, CURLOPT_VERBOSE, 1 ); + curl_easy_setopt( m_pCURL, CURLOPT_DEBUGFUNCTION, debug_callback ); + curl_easy_setopt( m_pCURL, CURLOPT_DEBUGDATA, this ); +#else + curl_easy_setopt( m_pCURL, CURLOPT_VERBOSE, 0 ); +#endif +#ifdef __linux__ + curl_easy_setopt( m_pCURL, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, 0 ); +#endif + curl_easy_setopt( m_pCURL, CURLOPT_NOPROGRESS, 1 ); + curl_easy_setopt( m_pCURL, CURLOPT_TCP_FASTOPEN, 1 ); + curl_easy_setopt( m_pCURL, CURLOPT_TCP_NODELAY, 1 ); + curl_easy_setopt( m_pCURL, CURLOPT_NOSIGNAL, 1 ); + curl_easy_setopt( m_pCURL, CURLOPT_URL, m_pURL ); + curl_easy_setopt( m_pCURL, CURLOPT_WRITEFUNCTION, m_fWriteMemoryHandler ); + curl_easy_setopt( m_pCURL, CURLOPT_WRITEDATA, this ); + curl_easy_setopt( m_pCURL, CURLOPT_USERAGENT, "Mozilla/5.0 (PC; U; Intel; Linux; en) AppleWebKit/420+ (KHTML, like Gecko)" ); + }; }; +void curlRequest::setCredentials( CSTR user, CSTR password, bool use_digest ){ + if( !strlen(user) || !strlen(password) ) return; + sprintf(m_cUserPassword, "%s:%s", user, password ); + curl_easy_setopt( m_pCURL, CURLOPT_USERPWD, m_cUserPassword ); + if( use_digest ) { + curl_easy_setopt( m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST ); + } else { + curl_easy_setopt( m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); + }; +}; + +static char *EmptyExpectConstant = (CSTR)"Expect:"; +static char *EmptyAcceptConstant = (CSTR)"Accept: */*"; +static char *AcceptEncoding = (CSTR)"Accept-Encoding: gzip, deflate"; +void curlRequest::setPOST( CSTR postDATA, int size ){ + if( m_pCURL != NULL ){ + if( !postDATA ){ +#ifdef DEBUG + LOG_ERROR("No Post Data Supplied In Post Request!"); +#endif + return; + }; + if( !size ) size = strlen( postDATA ); + m_pPostData = (CSTR) malloc( size+1 ); + if( !m_pPostData ){ + LOG_ERROR("Memory Allocation Error!"); + return; + }; + memcpy( m_pPostData, postDATA, size ); + m_pPostData[size] = (char)0; + sprintf( m_cContentLength, "Content-Length: %d", size ); + m_HeaderList = curl_slist_append( m_HeaderList, EmptyExpectConstant ); + m_HeaderList = curl_slist_append( m_HeaderList, EmptyAcceptConstant ); + //m_HeaderList = curl_slist_append( m_HeaderList, AcceptEncoding ); + m_HeaderList = curl_slist_append( m_HeaderList, m_cContentLength ); + curl_easy_setopt( m_pCURL, CURLOPT_HTTPHEADER, m_HeaderList ); + curl_easy_setopt( m_pCURL, CURLOPT_POST, 1 ); + curl_easy_setopt( m_pCURL, CURLOPT_POSTFIELDS, m_pPostData ); + } else LOG_ERROR("Wrong CURL handle!"); +}; + void curlRequest::setHandler(void *baseObject, void *(*start_routine) (void *, void*), void* ptr ){ - //LOG("Set Handler"); +#ifdef DEBUG_EXTRA + LOG("Set Handler"); +#endif m_pBaseObject = baseObject; m_pSignalFunc = start_routine; m_pBaseParam = ptr; @@ -110,23 +200,29 @@ BYTE *curlRequest::getBuffer(void){ size_t curlRequest::m_fWriteMemoryHandler(void *ptr, size_t nsize, size_t nmemb, void *data){ size_t realsize = nsize * nmemb; curlRequest *me = (curlRequest *)data; - me->m_pMemoryBuffer = (BYTE *)realloc(me->m_pMemoryBuffer, me->m_nMemorySize + realsize + 1); // +1 to transfer String terminator - if (me->m_pMemoryBuffer == NULL) { - /* out of memory! */ +#ifdef DEBUG_EXTRA + SLOG("*<-D"); +#endif + BYTE *tMB = (BYTE*)realloc(me->m_pMemoryBuffer, me->m_nMemorySize + realsize + 1); // +1 to transfer String terminator + if( tMB ){ + me->m_pMemoryBuffer = tMB; + } else { + //free(me->m_pMemoryBuffer); + //me->m_pMemoryBuffer = NULL; + //Well be Fried at destruction; + SLOG_ERROR("Out Of Memory!"); return -1; }; memcpy(&(me->m_pMemoryBuffer[me->m_nMemorySize]), ptr, realsize); me->m_nMemorySize += realsize; - me->m_pMemoryBuffer[me->m_nMemorySize] = 0; + me->m_pMemoryBuffer[me->m_nMemorySize] = 0; return realsize; }; void curlRequest::issue(void){ if( m_pCURL ){ - //LOG("Issued"); m_bRequestComplete = true; if ( m_pSignalFunc != NULL)(*m_pSignalFunc)(m_pBaseObject, m_pBaseParam); - //LOG("Issue Finished"); }; }; diff --git a/lib/data/curl/curlRequest.h b/lib/data/curl/curlRequest.h index 5a3da75b..e5c76b55 100644 --- a/lib/data/curl/curlRequest.h +++ b/lib/data/curl/curlRequest.h @@ -4,7 +4,9 @@ #pragma comment(lib, "wldap32.lib" ) #pragma comment(lib, "crypt32.lib" ) #pragma comment(lib, "Ws2_32.lib") -#define CURL_STATICLIB +#ifndef CURL_STATICLIB + #define CURL_STATICLIB +#endif #include #include "../../components/base/basicLogCollection.h" @@ -23,35 +25,38 @@ class curlRequest{ private: - CURL *m_pCURL; - //CURLcode m_eCURL; - CSTR m_pURL; - CSTR m_pHost; - CSTR m_pPath; - char m_cContentType[128]; - BYTE *m_pMemoryBuffer; - CSTR m_pPostData; - size_t m_nMemorySize; - bool m_bRequestComplete; - void *m_pBaseObject; - void *m_pBaseParam; - void *(*m_pSignalFunc) (void *, void*); - static size_t m_fWriteMemoryHandler(void *ptr, size_t nsize, size_t nmemb, void *data); + basicLogCollection * m_pLog; + CURL * m_pCURL; + CSTR m_pURL; + char m_cContentType[128]; + char m_cContentLength[128]; + BYTE * m_pMemoryBuffer; + CSTR m_pPostData; + struct curl_slist * m_HeaderList; + size_t m_nMemorySize; + bool m_bRequestComplete; + void * m_pBaseObject; + void * m_pBaseParam; + char m_cUserPassword[256]; + void init_CURL(); + void * (*m_pSignalFunc) (void *, void*); + static size_t m_fWriteMemoryHandler(void *ptr, size_t nsize, size_t nmemb, void *data); +#ifdef DEBUG + static int debug_callback(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr ); +#endif public: - basicLogCollection *m_pLog; - explicit curlRequest(CSTR URL, CSTR cntType ); - curlRequest(CSTR Host, CSTR Path, CSTR cntType ); - ~curlRequest(); - BYTE *getBuffer(void); - size_t getSize(void){ return m_nMemorySize; }; - CSTR getURL(void){ return m_pURL; }; - CSTR getHost(void){ return m_pHost; }; - CSTR getPath(void){ return m_pPath; }; - void setHandler(void *baseObject, void *(*start_routine) (void *, void*), void *ptr ); - void setPOST( CSTR postDATA , int size = 0 ); - void issue(void); - bool isFinished(void){ return m_bRequestComplete; }; - CURL *getEH(void){ return m_pCURL; }; + explicit curlRequest( CSTR URL, CSTR cntType ); + curlRequest( CSTR Host, CSTR Path, CSTR cntType ); + ~curlRequest(); + BYTE * getBuffer(void); + size_t getSize(void){ return m_nMemorySize; }; + CSTR getURL(void){ return m_pURL; }; + void setHandler(void *baseObject, void *(*start_routine) (void *, void*), void *ptr ); + void setCredentials( CSTR user, CSTR password, bool use_digest = true ); + void setPOST( CSTR postDATA , int size = 0 ); + void issue(void); + bool isFinished(void){ return m_bRequestComplete; }; + CURL * getEH(void){ return m_pCURL; }; }; typedef vector< curlRequest * > RequestPool; diff --git a/lib/data/curl/curlRequestsManager.cpp b/lib/data/curl/curlRequestsManager.cpp index 8defb38a..7100fbb5 100644 --- a/lib/data/curl/curlRequestsManager.cpp +++ b/lib/data/curl/curlRequestsManager.cpp @@ -1,16 +1,21 @@ #include "curlRequestsManager.h" -#define LOG( X ) m_pLog->Log( "curlRequestsManager", this, X ) -#define LOG_ERROR( X ) m_pLog->Log( "curlRequestsManager", this, _LOG_ERROR, X ) -//Thread Logging -#define SLOG( X ) mThis->m_pLog->Log( "curlRequestsManagerS", mThis, X ) -#define SLOG_ERROR( X ) mThis->m_pLog->Log( "curlRequestsManagerS", mThis, _LOG_ERROR, X ) - -#ifdef _WIN32 - #define SHORT_SLEEP Sleep(100) -#else - #define SHORT_SLEEP usleep(100000) -#endif +#define LOG( X ) m_pLog->Log( "CURL_RQM", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "CURL_RQM", this, _LOG_ERROR, X ) + +// Constructor implementation +curlRequestsManager::curlRequestsManager(){ + m_pLog = basicLogCollection::getInstance(); + curl_global_init(CURL_GLOBAL_ALL); + m_pCURLM = curl_multi_init(); + init(); +}; + + +curlRequestsManager::~curlRequestsManager(){ + waitThreadEnd( true ); + curl_multi_cleanup( m_pCURLM ); +}; curlRequestsManager* curlRequestsManager::_instance = 0; @@ -28,37 +33,29 @@ curlRequestsManager* curlRequestsManager::getInstance() { }; -#ifdef __linux__ -void *curlRequestsManager::m_fReaperEntryPoint(void *ptr){ -#else -DWORD WINAPI curlRequestsManager::m_fReaperEntryPoint( LPVOID ptr){ -#endif - curlRequestsManager *mThis; - CURLMsg *mMsg; /* for picking up messages with the transfer status */ - int nMsgsLeft; /* how many messages are left */ +void curlRequestsManager::m_fThreadProc( void ){ + CURLMsg *mMsg = NULL; /* for picking up messages with the transfer status */ + int nMsgsLeft = 0; /* how many messages are left */ struct timeval mTimeOut; - int RetVal; /* select() return code */ - CURLMcode mRetCode; /* curl_multi_fdset() return code */ + int RetVal; /* select() return code */ + CURLMcode mRetCode; /* curl_multi_fdset() return code */ fd_set mReadFD; fd_set mWriteFD; fd_set mExcepFD; int mMaxFD = -1; long mCURLTimeOut; - int mStillRunning; - - mThis = (curlRequestsManager *)ptr; - SLOG("Starting Finished Requests Reaper"); - mThis->m_bThreadStatus = TH_WORKING; - while (mThis->m_bThreadStatus < TH_ENDED ){ - + int mStillRunning; +#ifdef DEBUG + LOG("Starting Finished Requests Reaper"); +#endif + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ){ /* we start some action by calling perform right away */ - curl_multi_perform( mThis->m_pCURLM, &mStillRunning ); - + curl_multi_perform( m_pCURLM, &mStillRunning ); do{ + curl_multi_timeout( m_pCURLM, &mCURLTimeOut ); - curl_multi_timeout( mThis->m_pCURLM, &mCURLTimeOut ); - - if ( mCURLTimeOut < 0 ) mCURLTimeOut = 1000; + if( mCURLTimeOut < 0 ) mCURLTimeOut = 1000; mTimeOut.tv_sec = mCURLTimeOut / 1000; mTimeOut.tv_usec = (mCURLTimeOut % 1000) * 1000; @@ -68,121 +65,124 @@ DWORD WINAPI curlRequestsManager::m_fReaperEntryPoint( LPVOID ptr){ FD_ZERO(&mExcepFD); /* get file descriptors from the transfers */ - mRetCode = curl_multi_fdset(mThis->m_pCURLM, &mReadFD, &mWriteFD, &mExcepFD, &mMaxFD); + mRetCode = curl_multi_fdset( m_pCURLM, &mReadFD, &mWriteFD, &mExcepFD, &mMaxFD ); if( mMaxFD == -1 ){ - SHORT_SLEEP; + SLEEP( 10 ); RetVal = 0; } else { RetVal = select( mMaxFD + 1, &mReadFD, &mWriteFD, &mExcepFD, &mTimeOut ); }; - switch (RetVal) { + switch( RetVal ){ case -1: /* select error */ break; case 0: default: /* timeout or readable/writable sockets */ - curl_multi_perform( mThis->m_pCURLM, &mStillRunning ); + curl_multi_perform( m_pCURLM, &mStillRunning ); break; }; - - }while( mStillRunning ); /* if there are still transfers, loop! */ + /* See how the transfers went */ + while( ( mMsg = curl_multi_info_read( m_pCURLM, &nMsgsLeft ) ) && ( m_bThreadStatus < TH_ENDED ) ){ + if( mMsg->msg == CURLMSG_DONE ){ + CURLcode rC = mMsg->data.result; +#ifdef DEBUG + char tB[256]; + sprintf( tB, "Request Done with Code: %d", rC ); + LOG( tB ); +#endif + /* Find out which handle this message is about */ + m_mPoolProtector.lock(); + for (RequestPool::iterator index = m_vRequestPool.begin(); index < m_vRequestPool.end(); index++){ + if ((*index)->getEH() == mMsg->easy_handle){ + mRetCode = curl_multi_remove_handle( m_pCURLM, (*index)->getEH()); + if( rC == CURLE_OK ){ + (*index)->issue(); + }; + //CURLE_OPERATION_TIMEDOUT + delete( (*index) ); + m_vRequestPool.erase( index ); + break; + }; + }; + m_mPoolProtector.unlock(); + }; + }; + } while ( mStillRunning && ( m_bThreadStatus < TH_ENDED ) ); /* if there are still transfers, loop! */ /* call curl_multi_perform or curl_multi_socket_action first, then loop through and check if there are any transfers that have completed */ - /* See how the transfers went */ - while( ( mMsg = curl_multi_info_read( mThis->m_pCURLM, &nMsgsLeft ) ) ){ + /* + while( ( mMsg = curl_multi_info_read( m_pCURLM, &nMsgsLeft ) ) && ( m_bThreadStatus < TH_ENDED ) ){ + char tB[129]; + printf( tB, "[%d] Msgs Left", nMsgsLeft); + LOG( tB ); if( mMsg->msg == CURLMSG_DONE ){ - /* Find out which handle this message is about */ - for (RequestPool::iterator index = mThis->m_vRequestPool.begin(); index < mThis->m_vRequestPool.end(); index++){ + // Find out which handle this message is about + LOG("REQ -> Done!"); + m_mPoolProtector.lock(); + for (RequestPool::iterator index = m_vRequestPool.begin(); index < m_vRequestPool.end(); index++){ if ((*index)->getEH() == mMsg->easy_handle){ - mRetCode = curl_multi_remove_handle(mThis->m_pCURLM, (*index)->getEH()); + mRetCode = curl_multi_remove_handle( m_pCURLM, (*index)->getEH()); (*index)->issue(); delete( (*index) ); - mThis->m_vRequestPool.erase( index ); + m_vRequestPool.erase( index ); break; }; }; + m_mPoolProtector.unlock(); }; }; + */ + SLEEP( 10 ); }; - SLOG("Ending Finished Requests Reaper"); -#ifdef __linux__ - pthread_exit(NULL); - return NULL; -#else - return 0; +#ifdef DEBUG + LOG("Ending Finished Requests Reaper"); #endif }; -#ifdef __linux__ -void *curlRequestsManager::m_fRequestEntryPoint(void *ptr){ -#else -DWORD WINAPI curlRequestsManager::m_fRequestEntryPoint(LPVOID ptr){ -#endif - curlRequest *mThis; - mThis = (curlRequest *)ptr; - //SLOG("Request Thread Entry Point Enter."); - //mThis->issue(); - //SLOG("Request Thread Entry Point Exit."); -#ifdef __linux__ - pthread_exit(NULL); - return NULL; -#else - return 0; -#endif -}; - -bool curlRequestsManager::get(curlRequest *RC){ - if (RC != NULL){ - CURLMcode RetCode; +bool curlRequestsManager::accomplish(curlRequest *RC){ + if( RC ){ +#ifdef DEBUG_EXTRA LOG("New Request"); - m_vRequestPool.push_back(RC); - RetCode = curl_multi_add_handle( m_pCURLM, RC->getEH()); -/* -#ifdef __linux__ - int RetVal = pthread_create(&m_sThreadHandler, NULL, m_fThreadEntryPoint, (void *) this); - if (RetVal == -1) { - LOG_ERROR("Thread Creation Faled."); - return false; - }; -#else - DWORD tThreadID; - HANDLE tThreadHandle = CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE)m_fRequestEntryPoint, - (LPVOID)RC, - 0, - &tThreadID); - if (tThreadHandle == NULL) { - LOG_ERROR("Thread Creation Faled."); - return false; - }; - LOG("Thread to be started."); - m_vRequestThreadPool.push_back(tThreadHandle); #endif -*/ - return true; + m_mPoolProtector.lock(); + CURLMcode RetCode = curl_multi_add_handle( m_pCURLM, RC->getEH()); + if( RetCode == CURLM_OK ) { + m_vRequestPool.push_back( RC ); + m_mPoolProtector.unlock(); + return true; + } else { + LOG_ERROR(curl_multi_strerror(RetCode)); + }; + m_mPoolProtector.unlock(); }; return false; }; bool curlRequestsManager::get(CSTR URL, CSTR contentType ){ curlRequest *tRC; - //LOG("Get URL."); - tRC = new curlRequest(URL, contentType ); + tRC = new curlRequest( URL, contentType ); if (tRC != NULL){ - return get(tRC); + return accomplish(tRC); }; return false; }; +bool curlRequestsManager::post(CSTR URL, CSTR postData, CSTR contentType ){ + curlRequest *tRC; + tRC = new curlRequest( URL, contentType ); + if (tRC != NULL){ + tRC->setPOST( postData, strlen(postData) ); + return accomplish(tRC); + }; + return false; +}; + + #undef LOG #undef LOG_ERROR -#undef SLOG -#undef SLOG_ERROR \ No newline at end of file diff --git a/lib/data/curl/curlRequestsManager.h b/lib/data/curl/curlRequestsManager.h index abf6d816..ea3ee312 100644 --- a/lib/data/curl/curlRequestsManager.h +++ b/lib/data/curl/curlRequestsManager.h @@ -3,105 +3,32 @@ #include "curlRequest.h" #include "../../components/base/basicThread.h" +#include "../../components/base/basicMutex.h" /** * TODO: Add class description * * @author Gagua */ -class curlRequestsManager { +class curlRequestsManager: public basicThread { private: basicLogCollection *m_pLog; CURLM *m_pCURLM; RequestPool m_vRequestPool; RequestThreadPool m_vRequestThreadPool; -#ifdef __linux__ - U8 m_bThreadStatus; - pthread_t m_sThreadHandle; - static void *m_fReaperEntryPoint(void *); - static void *m_fRequestEntryPoint(void *); -#else - DWORD m_dwThreadID; - BYTE m_bThreadStatus; - HANDLE m_hThreadHandle; - static DWORD WINAPI m_fReaperEntryPoint( LPVOID lpParameter); - static DWORD WINAPI m_fRequestEntryPoint( LPVOID lpParameter); -#endif + basicMutex m_mPoolProtector; public: - // Method to fetch singleton instance. static curlRequestsManager* getInstance(); - // Destructor virtual ~curlRequestsManager(); - bool get(curlRequest *RC); bool get(CSTR URL, CSTR contentType = DEFAULT_CONTENT_TYPE); + bool post(CSTR URL, CSTR postData, CSTR contentType = DEFAULT_CONTENT_TYPE ); + bool accomplish(curlRequest *RC); protected: - // Constructor - protected so users cannot call it. curlRequestsManager(); - + virtual void m_fThreadProc( void ); private: - // private static member referencing the single instance of the object - // TODO: Replace curlRequestsManager with the type of object you want to - // return the single instance of static curlRequestsManager* _instance; - - // Copy constructor - // Declared but not defined to prevent auto-generated - // copy constructor. Refer to "Effective C++" by Meyers - curlRequestsManager(const curlRequestsManager& src); - - // Assignment operator - // Declared but not defined to prevent auto-generated - // assignment operator. Refer to "Effective C++" by Meyers - curlRequestsManager& operator=(const curlRequestsManager& src); - -}; - -// Constructor implementation -inline curlRequestsManager::curlRequestsManager(){ - m_pLog = basicLogCollection::getInstance(); - curl_global_init(CURL_GLOBAL_ALL); - m_pCURLM = curl_multi_init(); -#ifdef __linux__ - int RetVal = pthread_create(&m_sThreadHandle, NULL, m_fReaperEntryPoint, (void *) this); - if (RetVal == -1) { - //LOG_ERROR("Thread Creation Faled."); - return; - }; -#else - m_hThreadHandle = CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE)m_fReaperEntryPoint, - (LPVOID)this, - 0, - &m_dwThreadID); - //TODO: Add thread creation check -#endif }; -// Destructor implementation -inline curlRequestsManager::~curlRequestsManager(){ - m_bThreadStatus = 3; - m_pLog->Log("curlRequestsManager", this, "~curlRequestsManager"); - curl_multi_cleanup( m_pCURLM ); -}; - -// TODO: Uncomment the copy constructor when you need it. -//inline curlRequestsManager::curlRequestsManager(const curlRequestsManager& src) -//{ -// // TODO: copy -//} - -// TODO: Uncomment the assignment operator when you need it. -//inline curlRequestsManager& curlRequestsManager::operator=(const curlRequestsManager& rhs) -//{ -// if (this == &rhs) { -// return *this; -// } -// -// // TODO: assignment -// -// return *this; -//} - #endif // __CURLREQUESTSMANAGER_H_INCL__ + diff --git a/lib/data/media/lapsedVideoRecorder.cpp b/lib/data/media/lapsedVideoRecorder.cpp index acdfdb71..d98fdb82 100644 --- a/lib/data/media/lapsedVideoRecorder.cpp +++ b/lib/data/media/lapsedVideoRecorder.cpp @@ -156,7 +156,7 @@ bool lapsedVideoRecorder::finishOutput( void ){ return true; }; -void lapsedVideoRecorder::dispatchEvent(basicEvent *Evt){ +void lapsedVideoRecorder::dispatchEvent(EVENT_CONTAINER *Evt){ if (Evt == NULL)return; }; diff --git a/lib/data/media/lapsedVideoRecorder.h b/lib/data/media/lapsedVideoRecorder.h index 751c5713..12d83056 100644 --- a/lib/data/media/lapsedVideoRecorder.h +++ b/lib/data/media/lapsedVideoRecorder.h @@ -31,7 +31,7 @@ class lapsedVideoRecorder : public basicMediaDestination, public basicEventHandl lapsedVideoRecorder(); ~lapsedVideoRecorder(); virtual void pushFrame( cv::Mat *Frame ); - virtual void dispatchEvent( basicEvent *Evt ); + virtual void dispatchEvent(EVENT_CONTAINER*Evt ); void setTargetOutput( CSTR FileName ); void setTimeLapse( uint32_t milliseconds ); void setFrameLapse( uint32_t frames ); diff --git a/lib/data/media/video/videoAVLIBDestination.h b/lib/data/media/video/videoAVLIBDestination.h index 427c3555..34b546ec 100644 --- a/lib/data/media/video/videoAVLIBDestination.h +++ b/lib/data/media/video/videoAVLIBDestination.h @@ -90,6 +90,8 @@ ffmpeg -y -i in.suffix \\ #endif #endif +#define PICTURE_OUTPUT_CONTAINER "jpg" + /** * TODO: Add class description * diff --git a/lib/data/media/video/videoAVLIBSource.cpp b/lib/data/media/video/videoAVLIBSource.cpp index 19854912..647fdcd0 100644 --- a/lib/data/media/video/videoAVLIBSource.cpp +++ b/lib/data/media/video/videoAVLIBSource.cpp @@ -2,7 +2,27 @@ #include "libavutil/error.h" #define LOG( X ) m_pLog->Log( "LibAV_SRC", this, X ) -#define LOG_ERROR( X ) m_pLog->Log( "LibAV_SRC", this, _LOG_ERROR, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "LIBAV_SRC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "LIBAV_SRC", this, _LOG_ERROR, X ); +#endif + +#define TLOG( X ) basicLogCollection::getInstance()->Log( "LIBAV_SRC_T", NULL, X ) +#ifdef DEBUG + #define TLOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + basicLogCollection::getInstance()->Log( "LIBAV_SRC_T", NULL, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "LIBAV_SRC_T", NULL, _LOG_ERROR, X ); +#endif + videoAVLIBSource::videoAVLIBSource( void *opaque ): basicMediaSource(), basicThread() { m_pLog = basicLogCollection::getInstance(); @@ -85,12 +105,7 @@ videoAVLIBSource::~videoAVLIBSource(){ if (m_pVideoState != NULL){ if( m_pVideoState->m_bStatus > MS_INIT ){ m_bThreadStatus = TH_ENDED; - while (m_pVideoState->m_bStatus == MS_PRESENT) -#ifdef __linux__ - usleep(1000); -#else - Sleep(1); -#endif + while (m_pVideoState->m_bStatus == MS_PRESENT) SLEEP( 10 ); #ifndef _NOAUDIO_ if( m_pVideoState->m_pAudioCtx!=NULL ){ @@ -150,7 +165,7 @@ bool videoAVLIBSource::_close(void){ m_pVideoState->m_bStatus = MS_CLOSING; - while( m_pVideoState->m_bStatus != MS_CLOSED ) SLEEP(2); + while( m_pVideoState->m_bStatus != MS_CLOSED ) SLEEP(10); if (m_pVideoState->m_bStatus > MS_ALOCATED){ @@ -281,9 +296,10 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in } else { m_bSizeIsAutomatic = true; }; - //av_dict_set(&options, "rtsp_transport", "tcp", 0); + av_dict_set(&options, "movflags", "faststart", 0); + av_dict_set(&options, "rtsp_transport", "tcp", 0); av_dict_set(&options, "max_delay", "300000", 0); - //av_dict_set(&options, "stimeout", "1000000", 0); + av_dict_set(&options, "stimeout", "1000000", 0); av_dict_set(&options, "fflags", "nobuffer", 0); //av_dict_set(&options, "analyzeduration", "1000000", 0); if( framerate != -1 ){ @@ -399,6 +415,10 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in LOG_ERROR( Buffer ); return false; }; + + /* 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; + #ifndef _NOAUDIO_ 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 ); @@ -470,12 +490,7 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in //img_convert_ctx = sws_getContext(m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, m_pVideoState->m_pCodecCtx->pix_fmt, m_nWidth, m_nHeight, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL); #endif m_pVideoState->m_bStatus = MS_ALOCATED; // All seems to be good -> allocating mem - - //LOG("YABABA!!!!"); - if( m_bThreadStatus < TH_WORKING ) init(); - - //LOG("YABABA232!"); - return true; + if( m_bThreadStatus < TH_WORKING ) return init(); }; return false; }; @@ -506,136 +521,107 @@ void videoAVLIBSource::m_fThreadProc( void ){ cv::Mat mRGB(m_nHeight, m_nWidth, CV_8UC3); #endif m_bThreadStatus = TH_WORKING; +#ifdef DEBUG_EXTRA LOG("Reader Thread Started."); +#endif //cv::setBreakOnError( true ); m_pVideoState->m_bStatus = MS_STOPED; while( m_pMediaDestination == NULL && m_bThreadStatus == TH_WORKING ){ - SLEEP(20); + SLEEP(10); }; +#ifdef DEBUG LOG("Presentation Started."); +#endif //m_pVideoState->m_bStatus = MS_PRESENT; + av_read_play( m_pVideoState->m_pFormatCtx ); while( m_pVideoState->m_bStatus < MS_CLOSING && m_bThreadStatus != TH_ENDED ){ if ( m_pMediaDestination != NULL ){ if( av_read_frame( m_pVideoState->m_pFormatCtx, m_pPacket ) >= 0 ){ if( m_pPacket->stream_index == m_pVideoState->m_iVideoStreamID ){ -# if ( LIBAVCODEC_VERSION_MAJOR < 58 ) //&& ( LIBAVCODEC_VERSION_MINOR < 50 ) - RetVal = avcodec_decode_video2(m_pVideoState->m_pCodecCtx, m_pFrame, &bGotPicture, m_pPacket); -# else - RetVal = decode(m_pVideoState->m_pCodecCtx, m_pFrame, &bGotPicture, m_pPacket); -#endif - if( RetVal < 0 ){ - LOG_ERROR( "MediaSource::DecoderProc - Decode Error." ); - m_bThreadStatus = TH_ENDED; - m_pVideoState->m_bStatus = MS_STOPED; - continue; - }; - if( m_bThreadStatus == TH_ENDED ){ - m_pVideoState->m_bStatus = MS_STOPED; - continue; - }; - if (bGotPicture){ + //Video Packet + int dec_ret = avcodec_send_packet( m_pVideoState->m_pCodecCtx, m_pPacket ); + if( dec_ret < 0 ){ + //char tB[256]; + //sprintf( tB, "Error decoding video frame (%s)\n", av_err2str( dec_ret )); + LOG_ERROR( "Error decoding video frame" ); + m_pVideoState->m_bStatus = MS_CLOSING; + m_bThreadStatus = TH_ENDED; + break; + }; + while( dec_ret >= 0 && m_bThreadStatus != TH_ENDED ) { + + dec_ret = avcodec_receive_frame( m_pVideoState->m_pCodecCtx, m_pFrame ); + + if( dec_ret == AVERROR(EAGAIN) || dec_ret == AVERROR_EOF ){ + continue;//Skip to next data + } else if( dec_ret < 0 ){ + LOG_ERROR("Error in video decoding"); + m_pVideoState->m_bStatus = MS_STOPED; + m_bThreadStatus = TH_ENDED; + break; + }; + #ifdef PROCESS_YUV420P sws_scale( img_convert_ctx, (const uint8_t* const*) m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameYUV->data, m_pFrameYUV->linesize ); //SDL_UpdateYUVTexture(m_pTexture, &m_oRect, m_pFrameYUV->data[0], m_pFrameYUV->linesize[0], m_pFrameYUV->data[1], m_pFrameYUV->linesize[1], m_pFrameYUV->data[2], m_pFrameYUV->linesize[2]); if (m_pMediaDestination != NULL) m_pMediaDestination->pushFrame( m_pFrameYUV, m_pOpaque ); #else // PROCESS_BGR24 - sws_scale(img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameBGR->data, m_pFrameBGR->linesize); + sws_scale( img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameBGR->data, m_pFrameBGR->linesize ); try{ -# ifdef USE_QVideoFrame - QVideoFrame *tFrame; - tFrame = new QVideoFrame(m_pFrameBGR->linesize[0] * m_nHeight, QSize(m_nHeight, m_nWidth), m_pFrameBGR->linesize[0], QVideoFrame::Format_BGR24); - memcpy(tFrame->bits(), m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight); - if (m_pMediaDestination != NULL) m_pMediaDestination->pushFrame(tFrame, m_pOpaque ); -# else -#ifdef _OPENCV_ - //cv::Mat *mRGB; - //mRGB = new cv::Mat(m_nHeight, m_nWidth, CV_8UC3); - //memcpy(mRGB->data, m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight); - memcpy( mRGB.data, m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight ); -#endif -#ifdef _SDL_ - SDL_Surface* mRGB; - mRGB = SDL_CreateRGBSurfaceFrom(m_pFrameBGR->data[0], - m_nHeight, m_nWidth, - int depth, - Uint32 Rmask, - Uint32 Gmask, - Uint32 Bmask, - Uint32 Amask); -#endif - if( m_pMediaDestination != NULL) m_pMediaDestination->pushFrame( mRGB, m_pOpaque ); -#ifdef _OPENCV_ + #ifdef USE_QVideoFrame + QVideoFrame *tFrame; + tFrame = new QVideoFrame(m_pFrameBGR->linesize[0] * m_nHeight, QSize(m_nHeight, m_nWidth), m_pFrameBGR->linesize[0], QVideoFrame::Format_BGR24); + memcpy(tFrame->bits(), m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight); + if (m_pMediaDestination != NULL) m_pMediaDestination->pushFrame(tFrame, m_pOpaque ); + #else + #ifdef _OPENCV_ + memcpy( mRGB.data, m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight ); + #endif + #ifdef _SDL_ + SDL_Surface* mRGB; + mRGB = SDL_CreateRGBSurfaceFrom( + m_pFrameBGR->data[0], + m_nHeight, m_nWidth, + int depth, + Uint32 Rmask, + Uint32 Gmask, + Uint32 Bmask, + Uint32 Amask + ); + #endif + if (m_pMediaDestination != NULL) { + m_pMediaDestination->pushFrame( mRGB, m_pOpaque); + } else LOG(">"); + #ifdef _OPENCV_ //delete(mRGB); -#endif -#ifdef _SDL_ - SDL_FreeSurface(mRGB); -#endif -# endif // !USE_QVideoFrame + #endif + #ifdef _SDL_ + SDL_FreeSurface(mRGB); + #endif + #endif // !USE_QVideoFrame } catch (cv::Exception & e) { LOG_ERROR(e.msg.c_str()); // output exception message - }; + }; #endif - //if(!m_bStreamingSource) SLEEP( m_pFrame->pkt_duration / 1000 ); - }; - }; -# if ( LIBAVCODEC_VERSION_MAJOR < 58 ) //&& ( LIBAVCODEC_VERSION_MINOR < 50 ) - av_free_packet( m_pPacket ); -# else - av_packet_unref(m_pPacket); -# endif - } else { - // Read Tale of data - while(1){ -# if ( LIBAVCODEC_VERSION_MAJOR < 58 ) //&& ( LIBAVCODEC_VERSION_MINOR < 50 ) - RetVal = avcodec_decode_video2( m_pVideoState->m_pCodecCtx, m_pFrame, &bGotPicture, m_pPacket ); -# else - RetVal = decode(m_pVideoState->m_pCodecCtx, m_pFrame, &bGotPicture, m_pPacket); -# endif - if( RetVal < 0 ) break; - if( !bGotPicture ) break; - if( m_bThreadStatus == TH_ENDED ){ - m_pVideoState->m_bStatus = MS_STOPED; - break; - }; -#ifdef PROCESS_YUV420P - sws_scale( img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameYUV->data, m_pFrameYUV->linesize); - //SDL_UpdateYUVTexture( m_pTexture, &m_oRect, m_pFrameYUV->data[0], m_pFrameYUV->linesize[0], m_pFrameYUV->data[1], m_pFrameYUV->linesize[1], m_pFrameYUV->data[2], m_pFrameYUV->linesize[2] ); - if (m_pMediaDestination != NULL) m_pMediaDestination->pushFrame( m_pFrameYUV, m_pOpaque ); -#endif -#ifdef PROCESS_BGR24 - sws_scale(img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameBGR->data, m_pFrameBGR->linesize); - try{ - //cv::Mat *mRGB; - //mRGB = new cv::Mat(m_nHeight, m_nWidth, CV_8UC3); - //memcpy( mRGB->data, m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight ); - cv::Mat mRGB(m_nHeight, m_nWidth, CV_8UC3); - memcpy( mRGB.data, m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight ); - if( m_pMediaDestination != NULL )m_pMediaDestination->pushFrame( mRGB, m_pOpaque ); - //delete(mRGB); - } catch (cv::Exception & e) { - LOG_ERROR(e.msg.c_str()); // output exception message - }; + }; + }; + }; + } else { +#if ( LIBAVCODEC_VERSION_MAJOR < 58 ) //&& ( LIBAVCODEC_VERSION_MINOR < 50 ) + av_free_packet(m_pPacket); +#else + av_packet_unref(m_pPacket); #endif - }; - LOG("Video Stream Ended"); -# if ( LIBAVCODEC_VERSION_MAJOR < 58 ) //&& ( LIBAVCODEC_VERSION_MINOR < 50 ) - av_free_packet(m_pPacket); -# else - av_packet_unref(m_pPacket); -# endif - m_pVideoState->m_bStatus = MS_CLOSED; - m_bThreadStatus = TH_ENDED; - }; - }else{ m_pVideoState->m_bStatus = MS_CLOSED; - SLEEP(5); + m_bThreadStatus = TH_ENDED; }; }; m_pVideoState->m_bStatus = MS_CLOSED; m_bThreadStatus = TH_ENDED; - LOG("Thread Ended."); }; +#undef TLOG +#undef TLOG_ERROR #undef LOG #undef LOG_ERROR diff --git a/lib/data/mysql/database_class.cpp b/lib/data/mysql/database_class.cpp index 3ca7b15e..77c3e031 100644 --- a/lib/data/mysql/database_class.cpp +++ b/lib/data/mysql/database_class.cpp @@ -332,12 +332,12 @@ void MySQL_Connector::SilentQuery( CSTR QS ){ m_mAccessMutex.unlock(); }; -void deleteResult( AAssoc *R ){ - if (R) { - //while( R->size() ){ - // delete( (Assoc *) R->at(0) ); - // R->erase( R->begin()); - //}; +void deleteResult( AAssoc *&R ){ + if( R ){ + while( R->size() ){ + delete( (Assoc *) R->at(0) ); + R->erase( R->begin()); + }; R->clear(); delete( R ); R = NULL; diff --git a/lib/data/mysql/database_class.h b/lib/data/mysql/database_class.h index 9513ebcb..87303ecb 100644 --- a/lib/data/mysql/database_class.h +++ b/lib/data/mysql/database_class.h @@ -39,7 +39,7 @@ class MySQL_Connector{ AAssoc * Query( CSTR QS, bool useCache = false ); }; -void deleteResult( AAssoc * ); +void deleteResult( AAssoc *&ptr ); //extern MySQL_Connector DBC; #endif diff --git a/lib/data/onvif/gsoap/mecevp.cpp b/lib/data/onvif/gsoap/mecevp.cpp index 445e3cee..61741ac2 100644 --- a/lib/data/onvif/gsoap/mecevp.cpp +++ b/lib/data/onvif/gsoap/mecevp.cpp @@ -271,7 +271,8 @@ soap_mec_init(struct soap *soap, struct soap_mec_data *data, int alg, SOAP_MEC_K { int ok = 1; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_mec_init()\n")); soap_ssl_init(); - data->ctx = (EVP_CIPHER_CTX*)SOAP_MALLOC(soap, sizeof(EVP_CIPHER_CTX)); + data->ctx = //(EVP_CIPHER_CTX*)SOAP_MALLOC(soap, sizeof(EVP_CIPHER_CTX)); + EVP_CIPHER_CTX_new(); if (!data->ctx) return soap->error = SOAP_EOM; EVP_CIPHER_CTX_init(data->ctx); @@ -393,7 +394,8 @@ soap_mec_cleanup(struct soap *soap, struct soap_mec_data *data) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_mec_cleanup()\n")); if (data->ctx) { EVP_CIPHER_CTX_cleanup(data->ctx); - SOAP_FREE(soap, data->ctx); + EVP_CIPHER_CTX_free( data->ctx ); + //SOAP_FREE(soap, data->ctx); data->ctx = NULL; } if (data->buf) diff --git a/lib/data/onvif/gsoap/smdevp.cpp b/lib/data/onvif/gsoap/smdevp.cpp index 7077eed4..64c95711 100644 --- a/lib/data/onvif/gsoap/smdevp.cpp +++ b/lib/data/onvif/gsoap/smdevp.cpp @@ -428,13 +428,14 @@ soap_smd_init(struct soap *soap, struct soap_smd_data *data, int alg, const void /* the key to use */ data->key = key; /* allocate and init the OpenSSL HMAC or EVP_MD context */ - if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC) - { data->ctx = (void*)SOAP_MALLOC(soap, sizeof(HMAC_CTX)); - HMAC_CTX_init((HMAC_CTX*)data->ctx); - } - else - { data->ctx = (void*)SOAP_MALLOC(soap, sizeof(EVP_MD_CTX)); - EVP_MD_CTX_init((EVP_MD_CTX*)data->ctx); + if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC){ + data->ctx = (void*)HMAC_CTX_new();//(void*)SOAP_MALLOC(soap, sizeof(HMAC_CTX)); + //HMAC_CTX_init((HMAC_CTX*)data->ctx); + HMAC_CTX_reset((HMAC_CTX*)data->ctx); + } else { + data->ctx = (void*)EVP_MD_CTX_new();//(void*)SOAP_MALLOC(soap, sizeof(EVP_MD_CTX)); + //EVP_MD_CTX_init((EVP_MD_CTX*)data->ctx); + EVP_MD_CTX_reset((EVP_MD_CTX*)data->ctx); } DBGLOG(TEST, SOAP_MESSAGE(fdebug, "-- SMD Init alg=%x (%p) --\n", alg, data->ctx)); /* init the digest or signature computations */ @@ -531,7 +532,9 @@ soap_smd_final(struct soap *soap, struct soap_smd_data *data, char *buf, int *le switch (data->alg & SOAP_SMD_ALGO) { case SOAP_SMD_HMAC: HMAC_Final((HMAC_CTX*)data->ctx, (unsigned char*)buf, &n); - HMAC_CTX_cleanup((HMAC_CTX*)data->ctx); + //HMAC_CTX_cleanup((HMAC_CTX*)data->ctx); + HMAC_CTX_free((HMAC_CTX*)data->ctx); + data->ctx = NULL; break; case SOAP_SMD_DGST: EVP_DigestFinal((EVP_MD_CTX*)data->ctx, (unsigned char*)buf, &n); @@ -586,10 +589,12 @@ soap_smd_check(struct soap *soap, struct soap_smd_data *data, int err, const cha } if (data->ctx) { if ((data->alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC) - HMAC_CTX_cleanup((HMAC_CTX*)data->ctx); + //HMAC_CTX_cleanup((HMAC_CTX*)data->ctx); + HMAC_CTX_free((HMAC_CTX*)data->ctx); else - EVP_MD_CTX_cleanup((EVP_MD_CTX*)data->ctx); - SOAP_FREE(soap, data->ctx); + //EVP_MD_CTX_cleanup((EVP_MD_CTX*)data->ctx); + //SOAP_FREE(soap, data->ctx); + EVP_MD_CTX_free((EVP_MD_CTX *)data->ctx ); data->ctx = NULL; } return soap_set_receiver_error(soap, msg, soap->msgbuf, SOAP_SSL_ERROR); diff --git a/lib/data/onvif/gsoap/stdsoap2.cpp b/lib/data/onvif/gsoap/stdsoap2.cpp index f2c921df..bda0f61e 100644 --- a/lib/data/onvif/gsoap/stdsoap2.cpp +++ b/lib/data/onvif/gsoap/stdsoap2.cpp @@ -4403,7 +4403,8 @@ again: break; name = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subj, i)); if (name) - { if (!soap_tag_cmp(host, (const char*)M_ASN1_STRING_data(name))) + //{ if (!soap_tag_cmp(host, (const char*)M_ASN1_STRING_data(name))) + { if (!soap_tag_cmp(host, (const char*)ASN1_STRING_data(name))) ok = 1; else { unsigned char *tmp = NULL; diff --git a/lib/data/ponvif/ponvif.cpp b/lib/data/ponvif/ponvif.cpp index 778a6052..3f136f76 100644 --- a/lib/data/ponvif/ponvif.cpp +++ b/lib/data/ponvif/ponvif.cpp @@ -1,25 +1,30 @@ #include "ponvif.h" -#include #include -#include + #include /* See NOTES */ -#include + #include #include -#include + #include #include -#include -#include -#include - + + //http://dspace.nplg.gov.ge/handle/1234/3051 //http://dspace.nplg.gov.ge/handle/1234/3057 //http://dspace.nplg.gov.ge/handle/1234/3061 -#define LOG( X ) m_pLog->Log( "pOnVif", this, X ) -#define TLOG( X ) basicLogCollection::getInstance()->Log( "TpOnVif", NULL, X ) -#define LOG_ERROR( X ) m_pLog->Log( "pOnVif", this, _LOG_ERROR, X ) +#define LOG( X ) m_pLog->Log( "PONVIF", this, X ) +#define TLOG( X ) basicLogCollection::getInstance()->Log( "PONVIF_T", NULL, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "PONVIF", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "PONVIF", this, _LOG_ERROR, X ); +#endif inline bool checkBool( const char *A ){ if(A == NULL) return false; @@ -60,7 +65,7 @@ pOnvif::pOnvif(){ m_pDiscoveryMCastIP = NULL;//PONVIF_DEFAULT_DISCOVERYMCASTIP; m_nDiscoveryMCastPort = PONVIF_DEFAULT_DISCOVERYMCASTPORT; m_bDiscoveryHideDuplicates = true; - + m_pHttpAccessManager = NULL; m_sCapabilities.Analytics = NULL; m_sCapabilities.Device = NULL; m_sCapabilities.Events = NULL; @@ -201,15 +206,35 @@ CSTR pOnvif::getDeviceUri( void ){ return m_pDeviceURI; }; -bool pOnvif::setDeviceUri( CSTR deviceUri ){ - if( m_pDeviceURI != NULL ) free( m_pDeviceURI ); +bool pOnvif::setDeviceUri( CSTR deviceUri ){ if( deviceUri == NULL || strlen(deviceUri) == 0 ){ m_pDeviceURI = NULL; - return true; + return false; }; + if( strstr( deviceUri, "http" ) == NULL ) { + LOG_ERROR("Malformed device URI"); + return false; + }; + if( m_pDeviceURI != NULL ) free( m_pDeviceURI ); m_pDeviceURI = (CSTR) malloc( strlen(deviceUri)+1); if( m_pDeviceURI == NULL ) return false; - memcpy(m_pDeviceURI,deviceUri,strlen(deviceUri)+1); + memcpy(m_pDeviceURI,deviceUri,strlen(deviceUri)); + m_pDeviceURI[strlen(deviceUri)] = (char)0; + + //toDo: Must parsed Host/IP + char *tT = strstr( m_pDeviceURI, "/" ); + if( tT ) { + tT+=2; + char *tB = strstr( tT, "/" ); + int len = tB - tT+1; + m_pIpAddress = (CSTR) malloc( len ); + if( m_pIpAddress ) { + len--; + memcpy( m_pIpAddress, tT, len ); + m_pIpAddress[len]=(char)0; + LOG( m_pIpAddress ); + }; + }; return true; }; @@ -218,14 +243,22 @@ CSTR pOnvif::getIPAddress( void ){ }; bool pOnvif::setIPAddress( CSTR ipAddress ){ - if( m_pIpAddress != NULL ) free( m_pIpAddress ); if( ipAddress == NULL || strlen(ipAddress) == 0 ){ m_pIpAddress = NULL; - return true; + return false; }; + if( m_pIpAddress != NULL ) free( m_pIpAddress ); m_pIpAddress = (CSTR) malloc( strlen(ipAddress)+1); if( m_pIpAddress == NULL ) return false; - memcpy(m_pIpAddress,ipAddress,strlen(ipAddress)+1); + memcpy( m_pIpAddress, ipAddress, strlen(ipAddress)); + m_pIpAddress[strlen(ipAddress)]=(char)0; + //ToDo: Must be created URI ... sprintf(tURL, "http://%s/onvif/device_service", m_pIpAddress); + int len = strlen(ipAddress) + 28; + m_pDeviceURI = (CSTR) malloc( len+1); + if(m_pDeviceURI) { + sprintf( m_pDeviceURI, "http://%s/onvif/device_service", m_pIpAddress ); + LOG( m_pDeviceURI ); + }; return true; }; @@ -324,7 +357,11 @@ discoveryResults pOnvif::discover( void ){ CSTR tPostString = PONVIF_PACK_DISCOVERY; struct sockaddr_in tSockAddr; struct hostent * h_info; +#ifdef __linux__ int tSocket; +#else + int tSocket; +#endif int RetCode; char Response[DEFAULT_BUFFER_SIZE]; try { @@ -335,7 +372,7 @@ discoveryResults pOnvif::discover( void ){ return RetVal; }; LOG("Socket Created!"); - bzero( &tSockAddr, sizeof( struct sockaddr_in ) ); + memset(&tSockAddr, 0, sizeof( struct sockaddr_in ) ); h_info = gethostbyname ( m_pDiscoveryBindIP ); if ( h_info == NULL ){ LOG_ERROR( "Some throuble with networking on this machine (Cannot Get Hostname)!" ); @@ -345,7 +382,7 @@ discoveryResults pOnvif::discover( void ){ //***************************************** //* there we building our network address * //***************************************** - bcopy( h_info->h_addr, &(tSockAddr.sin_addr), h_info->h_length ); + memcpy( h_info->h_addr, &(tSockAddr.sin_addr), h_info->h_length ); tSockAddr.sin_family = h_info->h_addrtype; tSockAddr.sin_port = htons( 20000 + ( 20000 * rand() ) / RAND_MAX ); @@ -355,15 +392,31 @@ discoveryResults pOnvif::discover( void ){ return RetVal; }; LOG("Binding Done!"); - //setsockopt( tSocket, IPPROTO_IP, MCAST_JOIN_GROUP, ); - int tVal = 1; - setsockopt( tSocket, SOL_SOCKET, SO_BROADCAST, &tVal, sizeof(int)); - //socket_sendto($sock, $post_string, strlen(tPostString), 0, $this->discoverymcastip, $this->discoverymcastport); - sendto( tSocket, tPostString, strlen(tPostString), 0, (const sockaddr*)&tSockAddr, sizeof( struct sockaddr_in )); - LOG("Broadcast Ping Sent!"); + +#ifdef __linux__ + //setsockopt( tSocket, IPPROTO_IP, MCAST_JOIN_GROUP, ); + int tVal = 1; + setsockopt(tSocket, SOL_SOCKET, SO_BROADCAST, &tVal, sizeof(int)); + //socket_sendto($sock, $post_string, strlen(tPostString), 0, $this->discoverymcastip, $this->discoverymcastport); + sendto(tSocket, tPostString, strlen(tPostString), 0, (const sockaddr*)&tSockAddr, sizeof(struct sockaddr_in)); + LOG("Broadcast Ping Sent!"); fcntl( tSocket, F_SETFL, fcntl(tSocket, F_GETFL, 0) | O_NONBLOCK ); - //socket_set_nonblock($sock); - LOG("Socket Set Not Bloking Mode!"); + LOG("Socket Set Not Bloking Mode!"); +#else + //setsockopt( tSocket, IPPROTO_IP, MCAST_JOIN_GROUP, ); + bool tVal = 1; + setsockopt(tSocket, SOL_SOCKET, SO_BROADCAST, (const char *)&tVal, sizeof(bool)); + //socket_sendto($sock, $post_string, strlen(tPostString), 0, $this->discoverymcastip, $this->discoverymcastport); + sendto(tSocket, tPostString, strlen(tPostString), 0, (const sockaddr*)&tSockAddr, sizeof(struct sockaddr_in)); + LOG("Broadcast Ping Sent!"); + u_long arg = 1; + if (ioctlsocket(tSocket, FIONBIO, &arg) < 0) { + char tBuf[128]; + sprintf(tBuf, "Error ioctlsocket(..., FIONBIO) (%s)", strerror(errno)); + LOG_ERROR(tBuf); + return RetVal; + }; +#endif while( time( NULL ) < tTimeout ){ //n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); tVal = recvfrom( tSocket, Response, DEFAULT_BUFFER_SIZE, 0, NULL, NULL ); @@ -386,7 +439,11 @@ discoveryResults pOnvif::discover( void ){ //}; }; }; +#ifdef __linux__ close( tSocket ); +#else + closesocket(tSocket); +#endif } catch ( exception e ) { LOG_ERROR( "Communication at Discovery Exception Catched!"); }; @@ -397,20 +454,26 @@ discoveryResults pOnvif::discover( void ){ Public functions (basic initialization method and other collaterals) */ bool pOnvif::create( void ) { + m_pHttpAccessManager = curlRequestsManager::getInstance(); + if( m_pHttpAccessManager == NULL ) return false; + LOG("CURL MANAGER OK"); try { struct tm * tTS; tTS = core_GetSystemDateAndTime(); if( tTS != NULL ){ time_t tTimeStamp = mktime( tTS ); - m_nDeltaTime = time( NULL ) - tTimeStamp - 5; + m_nDeltaTime = time(NULL) - tTimeStamp;// -5; free( tTS ); - }; - } catch ( exception e ) {} + } else return false; + } catch ( exception e ) { + LOG_ERROR("Catched Exception!"); + return false; + }; if( !core_GetCapabilities() ){ LOG_ERROR("Error Getting Caps!"); return false; - } + }; _getOnvifVersion( m_sCapabilities ); // Update some Vars Online! //preg_match("/^http(.*)onvif\//",$this->mediauri,$matches); @@ -430,13 +493,21 @@ bool pOnvif::create( void ) { struct tm *pOnvif::core_GetSystemDateAndTime( void ) { struct tm * RetVal = NULL; char tURL[CTEXT]; - sprintf( tURL, "http://%s/onvif/device_service", m_pIpAddress ); - if( _send_request( tURL, PONVIF_PACK_GET_SYS_DTS ) ){ + if( m_pDeviceURI != NULL ){ + sprintf(tURL, m_pDeviceURI ); + } else { + if( m_pIpAddress != NULL ){ + sprintf(tURL, "http://%s/onvif/device_service", m_pIpAddress); + } else { + return NULL; + }; + }; + LOG("Before REQ"); + if( _send_request( tURL, PONVIF_PACK_GET_SYS_DTS, true ) ){ XMLResults tParseResults; XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); -#ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES - LOG("RCPT:"); - printf(m_pLastResponse); +#ifdef DEBUG + LOG("core_GetSystemDateAndTime"); #endif if( tParseResults.error ){ char tBuffer[CTEXT]; @@ -493,7 +564,15 @@ bool pOnvif::core_GetCapabilities( void ){ accessToken tTOKEN; tTOKEN = _makeToken(); char tURL[CTEXT]; - sprintf( tURL, "http://%s/onvif/device_service", m_pIpAddress ); + if (m_pDeviceURI != NULL) { + sprintf(tURL, m_pDeviceURI); + } else { + if (m_pIpAddress != NULL) { + sprintf(tURL, "http://%s/onvif/device_service", m_pIpAddress); + } else { + return NULL; + }; + }; //char tSTR[CTEXT]; sprintf( tBuffer, PONVIF_PACK_GET_CAPABILITIES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP ); //sprintf( tSTR, PONVIF_PCK_GET_CAPABILITIES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP ); @@ -1312,28 +1391,17 @@ CSTR pOnvif::media_GetSnapshotUri( CSTR profileToken ){ }; return NULL; }; - + bool pOnvif::ptz_GetStatus( CSTR profileToken, ptzStatus *tStatus ){ - if( m_pPTZURI==NULL ) return false; if( tStatus == NULL ) return false; char tBuffer[DEFAULT_BUFFER_SIZE]; accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_GET_PTZ_STATUS, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken ); - if( _send_request( m_pPTZURI, tBuffer ) ){ + if( _send_request( m_pPTZURI, tBuffer, true ) ){ XMLResults tParseResults; XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - //LOG( m_pLastResponse ); -#ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES - FILE *fd; - fd = fopen("ONVIF_MSGS.txt","a+"); - fprintf(fd, "--------------------\r\n"); - fprintf(fd, m_pLastResponse ); - fprintf(fd, "--------------------\r\n"); - fclose(fd); -#endif - if( tParseResults.error ){ char tBuf[CTEXT]; sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); @@ -1441,18 +1509,7 @@ bool pOnvif::ptz_GotoPreset( CSTR profileToken, CSTR presetToken, float speed_pa accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_GOTO_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetToken, speed_pantilt_x, speed_pantilt_y, speed_zoom_x ); - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - LOG("RCPT:"); - printf(m_pLastResponse); - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else return true; - }; - return false; + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_RemovePreset( CSTR profileToken, CSTR presetToken ){ @@ -1461,18 +1518,7 @@ bool pOnvif::ptz_RemovePreset( CSTR profileToken, CSTR presetToken ){ accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_REMOVE_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetToken ); - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - LOG("RCPT:"); - printf(m_pLastResponse); - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else return true; - }; - return false; + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_SetPreset( CSTR profileToken, CSTR presetName ){ @@ -1481,18 +1527,7 @@ bool pOnvif::ptz_SetPreset( CSTR profileToken, CSTR presetName ){ accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_SET_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetName ); - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - LOG("RCPT:"); - printf(m_pLastResponse); - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else return true; - }; - return false; + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_RelativeMove( CSTR profileToken, float translation_pantilt_x, float translation_pantilt_y, float speed_pantilt_x, float speed_pantilt_y ){ @@ -1501,18 +1536,7 @@ bool pOnvif::ptz_RelativeMove( CSTR profileToken, float translation_pantilt_x, f accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_RELATIVE_MOVE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, translation_pantilt_x, translation_pantilt_y, speed_pantilt_x, speed_pantilt_y ); - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - LOG("RCPT:"); - printf(m_pLastResponse); - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else return true; - }; - return false; + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_RelativeMoveZoom( CSTR profileToken, float zoom, float speedZoom ){ @@ -1521,16 +1545,7 @@ bool pOnvif::ptz_RelativeMoveZoom( CSTR profileToken, float zoom, float speedZoo accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_RELATIVE_ZOOM, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, zoom, speedZoom ); - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else return true; - }; - return false; + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_AbsoluteMove( CSTR profileToken, float position_pantilt_x, float position_pantilt_y, float zoom ){ @@ -1539,32 +1554,7 @@ bool pOnvif::ptz_AbsoluteMove( CSTR profileToken, float position_pantilt_x, floa accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_ABSOLUTE_MOVE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, position_pantilt_x, position_pantilt_y, zoom ); -#ifdef DEBUG_ONVIF_TRAFFIC - FILE *tf; - tf = fopen("Traffic.txt", "a+"); - fprintf( tf, "%s\n", tBuffer ); -#endif - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); -#ifdef DEBUG_ONVIF_TRAFFIC - fprintf( tf, "%s\n", m_pLastResponse ); -#endif - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else { -#ifdef DEBUG_ONVIF_TRAFFIC - fclose( tf ); -#endif - return true; - }; - }; -#ifdef DEBUG_ONVIF_TRAFFIC - fclose(tf); -#endif - return false; + return _send_request( m_pPTZURI, tBuffer, false ); }; bool pOnvif::ptz_ContinuousMove( CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y ){ @@ -1573,41 +1563,7 @@ bool pOnvif::ptz_ContinuousMove( CSTR profileToken, float velocity_pantilt_x, fl accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_CONTINUOUS_MOVE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, velocity_pantilt_x, velocity_pantilt_y ); -/* -#ifdef DEBUG_ONVIF_TRAFFIC - FILE *tf; - tf = fopen("Traffic.txt", "a+"); - fprintf( tf, "--------------------\r\n"); - fprintf( tf, ">>>>> %s\n", tBuffer ); - fprintf( tf, "--------------------\r\n"); -#endif -*/ - return _send_request( m_pPTZURI, tBuffer ); -/* - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); -#ifdef DEBUG_ONVIF_TRAFFIC - fprintf( tf, "--------------------\r\n"); - fprintf( tf, "<<<<< %s\n", m_pLastResponse ); - fprintf( tf, "--------------------\r\n"); -#endif - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else { -#ifdef DEBUG_ONVIF_TRAFFIC - fclose( tf ); -#endif - return true; - }; - }; -#ifdef DEBUG_ONVIF_TRAFFIC - fclose(tf); -#endif - return false; - //*/ + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_ContinuousMoveZoom( CSTR profileToken, float zoom ){ @@ -1616,39 +1572,7 @@ bool pOnvif::ptz_ContinuousMoveZoom( CSTR profileToken, float zoom ){ accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_CONTINUOUS_ZOOM, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, zoom ); -//#ifdef DEBUG_ONVIF_TRAFFIC -// FILE *tf; -// tf = fopen("Traffic.txt", "a+"); -// fprintf( tf, "--------------------\r\n"); -// fprintf( tf, ">>>>> %s\n", tBuffer ); -// fprintf( tf, "--------------------\r\n"); -//#endif - return _send_request( m_pPTZURI, tBuffer ); -/* - if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); -#ifdef DEBUG_ONVIF_TRAFFIC - fprintf( tf, "--------------------\r\n"); - fprintf( tf, "<<<<< %s\n", m_pLastResponse ); - fprintf( tf, "--------------------\r\n"); -#endif - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else { -#ifdef DEBUG_ONVIF_TRAFFIC - fclose( tf ); -#endif - return true; - } - }; -#ifdef DEBUG_ONVIF_TRAFFIC - fclose( tf ); -#endif - return false; - // */ + return _send_request( m_pPTZURI, tBuffer, true ); }; bool pOnvif::ptz_Stop( CSTR profileToken, bool pantilt, bool zoom ){ @@ -1657,19 +1581,7 @@ bool pOnvif::ptz_Stop( CSTR profileToken, bool pantilt, bool zoom ){ accessToken tTOKEN; tTOKEN = _makeToken(); sprintf( tBuffer, PONVIF_PACK_PTZ_STOP, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken );//, pantilt, zoom ); - return _send_request( m_pPTZURI, tBuffer ); - /*if( _send_request( m_pPTZURI, tBuffer ) ){ - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); - printf(m_pLastResponse); - if( tParseResults.error ){ - char tBuf[CTEXT]; - sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - LOG_ERROR( tBuf ); - } else return true; - }; - return false; - */ + return _send_request( m_pPTZURI, tBuffer, true ); }; /* @@ -1770,7 +1682,7 @@ accessToken pOnvif::_passwordDigest( CSTR username, CSTR password, time_t timest accessToken RetVal; char tTS[CTEXT]; unsigned char * tPDIGEST; - if( timestamp == 0 || 1 ){ + if( timestamp == 0 ){ time_t t; struct tm * tmp; t = time( NULL ); @@ -1791,7 +1703,7 @@ accessToken pOnvif::_passwordDigest( CSTR username, CSTR password, time_t timest LOG_ERROR("strftime returned 0!"); }; }; - if( nonce == 0 || 1 ){ + if( nonce == 0 ){ nonce = (uint32_t) rand(); }; unsigned char tBuff[CTEXT]; @@ -1827,9 +1739,72 @@ accessToken pOnvif::_passwordDigest( CSTR username, CSTR password, time_t timest free( tPDIGEST ); //$REQ['NONCE']=base64_encode($nonce); // alternative return RetVal; -} +}; -bool pOnvif::_send_request( CSTR url, CSTR post_string ){ +void *pOnvif::parser( void *obj, void *ptr ){ + pOnvif * ME = (pOnvif*)obj; + curlRequest * RQ = (curlRequest*)ptr; + + if( ME ) { + if( ME->m_pLastResponse ) free( ME->m_pLastResponse ); + ME->m_pLastResponse = (CSTR) malloc( RQ->getSize()+1); + if( ME->m_pLastResponse ) { + memcpy( ME->m_pLastResponse, RQ->getBuffer(), RQ->getSize() ); + ME->m_pLastResponse[RQ->getSize()] = (char)0; +#ifdef DEBUG_ONVIF_TRAFFIC + FILE *tf; + tf = fopen("Traffic.txt", "a+"); + fprintf( tf, "~~~~~~~~~~~~~~~~~~~~\r\n"); + fprintf( tf, "<<<<< [%d] %s\n", RQ->getSize(), ME->m_pLastResponse ); + fprintf( tf, "~~~~~~~~~~~~~~~~~~~~\r\n"); + fclose(tf); +#endif + }; + ME->parser_done = true; + }; + return NULL; +}; + +bool pOnvif::_send_request( CSTR url, CSTR post_string, bool mustReturnData ){ +#ifdef CURL_MANAGER + bool RetVal = false; + if( m_pHttpAccessManager ){ + m_mResponseProtector.lock(); + curlRequest *tRC;//application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver10/device/wsdl/GetSystemDateAndTime" + tRC = new curlRequest( url, (CSTR)"application/soap+xml; charset=utf-8;" ); + if( tRC != NULL ){ +#ifdef DEBUG_ONVIF_TRAFFIC + FILE *tf; + tf = fopen("Traffic.txt", "a+"); + fprintf( tf, "--------------------\r\n"); + fprintf( tf, "REQ: %s (%d)\n", url, strlen(post_string) ); + fprintf( tf, ">>>>> %s\n", post_string ); + fprintf( tf, "--------------------\r\n"); + fclose(tf); + mustReturnData = true; //In Debug Allways Read Return +#endif + tRC->setCredentials( m_pUsername, m_pPassword, false ); + tRC->setPOST( post_string, strlen(post_string) ); + if( mustReturnData ) { + tRC->setHandler( (void*)this, pOnvif::parser, (void*)tRC ); + if( m_pHttpAccessManager->accomplish( tRC ) ){ + parser_done = false; + uint8_t cnt = 200; // TO = 2 second + bool chk = false; + while( !chk && cnt-- ){ + chk = parser_done; + SLEEP( 10 ); + }; + if( chk )RetVal = true; + }; + } else { + RetVal = m_pHttpAccessManager->accomplish( tRC ); + }; + }; + m_mResponseProtector.unlock(); + }; + return RetVal; +#else char tBuffer[CTEXT]; if( m_pCURL == NULL ) { if( m_pLastResponse == NULL ){ @@ -1844,18 +1819,18 @@ bool pOnvif::_send_request( CSTR url, CSTR post_string ){ curl_easy_setopt( m_pCURL, CURLOPT_PROXYUSERPWD, tBuffer ); }; }; - curl_easy_setopt( m_pCURL, CURLOPT_CONNECTTIMEOUT, 10); - curl_easy_setopt( m_pCURL, CURLOPT_TIMEOUT, 10); + curl_easy_setopt( m_pCURL, CURLOPT_CONNECTTIMEOUT, 1); + curl_easy_setopt( m_pCURL, CURLOPT_TIMEOUT, 2); curl_easy_setopt( m_pCURL, CURLOPT_SSL_VERIFYPEER, 0 ); curl_easy_setopt( m_pCURL, CURLOPT_SSL_VERIFYHOST, 0 ); curl_easy_setopt( m_pCURL, CURLOPT_VERBOSE, 0 ); curl_easy_setopt( m_pCURL, CURLOPT_POST, 1 ); - curl_easy_setopt( m_pCURL, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, 0 ); - curl_easy_setopt( m_pCURL, CURLOPT_NOPROGRESS, 1 ); - curl_easy_setopt( m_pCURL, CURLOPT_NOSIGNAL, 1 ); + //curl_easy_setopt( m_pCURL, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, 0 ); + //curl_easy_setopt( m_pCURL, CURLOPT_NOPROGRESS, 1 ); + //curl_easy_setopt( m_pCURL, CURLOPT_NOSIGNAL, 1 ); curl_easy_setopt( m_pCURL, CURLOPT_TCP_FASTOPEN, 1 ); curl_easy_setopt( m_pCURL, CURLOPT_TCP_NODELAY, 1 ); - curl_easy_setopt( m_pCURL, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); + //curl_easy_setopt( m_pCURL, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); curl_easy_setopt( m_pCURL, CURLOPT_WRITEFUNCTION, pOnvif::_writer ); curl_easy_setopt( m_pCURL, CURLOPT_WRITEDATA, this ); }; @@ -1871,9 +1846,16 @@ bool pOnvif::_send_request( CSTR url, CSTR post_string ){ curl_easy_setopt( m_pCURL, CURLOPT_POSTFIELDS, post_string); sprintf( tBuffer,"%s:%s", m_pUsername, m_pPassword ); curl_easy_setopt( m_pCURL, CURLOPT_USERPWD, tBuffer ); +#ifdef DEBUG + char tErrorBuffer[CURL_ERROR_SIZE]; + curl_easy_setopt( m_pCURL, CURLOPT_ERRORBUFFER, tErrorBuffer ); +#endif m_pLastIndex = 0; if( curl_easy_perform( m_pCURL ) ) { LOG_ERROR("CURL Failure!"); +#ifdef DEBUG + LOG_ERROR( tErrorBuffer ); +#endif } else { m_pLastResponse[m_pLastIndex] = (char)0; return true; @@ -1881,8 +1863,10 @@ bool pOnvif::_send_request( CSTR url, CSTR post_string ){ m_pLastIndex = 0; }; return false; +#endif }; +#ifndef CURL_MANAGER int pOnvif::_writer( char *data, size_t size, size_t nmemb, pOnvif *Ptr ){ if( Ptr == NULL ) return 0; //TLOG("*"); @@ -1890,6 +1874,7 @@ int pOnvif::_writer( char *data, size_t size, size_t nmemb, pOnvif *Ptr ){ Ptr->m_pLastIndex += size*nmemb; return size*nmemb; }; +#endif #undef LOG #undef TLOG diff --git a/lib/data/ponvif/ponvif.h b/lib/data/ponvif/ponvif.h index 887ff2ce..3e45dd82 100644 --- a/lib/data/ponvif/ponvif.h +++ b/lib/data/ponvif/ponvif.h @@ -5,51 +5,62 @@ #include #include #include -#include + +#ifdef __linux__ + #include + #include + #include + #include + #include + #include + #include +#endif #include "../protocol/xmlParser.h" #include "../../alg/generic/base64.h" #include "../../components/base/basicTypes.h" #include "../../components/base/basicLogCollection.h" +#include "../curl/curlRequestsManager.h" +#define CURL_MANAGER //#define DEBUG_ONVIF_PRINTOUT_MESSAGES //#define DEBUG_ONVIF_TRAFFIC -#define PONVIF_DEFAULT_DISCOVERYBINDIP "0.0.0.0" -#define PONVIF_DEFAULT_DISCOVERYMCASTIP "239.255.255.250" +#define PONVIF_DEFAULT_DISCOVERYBINDIP (CSTR)"0.0.0.0" +#define PONVIF_DEFAULT_DISCOVERYMCASTIP (CSTR)"239.255.255.250" #define PONVIF_DEFAULT_DISCOVERYMCASTPORT 3702 #define PONVIF_DEFAULT_DISCOVERYTIMEOUT 12 -#define PONVIF_PACK_DISCOVERY "uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probedn:NetworkVideoTransmitter" -#define PONVIF_PACK_GET_SYS_DTS "" -#define PONVIF_PACK_GET_CAPABILITIES "%s%s%s%sAll" -#define PONVIF_PACK_GET_VIDEO_SOURCES "%s%s%s%s" -#define PONVIF_PACK_GET_PROFILES "%s%s%s%s" -#define PONVIF_PACK_GET_SERVICES "%s%s%s%sfalse" -#define PONVIF_PACK_GET_DEV_INFO "%s%s%s%s" -#define PONVIF_PACK_GET_STREAM_URI "%s%s%s%s%%STREAM%%%%PROTOCOL%%%%PROFILETOKEN%%" -#define PONVIF_PACK_GET_PICTURE_URI "%s%s%s%s%s" -#define PONVIF_PACK_GET_PRESETS "%s%s%s%s%s" -#define PONVIF_PACK_GET_PTZ_NODE "%s%s%s%s%s" -#define PONVIF_PACK_GET_PTZ_STATUS "%s%s%s%s%s" -#define PONVIF_PACK_GOTO_PRESET "%s%s%s%s%s%s" -#define PONVIF_PACK_REMOVE_PRESET "%s%s%s%s%s%s" -#define PONVIF_PACK_SET_PRESET "%s%s%s%s%s%s" -#define PONVIF_PACK_RELATIVE_MOVE "%s%s%s%s%s" -#define PONVIF_PACK_RELATIVE_ZOOM "%s%s%s%s%s" -#define PONVIF_PACK_ABSOLUTE_MOVE "%s%s%s%s%s" -#define PONVIF_PACK_CONTINUOUS_MOVE "%s%s%s%s%s" -//#define PONVIF_PACK_CONTINUOUS_MOVE_A "Profile_1" -#define PONVIF_PACK_CONTINUOUS_ZOOM "%s%s%s%s%s" -#define PONVIF_PACK_PTZ_STOP "%s%s%s%s%struetrue" - -#define PONVIF_ENVELOPE_EXT "%s%s" -#define PONVIF_ENVELOPE_SIM "%s%s" -#define PONVIF_BODY "%s" -#define PONVIF_HEADER_PROBE "uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probe" -#define PONVIF_HEADER_SECUR "%s%s%s%s" - -#define PONVIF_PCK_GET_CAPABILITIES "All" +#define PONVIF_PACK_DISCOVERY (CSTR)"uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probedn:NetworkVideoTransmitter" +#define PONVIF_PACK_GET_SYS_DTS (CSTR)"" +#define PONVIF_PACK_GET_CAPABILITIES (CSTR)"%s%s%s%sAll" +#define PONVIF_PACK_GET_VIDEO_SOURCES (CSTR)"%s%s%s%s" +#define PONVIF_PACK_GET_PROFILES (CSTR)"%s%s%s%s" +#define PONVIF_PACK_GET_SERVICES (CSTR)"%s%s%s%sfalse" +#define PONVIF_PACK_GET_DEV_INFO (CSTR)"%s%s%s%s" +#define PONVIF_PACK_GET_STREAM_URI (CSTR)"%s%s%s%s%%STREAM%%%%PROTOCOL%%%%PROFILETOKEN%%" +#define PONVIF_PACK_GET_PICTURE_URI (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_GET_PRESETS (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_GET_PTZ_NODE (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_GET_PTZ_STATUS (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_GOTO_PRESET (CSTR)"%s%s%s%s%s%s" +#define PONVIF_PACK_REMOVE_PRESET (CSTR)"%s%s%s%s%s%s" +#define PONVIF_PACK_SET_PRESET (CSTR)"%s%s%s%s%s%s" +#define PONVIF_PACK_RELATIVE_MOVE (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_RELATIVE_ZOOM (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_ABSOLUTE_MOVE (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_CONTINUOUS_MOVE (CSTR)"%s%s%s%s%s" +//#define PONVIF_PACK_CONTINUOUS_MOVE_A (CSTR)"Profile_1" +#define PONVIF_PACK_CONTINUOUS_ZOOM (CSTR)"%s%s%s%s%s" +#define PONVIF_PACK_PTZ_STOP (CSTR)"%s%s%s%s%struetrue" + +#define PONVIF_ENVELOPE_EXT (CSTR)"%s%s" +#define PONVIF_ENVELOPE_SIM (CSTR)"%s%s" +#define PONVIF_BODY (CSTR)"%s" +#define PONVIF_HEADER_PROBE (CSTR)"uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probe" +#define PONVIF_HEADER_SECUR (CSTR)"%s%s%s%s" + +#define PONVIF_PCK_GET_CAPABILITIES (CSTR)"All" typedef struct S_accessToken{ char USERNAME[CTEXT]; @@ -393,12 +404,16 @@ typedef struct S_ptzStatus{ bool ZoomIdle; }ptzStatus; +class pOnvif; + typedef std::vector videoSourceProfiles; typedef std::vector videoSources; typedef std::vector discoveryResults; class pOnvif{ - private: + private: + curlRequestsManager * m_pHttpAccessManager; + basicMutex m_mResponseProtector; CURL * m_pCURL; basicLogCollection * m_pLog; CSTR m_pIpAddress; @@ -428,13 +443,11 @@ class pOnvif{ CSTR m_pDiscoveryMCastIP; int m_nDiscoveryMCastPort; bool m_bDiscoveryHideDuplicates; - /* - char UP[128]; - char HEADER_STR1[128]; - char HEADER_STR2[128]; - struct curl_slist * HEADER; - */ - static int _writer( char *data, size_t size, size_t nmemb, pOnvif *Ptr ); + bool parser_done; +#ifndef CURL_MANAGER + static int _writer( char *data, size_t size, size_t nmemb, pOnvif *Ptr ); +#endif + static void * parser( void *obj, void *ptr ); public: pOnvif(); ~pOnvif(); @@ -481,7 +494,7 @@ class pOnvif{ bool media_GetVideoSources(); bool media_GetProfiles(); bool media_GetServices(); - CSTR media_GetStreamUri( CSTR profileToken, CSTR stream="RTP-Unicast", CSTR protocol="RTSP" ); + CSTR media_GetStreamUri( CSTR profileToken, CSTR stream=(CSTR)"RTP-Unicast", CSTR protocol=(CSTR)"RTSP" ); CSTR media_GetSnapshotUri( CSTR profileToken ); bool ptz_GetPresets( CSTR profileToken ); @@ -506,7 +519,8 @@ class pOnvif{ void _getProfileData( videoSourceProfiles &videoSources, videoSourceProfiles profiles ); //protected function _xml2array($response); accessToken _passwordDigest( CSTR username, CSTR password, time_t timestamp = 0, uint32_t nonce = 0 ); - bool _send_request( CSTR url, CSTR post_string ); + bool _send_request( CSTR url, CSTR post_string, bool mr=true ); + bool _post_request( CSTR url, CSTR post_string ); }; #endif diff --git a/lib/data/protocol/protocolHTTP.cpp b/lib/data/protocol/protocolHTTP.cpp index f18f3520..0bf914bd 100644 --- a/lib/data/protocol/protocolHTTP.cpp +++ b/lib/data/protocol/protocolHTTP.cpp @@ -40,7 +40,8 @@ protocolHTTP::~protocolHTTP(){ m_pHttpAccessManager = NULL; }; -bool protocolHTTP::issueGet(CSTR URL){ +bool protocolHTTP::issueGet(CSTR URL){ + /* curlRequest *tRequest = new curlRequest(URL, m_pCurlPostType ); if (tRequest != NULL){ tRequest->setHandler(this, &protocolHTTP::requestFinished, tRequest); @@ -49,11 +50,14 @@ bool protocolHTTP::issueGet(CSTR URL){ } else { LOG_ERROR("Cannot issue request!"); }; - }; - return true; + } + return true; + ;*/ + return m_pHttpAccessManager->get( URL, m_pCurlPostType ); }; bool protocolHTTP::issuePost(CSTR URL, char *Buffer, int &BufferSize ){ + /* curlRequest *tRequest = new curlRequest(URL, m_pCurlPostType); if (tRequest != NULL){ tRequest->setPOST( Buffer, BufferSize ); @@ -63,8 +67,10 @@ bool protocolHTTP::issuePost(CSTR URL, char *Buffer, int &BufferSize ){ } else { LOG_ERROR("Cannot issue request!"); }; - }; - return true; + } + return true; + ;*/ + return m_pHttpAccessManager->post( URL, Buffer, m_pCurlPostType ); }; void *protocolHTTP::requestFinished(void *ptr1, void *ptr2){ diff --git a/lib/data/protocol/protocolLGS.cpp b/lib/data/protocol/protocolLGS.cpp index d72fe4b7..569e8bd0 100644 --- a/lib/data/protocol/protocolLGS.cpp +++ b/lib/data/protocol/protocolLGS.cpp @@ -3,7 +3,15 @@ #define LOG( X ) m_pLog->Log( "LGSP", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "LGSP", this, _LOG_ERROR, X ) -inline int FinishUpPackage(U8* Buffer, size_t Size, U8 DeviceID) { +#define SIZE_IDX 1 +#define DEV_ID_IDX 2 +#define CMD_IDX 3 +#define SUB_CMD_IDX 4 +#define DATA_BEGIN_IDX 5 + +#undef PACKET_MULTIBYTE_SIZE + +inline size_t FinishUpPackage(U8* Buffer, size_t Size, U8 DeviceID) { Buffer[0] = 0x55; #ifdef PACKET_MULTIBYTE_SIZE Buffer[SIZE_IDX_A] = ((Size - 2) >> 8) | SEND_TAG; @@ -139,13 +147,13 @@ bool protocolLGS_CLIENT::getParameters( void ){ return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); }; -bool protocolLGS_CLIENT::setParameters( PLGS_PARAMETERS ptr ){ +bool protocolLGS_CLIENT::setParameters(PLGS_2D_PARAMETERS ptr ){ if( m_oDataTransport == NULL ) return false; U8 counter; U8 Buffer[64]; Buffer[CMD_IDX] = CMD_SET_PARAMETERS; counter = SUB_CMD_IDX; - for( int i=0; i < sizeof( LGS_PARAMETERS ); i++ ){ + for( int i=0; i < sizeof(LGS_2D_PARAMETERS); i++ ){ Buffer[counter] = *(((U8*)ptr)+i); counter++; }; @@ -231,9 +239,9 @@ bool protocolLGS_CLIENT::setShadowStatus( bool Status, uint8_t MaskID ){ bool protocolLGS_CLIENT::setShadowTrace( vectorZoneMask *VM ){ if( VM == NULL ) return false; if( m_oDataTransport == NULL ) return false; - uint16_t counter; - uint8_t Buffer[PROTOCOL_PARSER_BUFFER_SIZE]; - uint16_t tVal; + uint16_t counter; + uint8_t Buffer[PROTOCOL_PARSER_BUFFER_SIZE]; + size_t tVal; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; tVal = VM->size(); Buffer[SUB_CMD_IDX] = ( tVal >> 8 ) & 0xFF; @@ -477,7 +485,7 @@ bool protocolLGS_SERVER::sendState2(U8 State, U8 bTargetsCount, U8 *pTargetsData }; }; -bool protocolLGS_SERVER::sendParameters(PLGS_PARAMETERS ptr){ +bool protocolLGS_SERVER::sendParameters(PLGS_2D_PARAMETERS ptr){ if( m_oDataTransport == NULL ) return false; if( ptr != NULL ) { U8 counter; @@ -486,7 +494,7 @@ bool protocolLGS_SERVER::sendParameters(PLGS_PARAMETERS ptr){ Buffer[CMD_IDX] = CMD_PARAMETERS; Buffer[SUB_CMD_IDX] = SUB_DATA_INTEGRITY_VALID; counter = 6; - for( int i=0; i < sizeof( LGS_PARAMETERS ); i++ ){ + for( int i=0; i < sizeof(LGS_2D_PARAMETERS); i++ ){ Buffer[counter] = *(((U8*)ptr)+i); counter++; }; @@ -601,5 +609,11 @@ bool protocolLGS_SERVER::sendGenericACK(bool Status){ return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); }; +#undef SIZE_IDX +#undef DEV_ID_IDX +#undef CMD_IDX +#undef SUB_CMD_IDX +#undef DATA_BEGIN_IDX + #undef LOG #undef LOG_ERROR diff --git a/lib/data/protocol/protocolLGS.h b/lib/data/protocol/protocolLGS.h index 0002058c..4ef68b47 100644 --- a/lib/data/protocol/protocolLGS.h +++ b/lib/data/protocol/protocolLGS.h @@ -30,7 +30,7 @@ class protocolLGS_CLIENT: public protocolLGSM{ bool setShadowPoly( simplePolygone *SP ); bool setShadowStatus( bool Status, uint8_t MaskID = 0 ); bool setShadowTrace( vectorZoneMask *VM ); - bool setParameters( PLGS_PARAMETERS ptr ); + bool setParameters(PLGS_2D_PARAMETERS ptr ); }; @@ -47,7 +47,7 @@ class protocolLGS_SERVER: public protocolLGSM{ bool sendEvent( uint8_t Code); bool sendFlip( uint16_t Count); bool sendMode( uint8_t Mode); - bool sendParameters( PLGS_PARAMETERS ptr ); + bool sendParameters(PLGS_2D_PARAMETERS ptr ); bool sendScan( void ); bool sendShadowInfo( ShadowMask *ShObj ); bool sendShadowStatus( bool Status, uint8_t ShadowID = 0 ); diff --git a/lib/data/protocol/protocolLGS2D.cpp b/lib/data/protocol/protocolLGS2D.cpp index cb9fa3c4..a5cda6d8 100644 --- a/lib/data/protocol/protocolLGS2D.cpp +++ b/lib/data/protocol/protocolLGS2D.cpp @@ -42,7 +42,7 @@ int protocolLGS_2D::FinishUpPackage( uint8_t *Buffer, size_t Size, uint8_t Devic Buffer[SIZE_IDX] = ((Size - 2) & 0xFF) | SEND_TAG; Buffer[DEV_ID_IDX] = DeviceID; Buffer[Size] = checksumLGS( Buffer, Size ); - return Size + 1; + return (int)(Size + 1); }; int protocolLGS_2D::packetChecker(U8 *Buffer, size_t BufferSize ){ @@ -351,7 +351,7 @@ bool protocolLGS_2D::setShadowTrace( vectorZoneMask *VM ){ uint8_t Buffer[PROTOCOL_PARSER_BUFFER_SIZE]; uint16_t tVal; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; - tVal = VM->size(); + tVal = (uint16_t)VM->size(); Buffer[SUB_CMD_IDX] = ( tVal >> 8 ) & 0xFF; Buffer[SUB_CMD_IDX+1] = tVal & 0xFF; counter = SUB_CMD_IDX+2; diff --git a/lib/data/protocol/protocolLGSm.h b/lib/data/protocol/protocolLGSm.h index b5c15ee8..0f9849e8 100644 --- a/lib/data/protocol/protocolLGSm.h +++ b/lib/data/protocol/protocolLGSm.h @@ -6,10 +6,11 @@ #include "../../components/base/basicMutex.h" #include "../../components/base/basicEventHeap.h" #include "../../hardware/soc/general/3DLRF.h" -#include "../../alg/lgs/mask.h" - #include "protocol.h" #include "protocolLGS_data.h" +#include "../../alg/lgs/mask.h" +#include "../../alg/lgs/detectorStructures.h" + #ifdef _CLIENT_APPLICATION_ #define SEND_TAG MASTER_TAG diff --git a/lib/data/protocol/protocolPTZ_ONVIF.cpp b/lib/data/protocol/protocolPTZ_ONVIF.cpp index 54de8407..4031758f 100644 --- a/lib/data/protocol/protocolPTZ_ONVIF.cpp +++ b/lib/data/protocol/protocolPTZ_ONVIF.cpp @@ -3,12 +3,18 @@ #define LOG( X ) m_pLog->Log( "ONVIF", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "ONVIF", this, _LOG_ERROR, X ) - + protocolPTZ_ONVIF::protocolPTZ_ONVIF( config_setting_t *Settings ) :protocolPTZ(), m_mInquiryMutex(){ m_pLog = basicLogCollection::getInstance(); m_bLastCommandIssued = CMD_PTZ_NOOP; m_pSettings = Settings; +#ifdef USE_PONVIF m_pOnVif = NULL; + m_pProfile = NULL; +#else + m_pDevice = NULL; + m_pPTZ = NULL; +#endif memset( m_pDeviceURI, 0, MAX_PATH_LEN ); memset( m_pUser, 0, MAX_CRED_LEN ); memset( m_pPassword, 0, MAX_CRED_LEN ); @@ -18,11 +24,18 @@ protocolPTZ_ONVIF::protocolPTZ_ONVIF( CSTR ip, CSTR username, CSTR password ) :p m_pLog = basicLogCollection::getInstance(); m_bLastCommandIssued = CMD_PTZ_NOOP; m_pSettings = NULL; +#ifdef USE_PONVIF m_pOnVif = NULL; + m_pProfile = NULL; +#else + m_pDevice = NULL; + m_pPTZ = NULL; +#endif LOG( ip ); LOG( username ); LOG( password ); - strncpy( m_pDeviceURI, ip, MAX_PATH_LEN ); + sprintf( m_pDeviceURI, "http://%s/onvif/device_service", ip ); + //strncpy( m_pDeviceURI, ip, MAX_PATH_LEN ); strncpy( m_pUser, username, MAX_CRED_LEN ); strncpy( m_pPassword, password, MAX_CRED_LEN ); }; @@ -31,16 +44,22 @@ protocolPTZ_ONVIF::~protocolPTZ_ONVIF(){ }; bool protocolPTZ_ONVIF::setIPAddress( CSTR ip ){ + if( ip== NULL ) return false; if( strlen(ip) == 0 ) return false; - strncpy( m_pDeviceURI, ip, MAX_PATH_LEN ); + sprintf( m_pDeviceURI, "http://%s/onvif/device_service", ip ); + //strncpy( m_pDeviceURI, ip, MAX_PATH_LEN ); return true; }; + bool protocolPTZ_ONVIF::setUsername( CSTR username ){ + if( username == NULL ) return false; if( strlen(username) == 0 ) return false; strncpy( m_pUser, username, MAX_CRED_LEN ); return true; }; + bool protocolPTZ_ONVIF::setPassword( CSTR password ){ + if( password == NULL ) return false; if( strlen(password) == 0 ) return false; strncpy( m_pPassword, password, MAX_CRED_LEN ); return true; @@ -66,17 +85,20 @@ bool protocolPTZ_ONVIF::create( void ){ if (pSetting == NULL) return false; sprintf( m_pDeviceURI, "%s", config_setting_get_string(pSetting)); }; +#ifdef DEBUG LOG( m_pDeviceURI ); +#endif if( strlen( m_pDeviceURI ) < 4 ){ LOG_ERROR("No Device URI Is Set!"); return false; }; +#ifdef USE_PONVIF m_pOnVif = new pOnvif(); if( m_pOnVif == NULL ){ LOG_ERROR("PONVIF NEW FAILURE!"); return false; }; - m_pOnVif->setIPAddress( m_pDeviceURI ); + m_pOnVif->setDeviceUri( m_pDeviceURI ); m_pOnVif->setUsername( m_pUser ); m_pOnVif->setPassword( m_pPassword ); LOG("PONVIF BEFORE CREATE"); @@ -90,11 +112,52 @@ bool protocolPTZ_ONVIF::create( void ){ delete( m_pOnVif ); m_pOnVif = NULL; }; +#else + std::string A(m_pUser); + std::string B(m_pPassword); + std::string C(m_pDeviceURI); + m_pDevice = new OnvifClientDevice(C, A, B); + if (m_pDevice != NULL){ + m_pPTZ = new OnvifClientPTZ(*m_pDevice); + if (m_pPTZ!=NULL){ + _tptz__GetNodesResponse tNodes; + int RetVal; + RetVal = m_pPTZ->GetNodes(tNodes); + if (RetVal == 0){ + OnvifClientMedia media(*m_pDevice); + _trt__GetProfilesResponse profiles; + media.GetProfiles(profiles); + m_pPTZToken = profiles.Profiles.at(0)->token;// PTZConfiguration->token; + //m_pPTZToken = tNodes.PTZNode.at(0)->token; + //_tptz__GetConfigurationOptionsResponse COResp; + //int RetVal = m_pPTZ->GetConfigurationOptions(COResp, m_pToken); + //_tptz__GetConfigurationResponse configResponce; + //configResponce.PTZConfiguration = new tt__PTZConfiguration(); + //m_pPTZ->GetConfiguration(configResponce); + //m_pToken = configResponce.PTZConfiguration->token; + setConnectionStatus(CS_CONNECTED); + m_bStatus = 1; + return true; + }; + }; + }; +#endif return false; }; +#ifndef USE_PONVIF +bool protocolPTZ_ONVIF::initCamera(void){ + if (m_bStatus == 0) return false; + //if (m_bReplyRequired) if ( m_bLastCommandIssued != CMD_PTZ_NOOP ) return false; + m_bLastCommandIssued = CMD_PTZ_INIT; + m_pPTZ->Initialize(); + return true; +}; +#endif + bool protocolPTZ_ONVIF::move( uint32_t MoveMatrix ){ - //if( m_bStatus == 0 ) return false; + //if( m_bStatus == 0 ) return false; +#ifdef USE_PONVIF if( m_pProfile == NULL ) return false; //if (m_bReplyRequired) if (m_bLastCommandIssued != CMD_PTZ_NOOP) return false; float Speed_x, Speed_y, Speed_z; @@ -133,12 +196,49 @@ bool protocolPTZ_ONVIF::move( uint32_t MoveMatrix ){ } else { return m_pOnVif->ptz_Stop( m_pProfile->profiletoken, true, true ); }; - return false; + return false; +#else + if (m_bStatus == 0) return false; + //if (m_bReplyRequired) if (m_bLastCommandIssued != CMD_PTZ_NOOP) return false; + _tptz__ContinuousMoveResponse ContMoveResponse; + tt__PTZSpeed tSpeed; + tSpeed.PanTilt = new tt__Vector2D(); + tSpeed.Zoom = new tt__Vector1D(); + LONG64 to = 1000; + int RetVal; + if ((MoveMatrix & PTZ_DRIVE_PAN_MASK) == 0){ + tSpeed.PanTilt->x = 0.0; + } else if ((MoveMatrix & PTZ_DRIVE_PAN_LEFT) != 0){ + tSpeed.PanTilt->x = -m_dPanSpeed; + } else { + tSpeed.PanTilt->x = m_dPanSpeed; + }; + if ((MoveMatrix & PTZ_DRIVE_TILT_MASK) == 0){ + tSpeed.PanTilt->y = 0.0; + } else if ((MoveMatrix & PTZ_DRIVE_TILT_UP) != 0){ + tSpeed.PanTilt->y = m_dTiltSpeed; + } else { + tSpeed.PanTilt->y = -m_dTiltSpeed; + }; + if ((MoveMatrix & PTZ_DRIVE_ZOOM_MASK) == 0){ + tSpeed.Zoom->x = 0.0; + } else if ((MoveMatrix & PTZ_DRIVE_ZOOM_WIDE) != 0){ + tSpeed.Zoom->x = m_dZoomSpeed; + } else { + tSpeed.Zoom->x = -m_dZoomSpeed; + }; + RetVal = m_pPTZ->ContinuousMove(ContMoveResponse, tSpeed, to, m_pPTZToken); + delete(tSpeed.PanTilt); + delete(tSpeed.Zoom); + if (RetVal) return false; + return true; +#endif }; #include bool protocolPTZ_ONVIF::goAbsolute( float dPan, float dTilt, float dZoom ){ +#ifdef USE_PONVIF //if (m_bStatus == 0) return false; //LOG("ABS Move"); if( m_pProfile == NULL ){ @@ -168,6 +268,32 @@ bool protocolPTZ_ONVIF::goAbsolute( float dPan, float dTilt, float dZoom ){ } else LOG_ERROR("Error Fetching PTZ Status!"); }; return false; +#else + if (m_bStatus == 0) return false; + //if (m_bReplyRequired) if (m_bLastCommandIssued != CMD_PTZ_NOOP) return false; + _tptz__AbsoluteMoveResponse AbsMoveResponse; + tt__PTZSpeed tSpeed; + tt__PTZVector tPos; + tSpeed.PanTilt = new tt__Vector2D(); + tSpeed.Zoom = new tt__Vector1D(); + tSpeed.PanTilt->x = 1.f; + tSpeed.PanTilt->y = 1.f; + tSpeed.Zoom->x = 1.f; + + tPos.PanTilt = new tt__Vector2D(); + tPos.Zoom = new tt__Vector1D(); + tPos.PanTilt->x = dPan; + tPos.PanTilt->y = dTilt; + tPos.Zoom->x = dZoom; + + int RetVal; + RetVal = m_pPTZ->AbsoluteMove(AbsMoveResponse, tSpeed, tPos, m_pPTZToken); + delete(tSpeed.PanTilt); + delete(tSpeed.Zoom); + delete(tPos.PanTilt); + delete(tPos.Zoom); + return true; +#endif }; diff --git a/lib/data/protocol/protocolPTZ_ONVIF.h b/lib/data/protocol/protocolPTZ_ONVIF.h index ac190719..09b05e86 100644 --- a/lib/data/protocol/protocolPTZ_ONVIF.h +++ b/lib/data/protocol/protocolPTZ_ONVIF.h @@ -2,8 +2,13 @@ #define __PROTOCOL_PTZ_ONVIF_HEADER__ #include "protocolPTZ.h" -//#include "../onvif/include/onvifclient.hpp" -#include "../data/ponvif/ponvif.h" +#define USE_PONVIF + +#ifdef USE_PONVIF + #include "../ponvif/ponvif.h" +#else + #include "../onvif/include/onvifclient.hpp" +#endif class protocolPTZ_ONVIF: public protocolPTZ{ private: @@ -11,8 +16,15 @@ class protocolPTZ_ONVIF: public protocolPTZ{ char m_pUser[MAX_CRED_LEN]; char m_pPassword[MAX_CRED_LEN]; char m_pDeviceURI[MAX_PATH_LEN]; +#ifdef USE_PONVIF pOnvif * m_pOnVif; videoSourceProfile * m_pProfile; +#else + OnvifClientDevice * m_pDevice; + OnvifClientPTZ * m_pPTZ; + std::string m_pPTZToken; + std::string m_pMediaToken; +#endif config_setting_t * m_pSettings; basicMutex m_mInquiryMutex; public: @@ -20,6 +32,9 @@ class protocolPTZ_ONVIF: public protocolPTZ{ protocolPTZ_ONVIF( CSTR ip, CSTR username, CSTR password ); virtual ~protocolPTZ_ONVIF(); virtual bool create( void ); +#ifndef USE_PONVIF + bool initCamera( void ); +#endif virtual bool move( uint32_t MoveMatrix ); virtual bool goAbsolute( float dPan, float dTilt, float dZoom ); diff --git a/lib/data/transport/transportSerial.cpp b/lib/data/transport/transportSerial.cpp index 9c34b55e..d89d18ab 100644 --- a/lib/data/transport/transportSerial.cpp +++ b/lib/data/transport/transportSerial.cpp @@ -14,25 +14,18 @@ transportSerial::transportSerial() :basicTransport(), basicDualThread(){ m_pOutputBuffer = ( U8 * ) malloc ( MAXIMAL_SERIAL_PACKET_LENGTH ); if( m_pOutputBuffer != NULL ) { m_nOutputBufferSize = 0; - //LOG("Starting"); - //init(); // Moved to SerialPort }; }; }; transportSerial::~transportSerial(){ - //waitThreadAEnd( true ); - //waitThreadBEnd( true ); Moved to SerialPort - if( m_pInputBuffer != NULL ) { - free(m_pInputBuffer); - }; - if( m_pOutputBuffer != NULL ) { - free(m_pOutputBuffer); - }; + if( m_pInputBuffer != NULL ) free( m_pInputBuffer ); + if( m_pOutputBuffer != NULL ) free( m_pOutputBuffer ); }; //void *transportSerial::senderProc( void *param ){ void transportSerial::m_fThreadAProc( void ){ m_bThreadAStatus = TH_WORKING; + uint32_t nSleepTime = 1; #ifdef DEBUG_COMMUNICATION LOG("Output Thread Started"); #endif @@ -45,7 +38,7 @@ void transportSerial::m_fThreadAProc( void ){ #ifdef DEBUG_COMMUNICATION LOG("Buffer ready to Send"); #endif - while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){ + while( (index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED) ){ RetVal = sendBlock( m_pOutputBuffer + index, m_nOutputBufferSize - index ); if( RetVal > 0 ) index += RetVal; if (RetVal < 0) { @@ -57,16 +50,20 @@ void transportSerial::m_fThreadAProc( void ){ LOG("Buffer is Sent"); #endif m_nOutputBufferSize = 0; - }; + nSleepTime = 1; + } else { + nSleepTime = 10; + }; m_mBufferProtectorMutex.unlock(); - //SLEEP(10); - SLEEP(1); + SLEEP( nSleepTime ); }; }; //void *transportSerial::receiverProc( void *param ){ + void transportSerial::m_fThreadBProc(void){ m_bThreadBStatus = TH_WORKING; + uint32_t nSleepTime = 1; #ifdef DEBUG_COMMUNICATION LOG("Input Thread Started"); #endif @@ -75,6 +72,7 @@ void transportSerial::m_fThreadBProc(void){ if (retVal < 0) { setConnectionStatus(CS_DISCONNECTED); m_bThreadBStatus = TH_ENDED; + continue; } else { if (m_nInputBufferSize > 0 && m_bThreadBStatus == TH_WORKING) { m_mQueueProtectorMutex.lock(); @@ -84,10 +82,13 @@ void transportSerial::m_fThreadBProc(void){ } }; m_mQueueProtectorMutex.unlock(); - }; - //SLEEP(5); - SLEEP(1); + nSleepTime = 1; + } else { + nSleepTime = 10; + if( m_bThreadBStatus != TH_WORKING ) continue; + }; }; + SLEEP( nSleepTime ); }; }; diff --git a/lib/hardware/hid/hid_dc.h b/lib/hardware/hid/hid_dc.h index 28c8403c..964acf83 100644 --- a/lib/hardware/hid/hid_dc.h +++ b/lib/hardware/hid/hid_dc.h @@ -14,7 +14,7 @@ typedef struct S_DC_BOARD{ char serial[HID_DCR_SERIIAL_LENGTH+1]; unsigned char relay_count; unsigned char state; - char * path; + char path[MAX_PATH_LEN]; } DC_BOARD; //Public methods diff --git a/lib/hardware/socat-1.7.3.4/configure b/lib/hardware/socat-1.7.3.4/configure old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/daemon.sh b/lib/hardware/socat-1.7.3.4/daemon.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/ftp.sh b/lib/hardware/socat-1.7.3.4/ftp.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/gatherinfo.sh b/lib/hardware/socat-1.7.3.4/gatherinfo.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/install-sh b/lib/hardware/socat-1.7.3.4/install-sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/mail.sh b/lib/hardware/socat-1.7.3.4/mail.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/proxy.sh b/lib/hardware/socat-1.7.3.4/proxy.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/proxyecho.sh b/lib/hardware/socat-1.7.3.4/proxyecho.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/readline-test.sh b/lib/hardware/socat-1.7.3.4/readline-test.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/readline.sh b/lib/hardware/socat-1.7.3.4/readline.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/socat_buildscript_for_android.sh b/lib/hardware/socat-1.7.3.4/socat_buildscript_for_android.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/socks4a-echo.sh b/lib/hardware/socat-1.7.3.4/socks4a-echo.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/socks4echo.sh b/lib/hardware/socat-1.7.3.4/socks4echo.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/socat-1.7.3.4/test.sh b/lib/hardware/socat-1.7.3.4/test.sh old mode 100755 new mode 100644 diff --git a/lib/hardware/uart/serialSOL.cpp b/lib/hardware/uart/serialSOL.cpp index c58e0634..3297ee17 100644 --- a/lib/hardware/uart/serialSOL.cpp +++ b/lib/hardware/uart/serialSOL.cpp @@ -39,14 +39,18 @@ bool serialSOL::closePort(){ if( m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT ){ uninit(); }; - if( m_nSocketFD != -1 ) { +#ifdef __linux__ + if( m_nSocketFD != -1 ){ +#else + if( m_sSocket != INVALID_SOCKET ){ +#endif switch( m_eType ) { case SOL_UDP_CLIENT: case SOL_TCP_CLIENT: case SOL_UDP_SERVER: { - #ifdef __linux__ +#ifdef __linux__ close( m_nSocketFD ); - #else +#else // When your application is finished receiving datagrams close the socket. LOG("Server: Finished receiving.Closing the listening socket..."); if( closesocket(m_sSocket) != 0 ){ @@ -63,15 +67,38 @@ bool serialSOL::closePort(){ } else { LOG("WSACleanup() is OK"); }; - #endif +#endif break; }; case SOL_TCP_SERVER:{ - close( m_nSocketFD ); +#ifdef __linux__ + close(m_nSocketFD); +#else + // When your application is finished receiving datagrams close the socket. + LOG("Server: Finished receiving.Closing the listening socket..."); + if (closesocket(m_sSocket) != 0) { + sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + } else { + LOG("closesocket() is OK..."); + }; + // When your application is finished call WSACleanup. + LOG("Server: Cleaning up..."); + if (WSACleanup() != 0) { + sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + } else { + LOG("WSACleanup() is OK"); + }; +#endif break; }; }; +#ifdef __linux__ m_nSocketFD = -1; +#else + m_sSocket = INVALID_SOCKET; +#endif }; return true; }; @@ -185,14 +212,14 @@ bool serialSOL::create( CSTR address, uint16_t port, int Speed, SOL_TYPE t ){ // Set up a SOCKADDR_IN structure that will tell bind that we // want to receive datagrams from all interfaces using port 5150. // The IPv4 family - ReceiverAddr.sin_family = AF_INET; + m_sServerAddr.sin_family = AF_INET; // Port no. 5150 - ReceiverAddr.sin_port = htons( m_nPort ); + m_sServerAddr.sin_port = htons( m_nPort ); // From all interface (0.0.0.0) - ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY); + m_sServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Associate the address information with the socket using bind. // At this point you can receive datagrams on your bound socket. - if( bind(m_sSocket, (SOCKADDR*)&ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR ){ + if( bind(m_sSocket, (SOCKADDR*)&m_sServerAddr, sizeof(m_sServerAddr)) == SOCKET_ERROR ){ sprintf( tBuff, "Server: bind() failed!Error : %ld.", WSAGetLastError()); // Close the socket closesocket(m_sSocket); @@ -248,11 +275,19 @@ bool serialSOL::create( CSTR address, uint16_t port, int Speed, SOL_TYPE t ){ LOG("PORT IS SERVER - Create TCP Client"); #endif // socket create and varification +#ifdef __linux__ m_nSocketFD = socket( AF_INET, SOCK_STREAM, 0 ); if( m_nSocketFD == -1) { LOG_ERROR("Socket creation failed!"); return false; } +#else + m_sSocket = socket(AF_INET, SOCK_STREAM, 0); + if (m_sSocket == INVALID_SOCKET ) { + LOG_ERROR("Socket creation failed!"); + return false; + } +#endif #ifdef DEBUG else LOG("Socket successfully created"); #endif @@ -264,7 +299,11 @@ bool serialSOL::create( CSTR address, uint16_t port, int Speed, SOL_TYPE t ){ m_sServerAddr.sin_port = htons( m_nPort ); // connect the client socket to server socket +#ifdef __linux__ if( connect( m_nSocketFD, (struct sockaddr *)&m_sServerAddr, sizeof( struct sockaddr ) ) !=0 ){ +#else + if (connect(m_sSocket, (struct sockaddr*) & m_sServerAddr, sizeof(struct sockaddr)) != 0) { +#endif char cBuffer[128]; sprintf(cBuffer,"ERROR connect to [%s:%d] (%s)", m_cDeviceAddress, m_nPort, strerror(errno) ); LOG_ERROR( cBuffer ); @@ -275,7 +314,8 @@ bool serialSOL::create( CSTR address, uint16_t port, int Speed, SOL_TYPE t ){ #endif // Set non-blocking - int arg; +#ifdef __linux__ + int arg; if( (arg = fcntl( m_nSocketFD, F_GETFL, NULL)) < 0) { char tBuf[128]; sprintf( tBuf, "Error fcntl(..., F_GETFL) (%s)", strerror(errno)); @@ -289,7 +329,15 @@ bool serialSOL::create( CSTR address, uint16_t port, int Speed, SOL_TYPE t ){ LOG_ERROR( tBuf ); return false; }; - +#else + u_long arg = 1; + if (ioctlsocket(m_sSocket, FIONBIO, &arg) < 0) { + char tBuf[128]; + sprintf(tBuf, "Error ioctlsocket(..., FIONBIO) (%s)", strerror(errno)); + LOG_ERROR(tBuf); + return false; + }; +#endif setConnectionStatus( CS_CONNECTED ); break; @@ -340,7 +388,7 @@ int serialSOL::sendBlock(unsigned char* Data, int DataSize) { return -1; }; #else - if (sendto( m_sSocket, (char *)Data, DataSize, 0, (struct sockaddr*) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR) { + if (sendto( m_sSocket, (char *)Data, DataSize, 0, (struct sockaddr*) & m_sServerAddr, sizeof(m_sServerAddr)) == SOCKET_ERROR) { printf("sendto() failed with error code : %d", WSAGetLastError()); exit(EXIT_FAILURE); } @@ -350,31 +398,31 @@ int serialSOL::sendBlock(unsigned char* Data, int DataSize) { int serialSOL::recptBlock( unsigned char *Buffer, int *BufferLength ){ int RetVal = 0; - if( m_eConnectionStatus != CS_CONNECTED ){ +#ifdef __linux__ + if (m_eConnectionStatus != CS_CONNECTED) { //make prep for connection - if( m_eType == SOL_TCP_CLIENT ){ + if (m_eType == SOL_TCP_CLIENT) { //ACCEPT - struct sockaddr ClientAddress; - socklen_t size = (socklen_t) sizeof( struct sockaddr_in ); - int ClientSocket; - m_nSocketFD = accept( m_nMasterSocketFD, &ClientAddress, &size ); - if( m_nSocketFD < 0 ) { - setConnectionStatus( CS_DISCONNECTED ); - LOG_ERROR("Connection Accept Failure!"); - return -1; - }; - } else { - LOG_ERROR("RCPT ON not connected!"); - shutdown( m_nSocketFD, 2 ); - close( m_nSocketFD ); - *BufferLength = 0; - m_nSocketFD = -1; - setConnectionStatus( CS_DISCONNECTED ); - return -1; - }; + struct sockaddr ClientAddress; + size_t size = (size_t) sizeof(struct sockaddr_in); + int ClientSocket; + m_nSocketFD = accept(m_nMasterSocketFD, &ClientAddress, &size); + if (m_nSocketFD < 0) { + setConnectionStatus(CS_DISCONNECTED); + LOG_ERROR("Connection Accept Failure!"); + return -1; + }; + } + else { + LOG_ERROR("RCPT ON not connected!"); + shutdown(m_nSocketFD, 2); + close(m_nSocketFD); + *BufferLength = 0; + m_nSocketFD = -1; + setConnectionStatus(CS_DISCONNECTED); + return -1; + }; }; - -#ifdef __linux__ if( m_nSocketFD > -1 ) { socklen_t addr_len = sizeof( m_sClientAddr ); //len is value/resuslt //RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len ); @@ -398,20 +446,48 @@ int serialSOL::recptBlock( unsigned char *Buffer, int *BufferLength ){ return -1; }; #else - switch ( m_eType ) { - case SOL_UDP_CLIENT: - case SOL_TCP_CLIENT: - case SOL_UDP_SERVER: { - SOCKADDR_IN tAddr; - int tLen = sizeof(SOCKADDR_IN); - RetVal = recvfrom( m_sSocket, (char*)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, 0, (struct sockaddr*) &tAddr, &tLen); - if (RetVal == SOCKET_ERROR){ - char cBuffer[165]; - sprintf(cBuffer,"recvfrom() failed with error code : %d", WSAGetLastError()); - LOG_ERROR(cBuffer); + if (m_eConnectionStatus != CS_CONNECTED) { + //make prep for connection + if (m_eType == SOL_TCP_CLIENT) { + //ACCEPT + int size = sizeof(m_sClientAddr); + //int ClientSocket; + m_sSocket = accept(m_sMasterSocket, (sockaddr *) &m_sClientAddr, &size); + if( m_sSocket == INVALID_SOCKET ){ + setConnectionStatus(CS_DISCONNECTED); + LOG_ERROR("Connection Accept Failure!"); + return -1; + }; + } else { + LOG_ERROR("RCPT ON not connected!"); + shutdown(m_sSocket, 2); + closesocket(m_sSocket); + *BufferLength = 0; + m_sSocket = INVALID_SOCKET; + setConnectionStatus(CS_DISCONNECTED); + return -1; + }; + }; + if( m_sSocket != INVALID_SOCKET ) { + switch (m_eType) { + case SOL_UDP_CLIENT: + case SOL_TCP_CLIENT: + case SOL_UDP_SERVER: { + int tLen = sizeof(m_sClientAddr); + RetVal = recvfrom(m_sSocket, (char*)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, 0, (struct sockaddr*) &m_sClientAddr, &tLen); + if (RetVal == SOCKET_ERROR) { + char cBuffer[165]; + sprintf(cBuffer, "recvfrom() failed with error code : %d", WSAGetLastError()); + LOG_ERROR(cBuffer); + }; + break; }; - break; }; + } else { + LOG_ERROR("Not Connected!"); + *BufferLength = 0; + setConnectionStatus(CS_DISCONNECTED); + return -1; }; #endif if (RetVal > 0) { diff --git a/lib/hardware/uart/serialSOL.h b/lib/hardware/uart/serialSOL.h index 4494aadf..a3efa350 100644 --- a/lib/hardware/uart/serialSOL.h +++ b/lib/hardware/uart/serialSOL.h @@ -64,7 +64,9 @@ class serialSOL: public transportSocket { #else WSADATA wsaData; SOCKET m_sSocket; - SOCKADDR_IN ReceiverAddr; + SOCKET m_sMasterSocket; + SOCKADDR_IN m_sServerAddr; + SOCKADDR_IN m_sClientAddr; int SelectTiming; #endif protected: diff --git a/lib/rgoose/rgooseCamera.cpp b/lib/rgoose/rgooseCamera.cpp index cf06d22d..0d4b6fae 100644 --- a/lib/rgoose/rgooseCamera.cpp +++ b/lib/rgoose/rgooseCamera.cpp @@ -57,18 +57,20 @@ ARGUS_Camera::~ARGUS_Camera(){ waitThreadEnd( true ); LOG("Thread Del OK"); if( m_pTransport!= NULL ) { - DBC_UART_DATA *tData = NULL; - tData = m_pDBC->getUartData( m_sCamData.uart_id ); - switch( tData->type ) { - case UART_TYPE_HARDWARE:{ - delete((serialPort*)m_pTransport); - break; - }; - case UART_TYPE_SOL:{ - delete((serialSOL*)m_pTransport); - break; + if( m_sCamData.uart_id ) { + DBC_UART_DATA *tData = NULL; + tData = m_pDBC->getUartData( m_sCamData.uart_id ); + switch( tData->type ) { + case UART_TYPE_HARDWARE:{ + delete((serialPort*)m_pTransport); + break; + }; + case UART_TYPE_SOL:{ + delete((serialSOL*)m_pTransport); + break; + }; }; - }; + } }; LOG("Transport Del OK"); if( m_pProtocol != NULL ) { @@ -269,10 +271,16 @@ bool ARGUS_Camera::create( uint32_t id ){ }; break; }; + default:{ +#ifdef DEBUG + LOG("Camera Has no defined control protocol"); +#endif + }; }; if( m_pProtocol == NULL ) { - LOG_ERROR("No Proto Created!!"); - m_sCamData.online = false; + if(m_sCamData.protocol == 0 ) { + m_sCamData.online = true; + } else LOG_ERROR("No Proto Created!"); } else { #ifdef DEBUG LOG("Proto is OK"); @@ -764,7 +772,8 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ LOG( tDATA->mrl_proto ); if( strncmp( tDATA->mrl_proto, "v4l2", 4 ) == 0 ){ LOG( tDATA->mrl ); - m_pSource = new videoAVLIBSource( tDATA->mrl ); + m_sMediaSource.mediaStreamId = id; + m_pSource = new videoAVLIBSource( tDATA->mrl, &m_sMediaSource ); } else { char tMRL[1024]; DBC_CAM_DATA *tCAM = m_pDBC->getCamData( tDATA->source_id ); @@ -774,6 +783,8 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ LOG( tMRL ); m_sMediaSource.mediaStreamId = id; m_pSource = new videoAVLIBSource( tMRL, &m_sMediaSource ); + } else { + LOG_ERROR("Error Getting CAM Data!"); }; }; if( m_pSource != NULL ) { @@ -789,10 +800,10 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ free( tDATA ); }; } else { -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("No Video Module!"); #endif - return true; + //return true; }; }; return false; diff --git a/lib/rgoose/rgooseDBConnector.cpp b/lib/rgoose/rgooseDBConnector.cpp index 2649f0d0..b6cc069e 100644 --- a/lib/rgoose/rgooseDBConnector.cpp +++ b/lib/rgoose/rgooseDBConnector.cpp @@ -2017,7 +2017,7 @@ void argusDBC::registerServer(uint32_t SiteID, CSTR identity ){ m_nSiteID = SiteID; char tQBuf[CTEXT]; - sprintf(tQBuf,"INSERT INTO servers SET `site_id`=%d, `identity`='%s', `online`=1 ON DUPLICATE KEY UPDATE `online`=1", SiteID, identity ); + sprintf(tQBuf,"INSERT INTO servers SET `site_id`=%d, `identity`='%s', `online`=1, `ts`=UNIX_TIMESTAMP(now()) ON DUPLICATE KEY UPDATE `ts`=UNIX_TIMESTAMP(now()), `online`=1", SiteID, identity ); #ifdef DEBUG //LOG(tQBuf); #endif @@ -2063,7 +2063,7 @@ void argusDBC::registerServer(uint32_t SiteID, CSTR identity ){ void argusDBC::unregisterServer(uint32_t ServerID, uint32_t NodeID ){ if( setNodeOffline( NodeID ) ){ char tQBuf[CTEXT]; - sprintf(tQBuf,"UPDATE servers SET `online`=0 WHERE `id`=%d", ServerID ); + sprintf(tQBuf,"UPDATE servers SET `online`=0, `ts`=UNIX_TIMESTAMP(now()) WHERE `id`=%d", ServerID ); #ifdef DEBUG LOG(tQBuf); #endif @@ -2582,6 +2582,32 @@ bool argusDBC::updateResourceAUX( uint32_t ResID, uint32_t AUX ){ return false; }; +bool argusDBC::updateServerUtilisation( uint32_t ServerID, uint32_t nCores, float cpu1, float cpu5, float cpu15, float mem, float disk, uint64_t dtsize, uint64_t dcsize, uint64_t mtsize, uint64_t mcsize ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `servers` SET `ts`=UNIX_TIMESTAMP(now()), `cpu_cores`=%d, `stat_cpu1`=%0.2f, `stat_cpu5`=%0.2f, `stat_cpu15`=%0.2f, `stat_mem`=%0.2f, `stat_disk`=%0.2f, `val_mem_tottal`=%" PRIu64 ", `val_mem_current`=%" PRIu64 ", `val_disk_tottal`=%" PRIu64 ", `val_disk_current`=%" PRIu64 " WHERE `id`=%d", + nCores, + cpu1, + cpu5, + cpu15, + mem, + disk, + + dtsize, + dcsize, + mtsize, + mcsize, + ServerID + ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + uint32_t argusDBC::addLocalDCB( uint32_t SiteID, CSTR PATH, CSTR SERIAL, uint8_t CNT, uint32_t status ){ uint32_t RetVal = 0; if( m_bIsConnected ) { @@ -2979,16 +3005,21 @@ DBC_MODULE_EMBED_VIDEO_DATA *argusDBC::getEmbedVideoData( uint32_t ID ){ AAssoc *result; sprintf( tQBuf, "SELECT * FROM `module_embed_video_settings` WHERE `id`=%d", ID ); #ifdef DEBUG - //LOG(tQBuf); + LOG(tQBuf); #endif result = m_pDatabase->Query( tQBuf ); + LOG("Q is issued"); if( result!= NULL ) { + LOG("Result NN"); if( result->size() > 0 ) { + LOG("Result CNT"); Assoc *cArr; tPtr = (DBC_MODULE_EMBED_VIDEO_DATA*)malloc(sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); + LOG("Result ALLOC"); if( tPtr!= NULL ) { + LOG("Result ALLOC OK"); Assoc::iterator it; - memset(tPtr,0,sizeof(DBC_EVT_DATA)); + memset(tPtr,0,sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); cArr = result->at(0); it = cArr->find("web_port"); if( it != cArr->end() ){ @@ -3006,6 +3037,10 @@ DBC_MODULE_EMBED_VIDEO_DATA *argusDBC::getEmbedVideoData( uint32_t ID ){ if( it != cArr->end() ){ tPtr->height = atoi( it->second.c_str() ); }; + it = cArr->find("compression_quality"); + if( it != cArr->end() ){ + tPtr->compression_quality = atoi( it->second.c_str() ); + }; it = cArr->find("ts_x"); if( it != cArr->end() ){ tPtr->ts_x = atoi( it->second.c_str() ); @@ -3094,6 +3129,7 @@ DBC_MODULE_EMBED_VIDEO_DATA *argusDBC::getEmbedVideoData( uint32_t ID ){ }; }; }; + LOG("Del Result"); deleteResult( result ); }; return tPtr; diff --git a/lib/rgoose/rgooseDBConnector.h b/lib/rgoose/rgooseDBConnector.h index c4d6e030..464f67c1 100644 --- a/lib/rgoose/rgooseDBConnector.h +++ b/lib/rgoose/rgooseDBConnector.h @@ -129,6 +129,7 @@ class argusDBC{ bool updateMediaServerStream( uint32_t id, CSTR mrl=NULL, CSTR key = NULL ); bool updateNetworkNode( bool OnlineStatus ); bool updateResourceAUX( uint32_t ResID, uint32_t AUX ); + bool updateServerUtilisation( uint32_t ServerID, uint32_t nCores, float cpu1, float cpu5, float cpu15, float mem, float disk, uint64_t dtsize, uint64_t dcsize, uint64_t mtsize, uint64_t mcsize ); private: static argusDBC * _instance; explicit argusDBC( config_setting_t * Settings = NULL ); diff --git a/lib/rgoose/rgooseHardwareManager.cpp b/lib/rgoose/rgooseHardwareManager.cpp index ebf6574a..be93be2b 100644 --- a/lib/rgoose/rgooseHardwareManager.cpp +++ b/lib/rgoose/rgooseHardwareManager.cpp @@ -23,19 +23,19 @@ argusHardwareManager *argusHardwareManager::_instance = NULL; /** * Returns the single instance of the object. */ -argusHardwareManager* argusHardwareManager::getInstance() { +argusHardwareManager* argusHardwareManager::getInstance( bool cold_start ) { // check if the instance has been created yet if( 0 == _instance ){ // if not, then create it - _instance = new argusHardwareManager; + _instance = new argusHardwareManager( cold_start ); }; // return the single instance return _instance; }; -argusHardwareManager::argusHardwareManager(){ +argusHardwareManager::argusHardwareManager( bool cold_start ){ m_pLog = basicLogCollection::getInstance(); - m_bHardwareEnumerated = false; + //m_bHardwareEnumerated = false; m_nServerNodeID = 0; m_nServerID = 0; m_nSiteID = 0; @@ -49,18 +49,16 @@ argusHardwareManager::argusHardwareManager(){ }; m_pDBC = argusDBC::getInstance(); if( m_pDBC == NULL ) { - LOG_ERROR( "Failure to get DBC Instance!" ); + LOG_ERROR( "Failure to get DBC Instance -> Forced HW Enumeration!" ); + enumerateHardware(); } else { - if( !m_bHardwareEnumerated ){ - enumerateHardware(); - m_bHardwareEnumerated = true; - }; + //enumerateHardware( !cold_start ); loadResources(); }; }; argusHardwareManager::~argusHardwareManager(){ - + unloadResources(); }; void argusHardwareManager::unloadResources( void ){ @@ -138,11 +136,13 @@ void argusHardwareManager::loadResources( void ){ }; }; -void argusHardwareManager::validate( void ){ -#ifdef DEBUG_EXTRA +bool argusHardwareManager::validate( void ){ + bool RetVal = true; +#ifdef DEBUG LOG("Validator"); #endif - if( !m_bHardwareEnumerated ) return; + //if( !m_bHardwareEnumerated ) return;// RetVal; + //enumerateHardware( m_bHardwareEnumerated ); if( m_vResources.size() ) { for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { if( !(*idx)->validate() ) { @@ -152,7 +152,7 @@ void argusHardwareManager::validate( void ){ LOG_ERROR( "HW Resource Creation Failure!" ); } else LOG("Re-Created OK"); } -#ifdef DEBUG_EXTRA +#ifdef DEBUG else LOG("Resource OK!") #endif ; @@ -162,6 +162,11 @@ void argusHardwareManager::validate( void ){ else LOG("No Resources!") #endif ; + //Mem Validator + //size_t memStat; + //memStat = getCurrentRSS(); + //sprintf( MEM_MSG, "MemStat: %d\n", memStat ); + return RetVal; }; int xioctl(int fh, int request, void *arg){ @@ -178,16 +183,13 @@ int xioctl(int fh, int request, void *arg){ #include void argusHardwareManager::enumerateHardware( void ){ - DIR * dFD; - struct dirent * pDR = NULL; char tBuffer[CTEXT]; + DIR * dFD = NULL; + struct dirent * pDR = NULL; struct ifaddrs * ifaddr = NULL; - - - + //ToDo: Check Ability to work without Kernel and DBC if( m_pKernel == NULL ) return; if( m_pDBC == NULL ) return; - if( m_bHardwareEnumerated ) return; #ifdef DEBUG LOG("HW Enumeration Started!"); #endif @@ -295,7 +297,7 @@ void argusHardwareManager::enumerateHardware( void ){ m_pDBC->addResource( m_nSiteID, m_nServerNodeID, ARGUS_HARDWARE_NETWORK_IPV6, addr, tID ); }; }; -#ifdef DEBUG +#ifdef DEBUG_EXTRA sprintf( tBuffer, "Network Interface: %s [%s]", ifa->ifa_name, addr ); LOG(tBuffer); #endif @@ -309,43 +311,40 @@ void argusHardwareManager::enumerateHardware( void ){ //Enumerate USB devices with the given IDs pDevs = hid_enumerate( 0x16c0, 0x05df ); if( pDevs!=NULL ){ - struct hid_device_info * pCDev=pDevs; + struct hid_device_info * pCDev = pDevs; //Count the number of returned devices - for( DCBCount = 0; pCDev!=NULL; DCBCount++ ){ - pCDev = pCDev->next; - }; + for( DCBCount = 0; pCDev!=NULL; DCBCount++ ) pCDev = pCDev->next; //Allocate a buffer for the relays if( DCBCount > 0 ){ DC_BOARD tDCB; //Fill the relay structs pCDev = pDevs; - for( int idx = 0; idx < DCBCount; idx++ ){ + for( int idx = 0; idx < DCBCount; idx++ ){ //Save the path to this device - //pDCB[idx].path = malloc(strlen(pCDev->path)+1); - //memcpy( pDCB[idx].path, pCDev->path, strlen(pCDev->path) + 1 ); - tDCB.path = pCDev->path; - + memset( tDCB.path, 0, MAX_PATH_LEN ); + strncpy( tDCB.path, pCDev->path, MAX_PATH_LEN ); // The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9 tDCB.relay_count = atoi((const char *)&pCDev->product_string[8]); - //Open it to get more details hid_device * handle; - handle = hid_open_path( pCDev->path ); + handle = hid_open_path( tDCB.path ); if( handle ){ unsigned char buf[9]; //Get the features of the device buf[0] = 0x01; - if ( hid_get_feature_report(handle, buf, sizeof(buf)) == -1){ + if( hid_get_feature_report( handle, buf, sizeof(buf)) == -1 ){ LOG_ERROR("hid_get_feature_report"); pCDev = pCDev->next; + hid_close( handle ); continue; }; //Set the serial number (0x0 for termination) - memset( tDCB.serial, 0x0, sizeof( tDCB.serial )); + memset( tDCB.serial, 0x0, (HID_DCR_SERIIAL_LENGTH+1) ); memcpy( tDCB.serial, buf, HID_DCR_SERIIAL_LENGTH ); //Byte 7 in the response contains the target_state of the relays tDCB.state = buf[7]; hid_close( handle ); +#ifdef DEBUG //Output the device enumeration details if verbose is on LOG("HID DCB Found"); sprintf(tBuffer, " Type: %04hx::%04hx", pCDev->vendor_id, pCDev->product_id); @@ -364,7 +363,6 @@ void argusHardwareManager::enumerateHardware( void ){ LOG(tBuffer); sprintf(tBuffer, " Number of Relays = %d", tDCB.relay_count); LOG(tBuffer); -#ifdef DEBUG //If debug are on, output individual relay details for( int k = 0; k < tDCB.relay_count; k++ ){ if( tDCB.state & 1 << k ){ @@ -409,14 +407,14 @@ void argusHardwareManager::enumerateHardware( void ){ }; closedir( dFD ); }; - m_bHardwareEnumerated = true; + //m_bHardwareEnumerated = true; }; uint32_t argusHardwareManager::createResourceUART( CSTR devName ){ uint32_t RetVal = 0; char tBuffer[256]; /* Enumerate BuiltIn Serial */ -#ifdef DEBUG +#ifdef DEBUG_EXTRA sprintf( tBuffer, "Serial Device: %s", devName ); LOG( tBuffer ); #endif @@ -432,7 +430,7 @@ uint32_t argusHardwareManager::createResourceUART( CSTR devName ){ if (-1 == xioctl(fd, TIOCGSERIAL, &ss)){ LOG_ERROR("TIOCGSERIAL"); } else { -#ifdef DEBUG +#ifdef DEBUG_EXTRA sprintf( tBuffer, "Serial Port[Port:0x%X IRQ:%d BB:%d Line:%d Type:%d Flags:%X]", ss.port, ss.irq, @@ -465,7 +463,7 @@ uint32_t argusHardwareManager::createResourceVIDEO( CSTR devName ){ uint32_t RetVal = 0; char tBuffer[256]; /* Enumerate Video Capture */ -#ifdef DEBUG +#ifdef DEBUG_EXTRA sprintf( tBuffer, "Video Source: %s", devName ); LOG( tBuffer ); #endif @@ -505,8 +503,10 @@ uint32_t argusHardwareManager::createResourceVIDEO( CSTR devName ){ return 0; }; if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { +#ifdef DEBUG_EXTRA sprintf(tBuffer, "%s is no video capture device", dev_name); LOG_ERROR( tBuffer ); +#endif close(fd); return 0; }; @@ -516,7 +516,7 @@ uint32_t argusHardwareManager::createResourceVIDEO( CSTR devName ){ if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt)){ //LOG_ERROR("VIDIOC_G_FMT"); } else { -#ifdef DEBUG +#ifdef DEBUG_EXTRA sprintf( tBuffer, "Grabber[%dx%d]",fmt.fmt.pix.width,fmt.fmt.pix.height); LOG( tBuffer ); #endif diff --git a/lib/rgoose/rgooseHardwareManager.h b/lib/rgoose/rgooseHardwareManager.h index bc82f3c4..cf0c7404 100644 --- a/lib/rgoose/rgooseHardwareManager.h +++ b/lib/rgoose/rgooseHardwareManager.h @@ -18,9 +18,9 @@ class argusHardwareManager{ uint32_t m_nServerID; uint32_t m_nSiteID; - bool m_bHardwareEnumerated; + //bool m_bHardwareEnumerated; void loadResources( void ); - void enumerateHardware( void ); + void unloadResources( void ); uint32_t createResourceUART( CSTR devName ); uint32_t createResourceVIDEO( CSTR devName ); @@ -28,14 +28,14 @@ class argusHardwareManager{ uint32_t createResourceNETWORK( CSTR devName ); public: virtual ~argusHardwareManager(); - static argusHardwareManager * getInstance( void ); - void validate( void ); + static argusHardwareManager * getInstance( bool cold_start = true ); + bool validate( void ); argusHardwareResource * requestResource( ARGUS_HARDWARE_PROVIDERS type, uint32_t id ); - DBC_INT_LIST * requestResourcesByType( ARGUS_HARDWARE_PROVIDERS type ); - void unloadResources( void ); + DBC_INT_LIST * requestResourcesByType( ARGUS_HARDWARE_PROVIDERS type ); + void enumerateHardware( void ); private: static argusHardwareManager * _instance; - argusHardwareManager(); + explicit argusHardwareManager( bool cold_start ); }; diff --git a/lib/rgoose/rgooseKernel.cpp b/lib/rgoose/rgooseKernel.cpp index 2dace076..f379ef92 100644 --- a/lib/rgoose/rgooseKernel.cpp +++ b/lib/rgoose/rgooseKernel.cpp @@ -12,7 +12,9 @@ #include "rgooseKernel.h" #include "rgooseFilterAPF.h" -#include +#include +#include +#include #define LOG( X ) m_pLog->Log( "KRNL", this, X ) @@ -31,21 +33,22 @@ argusKernel *argusKernel::_instance = NULL; /** * Returns the single instance of the object. */ -argusKernel* argusKernel::getInstance( config_setting_t *Settings ) { +argusKernel* argusKernel::getInstance( bool cold_start, config_setting_t *Settings ) { // check if the instance has been created yet if( 0 == _instance ){ // if not, then create it - _instance = new argusKernel( Settings ); + _instance = new argusKernel( cold_start, Settings ); }; // return the single instance return _instance; }; -argusKernel::argusKernel( config_setting_t *Settings ):basicThread(), basicEventHandler(){ +argusKernel::argusKernel( bool cold_start, config_setting_t *Settings ):basicThread(), basicEventHandler(){ m_bExitCause = 0; m_nServerID = 0; m_nSiteID = 0; m_pDBC = NULL; + m_bSkipResignComponents = cold_start; m_tTimeTSeconds = time( NULL ); m_pLog = basicLogCollection::getInstance(); m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "KERNEL" ); @@ -81,7 +84,7 @@ argusKernel::~argusKernel(){ #ifdef DEBUG LOG("Deleting Resources"); #endif - m_pHardwareManager->unloadResources(); + //m_pHardwareManager->unloadResources(); #ifdef DEBUG LOG("Unregister Server"); #endif @@ -170,7 +173,7 @@ bool argusKernel::create( void ){ LOG_ERROR("Error Loading Site DATA!"); }; //Init Subcomponents - m_pHardwareManager = argusHardwareManager::getInstance(); + m_pHardwareManager = argusHardwareManager::getInstance( m_bSkipResignComponents ); if( m_pHardwareManager!= NULL ) { m_pHardwareManager->validate(); } else { @@ -271,17 +274,24 @@ void argusKernel::loadFilters(){ break; }; }; + free( tData ); }; }; tList->clear(); }; delete( tList ); + } else { +#ifdef DEBUG + LOG("No Target Filters Assigned!"); +#endif }; }; void argusKernel::unloadFilters(){ if( m_vTargetFilters.size() > 0 ) { +#ifdef DEBUG LOG("Have Filters to Unload"); +#endif for( V_TARGET_FILTERS::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++ ){ switch( (*idx)->getType() ) { case TF_AUTHORISED_PEOPLE_FILTER:{ @@ -291,11 +301,17 @@ void argusKernel::unloadFilters(){ default:{ char tBuffer[64]; sprintf( tBuffer, "Unknown Filter: %d", (*idx)->getType() ); + LOG( tBuffer ); }; }; }; + m_vTargetFilters.clear(); LOG("Unload Filters Done!"); - }; + } else { +#ifdef DEBUG + LOG("No Filters to Unload!"); +#endif + } }; ARGUS_TARGET_FILTER *argusKernel::getFilter( uint32_t id ){ @@ -343,44 +359,45 @@ void argusKernel::m_fThreadProc( void ){ m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ){ m_tTimeTSeconds = time( NULL ); - - // Network IP OnVif Discovery -/* - if( m_pOnvifMediaObserver!= NULL ){ - if( !m_bDiscoveryStarted ) { - if((m_tTimeTSeconds%ONVIF_DISCOVERY_INTERVAL)==0){ -#ifdef DEBUG - LOG("Start OnVIF Discovery"); -#endif - m_pOnvifMediaObserver->startDiscovery(); - m_bDiscoveryStarted = true; - }; - } else { - //* - if((m_tTimeTSeconds%ONVIF_DISCOVERY_INTERVAL)==ONVIF_DISCOVERY_RESULT_TIME){ -#ifdef DEBUG - LOG("Validate IP Cameras"); -#endif - validateCameras(); - m_bDiscoveryStarted = false; - }; - //* / - }; - }; -//*/ -//* - // Web CTRL Event Processing Loop -// if( !m_pDBC->getLastEvents( m_vEvtRecords, lastTSS, lastTMS ) ){ -// // Error In DB Access -// m_bThreadStatus = TH_ENDED; -// m_bExitCause = 1; -// continue; -// }; - -//*/ - if( m_tTimeTSeconds != tTimeTSeconds ){ // Each Second Process + // Process Once per Second + if( m_tTimeTSeconds != tTimeTSeconds ){ tTimeTSeconds = m_tTimeTSeconds; - DBC_KRNL_CMD *tCMD; + struct sysinfo SI; + struct statvfs DI; + + float cpu1 = 0.0f; + float cpu5 = 0.0f; + float cpu15 = 0.0f; + float mem = 0.0f; + float disk = 0.0f; + uint64_t tMEM = 0; + uint64_t tDISK = 0; + uint64_t cMEM = 0; + uint64_t cDISK = 0; + uint32_t cCORES = get_nprocs(); + if( sysinfo( &SI ) == 0 ){ + float f_load = 100.f / (float)( cCORES * ( 1 << SI_LOAD_SHIFT ) ); + cpu1 = SI.loads[0] * f_load; + cpu5 = SI.loads[1] * f_load; + cpu15 = SI.loads[2] * f_load; + tMEM = SI.totalram; + cMEM = SI.totalram - SI.freeram; + mem = (float)cMEM / (float)tMEM; + } else { + LOG_ERROR("Error while getting System Info!"); + }; + const uint32_t MB = 1 << 10;//(1024 * 1024);// * 1024; + + if( statvfs("/", &DI) == 0 ){ + tDISK = ( DI.f_blocks * DI.f_frsize ) / MB; + cDISK = ( DI.f_bavail * DI.f_frsize ) / MB; + disk = (float)cDISK / (float)tDISK; + } else { + LOG_ERROR("Error while getting Disk Info!"); + }; + if( !m_pDBC->updateServerUtilisation( m_nServerID, cCORES, cpu1, cpu5, cpu15, mem, disk, tMEM, cMEM, tDISK, cDISK ) ) LOG_ERROR("Cannot update System Utilisation Stats!"); + //Get Queued Commands + DBC_KRNL_CMD *tCMD = NULL; tCMD = m_pDBC->getActiveCommand( m_nSiteID ); if( tCMD != NULL ){ switch( tCMD->cmd ) { @@ -421,106 +438,10 @@ void argusKernel::m_fThreadProc( void ){ if( m_pNodeFactory != NULL ) { m_pNodeFactory->validate(); }; - }; -// if( m_vEvtRecords.size() > 0 ){ -// validateEvents( lastTSS, lastTMS ); -// // SLEEP( 2 ); // short loop if had an events -// } else - SLEEP( SLEEP_KERNEL_INTERVAL ); - + + };// ops loop -#ifdef SIMULATE_KERNEL_TARGETS - /* - // Simulate FlyHunter - if( m_tTimeTSeconds!= m_nEachSec ) { - m_nEachSec = m_tTimeTSeconds; - if( m_bLandingTO ) { - m_bLandingTO--; - if( m_bLandingTO == 1 ) { - //Landing - LOG("Simulate Landing"); - LOG( m_cCurrentMission ); - //Simulate FH Module Event; - EVENT_CONTAINER *ttt; - FH_MISSION_DATA * nnn = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); - if( nnn ){ - nnn->location.lat = 0; - nnn->location.lon = 0; - nnn->location.alt = 0; - sprintf( nnn->missionID, m_cCurrentMission ); - ttt = createBasicEvent( 0, EVT_CLASS_FLY_HUNTER, EVT_FH_LANDED, NULL, NULL, nnn ); - if( ttt ) { - m_pEventHeap->broadcast( ttt ); - } else { - free( nnn ); - }; - }; - }; - }; - if( m_bJamingTO ) { - m_bJamingTO--; - if( m_bJamingTO == 1 ) { - //Jaming Off - //Simulate FH Module Event; - EVENT_CONTAINER *ttt; - FH_MISSION_DATA * nnn = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); - if( nnn ){ - nnn->location.lat = 0; - nnn->location.lon = 0; - nnn->location.alt = 0; - sprintf( nnn->missionID, m_cCurrentMission ); - ttt = createBasicEvent( 0, EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_OFF, NULL, NULL, nnn ); - if( ttt ) { - m_pEventHeap->broadcast( ttt ); - } else { - free( nnn ); - }; - }; - }; - }; - }; - */ - - //Target Simulation To Test Events - Database - /* - if(( m_tTimeTSeconds%SIMULATE_KERNEL_INTERVAL)==(SIMULATE_KERNEL_3D_INTERVAL>>1)){ - if( m_tTimeTSeconds!= m_nLastSimRun ){ - m_nLastSimRun = m_tTimeTSeconds; - if( m_pNodeFactory != NULL ) { - argusNetNode *tNode = m_pNodeFactory->getNode( SIMULATE_KERNEL_3D_ID ); - if( tNode!= NULL ) { - tNode->simulateTarget(); - }; - }; - }; - }; - */ - - if(( m_tTimeTSeconds%SIMULATE_KERNEL_PLS_INTERVAL)==(SIMULATE_KERNEL_PLS_INTERVAL>>1)){ - if( m_tTimeTSeconds!= m_nLastSimRun ){ - m_nLastSimRun = m_tTimeTSeconds; - if( m_pNodeFactory != NULL ) { - argusNetNode *tNode = m_pNodeFactory->getNode( SIMULATE_KERNEL_PLS_ID ); - if( tNode!= NULL ) { - tNode->simulateTarget(); - }; - }; - }; - }; - - if(( m_tTimeTSeconds%SIMULATE_KERNEL_MND_INTERVAL)==(SIMULATE_KERNEL_MND_INTERVAL>>1)){ - if( m_tTimeTSeconds!= m_nLastSimRun ){ - m_nLastSimRun = m_tTimeTSeconds; - if( m_pNodeFactory != NULL ) { - argusNetNode *tNode = m_pNodeFactory->getNode( SIMULATE_KERNEL_MND_ID ); - if( tNode!= NULL ) { - tNode->simulateTarget(); - }; - }; - }; - }; - -#endif + SLEEP( SLEEP_KERNEL_INTERVAL ); }; }; diff --git a/lib/rgoose/rgooseKernel.h b/lib/rgoose/rgooseKernel.h index 980a97da..a20839b9 100644 --- a/lib/rgoose/rgooseKernel.h +++ b/lib/rgoose/rgooseKernel.h @@ -125,7 +125,7 @@ class argusKernel: public basicThread, public basicEventHandler { uint32_t m_nSiteID; uint32_t m_nServerID; uint32_t m_nServerNodeID; - + bool m_bSkipResignComponents; char m_sIdentity[33]; time_t m_tTimeTSeconds; basicLogCollection * m_pLog; @@ -158,7 +158,7 @@ class argusKernel: public basicThread, public basicEventHandler { protected: void m_fThreadProc( void ); public: - static argusKernel * getInstance( config_setting_t *Settings = NULL ); + static argusKernel * getInstance( bool cold_start = true, config_setting_t *Settings = NULL ); // Destructor virtual ~argusKernel(); bool create( void ); @@ -182,7 +182,7 @@ class argusKernel: public basicThread, public basicEventHandler { private: static argusKernel * _instance; // Constructor - explicit argusKernel( config_setting_t *Settings = NULL ); + explicit argusKernel( bool cold_start, config_setting_t *Settings ); }; diff --git a/lib/rgoose/rgooseModule.cpp b/lib/rgoose/rgooseModule.cpp index d6859a52..5f8943ec 100644 --- a/lib/rgoose/rgooseModule.cpp +++ b/lib/rgoose/rgooseModule.cpp @@ -3,6 +3,7 @@ argusKernelModule::argusKernelModule( uint32_t id, ARGUS_MODULE_TYPE param ): basicEventHandler(), basicObject(){ m_pLog = basicLogCollection::getInstance(); + m_pLog->Log( "KMODULE", this, "Constructor Begin" ); m_pDBC = argusDBC::getInstance(); m_pKernel = argusKernel::getInstance(); m_eType = param; @@ -10,6 +11,7 @@ argusKernelModule::argusKernelModule( uint32_t id, ARGUS_MODULE_TYPE param ): ba m_bDetached = false; m_bEnabled = false; m_nDBAUXID = 0; + // Clear Events flags if( m_pDBC ) { DBC_MODULE_DATA *tData = NULL; @@ -21,6 +23,7 @@ argusKernelModule::argusKernelModule( uint32_t id, ARGUS_MODULE_TYPE param ): ba }; }; for( int i = 0; i < EVT_COUNT; i++ ) m_bEvtFlags[i] = false; + m_pLog->Log( "KMODULE", this, "Constructor End" ); }; argusKernelModule::~argusKernelModule(){ diff --git a/lib/rgoose/rgooseModuleEmbedVideo - Copy.cpp b/lib/rgoose/rgooseModuleEmbedVideo - Copy.cpp new file mode 100644 index 00000000..c14f240e --- /dev/null +++ b/lib/rgoose/rgooseModuleEmbedVideo - Copy.cpp @@ -0,0 +1,1464 @@ +#include "rgooseModuleEmbedVideo.h" +#include "rgooseHardwareResourceNetworkProvider.h" +#include "../alg/generic/base64.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include +#include + + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X ); +#endif + +#define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X ) +#define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ) + +enum { + WEBRTC_REQ_SIGNIN = 0, + WEBRTC_REQ_WAIT = 1, + WEBRTC_REQ_SIGNOUT = 2, + WEBRTC_REQ_MESSAGE = 3 +}; + +static const char* kRequestPaths[] = { "/sign_in", "/wait", "/sign_out", "/message" }; + +//buffer_data bd[1]={0}; + +argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicMediaDestination(), basicThread(){ + m_pEventHeap = basicEventHeap::getInstance(); +}; + +argusModuleEmbedVideo::~argusModuleEmbedVideo(){ + m_bEnabled = false; + stopService(); +}; + + +static int write_packet(void *opaque, uint8_t *buf, int buf_size) { + STREAM_CTX *CTX = (STREAM_CTX *)opaque; + buffer_data *bd = CTX->buffer; + TLOG("WRD"); + while( buf_size > bd->room ){ + int64_t offset = bd->ptr - bd->buf; + bd->buf = (uint8_t *) av_realloc_f( bd->buf, 2, bd->size ); + if (!bd->buf) + return AVERROR(ENOMEM); + bd->size *= 2; + bd->ptr = bd->buf + offset; + bd->room = bd->size - offset; + } + char tB[200]; + sprintf( tB, "write packet pkt_size:%d used_buf_size:%zu buf_size:%zu buf_room:%zu\n", buf_size, bd->ptr-bd->buf, bd->size, bd->room ); + TLOG( tB ); + memcpy(bd->ptr, buf, buf_size); + bd->ptr += buf_size; + bd->room -= buf_size; + + //free(buf); + return buf_size; +}; + +int argusModuleEmbedVideo::write_module_packet( void *opaque, uint8_t *buf, int buf_size ){ + STREAM_CTX *CTX = (STREAM_CTX *)opaque; + if( CTX->bHeaderIsReady ){ + uint32_t pSize = buf_size; + CTX->ModulePtr->m_mHandlersProtector.lock(); + for( vectorHANDLERS::iterator idx = CTX->ModulePtr->m_vHandlersPool.begin(); + idx < CTX->ModulePtr->m_vHandlersPool.end(); + idx++ ) + { + if( (*idx)->CTX->bValid ) { + if( (*idx)->CTX->STREAM->mediaStreamId == id ) { + write( (*idx)->CTX->m_iEncoderPipe[0], &pSize, sizeof(uint32_t)); + }; + }; + }; + CTX->ModulePtr->m_mHandlersProtector.unlock(); + } else { + CTX->header_size = buf_size; + CTX->header = (uint8_t*)av_malloc( buf_size ); + if( CTX->header== NULL ) return AVERROR(ENOMEM); + memcpy( CTX->header, buf, buf_size ); + CTX->bHeaderIsReady = true; + char tB[200]; + sprintf( tB, "write packet pkt_size:%d", buf_size ); + TLOG( tB ); + }; + return buf_size; +}; + +int argusModuleEmbedVideo::write_client_packet( void *opaque, uint8_t *buf, int buf_size ){ + STREAM_CTX *CTX = (STREAM_CTX *)opaque; + if( CTX->bHeaderIsReady ){ + + } else { + CTX->header_size = buf_size; + CTX->header = (uint8_t*)av_malloc( buf_size ); + if( CTX->header== NULL ) return AVERROR(ENOMEM); + memcpy( CTX->header, buf, buf_size ); + CTX->bHeaderIsReady = true; + char tB[200]; + sprintf( tB, "write packet pkt_size:%d", buf_size ); + TLOG( tB ); + }; + return buf_size; +}; + +void argusModuleEmbedVideo::encode_module_video( STREAM_CTX *CTX, AVFrame *DATA ){ + int ret; + if( DATA ) { + ret = avcodec_send_frame( CTX->video_ctx, DATA ); + } else { + ret = avcodec_send_frame( CTX->video_ctx, NULL ); + }; + if( ret < 0 ){ + TLOG_ERROR("Error sending a video frame for encoding"); + return; + }; + while( ret >= 0 ){ + AVPacket *pkt = NULL; + pkt = (AVPacket *) av_malloc( sizeof(AVPacket) ); + if( pkt ) { + av_init_packet( pkt ); + ret = avcodec_receive_packet( CTX->video_ctx, pkt ); + if( ret == AVERROR(EAGAIN) || ret == AVERROR_EOF ){ + av_packet_unref( pkt ); + av_free( pkt ); + return; + } else if( ret < 0 ){ + TLOG_ERROR("Error during video encoding"); + av_free( pkt ); + return; + }; + pkt->stream_index = CTX->video_stream->index; + av_packet_rescale_ts( pkt, CTX->video_ctx->time_base, CTX->video_stream->time_base ); + av_write_frame( CTX->ofmt_ctx, pkt ); + av_packet_unref( pkt ); + av_free( pkt ); + } + }; +}; + +void argusModuleEmbedVideo::encode_client_video( STREAM_CTX *CTX, AVPacket *pkt ){ + if( pkt ) { + pkt->stream_index = CTX->ts; + CTX->ts++; + av_packet_rescale_ts( pkt, CTX->video_ctx->time_base, CTX->video_stream->time_base ); + av_write_frame( CTX->ofmt_ctx, pkt ); + av_packet_unref( pkt ); + }; +}; + +#ifndef _NOAUDIO_ +void argusModuleEmbedVideo::encode_audio( STREAM_CTX *CTX, AVFrame *DATA ){ + int ret; + if( DATA ) { + ret = avcodec_send_frame( CTX->audio_ctx, CTX->audio_frame ); + } else { + ret = avcodec_send_frame( CTX->audio_ctx, NULL ); + }; + if( ret < 0 ){ + TLOG_ERROR("Error sending a audio frame for encoding"); + return; + }; + while( ret >= 0 ){ + ret = avcodec_receive_packet( CTX->audio_ctx, CTX->pkt ); + if( ret == AVERROR(EAGAIN) || ret == AVERROR_EOF ){ + av_packet_unref( CTX->pkt ); + return; + } else if( ret < 0 ){ + TLOG_ERROR("Error during audio encoding"); + return; + }; + CTX->pkt->stream_index = CTX->audio_stream->index; + av_packet_rescale_ts( CTX->pkt, CTX->audio_ctx->time_base, CTX->audio_stream->time_base); + av_write_frame( CTX->ofmt_ctx, CTX->pkt ); + av_packet_unref( CTX->pkt ); + }; +}; +#endif + +void argusModuleEmbedVideo::add_video_frame( STREAM_CTX *CTX ){ + if( CTX->InputMat ){ + if( CTX->video_sws_ctx ) { + int linesize[2] = {0}; + const uint8_t * dataPTR[2] = {0}; + + linesize[0] = CTX->InputMat->cols*3; + linesize[1] = 0; + + dataPTR[0] = (uint8_t *)CTX->InputMat->data; + dataPTR[1] = NULL; + + av_frame_make_writable( CTX->video_frame ); + + sws_scale( CTX->video_sws_ctx, + dataPTR, + linesize, + 0, + CTX->InputMat->rows, + CTX->video_frame->data, + CTX->video_frame->linesize + ); + CTX->video_frame->pts = CTX->ts; + CTX->ts++; + encode_module_video( CTX, CTX->video_frame ); + }; + }; +}; + + +bool argusModuleEmbedVideo::write_header( STREAM_CTX *CTX ) { + int ret = avformat_write_header( CTX->ofmt_ctx, NULL); + if (ret < 0) { + //printf(stderr, "Error occurred: %s\n", av_err2str(ret)); + TLOG_ERROR("Error occurred when opening output file"); + return false; + }; + return CTX->bHeaderIsReady = true; +}; + +void argusModuleEmbedVideo::cleanSTREAM_CTX( STREAM_CTX *&CTX ){ + if( CTX!= NULL ) { + /*video*/ + if( CTX->video_stream ){ + + }; + if( CTX->video_frame ){ + }; + if( CTX->video_ctx ) { + avcodec_close( CTX->video_ctx ); + avcodec_free_context( &CTX->video_ctx ); + }; + if( CTX->video_codec ){ + av_freep( CTX->video_codec ); + }; + /*audio*/ + + /*container*/ + if( CTX->ofmt_ctx ){ + if( CTX->ofmt_ctx->oformat ) av_freep( CTX->ofmt_ctx->oformat ); + avformat_free_context( CTX->ofmt_ctx ); + }; + if( CTX->avio_ctx ){ + av_freep(&CTX->avio_ctx->buffer); + av_freep(CTX->avio_ctx); + }; + if( CTX->avio_ctx_buffer ) av_freep( CTX->avio_ctx_buffer ); + /*output*/ + if( CTX->buffer ) { + if( CTX->buffer->buf ) av_free( CTX->buffer->buf ); + av_free(CTX->buffer); + }; + av_freep( CTX ); + }; +}; + +bool argusModuleEmbedVideo::open_client_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int codec_idx, int format_idx ){ + const char* formats[] = {"webm", "mp4", "mp3", "aac", "ogg", "mjpeg", "flv" }; + const char* codecs[] = { "libvpx", "libx264", "mp4", "mjpeg", "flv" }; + if( CTX == NULL ) { + CTX = (STREAM_CTX *) av_mallocz(sizeof(STREAM_CTX)); + }; + + if( CTX!= NULL ) { + if( CTX->have_video ) return false; + TLOG("Creating Video Stream"); + AVOutputFormat* of = av_guess_format(formats[format_idx], 0, 0); + if( of == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Format Guess OK"); + CTX->buffer = (buffer_data *) av_mallocz(sizeof(buffer_data)); + if( CTX->buffer == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Buffer OK"); + CTX->buffer->room = CTX->buffer->size = BD_BUFFER_SIZE; + CTX->buffer->ptr = CTX->buffer->buf = (uint8_t *) av_malloc( CTX->buffer->size ); + if( !CTX->buffer->buf ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Buffer OK"); + CTX->avio_ctx_buffer_size = AVIO_BUFFER_SIZE; + CTX->avio_ctx_buffer = (uint8_t *) av_malloc(CTX->avio_ctx_buffer_size); + if( !CTX->avio_ctx_buffer ){ + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVIO Buffer OK"); + CTX->avio_ctx = avio_alloc_context( + CTX->avio_ctx_buffer, + CTX->avio_ctx_buffer_size, + 1, + &CTX, + NULL, + &write_client_packet, + NULL //&seek + ); + if( !CTX->avio_ctx ){ + cleanSTREAM_CTX( CTX ); + return NULL; + } + TLOG("AVIO CTX OK"); + if( avformat_alloc_output_context2(&CTX->ofmt_ctx, of, NULL, NULL) < 0 ){ + TLOG_ERROR( "Could not create output context" ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVFormat CTX OK"); + CTX->video_codec = avcodec_find_encoder_by_name(codecs[codec_idx]); + if( !CTX->video_codec ){ + char tB[100]; + sprintf( tB,"Codec '%s' not found", codecs[codec_idx] ); + TLOG_ERROR( tB ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec OK"); + CTX->video_ctx = avcodec_alloc_context3( CTX->video_codec ); + if( !CTX->video_ctx ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec CTX OK"); + CTX->video_ctx->width = w; + CTX->video_ctx->height = h; + CTX->video_ctx->time_base.num = 1; + CTX->video_ctx->time_base.den = fps; + CTX->video_ctx->bit_rate = br; + CTX->video_ctx->gop_size = 10; + if( codec_idx == 3 ) { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUVJ422P; + } else { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + CTX->video_ctx->max_b_frames = 1; + }; + if( avcodec_open2( CTX->video_ctx, CTX->video_codec, NULL ) < 0 ){ + TLOG_ERROR("couldnt open codec"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec Open OK"); + CTX->video_stream = avformat_new_stream( CTX->ofmt_ctx, NULL); + if( !CTX->video_stream ){ + TLOG_ERROR("error making stream"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVStream OK"); + CTX->ofmt_ctx->pb = CTX->avio_ctx; + CTX->ofmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO; + + CTX->ofmt_ctx->oformat = of; + CTX->video_stream->codec->codec_tag = 0; + + CTX->video_stream->time_base = CTX->video_ctx->time_base; + CTX->video_stream->id = CTX->ofmt_ctx->nb_streams-1; + + avcodec_parameters_from_context( CTX->video_stream->codecpar, CTX->video_ctx ); + + CTX->frame_idx = 0; + CTX->have_video = true; + + TLOG("STREAM OK"); + return true; + }; + return false; +}; + +bool argusModuleEmbedVideo::open_module_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int preset_idx, int codec_idx, int format_idx ){ + const char* formats[] = {"webm", "mp4", "mp3", "aac", "ogg", "mjpeg", "flv" }; + const char* codecs[] = { "libvpx", "libx264", "mp4", "mjpeg", "flv" }; + const char *presets[] = { "ultrafast", "veryfast", "fast", "medium", "slow", "veryslow" }; + if( CTX == NULL ) { + CTX = (STREAM_CTX *) av_mallocz( sizeof(STREAM_CTX)); + }; + + if( CTX!= NULL ) { + + if( CTX->have_video ) return false; + TLOG("Creating Video Stream"); + AVOutputFormat* of = av_guess_format(formats[format_idx], 0, 0); + if( of == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Format Guess OK"); + CTX->buffer = (buffer_data *) av_mallocz(sizeof(buffer_data)); + if( CTX->buffer == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Buffer OK"); + CTX->buffer->room = CTX->buffer->size = BD_BUFFER_SIZE; + CTX->buffer->ptr = CTX->buffer->buf = (uint8_t *) av_malloc( CTX->buffer->size ); + if( !CTX->buffer->buf ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Buffer OK"); + CTX->avio_ctx_buffer_size = AVIO_BUFFER_SIZE; + CTX->avio_ctx_buffer = (uint8_t *) av_malloc(CTX->avio_ctx_buffer_size); + if( !CTX->avio_ctx_buffer ){ + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVIO Buffer OK"); + CTX->avio_ctx = avio_alloc_context( + CTX->avio_ctx_buffer, + CTX->avio_ctx_buffer_size, + 1, + &CTX, + NULL, + &write_module_packet, + NULL //&seek + ); + if( !CTX->avio_ctx ){ + cleanSTREAM_CTX( CTX ); + return NULL; + } + TLOG("AVIO CTX OK"); + if( avformat_alloc_output_context2(&CTX->ofmt_ctx, of, NULL, NULL) < 0 ){ + TLOG_ERROR( "Could not create output context" ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVFormat CTX OK"); + CTX->video_codec = avcodec_find_encoder_by_name(codecs[codec_idx]); + if( !CTX->video_codec ){ + char tB[100]; + sprintf( tB,"Codec '%s' not found", codecs[codec_idx] ); + TLOG_ERROR( tB ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec OK"); + CTX->video_ctx = avcodec_alloc_context3( CTX->video_codec ); + if( !CTX->video_ctx ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec CTX OK"); + CTX->video_ctx->width = w; + CTX->video_ctx->height = h; + CTX->video_ctx->time_base.num = 1; + CTX->video_ctx->time_base.den = fps; + CTX->video_ctx->bit_rate = br; + CTX->video_ctx->gop_size = 10; + if( codec_idx == 3 ) { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUVJ422P; + } else { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + CTX->video_ctx->max_b_frames = 1; + }; + + av_opt_set( CTX->video_ctx->priv_data, "preset", presets[preset_idx], 0 ); + if( avcodec_open2( CTX->video_ctx, CTX->video_codec, NULL ) < 0 ){ + TLOG_ERROR("couldnt open codec"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec Open OK"); + + // Frame initalization + CTX->video_frame = av_frame_alloc(); + if( !CTX->video_frame ) { + TLOG_ERROR("couldnt alloc frame"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Video Frame OK"); + CTX->video_frame->format = CTX->video_ctx->pix_fmt; + CTX->video_frame->width = w; + CTX->video_frame->height = h; + av_frame_get_buffer( CTX->video_frame, 0 ); + + CTX->video_stream = avformat_new_stream( CTX->ofmt_ctx, NULL); + if( !CTX->video_stream ){ + TLOG_ERROR("error making stream"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVStream OK"); + CTX->ofmt_ctx->pb = CTX->avio_ctx; + CTX->ofmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO; + + CTX->ofmt_ctx->oformat = of; + CTX->video_stream->codec->codec_tag = 0; + + CTX->video_stream->time_base = CTX->video_ctx->time_base; + CTX->video_stream->id = CTX->ofmt_ctx->nb_streams-1; + + avcodec_parameters_from_context( CTX->video_stream->codecpar, CTX->video_ctx ); + + CTX->frame_idx = 0; + CTX->have_video = 1; + + TLOG("STREAM OK"); + return true; + }; + return false; +}; + +uint8_t *argusModuleEmbedVideo::close_stream( STREAM_CTX *CTX, int* size ){ + if( CTX->have_video ) encode_module_video( CTX, NULL ); +#ifndef _NOAUDIO_ + if( CTX->have_audio ) encode_audio( CTX, NULL ); +#endif + + av_write_trailer( CTX->ofmt_ctx ); + /* + avformat_free_context(ofmt_ctx); + + if (have_video) { + avcodec_free_context(&video_ctx); + av_frame_free(&video_frame); + } + + if (have_audio) { + avcodec_free_context(&audio_ctx); + av_frame_free(&audio_frame); + swr_free(&audio_swr_ctx); + free(audio_buffer_right); + free(audio_buffer_left); + } + + av_freep(&avio_ctx->buffer); + av_free(avio_ctx); + */ + *size = CTX->buffer->size - CTX->buffer->room; + return CTX->buffer->buf; +}; + +//void free_buffer(){ +// av_free(bd.buf); +//} +#ifndef _NOAUDIO_ +bool argusModuleEmbedVideo::alloc_audio_frame( STREAM_CTX *CTX ){ + if( CTX->audio_frame ){ + av_freep( CTX->audio_frame ); + }; + CTX->audio_frame = av_frame_alloc(); + if( !CTX->audio_frame ){ + TLOG_ERROR("Error allocating an audio frame"); + return false; + }; + CTX->audio_frame->format = CTX->audio_ctx->sample_fmt; + CTX->audio_frame->channel_layout = CTX->audio_ctx->channel_layout; + CTX->audio_frame->sample_rate = CTX->audio_ctx->sample_rate; + CTX->audio_frame->nb_samples = CTX->audio_ctx->frame_size; + if( av_frame_get_buffer( CTX->audio_frame, 4 ) < 0 ){ + TLOG_ERROR("Error allocating an audio buffer"); + return false; + }; + return true; +}; + +int argusModuleEmbedVideo::check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt){ + const enum AVSampleFormat *p = codec->sample_fmts; + while (*p != AV_SAMPLE_FMT_NONE) { + if (*p == sample_fmt) + return 1; + p++; + } + return 0; +}; + +void argusModuleEmbedVideo::add_audio_frame( STREAM_CTX *CTX, float* left, float* right, int size ){ + if( size + CTX->audio_buffer_size > CTX->max_audio_buffer_size ){ + CTX->audio_buffer_left = (float *)realloc(CTX->audio_buffer_left, (size + CTX->audio_buffer_size) * sizeof(float)); + CTX->audio_buffer_right = (float *)realloc(CTX->audio_buffer_right, (size + CTX->audio_buffer_size) * sizeof(float)); + } + + memcpy( CTX->audio_buffer_left + CTX->audio_buffer_size, left, size * sizeof(float) ); + memcpy( CTX->audio_buffer_right + CTX->audio_buffer_size, right, size * sizeof(float) ); + CTX->audio_buffer_size += size; + int count = 0, ret; + + while( CTX->audio_buffer_size > CTX->audio_frame->nb_samples ){ + if( av_frame_make_writable( CTX->audio_frame ) < 0){ + TLOG_ERROR("Error: add audio frame!"); + return; + }; + + CTX->audio_frame->data[0] = (uint8_t *) CTX->audio_buffer_left; + CTX->audio_frame->data[1] = (uint8_t *) CTX->audio_buffer_right; + + CTX->dst_nb_samples = av_rescale_rnd ( + swr_get_delay( CTX->audio_swr_ctx, CTX->audio_ctx->sample_rate ) + CTX->audio_frame->nb_samples, + CTX->src_sample_rate, + CTX->audio_ctx->sample_rate, + AV_ROUND_UP + ); + + if( swr_convert ( + CTX->audio_swr_ctx, + CTX->audio_frame->data, + CTX->dst_nb_samples, + (const uint8_t **)CTX->audio_frame->data, + CTX->audio_frame->nb_samples + )< 0){ + TLOG_ERROR("error converting \n"); + return; + }; + + CTX->audio_frame->pts = av_rescale_q( + CTX->audio_frame_bytes, + (AVRational){ 1, CTX->audio_ctx->sample_rate }, + CTX->audio_ctx->time_base + ); + + CTX->audio_frame_bytes += CTX->dst_nb_samples; + encode_audio( CTX, CTX->audio_frame ); + //Shift array buffer + memcpy( CTX->audio_buffer_left, CTX->audio_buffer_left + CTX->audio_frame->nb_samples, CTX->audio_buffer_size*sizeof(float)); + memcpy( CTX->audio_buffer_right, CTX->audio_buffer_right + CTX->audio_frame->nb_samples, CTX->audio_buffer_size*sizeof(float)); + CTX->audio_buffer_size -= CTX->audio_frame->nb_samples; + }; +}; + +bool argusModuleEmbedVideo::open_audio( STREAM_CTX *&CTX, int sample_rate, int nr_channels, int bit_rate, int codec_idx ){ + const AVCodecID codecs[] = { AV_CODEC_ID_OPUS, AV_CODEC_ID_AAC, AV_CODEC_ID_MP3 }; + if( CTX == NULL ) { + CTX = (STREAM_CTX *) av_mallocz( sizeof(STREAM_CTX)); + }; + if( CTX!= NULL ) { + if( CTX->have_audio ) return false; + CTX->src_sample_rate = sample_rate; + CTX->src_bit_rate = bit_rate; + CTX->src_nr_channels = nr_channels; + + + + CTX->audio_codec = avcodec_find_encoder(codecs[codec_idx]); + if( !CTX->audio_codec ){ + TLOG_ERROR("error making audio codec context"); + cleanSTREAM_CTX( CTX ); + return false; + }; + + CTX->audio_stream = avformat_new_stream( CTX->ofmt_ctx, NULL); + CTX->audio_stream->id = CTX->ofmt_ctx->nb_streams-1; + CTX->audio_ctx = avcodec_alloc_context3( CTX->audio_codec ); + CTX->audio_ctx->bit_rate = bit_rate; + CTX->audio_ctx->sample_rate = sample_rate; + if( CTX->audio_codec->supported_samplerates ){ + CTX->audio_ctx->sample_rate = CTX->audio_codec->supported_samplerates[0]; + for( int i = 0; CTX->audio_codec->supported_samplerates[i]; i++ ){ + if( CTX->audio_codec->supported_samplerates[i] == sample_rate ) CTX->audio_ctx->sample_rate = sample_rate; + }; + }; + CTX->audio_ctx->channels = nr_channels; + CTX->audio_ctx->channel_layout = AV_CH_LAYOUT_STEREO; + if( CTX->audio_codec->channel_layouts ){ + CTX->audio_ctx->channel_layout = CTX->audio_codec->channel_layouts[0]; + for( int i = 0; CTX->audio_codec->channel_layouts[i]; i++ ){ + if( CTX->audio_codec->channel_layouts[i] == AV_CH_LAYOUT_STEREO ) CTX->audio_ctx->channel_layout = AV_CH_LAYOUT_STEREO; + }; + }; + + CTX->audio_ctx->channels = av_get_channel_layout_nb_channels( CTX->audio_ctx->channel_layout ); + CTX->audio_ctx->sample_fmt = CTX->audio_codec->sample_fmts[0]; + CTX->audio_stream->time_base = (AVRational){1, CTX->audio_ctx->sample_rate}; + + if( avcodec_open2( CTX->audio_ctx, CTX->audio_codec, NULL ) < 0 ){ + TLOG_ERROR("Could not open audio codec" ); + cleanSTREAM_CTX( CTX ); + return false; + }; + + if(!alloc_audio_frame( CTX )){ + TLOG_ERROR("Could not alloc audio frame" ); + cleanSTREAM_CTX( CTX ); + return false; + }; + + if( avcodec_parameters_from_context( CTX->audio_stream->codecpar, CTX->audio_ctx ) < 0 ){ + TLOG_ERROR("Could not copy the stream parameters"); + cleanSTREAM_CTX( CTX ); + return false; + }; + + CTX->audio_swr_ctx = swr_alloc(); + if( !CTX->audio_swr_ctx ){ + TLOG_ERROR("Could not allocate resampler context"); + cleanSTREAM_CTX( CTX ); + return false; + }; + + av_opt_set_int (CTX->audio_swr_ctx, "in_channel_count", nr_channels, 0); + av_opt_set_int (CTX->audio_swr_ctx, "in_sample_rate", sample_rate, 0); + av_opt_set_sample_fmt(CTX->audio_swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0); + av_opt_set_int (CTX->audio_swr_ctx, "out_channel_count", CTX->audio_ctx->channels, 0); + av_opt_set_int (CTX->audio_swr_ctx, "out_sample_rate", CTX->audio_ctx->sample_rate, 0); + av_opt_set_sample_fmt(CTX->audio_swr_ctx, "out_sample_fmt", CTX->audio_ctx->sample_fmt, 0); + + if( swr_init( CTX->audio_swr_ctx ) < 0 ){ + TLOG_ERROR("Failed to initialize the resampling context"); + return false; + }; + + if( !CTX->pkt ) CTX->pkt = av_packet_alloc(); + + if( !CTX->pkt ){ + return false; + }; + + CTX->audio_buffer_size = CTX->audio_frame_bytes = 0; + CTX->audio_buffer_left = (float *)malloc(sample_rate * sizeof(float)); + CTX->audio_buffer_right = (float *)malloc(sample_rate * sizeof(float)); + CTX->max_audio_buffer_size = sample_rate; + + CTX->have_audio = 1; + return true; + }; + return false; +}; +#endif // _NOAUDIO_ + + +static int IOWriteFunc( void *opaque, uint8_t *buf, int buf_size ){ + WEB_CLIENT_CTX *CTX = (WEB_CLIENT_CTX *)opaque; + TLOG("-chunk-"); + if( CTX ) { + if( CTX->m_iSocketFID > -1 ){ + char mesg[128]; + sprintf( mesg, "%x\r\n", buf_size ); + if( send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 ) < 0 ){ + sprintf( mesg, "Failed sending 1 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + return -1; + }; + if( send( CTX->m_iSocketFID, buf, buf_size, 0 ) < 0 ){ + sprintf( mesg, "Failed sending 1 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + return -1; + }; + if( send( CTX->m_iSocketFID, "\r\n", 2, 0 ) < 0 ){ + sprintf( mesg, "Failed sending 1 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + return -1; + }; + return buf_size; + }; + }; + return -1; +}; + +void *argusModuleEmbedVideo::webClientProc( void *ptr ){ + static char *head = "HTTP/1.1 200 OK\r\n" + "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" + "Pragma: no-cache\r\n" + "MIME-version: 1.0\r\n" + "Connection: close\r\n" + "Content-Type: video/mp4\r\n" + "Content-Transfer-Encoding: BINARY\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"; + WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; + argusModuleEmbedVideo * MODULE = CTX->ModulePtr; + STREAM_CTX * STREAM = NULL; + + if( CTX ) { + char mesg[1024]; + size_t RecvSize; + struct pollfd pfd[1]; + char cGetURI[1024]; + bool m_bDeflatePerMessage = false; + bool m_pInit; + +#ifdef DEBUG_EXTRA + pid_t pid = gettid(); + char pidBuf[16]; + sprintf( pidBuf, "pid:%d", pid); + TLOG( pidBuf ); +#endif + + pfd->fd = CTX->m_iSocketFID; + pfd->events = POLLIN | POLLHUP; + + while( CTX->bValid ) { + if( !CTX->initDone ){ + int RetVal; + char * reqline[256]; + RetVal = poll( pfd, 1, 1000 ); + if( RetVal <= 0 ){ + if ( EINTR == errno ) continue; + TLOG_ERROR("Unrecoverable error"); + CTX->bValid = false; + continue; + }; + memset( mesg, 0, sizeof(mesg) ); + + RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 ); + + if ( RetVal <= 0 ) { + sprintf( mesg, "web recv() error: %s", strerror(errno)); + TLOG_ERROR( mesg ); + CTX->bValid = false; + continue; + }; + //TLOG( mesg ); + + uint32_t index = 0; + reqline[index] = strtok( mesg, "\n" ); + if( strncmp( reqline[index], "GET", 3 ) == 0 ) { + char * pPartURI; + char * pPartPROTO; + pPartURI = strstr( reqline[index], " " ); + if( pPartURI != NULL ) { + pPartURI++; + pPartPROTO = strstr( pPartURI, " " ); + pPartPROTO++; + int URILen = pPartPROTO - pPartURI; + strncpy( cGetURI, pPartURI, URILen ); + cGetURI[URILen] = (char)0; + if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) { + TLOG_ERROR("No HTTP version supplied in request!"); + if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){ + sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + }; + CTX->bValid = false; + continue; + }; + }; + TLOG( cGetURI ); + }; + // parse rest of request + while( ( reqline[++index] = strtok( NULL, "\n" ) )!= NULL ) { + if( strncmp( reqline[index], "Connection:", 11 ) == 0 ) { + char * pPart; + pPart = strcasestr( reqline[index], "Upgrade" ); + if( pPart != NULL ) { + TLOG("Upgrade Mode ON"); + //bUpgradeMode = true; + }; + }; + if( strncmp( reqline[index], "Upgrade:", 8 ) == 0 ) { + /* + if( bUpgradeMode ) { + char * pPart; + pPart = strcasestr( reqline[index], "websocket" ); + if( pPart != NULL ) { + TLOG("WebSocket Mode ON"); + //bWebSocketMode = true; + }; + }; + */ + }; + if( strncmp( reqline[index], "Sec-WebSocket-Version:", 22 ) == 0 ) { + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + char tBuf[CTEXT]; + //nWebSocketVersion = atoi(pPart+1); + sprintf( tBuf,"Web Socket Version: %d", 0 );//nWebSocketVersion ); + TLOG( tBuf ); + }; + }; + if( strncmp( reqline[index], "Sec-WebSocket-Key:", 18 ) == 0 ) { + /*char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + char tGenStr[256]; + unsigned char * tBase64; + size_t nBase64; + int kLen; + unsigned char hash[SHA_DIGEST_LENGTH]; // == 20 + pPart++; + kLen = strstr(pPart,"\r") - pPart; + strncpy(cWSKey,pPart,kLen); + cWSKey[kLen]=(char)0; + TLOG( cWSKey ); + sprintf( tGenStr, "%s%s", cWSKey, ws_guid ); + SHA1( (const unsigned char*)tGenStr, strlen(tGenStr), hash ); + tBase64 = base64_encode( hash, SHA_DIGEST_LENGTH, &nBase64 ); + strncpy( cWSRep, (const char*)tBase64, nBase64 ); + free( tBase64 ); + cWSRep[nBase64] = (char)0; + TLOG( cWSRep ); + }; + */ + }; + if( strncmp( reqline[index], "Sec-WebSocket-Protocol:", 23 ) == 0 ) { + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + // Check for protos + }; + }; + if( strncmp( reqline[index], "Sec-WebSocket-Extensions:", 25 ) == 0 ) { + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + pPart++; + if(strncmp( pPart, "permessage-deflate", 18 ) == 0 ) { + m_bDeflatePerMessage = true; + TLOG("Using Deflate"); + }; + }; + }; + if( strncmp( reqline[index],"Accept-Encoding:", 16 ) == 0 ){ + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + pPart++; + if(strncmp( pPart, "gzip, deflate", 13 ) == 0 ) { + m_bDeflatePerMessage = true; + TLOG("Using Deflate"); + }; + }; + }; + }; + // Send Header + if( send( CTX->m_iSocketFID, head, strlen(head), 0 ) < 0 ){ + sprintf( mesg, "Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + }; + + if( CTX->ModulePtr->registerForMediaStream( 0, CTX ) ) { + if( !CTX->ModulePtr->open_client_video( + CTX->STREAM, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_FPS, + VIDEO_OUTPUT_BITRATE, + VC_MJPEG, + VF_MJPEG + ) ){ + TLOG_ERROR("Cannot ctreate VIDEO STREAM!"); + CTX->bValid = false; + break; + }; + TLOG("Header"); + CTX->ModulePtr->write_header( STREAM ); + TLOG("After Header"); + CTX->initDone = true; + }; + continue; + } else { + uint32_t msgSize; + int retVal; + retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[1]!"); + CTX->bValid = false; + break; + }; + if( CTX->pkt == NULL ){ + CTX->pkt = (AVPacket *) av_mallocz(sizeof(AVPacket)); + } else { + // Data cleared in Encoder procedure + //av_freep( CTX->pkt->data ); + //av_packet_unref( CTX->pkt ); + }; + retVal = read( CTX->m_iEncoderPipe[0], CTX->pkt, sizeof(AVPacket)); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[2]!"); + CTX->bValid = false; + break; + }; + CTX->pkt->data = (uint8_t *)av_malloc( CTX->pkt->size ); + if( CTX->pkt->data ){ + retVal = read( CTX->m_iEncoderPipe[0], CTX->pkt->data, CTX->pkt->size ); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[3]!"); + CTX->bValid = false; + break; + }; + CTX->ModulePtr->encode_client_video( CTX->STREAM, CTX->pkt ); + } else { + TLOG_ERROR("Pack Memory Allocation Error!"); + CTX->bValid = false; + break; + }; + }; + }; + }; + TLOG("Client Handler Ended!"); + shutdown( CTX->m_iSocketFID, SHUT_RDWR); + close( CTX->m_iSocketFID ); + CTX->bValid = false; + //pthread_exit( NULL ); + return NULL; +}; + +void argusModuleEmbedVideo::destroy( WEB_CLIENT_CTX *&ptr ){ + if( ptr != NULL ){ + if( ptr->pkt ){ + av_packet_unref( ptr->pkt ); + av_freep( ptr->pkt ); + }; + //if( ptr->StreamBuffer ) av_freep( ptr->StreamBuffer ); + //if( ptr->outputFrame ) av_freep( ptr->outputFrame ); + free( ptr ); + ptr = NULL; + }; +}; + +void argusModuleEmbedVideo::m_fThreadProc( void ){ + if( !m_bEnabled ) { +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + return; + }; +#ifdef DEBUG + LOG("Module Started!"); +#endif + struct pollfd pfd[1]; + pfd->fd = m_nSocketDescriptor; + pfd->events = POLLIN | POLLHUP; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; + continue; + }; + int RetVal = poll( pfd, 1, 1000 ); + if( RetVal < 0 ){ + if( EINTR == errno ) continue; + LOG_ERROR("Unrecoverable error"); + m_bThreadStatus = TH_ENDED; + continue; + }; + // Handle Connections + if( RetVal != 0 ){ + if ( pfd[0].revents & POLLIN ) { + LOG("Handle New Client"); + int tSID = accept( pfd[0].fd, NULL, NULL); + if( tSID < 0 ){ + char tBuf[CTEXT]; + sprintf(tBuf, "Accept() error: %s", strerror(errno)); + LOG_ERROR(tBuf); + } else { + LOG("Accept OK"); + WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); + if( tCTX ) { + LOG("CTX OK"); + WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); + if( tHANDLER ) { + LOG("HANDLER OK"); + memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) ); + memset( tHANDLER, 0, sizeof(WEB_HANDLER) ); + tCTX->m_iSocketFID = tSID; + //tCTX->m_iEncoderPipe[0] = -1; + //tCTX->m_iEncoderPipe[1] = -1; + tCTX->bValid = true; + tCTX->ModulePtr = this; + LOG("Before Thread Create"); + int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX ); + if( RetVal == -1 ) { + free(tCTX); + free(tHANDLER); + LOG_ERROR("Thread Creation Faled."); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + } else { + tHANDLER->CTX = tCTX; + LOG("After Thread Create"); + m_vHandlersPool.push_back( tHANDLER ); + LOG("Handler Pushed to a Pool"); + }; + } else { + free(tCTX); + LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + } else { + LOG_ERROR("CL_CTX Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + }; + }; + }; + // Handle Dead Clients + if( m_vHandlersPool.size() ) { + for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { + if( !( (*idx)->CTX->bValid ) ) { +#ifdef DEBUG + LOG("Web Handler Ripped!"); +#endif + pthread_join( (*idx)->m_hThreadHandle, NULL ); + destroy( (*idx)->CTX ); + free( (*idx) ); + m_vHandlersPool.erase(idx); + }; + }; + }; + SLEEP( 50 ); + }; +}; + +#define ENABLE_SOCKOPT(sd, level, opt) \ + do { \ + int val = 1; \ + if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ + warn("Failed enabling %s for web service", #opt); \ + } while (0); + + +bool argusModuleEmbedVideo::startService(){ + LOG("Create"); + //if( m_nListenPort == 0 && ListenPort == 0 ) return false; + //m_nListenPort = ListenPort; + struct sockaddr sa; + struct sockaddr_in *sin; + + memset(&sa, 0, sizeof(struct sockaddr)); + sa.sa_family = AF_INET; + sin = (struct sockaddr_in *)&sa; + sin->sin_addr.s_addr = htonl( INADDR_ANY ); + sin->sin_port = htons( 8972 ); + + m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); + if( m_nSocketDescriptor == -1 ){ + LOG_ERROR("Failed creating ACC socket"); + return false; + }; + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT); +#endif + if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){ + LOG_ERROR("Failed binding Socket"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Bind Socessfull"); + }; + if( listen( m_nSocketDescriptor, 10) != 0 ){ + LOG_ERROR("Failed setting web listen backlog"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Listen OK"); + }; + createStream( 0 ); + return init(); +}; + +bool argusModuleEmbedVideo::stopService(){ + waitThreadEnd( true ); + /* + if( m_vThreads.size() ) { // Kill-Wait Started Probes +#ifdef DEBUG + LOG("Have to Wait Probes!"); +#endif + for( vectorOBSERVER_CTX::iterator index = m_vThreads.begin(); index < m_vThreads.end(); index++ ) { + pthread_join( (*index)->m_hThreadHandle, NULL ); + }; + m_vThreads.clear(); + }; +#ifdef DEBUG + LOG("No More Probes!"); +#endif + if (m_vResultPool.size()){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ + free(*index); + }; + m_vResultPool.clear(); + }; +#ifdef DEBUG + LOG("Data is Cleared!"); +#endif +*/ + return true; +}; + +bool argusModuleEmbedVideo::reloadSettings(){ + + return true; +}; + +void argusModuleEmbedVideo::dispatchEvent(EVENT_CONTAINER *Evt){ +}; + +bool argusModuleEmbedVideo::validate(){ + // Scan Active Streams And Create + if( m_pDBC ) { + DBC_INT_LIST *IDS = m_pDBC->listMediaStreams( 1 ,LIST_VALID_RECORDS ); + if( IDS ) { + for( DBC_INT_LIST::iterator idx = IDS->begin(); idx < IDS->end(); idx++ ) { + if( !createStream((*idx)) ) LOG_ERROR( "STREAM Creation Failure!" ); + }; + delete( IDS ); + }; + }; + return true; +}; + +void argusModuleEmbedVideo::pushFrame(AVFrame *Frame, void* src){ + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + if( tMD ) { + }; +}; + +void argusModuleEmbedVideo::pushFrame(cv::Mat* Frame, void* src){ + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + if( tMD ) { + + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) { + if( (*idx)->mediaStreamId == tMD->mediaStreamId ) { + + break; + }; + }; + }; +}; + +bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){ + if( CTX ){ + if( id ){ + if( pipe( CTX->m_iEncoderPipe ) == -1 ){ + CTX->bValid = false; + return false; + }; + CTX->STREAM = (STREAM_CTX *) av_mallocz(sizeof(STREAM_CTX)); + if( CTX->STREAM ) { + CTX->STREAM->mediaStreamId = id; + + return true; + } else { + close( CTX->m_iEncoderPipe[0] ); CTX->m_iEncoderPipe[0] = -1; + close( CTX->m_iEncoderPipe[1] ); CTX->m_iEncoderPipe[1] = -1; + LOG_ERROR("STREAM memory allocation error!"); + CTX->bValid = false; + return false; + }; + } +#ifdef DEBUG + else { + CTX->bValid = true; + CTX->STREAM = (STREAM_CTX *) av_mallocz(sizeof(STREAM_CTX)); + if( CTX->STREAM ) { + CTX->STREAM->mediaStreamId = 0; + }; + return true; + } +#endif + ; + } else LOG_ERROR("Client Context error!"); + return false; +}; + +bool argusModuleEmbedVideo::registerStream( MEDIA_SOURCE_DESC *ptr ){ + if( ptr ){ + if( m_vRegisteredStreams.size() ){ + bool found = false; + m_mStreamsProtector.lock(); + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) { + if( (*idx)->mediaStreamId == ptr->mediaStreamId ) { + found = true; + break; + }; + }; + m_mStreamsProtector.unlock(); + if( !found ) return createStream( ptr->mediaStreamId ); + } else { + return createStream( ptr->mediaStreamId ); + }; + }; + return false; +}; + +bool argusModuleEmbedVideo::unregisterStream( MEDIA_SOURCE_DESC *ptr ){ + if( ptr ){ + if( m_vRegisteredStreams.size() ){ + m_mStreamsProtector.lock(); + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) { + if( (*idx)->mediaStreamId == ptr->mediaStreamId ) { + //destroyStream((*idx)); + m_vRegisteredStreams.erase( idx ); + m_mStreamsProtector.unlock(); + return true; + }; + }; + m_mStreamsProtector.unlock(); + }; + }; + return false; +}; + +bool argusModuleEmbedVideo::createStream( uint32_t id ){ + DBC_MEDIA_STREAM_DATA *tDATA = NULL; + bool retVal = false; + if( m_vRegisteredStreams.size() ){ + m_mStreamsProtector.lock(); + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) if( (*idx)->mediaStreamId == id ) return true; + m_mStreamsProtector.unlock(); + }; + if( m_pDBC ) { + tDATA = m_pDBC->getMediaStreamData( id ); + if( tDATA ) { + STREAM_CTX *CTX = (STREAM_CTX*) av_mallocz(sizeof(STREAM_CTX)); + if( CTX ) { + CTX->ModulePtr = this; + CTX->mediaStreamId = id; + initLibAV(); + if( open_module_video( + CTX, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_FPS, + VIDEO_OUTPUT_BITRATE, + VP_FAST, + VC_MJPEG, + VF_MJPEG + ) ){ + CTX->InputMat = new cv::Mat( VIDEO_OUTPUT_HEIGHT, VIDEO_OUTPUT_WIDTH, CV_8UC3 ); + if( CTX->InputMat == NULL ) { + TLOG_ERROR("Cannot ctreate cv::Mat for encoder!"); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("cv::Mat Created"); +#endif + cv::rectangle( *CTX->InputMat, cv::Point( 0, 0 ), cv::Point( VIDEO_OUTPUT_WIDTH, VIDEO_OUTPUT_HEIGHT ), cv::Scalar( 255, 0, 0 ), cv::FILLED ); + if( write_header( CTX ) ){ +#ifdef DEBUG + LOG( "Header SENT" ); +#endif + CTX->video_sws_ctx = sws_getContext( + tDATA->width, + tDATA->height, + AV_PIX_FMT_BGR24, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_PIX_FMT, + SWS_BICUBIC, + NULL, + NULL, + NULL + ); + if( CTX->video_sws_ctx == NULL ){ + char buffer[200]; + sprintf( buffer, "Failed to get SWS CTX [%dx%d]{%04X} ---> [%dx%d]{%04X} by (%d)", + tDATA->width, + tDATA->height, + AV_PIX_FMT_BGR24, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_PIX_FMT, + SWS_BICUBIC + ); + LOG_ERROR( buffer ); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("Finish Preparing SWS"); +#endif + CTX->video_frame = av_frame_alloc(); + if( CTX->video_frame == NULL ){ + LOG_ERROR("Error Create AVFrame!"); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("Frame Created"); +#endif + CTX->video_frame->width = VIDEO_OUTPUT_WIDTH; + CTX->video_frame->height = VIDEO_OUTPUT_HEIGHT; + CTX->video_frame->format = VIDEO_OUTPUT_PIX_FMT; + uint8_t *tBuff = (uint8_t *) av_malloc( + av_image_get_buffer_size( + (AVPixelFormat)CTX->video_frame->format, + CTX->video_frame->width, + CTX->video_frame->height, + BUFFER_ALIGN + ) + ); + if( tBuff == NULL) { + TLOG_ERROR("Error Allocate Buffer for AVFrame!"); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("Buffer Created"); +#endif + avpicture_fill( + (AVPicture *)CTX->video_frame, + tBuff, + (AVPixelFormat)CTX->video_frame->format, + CTX->video_frame->width, + CTX->video_frame->height + ); + TLOG("Finish Preparing output AVFrame"); + m_mStreamsProtector.lock(); + m_vRegisteredStreams.push_back( CTX ); + m_mStreamsProtector.unlock(); +#ifdef DEBUG + LOG("STREAM Created"); +#endif + retVal = true; + } else { + cleanSTREAM_CTX( CTX ); + }; + } else { + cleanSTREAM_CTX( CTX ); + }; + }; + free( tDATA ); + }; + }; + return retVal; +}; + + +#undef LOG +#undef LOG_ERROR +#undef TLOG +#undef TLOG_ERROR diff --git a/lib/rgoose/rgooseModuleEmbedVideo - Copy.h b/lib/rgoose/rgooseModuleEmbedVideo - Copy.h new file mode 100644 index 00000000..691d0f8e --- /dev/null +++ b/lib/rgoose/rgooseModuleEmbedVideo - Copy.h @@ -0,0 +1,225 @@ +#ifndef __ARGUS_MODULE_EMBED_VIDEO_HEADER__ +#define __ARGUS_MODULE_EMBED_VIDEO_HEADER__ +#include "rgooseModule.h" +#include "../components/base/basicMutex.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" +//#include "../data/media/video/videoAVLIBDestination.h" +#include "../components/base/basicMediaDestination.h" + +class argusModuleEmbedVideo; + +#define FILESTREAMBUFFERSZ 1048576 + +/* Video CODECS */ +#define VC_VPX 0 +#define VC_X264 1 +#define VC_MP4 2 +#define VC_MJPEG 3 +#define VC_FLV 4 + +/* Video FORMATS */ +#define VF_WEBM 0 +#define VF_MP4 1 +#define VF_MP3 2 +#define VF_AAC 3 +#define VF_OGG 4 +#define VF_MJPEG 5 +#define VF_FLV 6 + +/* Encoder PROFILES */ +#define VP_ULTRAFAST 0 +#define VP_VERYFAST 1 +#define VP_FAST 2 +#define VP_MEDIUM 3 +#define VP_SLOW 4 +#define VP_VERYSLOW 5 +#define VP_ULTRASLOW 6 + +#define VIDEO_OUTPUT VO_MJPEG +//#define VIDEO_OUTPUT VO_MPEG4 +//#define VIDEO_OUTPUT VO_H264 +//#define VIDEO_OUTPUT VO_FLV + +#define VIDEO_OUTPUT_WIDTH 1920 +#define VIDEO_OUTPUT_HEIGHT 1080 +#define VIDEO_OUTPUT_FPS 10 +#define VIDEO_OUTPUT_GOP 30 + +#if( LIBAVCODEC_VERSION_MAJOR < 54 ) + //#define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG + //#define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P +#else + //#if( VIDEO_OUTPUT == VO_MJPEG ) + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUVJ422P + #define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "mjpeg" + /* + #endif + #if( VIDEO_OUTPUT == VO_MPEG4 ) + + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_BITRATE 100000000 + #define VIDEO_OUTPUT_CONTAINER "mp4" + //* + #endif + #if( VIDEO_OUTPUT == VO_H264 ) + //* / + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H264 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 100000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "matroska" + #define VIDEO_OUTPUT_CONTAINER "mkv" + /* + #endif + #if( VIDEO_OUTPUT == VO_FLV ) + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "flv" + #endif + */ +#endif + +typedef struct S_buffer_data { + uint8_t * buf; + int size; + uint8_t * ptr; + size_t room; ///< size left in the buffer +} buffer_data; + +#define NR_COLORS 4 +#define AVIO_BUFFER_SIZE 4096 +#define BD_BUFFER_SIZE 1024 + +typedef struct S_STREAM_CTX{ + argusModuleEmbedVideo * ModulePtr; + uint32_t mediaStreamId; + AVFormatContext * ofmt_ctx; + + + AVIOContext * avio_ctx; + uint8_t * avio_ctx_buffer; + size_t avio_ctx_buffer_size; + buffer_data * buffer; + + + /* VIDEO */ + AVStream * video_stream; + struct SwsContext * video_sws_ctx; + AVCodecContext * video_ctx; + AVCodec * video_codec; + AVFrame * video_frame; + + /* For Encoding */ + cv::Mat * InputMat; + AVFrame * outputFrame; + + int64_t ts; + uint32_t frame_idx; + int have_video; + bool bHeaderIsReady; + uint8_t * header; + uint32_t header_size; +#ifndef _NOAUDIO_ + /* AUDIO */ + AVStream * audio_stream; + AVCodecContext * audio_ctx; + AVCodec * audio_codec; + struct SwrContext * audio_swr_ctx; + AVFrame * audio_frame; + int have_audio; + uint32_t audio_buffer_size; + float * audio_buffer_left; + float * audio_buffer_right; + uint32_t max_audio_buffer_size; + int src_sample_rate; + int src_bit_rate; + int src_nr_channels; + int dst_nb_samples; + int audio_frame_bytes; +#endif +}STREAM_CTX; + + +typedef struct S_WEB_CLIENT_CTX{ + int m_iSocketFID; + int m_iEncoderPipe[2]; + AVPacket * pkt; + + bool bValid; + + bool initDone; + bool headerIsSent; + + argusModuleEmbedVideo * ModulePtr; + STREAM_CTX * STREAM; +}WEB_CLIENT_CTX; + + +typedef struct S_WEB_HANDLER{ + DWORD m_dwThreadID; +#ifdef __linux__ + pthread_t m_hThreadHandle; +#else + HANDLE m_hThreadHandle; +#endif + WEB_CLIENT_CTX * CTX; +}WEB_HANDLER; + +typedef vector vectorHANDLERS; +typedef vector vectorSTREAMS; + +class argusModuleEmbedVideo: public argusKernelModule, public basicMediaDestination, public basicThread { + private: + basicEventHeap * m_pEventHeap; + static void * webClientProc( void *ptr ); + //static int write_packet( void *opaque, uint8_t *buf, int buf_size ); + int m_nSocketDescriptor; + basicMutex m_mHandlersProtector; + vectorHANDLERS m_vHandlersPool; + basicMutex m_mStreamsProtector; + vectorSTREAMS m_vRegisteredStreams; + bool registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ); + bool write_header( STREAM_CTX *CTX ); + bool createStream( uint32_t id ); + bool open_client_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int codec_idx, int format_idx ); + bool open_module_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int preset_idx, int codec_idx, int format_idx ); + static int write_module_packet( void *opaque, uint8_t *buf, int buf_size ); + static int write_client_packet( void *opaque, uint8_t *buf, int buf_size ); + void encode_module_video( STREAM_CTX *CTX, AVFrame *DATA ); + void encode_client_video( STREAM_CTX *CTX, AVPacket *pkt ); + void add_video_frame( STREAM_CTX *CTX ); + void destroy( WEB_CLIENT_CTX *&ptr ); + void cleanSTREAM_CTX( STREAM_CTX *&CTX ); + uint8_t * close_stream( STREAM_CTX *CTX, int* size ); +#ifndef _NOAUDIO_ + void encode_audio( STREAM_CTX *CTX, AVFrame *DATA ); + bool alloc_audio_frame( STREAM_CTX *CTX ); + int check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt ); + void add_audio_frame( STREAM_CTX *CTX, float* left, float* right, int size ); + bool open_audio( STREAM_CTX *&CTX, int sample_rate, int nr_channels, int bit_rate, int codec_idx ); +#endif + protected: + /* From Basic Thread */ + virtual void m_fThreadProc( void ); + public: + explicit argusModuleEmbedVideo( uint32_t moduleID ); + ~argusModuleEmbedVideo(); + /* From Kernel Module */ + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService(); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); + bool registerStream( MEDIA_SOURCE_DESC *ptr ); + bool unregisterStream( MEDIA_SOURCE_DESC *ptr ); + /* from Media Destination */ + virtual void pushFrame(AVFrame *Frame, void* src = NULL); + virtual void pushFrame(cv::Mat* Frame, void* src = NULL); +}; +#endif diff --git a/lib/rgoose/rgooseModuleEmbedVideo.cpp b/lib/rgoose/rgooseModuleEmbedVideo.cpp index 9d596f61..59a7a54e 100644 --- a/lib/rgoose/rgooseModuleEmbedVideo.cpp +++ b/lib/rgoose/rgooseModuleEmbedVideo.cpp @@ -26,7 +26,6 @@ #define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X ) - #ifdef DEBUG #define LOG_ERROR( X ) {\ char _tBfrErrMSG2w34[256];\ @@ -38,7 +37,15 @@ #endif #define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X ) -#define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ) +#ifdef DEBUG + #define TLOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ); +#endif enum { WEBRTC_REQ_SIGNIN = 0, @@ -52,15 +59,27 @@ static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_ou //buffer_data bd[1]={0}; argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicMediaDestination(), basicThread(){ + LOG( "Begin C" ); m_pEventHeap = basicEventHeap::getInstance(); - DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); - if( tDATA ) { - memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); - free( tDATA ); + LOG( "Evt Heap" ); + if( m_pDBC ){ + LOG( "DB OK!" ); + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + LOG( "Query DB!" ); + if( tDATA ) { + LOG( "Data fetched from DB!" ); + memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); + free( tDATA ); + } else { + LOG( "No Data fetched from DB!" ); + memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); + m_sEmbedVideoData.port = 8972; + }; } else { - memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); - m_sEmbedVideoData.port = 8972; + LOG_ERROR( "DB Error!" ); }; + LOG( "DB data" ); + char tB[64]; sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port ); LOG( tB ); @@ -73,7 +92,18 @@ argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelMo if( m_sEmbedVideoData.show_logo ){ LOG("Show Logo"); LOG( m_sEmbedVideoData.logo_md5 ); + char tPath[256]; + sprintf( tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5); + if(!fileExist(tPath)){ + LOG_ERROR("Logo File Missed!"); + m_sEmbedVideoData.show_logo = false; + } +#ifdef DEBUG + else LOG("Logo File is OK"); +#endif + ; }; + LOG( "End C" ); }; argusModuleEmbedVideo::~argusModuleEmbedVideo(){ @@ -107,6 +137,9 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n"; WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; argusModuleEmbedVideo * MODULE = CTX->ModulePtr; + uint32_t msgSize; + uint8_t tBuf[FILESTREAMBUFFERSZ]; + int retVal; if( CTX ) { char mesg[1024]; @@ -147,7 +180,9 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ CTX->bValid = false; continue; }; - //TLOG( mesg ); +#ifdef DEBUG_EXTRA + TLOG( mesg ); +#endif uint32_t index = 0; reqline[index] = strtok( mesg, "\n" ); @@ -172,7 +207,9 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ continue; }; }; +#ifdef DEBUG_EXTRA TLOG( cGetURI ); +#endif }; // parse rest of request while( ( reqline[++index] = strtok( NULL, "\n" ) )!= NULL ) { @@ -180,7 +217,9 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ char * pPart; pPart = strcasestr( reqline[index], "Upgrade" ); if( pPart != NULL ) { +#ifdef DEBUG_EXTRA TLOG("Upgrade Mode ON"); +#endif //bUpgradeMode = true; }; }; @@ -202,8 +241,10 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ if( pPart != NULL ) { char tBuf[CTEXT]; //nWebSocketVersion = atoi(pPart+1); +#ifdef DEBUG_EXTRA sprintf( tBuf,"Web Socket Version: %d", 0 );//nWebSocketVersion ); TLOG( tBuf ); +#endif }; }; if( strncmp( reqline[index], "Sec-WebSocket-Key:", 18 ) == 0 ) { @@ -244,7 +285,9 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ pPart++; if(strncmp( pPart, "permessage-deflate", 18 ) == 0 ) { m_bDeflatePerMessage = true; +#ifdef DEBUG_EXTRA TLOG("Using Deflate"); +#endif }; }; }; @@ -255,11 +298,14 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ pPart++; if(strncmp( pPart, "gzip, deflate", 13 ) == 0 ) { m_bDeflatePerMessage = true; +#ifdef DEBUG_EXTRA TLOG("Using Deflate"); +#endif }; }; }; }; + if( strncmp( cGetURI, "/stream", 7 ) == 0 ) { uint32_t tStreamID = 0; CSTR tP; @@ -271,9 +317,11 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ }; }; if( tStreamID ) { +#ifdef DEBUG_EXTRA char tB[64]; sprintf(tB,"StremID: %d", tStreamID ); TLOG( tB ); +#endif if( CTX->ModulePtr->registerForMediaStream( tStreamID, CTX ) ){ // Send Header if( send( CTX->m_iSocketFID, head, strlen(head), 0 ) < 0 ){ @@ -284,26 +332,35 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ CTX->initDone = true; continue; } else { +#ifdef DEBUG_EXTRA TLOG("Stream id Not Online"); +#endif }; - } else TLOG("No Stream ID"); + } +#ifdef DEBUG_EXTRA + else TLOG("No Stream ID") +#endif + ; }; if( CTX->ModulePtr->n_pNoSignalData ) { sprintf( mesg, no_signal, CTX->ModulePtr->m_nNoSignalSize ); send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 ); send( CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0 ); send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 ); +#ifdef DEBUG_EXTRA TLOG("Sent No Signal Image!"); +#endif } else { // Send 404 Header send( CTX->m_iSocketFID, abort, strlen(abort), 0 ); +#ifdef DEBUG_EXTRA TLOG("Aborted!"); +#endif }; CTX->bValid = false; continue; } else { - uint32_t msgSize; - int retVal; + retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); if( retVal == -1 ){ if( errno == EAGAIN || errno == EWOULDBLOCK ){ @@ -313,11 +370,12 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ CTX->bValid = false; continue; }; - uint8_t *tBuf = (uint8_t *) malloc(msgSize); - if( tBuf ){ + + //uint8_t *tBuf = (uint8_t *) malloc(msgSize); + //if( tBuf ){ retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); if( retVal == -1 ){ - free( tBuf ); + //free( tBuf ); if( errno == EAGAIN || errno == EWOULDBLOCK ){ continue; }; @@ -344,16 +402,18 @@ void *argusModuleEmbedVideo::webClientProc( void *ptr ){ CTX->bValid = false; continue; }; - free( tBuf ); - } else { - TLOG_ERROR("Mem Alloc Error!"); - CTX->bValid = false; - }; + // free( tBuf ); + //} else { + // TLOG_ERROR("Mem Alloc Error!"); + // CTX->bValid = false; + //}; }; }; }; CTX->bValid = false; +#ifdef DEBUG_EXTRA TLOG("WEB Client Handler Ended!"); +#endif close( CTX->m_iEncoderPipe[0] ); shutdown( CTX->m_iSocketFID, SHUT_RDWR); close( CTX->m_iSocketFID ); @@ -390,20 +450,28 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ // Handle Connections if( RetVal != 0 ){ if ( pfd[0].revents & POLLIN ) { +#ifdef DEBUG_EXTRA LOG("Handle New Client"); +#endif int tSID = accept( pfd[0].fd, NULL, NULL); if( tSID < 0 ){ char tBuf[CTEXT]; sprintf(tBuf, "Accept() error: %s", strerror(errno)); LOG_ERROR(tBuf); } else { +#ifdef DEBUG_EXTRA LOG("Accept OK"); +#endif WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); if( tCTX ) { +#ifdef DEBUG_EXTRA LOG("CTX OK"); +#endif WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); if( tHANDLER ) { +#ifdef DEBUG_EXTRA LOG("HANDLER OK"); +#endif memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) ); memset( tHANDLER, 0, sizeof(WEB_HANDLER) ); tCTX->m_iSocketFID = tSID; @@ -412,7 +480,9 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ tCTX->mediaStreamId = 0; tCTX->bValid = true; tCTX->ModulePtr = this; +#ifdef DEBUG_EXTRA LOG("Before Thread Create"); +#endif int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX ); if( RetVal == -1 ) { free(tCTX); @@ -425,7 +495,9 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ m_mHandlersProtector.lock(); m_vHandlersPool.push_back( tHANDLER ); m_mHandlersProtector.unlock(); +#ifdef DEBUG_EXTRA LOG("Handler Pushed to a Pool"); +#endif }; } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click free(tCTX); @@ -453,7 +525,7 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ m_mHandlersProtector.lock(); m_vHandlersPool.erase(idx); m_mHandlersProtector.unlock(); -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("Web Handler Ripped!"); #endif }; @@ -474,12 +546,10 @@ void argusModuleEmbedVideo::m_fThreadProc( void ){ bool argusModuleEmbedVideo::startService(){ - LOG("Create"); //Create NoSignal Image cv::Mat tMat( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 ); cv::rectangle( tMat, cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::Scalar( 255, 0, 0 ), cv::FILLED ); cv::putText( tMat, "NO SIGNAL", cv::Point( 10, 30 ), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar( 0, 255, 255 ), 3 ); - if( m_sEmbedVideoData.show_logo ) { int a_x, a_y; if( m_sEmbedVideoData.logo_x < 0 ) { @@ -501,8 +571,9 @@ bool argusModuleEmbedVideo::startService(){ if( T.cols > 0 ) { cv::Mat mask; vector layers; - - +#ifdef DEBUG + LOG("Logo Loaded OK"); +#endif cv::split( T, layers); // seperate channels cv::Mat rgb[3] = { layers[0], layers[1], layers[2] }; mask = layers[3]; // png's alpha channel used as mask @@ -523,26 +594,30 @@ bool argusModuleEmbedVideo::startService(){ LOG("Logo Disabled - Wrong Coords"); m_sEmbedVideoData.show_logo = false; }; + LOG("Logo Draw OK"); }; - vector compression_params; - //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); - //compression_params.push_back(9); - compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); - compression_params.push_back(75); - vector buf; - cv::imencode( ".jpg", tMat, buf, compression_params ); - m_nNoSignalSize = buf.size(); - n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize ); - if( n_pNoSignalData ) { - memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize ); - } else m_nNoSignalSize =0; - buf.clear(); - + try{ + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_sEmbedVideoData.compression_quality ); + vector buf; + cv::imencode( ".jpg", tMat, buf, compression_params ); + m_nNoSignalSize = buf.size(); + n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize ); + if( n_pNoSignalData ) { + memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize ); + } else m_nNoSignalSize =0; + buf.clear(); + } catch (cv::Exception & e) { + LOG_ERROR(e.msg.c_str()); + }; + // Socket struct sockaddr sa; struct sockaddr_in *sin; - memset(&sa, 0, sizeof(struct sockaddr)); sa.sa_family = AF_INET; sin = (struct sockaddr_in *)&sa; @@ -572,6 +647,7 @@ bool argusModuleEmbedVideo::startService(){ } else { LOG("Listen OK"); }; + LOG("Start Thread"); return init(); }; @@ -608,9 +684,6 @@ bool argusModuleEmbedVideo::reloadSettings(){ return true; }; -void argusModuleEmbedVideo::dispatchEvent(EVENT_CONTAINER *Evt){ -}; - bool argusModuleEmbedVideo::validate(){ return true; }; @@ -622,50 +695,96 @@ void argusModuleEmbedVideo::pushFrame( AVFrame *Frame, void* src){ }; void argusModuleEmbedVideo::pushFrame( cv::Mat &Frame, void* src ){ - MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + char tBuffer[128]; if( tMD ) { - if( m_vHandlersPool.size() ) { - cv::Mat RD; - cv::resize( Frame, RD, cv::Size( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::INTER_LINEAR ); - if( m_sEmbedVideoData.show_ts ){ - char DateStr[200]; - time_t t = time( NULL ); - struct tm * tmp = gmtime( &t ); - if( tmp ){ - if( strftime( DateStr, sizeof(DateStr), "%F %T GMT", tmp )!=0 ){ - cv::rectangle( RD, cv::Point( 10, 10 ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); - cv::putText( RD, DateStr, cv::Point( 30, 45 ), - (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, - m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), - m_sEmbedVideoData.ts_font_thickness, - m_sEmbedVideoData.ts_line_type - ); - }; - }; + float mK, oK; + cv::Rect ROI; + if( !m_mPictureProtector.try_lock() ) return; + oK = ((float)m_sEmbedVideoData.height )/ ((float)m_sEmbedVideoData.width); + mK = ((float)Frame.rows )/ ((float)Frame.cols); + //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); + if( m_mapMATS[tMD->mediaStreamId].cols == 0 ) { + LOG("First Frame Enqueued"); + sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId ); + LOG( tBuffer ); + + m_mapMATS[tMD->mediaStreamId].create( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 ); + cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.height, m_sEmbedVideoData.width ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); + }; + if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) { + ROI.width = (int) m_sEmbedVideoData.width; + ROI.height = (int) m_sEmbedVideoData.height; + ROI.x = (int) 0; + ROI.y = (int) 0; + } else { + if( mK < oK ) { + ROI.width = (int) m_sEmbedVideoData.width; + ROI.height = (int) (((float)m_sEmbedVideoData.width) * mK ); + ROI.x = (int) 0; + ROI.y = (int)( m_sEmbedVideoData.height - ROI.height ) >> 1; + } else { + ROI.height = (int) m_sEmbedVideoData.height; + ROI.width = (int) (((float)m_sEmbedVideoData.height) / mK ); + ROI.y = (int) 0; + ROI.x = (int) ( m_sEmbedVideoData.width - ROI.width ) >> 1; }; - if( m_sEmbedVideoData.show_logo ){ - cv::Rect roi( cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h )); - cv::Mat destinationROI = RD( roi ); - m_mLogoPic.copyTo( destinationROI, m_mLogoMask ); + } + cv::Mat mROI = m_mapMATS[tMD->mediaStreamId]( ROI ); + cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR ); + /* + cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( 30, 45 ), + (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, + m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), + m_sEmbedVideoData.ts_font_thickness, + m_sEmbedVideoData.ts_line_type + ); + */ + if( m_sEmbedVideoData.show_ts ){ + char DateStr[200]; + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + if( strftime( DateStr, sizeof(DateStr), "%F %T GMT", tmp )!=0 ){ + cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( 10, 10 ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED ); + cv::putText( m_mapMATS[tMD->mediaStreamId], DateStr, cv::Point( 30, 45 ), + (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face, + m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ), + m_sEmbedVideoData.ts_font_thickness, + m_sEmbedVideoData.ts_line_type + ); + }; }; + }; + if( m_sEmbedVideoData.show_logo ){ + cv::Rect roi( cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h )); + cv::Mat destinationROI = m_mapMATS[tMD->mediaStreamId]( roi ); + m_mLogoPic.copyTo( destinationROI, m_mLogoMask ); + }; - vector compression_params; - //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); - //compression_params.push_back(9); - compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); - compression_params.push_back(75); - vector buf; - uint32_t DataSize; - cv::imencode( ".jpg", RD, buf, compression_params ); - DataSize = buf.size(); - uint8_t *pData = buf.data(); - for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { - if( (*idx)->CTX->mediaStreamId == tMD->mediaStreamId ) { - write( (*idx)->CTX->m_iEncoderPipe[1], &DataSize, sizeof(uint32_t)); - write( (*idx)->CTX->m_iEncoderPipe[1], pData, DataSize ); + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_sEmbedVideoData.compression_quality ); + //vector buf; + uint32_t DataSize; + //m_mPictureProtector.lock(); + m_mapCAPTURES[tMD->mediaStreamId].clear(); + cv::imencode( ".jpg", m_mapMATS[tMD->mediaStreamId], m_mapCAPTURES[tMD->mediaStreamId], compression_params ); + DataSize = m_mapCAPTURES[tMD->mediaStreamId].size(); //buf.size(); + if( DataSize ) { + uint8_t *pData = m_mapCAPTURES[tMD->mediaStreamId].data(); //buf.data(); + if( m_vHandlersPool.size() ) { + for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { + if( (*idx)->CTX->mediaStreamId == tMD->mediaStreamId ) { + write( (*idx)->CTX->m_iEncoderPipe[1], &DataSize, sizeof(uint32_t)); + write( (*idx)->CTX->m_iEncoderPipe[1], pData, DataSize ); + }; }; }; }; + m_mPictureProtector.unlock(); }; }; @@ -692,7 +811,45 @@ bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX return false; }; +void argusModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){ + if( Evt ) { + switch( Evt->m_eClass ) { + case EVT_CLASS_IMAGE: + case EVT_CLASS_VIDEO:{ + switch( Evt->m_eType ) { + case EVT_CAPTURE_START:{ +#ifdef DEBUG + LOG("Capture Event"); +#endif + //cam_id + //parent_evt_id + char MD5[33]; + uint32_t id = 0; + if( saveStreamPicture( id, (CSTR*)&MD5) ) { + }; + break; + }; + }; + break; + }; + }; + }; +}; + +bool argusModuleEmbedVideo::saveStreamPicture( uint32_t id, CSTR *MD5 ){ + if( m_mapCAPTURES.find( id ) != m_mapCAPTURES.end() ){ + CSTR cMD5 = NULL; + FILE *tFD; + m_mPictureProtector.lock(); + if( cMD5 ) { + strncpy( *MD5, cMD5, 32 ); + (*MD5)[32]=(char)0; + }; + m_mPictureProtector.unlock(); + }; + return false; +}; #undef LOG #undef LOG_ERROR diff --git a/lib/rgoose/rgooseModuleEmbedVideo.h b/lib/rgoose/rgooseModuleEmbedVideo.h index c9ff7e45..23dacd94 100644 --- a/lib/rgoose/rgooseModuleEmbedVideo.h +++ b/lib/rgoose/rgooseModuleEmbedVideo.h @@ -120,19 +120,34 @@ typedef struct S_WEB_HANDLER{ typedef vector vectorHANDLERS; //typedef vector vectorSTREAMS; +typedef struct S_STREAM_CAP{ + uint32_t stream_id; + uint32_t buffer_size; + uint8_t picture_buffer; +}STREAM_CAP; + +typedef vector compressedFRAME; +typedef map mapSTREAMCAPS; +typedef map mapSTREAMMAPS; + + class argusModuleEmbedVideo: public argusKernelModule, public basicMediaDestination, public basicThread { private: basicEventHeap * m_pEventHeap; static void * webClientProc( void *ptr ); int m_nSocketDescriptor; basicMutex m_mHandlersProtector; + basicMutex m_mPictureProtector; vectorHANDLERS m_vHandlersPool; DBC_MODULE_EMBED_VIDEO_DATA m_sEmbedVideoData; + mapSTREAMCAPS m_mapCAPTURES; + mapSTREAMMAPS m_mapMATS; uint8_t * n_pNoSignalData; uint32_t m_nNoSignalSize; cv::Mat m_mLogoPic; cv::Mat m_mLogoMask; bool registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ); + bool saveStreamPicture( uint32_t id, CSTR *MD5 ); protected: /* From Basic Thread */ virtual void m_fThreadProc( void ); diff --git a/lib/rgoose/rgooseModuleFactory.cpp b/lib/rgoose/rgooseModuleFactory.cpp index 2edea455..43b0554e 100644 --- a/lib/rgoose/rgooseModuleFactory.cpp +++ b/lib/rgoose/rgooseModuleFactory.cpp @@ -42,9 +42,10 @@ argusModuleFactory::~argusModuleFactory(){ }; bool argusModuleFactory::loadModules( uint32_t ServerID ){ + DBC_INT_LIST *tList = NULL; + if(m_pDBC == NULL) return false; m_nServerID = ServerID; - DBC_INT_LIST *tList = NULL; tList = m_pDBC->listModules( m_nServerID ); if( tList != NULL ) { if( tList->size() ) { @@ -57,11 +58,13 @@ bool argusModuleFactory::loadModules( uint32_t ServerID ){ } #endif delete( tList ); - return true; - } else { - LOG_ERROR("Cannot Fetch Modules from DB!"); - }; - return false; + } +#ifdef DEBUG + else { + LOG("No Modules Defined"); + } +#endif + return true; }; argusKernelModule *argusModuleFactory::createModule( int id ){ diff --git a/lib/rgoose/rgooseNodeFactory.cpp b/lib/rgoose/rgooseNodeFactory.cpp index ead48f87..c1b42a24 100644 --- a/lib/rgoose/rgooseNodeFactory.cpp +++ b/lib/rgoose/rgooseNodeFactory.cpp @@ -3,6 +3,7 @@ #include "rgooseNode3D.h" #include "rgooseNode2D.h" #include "rgooseNodePTZCamControl.h" +#include "rgooseNodeStaticCamControl.h" #ifdef MEM_DEBUG #include "../alg/generic/heapDebug.h" @@ -42,7 +43,14 @@ bool argusNodeFactory::unloadNodes( void ){ for( vectorNetNodes::iterator index = m_vNetNodes.begin(); index < m_vNetNodes.end(); index++ ){ LOG(" Unload Node... BEGIN"); switch( (*index)->getType() ){ - //case ARGUS_ANALOG_STATIC_CAMERA: delete( (chucha*) (*index) ); break; + case ARGUS_ANALOG_STATIC_CAMERA: + LOG(" Static Analog Cam"); + delete( (ARGUS_CAM*) (*index) ); + break; + case ARGUS_ANALOG_PTZ_CAMERA: + LOG(" PTZ Analog Cam"); + delete( (ARGUS_PTZCAM*) (*index) ); + break; case ARGUS_IP_PTZ_CAMERA:{ LOG(" PTZ IP Cam"); delete( (ARGUS_PTZCAM*) (*index) ); @@ -50,7 +58,7 @@ bool argusNodeFactory::unloadNodes( void ){ }; case ARGUS_IP_STATIC_CAMERA:{ LOG(" Static IP Cam"); - delete( (ARGUS_PTZCAM*) (*index) ); + delete( (ARGUS_CAM*) (*index) ); break; }; case ARGUS_IP_UART_GATEWAY:{ @@ -103,40 +111,32 @@ bool argusNodeFactory::loadNodes( uint32_t SiteID ){ */ bool argusNodeFactory::loadNodes( uint32_t SiteID ){ if( m_pDBC == NULL ) return false; - LOG("DB OK"); m_nSiteID = SiteID; DBC_INT_LIST *tList = m_pDBC->listNodes( SiteID ); if( tList != NULL ) { - LOG("Have Nodes"); - for( int index=0; index< tList->size(); index++ ) { - LOG("Have to Create"); - createNode( tList->at(index) ); - }; + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) createNode((*idx)); tList->clear(); delete( tList ); - return true; - }; - return false; + } +#ifdef DEBUG + else { + LOG("No Nodes Defined"); + } +#endif + return true; }; bool argusNodeFactory::reloadNodes( uint32_t SiteID ){ - if(m_pDBC == NULL) return false; if(!unloadNodes()) return false; - m_nSiteID = SiteID; - DBC_INT_LIST *tList = NULL; - tList = m_pDBC->listNodes( SiteID ); - if( tList != NULL ) { - for( int index=0; index< tList->size(); index++ ) { - createNode( tList->at(index) ); - }; - tList->clear(); - delete( tList ); - return true; - }; - return false; + return loadNodes( SiteID ); }; bool argusNodeFactory::reloadNode( uint32_t NodeID ){ + deleteNode( NodeID ); + argusNetNode *tNode = createNode( NodeID ); + if( tNode ) { + return true; + }; return false; }; @@ -148,27 +148,55 @@ argusNetNode *argusNodeFactory::createNode( uint32_t id ){ tData = m_pDBC->getNodeData( id ); if( tData!= NULL ) { switch( tData->type ) { - case ARGUS_ANALOG_STATIC_CAMERA: + case ARGUS_ANALOG_STATIC_CAMERA:{ #ifdef DEBUG - LOG("Creating Analog Static Camera"); -#endif - break; - case ARGUS_ANALOG_PTZ_CAMERA: + LOG("Creating Analog Static Camera"); +#endif + ARGUS_CAM *tCamera; + tCamera = new ARGUS_CAM( id ); + if( tCamera ) { + LOG("Starting Service"); + tCamera->startService(); + tVal = ( argusNetNode *) tCamera; + LOG("Success"); + }; + break; + }; + case ARGUS_ANALOG_PTZ_CAMERA:{ #ifdef DEBUG - LOG("Creating Analog PTZ Camera"); -#endif - break; + LOG("Creating Analog PTZ Camera"); +#endif + ARGUS_PTZCAM *tCamera; + tCamera = new ARGUS_PTZCAM( id ); + if( tCamera ) { + LOG("Starting Service"); + tCamera->startService(); + tVal = ( argusNetNode *) tCamera; + LOG("Success"); + }; + break; + }; case ARGUS_IP_STATIC_CAMERA:{ #ifdef DEBUG LOG("Creating IP Static Camera"); #endif - ARGUS_PTZCAM *tCamera; - tCamera = new ARGUS_PTZCAM( id ); + ARGUS_CAM *tCamera; + tCamera = new ARGUS_CAM( id ); if( tCamera ) { +#ifdef DEBUG LOG("Starting Service"); - tCamera->startService(); - tVal = ( argusNetNode *) tCamera; - LOG("Success"); +#endif + if( tCamera->startService() ){ + tVal = ( argusNetNode *) tCamera; +#ifdef DEBUG + LOG("Success"); +#endif + } else { +#ifdef DEBUG + LOG_ERROR("Error Sterting Service"); +#endif + delete( tCamera ); + }; }; break; }; @@ -180,10 +208,20 @@ argusNetNode *argusNodeFactory::createNode( uint32_t id ){ ARGUS_PTZCAM *tCamera; tCamera = new ARGUS_PTZCAM( id ); if( tCamera ) { +#ifdef DEBUG LOG("Starting Service"); - tCamera->startService(); - tVal = ( argusNetNode *) tCamera; - LOG("Success"); +#endif + if( tCamera->startService() ){ + tVal = ( argusNetNode *) tCamera; +#ifdef DEBUG + LOG("Success"); +#endif + } else { +#ifdef DEBUG + LOG_ERROR("Error Starting Service!"); +#endif + delete( tCamera ); + }; }; break; }; @@ -198,7 +236,7 @@ argusNetNode *argusNodeFactory::createNode( uint32_t id ){ #ifdef DEBUG LOG("Creating Network Video Encoder"); #endif - break; + break; case ARGUS_LFS_SENSOR:{ #ifdef DEBUG LOG("Creating LFS Sensor"); @@ -423,7 +461,12 @@ void argusNodeFactory::validate( void ){ for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) createNode( *idx ); tList->clear(); delete( tList ); - }; + } +#ifdef DEBUG_EXTRA + else { + LOG( "No New Nodes Added"); + } +#endif #ifdef MEM_DEBUG memEnd = getCurrentRSS(); memDiff = memEnd - memStart; @@ -450,7 +493,12 @@ void argusNodeFactory::validate( void ){ m_vNetNodes.clear(); m_mNetNodesIDS.clear(); }; - }; + } +#ifdef DEBUG + else { + LOG("No Nodes to Validate"); + } +#endif #ifdef MEM_DEBUG memEnd = getCurrentRSS(); memDiff = memEnd - memStart; diff --git a/lib/rgoose/rgooseNodeStaticCamControl.cpp b/lib/rgoose/rgooseNodeStaticCamControl.cpp new file mode 100644 index 00000000..9e4d507a --- /dev/null +++ b/lib/rgoose/rgooseNodeStaticCamControl.cpp @@ -0,0 +1,183 @@ +#include "rgooseNodeStaticCamControl.h" + +#define LOG( X ) m_pLog->Log( "STATIC_CAM", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "STATIC_CAM", this, _LOG_ERROR, X ) + +ARGUS_CAM::ARGUS_CAM( DBC_NODE_DATA *Data ): basicEventHandler(), argusNetNode( Data ), ARGUS_Camera(){ + m_pLog = basicLogCollection::getInstance(); +/* + DBC_CAM_DATA * tData = m_pDBC->getCamData( m_sNodeData.aux_id ); + + m_fMaxRange = m_fMinHFov = m_fMaxHFov = m_fMinVFov = m_fMaxVFov = .0f; + + if( tData != NULL ) { + memcpy( &m_sCamData, tData, sizeof(DBC_CAM_DATA) ); + free( tData ); + }; + memset( &m_sCtrlData, 0, sizeof(CAMERA_CTRL_DATA) ); + if( m_sCamData.max_range == .0f ){ + m_fMaxRange = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_sCamData.max_f, 1280 ); + } else { + m_fMaxRange = m_sCamData.max_range; + }; + m_fMinHFov = calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_sCamData.min_f ); + m_fMaxHFov = calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_sCamData.max_f ); + m_fMinVFov = calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_sCamData.min_f ); + m_fMaxVFov = calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_sCamData.max_f ); +#ifdef DEBUG + char tB[128]; + LOG("Camera Info:"); + sprintf( tB, "Maximal Range: %0.2f m. ", m_fMaxRange); + LOG(tB); + sprintf( tB, "Maximal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMinHFov, m_fMinVFov ); + LOG(tB); + sprintf( tB, "Minimal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMaxHFov, m_fMaxVFov ); + LOG(tB); +#endif + m_pPosition = new basicPosition( m_sCamData.lat, m_sCamData.lon, m_sCamData.alt, m_sCamData.roll, m_sCamData.pitch, m_sCamData.yaw ); + */ +}; + +ARGUS_CAM::ARGUS_CAM( uint32_t id ): basicEventHandler(), argusNetNode( id ), ARGUS_Camera(){ + m_pLog = basicLogCollection::getInstance(); + m_sMediaSource.mediaSourceId = m_sNodeData.aux_id; + memset( &m_sCtrlData, 0, sizeof( CAMERA_CTRL_DATA )); +}; + +ARGUS_CAM::~ARGUS_CAM(){ + LOG("Destructor"); + stopService(); +}; + +bool ARGUS_CAM::startService(){ + return create( m_sNodeData.aux_id ); +}; + +bool ARGUS_CAM::stopService(){ + return true; +}; + +void ARGUS_CAM::dispatchEvent( EVENT_CONTAINER *E ){ + if( E == NULL ) return; + //if( !m_sCamData.online ) return; + //if( m_bBusy ) return; + switch( E->m_eClass ) { + case EVT_CLASS_SENSOR_CLD: + case EVT_CLASS_SENSOR_LGS: + case EVT_CLASS_SENSOR_LFS: + case EVT_CLASS_SENSOR_MND: + case EVT_CLASS_SENSOR_PLS_210: + case EVT_CLASS_SENSOR_PLS_360: + case EVT_CLASS_SENSOR_ALS: + case EVT_CLASS_SENSOR_3D: + case EVT_CLASS_SENSOR_ACC:{ + switch( E->m_eType ) { + case EVT_TARGET_1D: + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_2D_WHITE: + case EVT_TARGET_3D_BLACK: + case EVT_TARGET_3D_WHITE:{ + TARGET_DATA *tDATA; + tDATA = (TARGET_DATA *)E->m_pEvtData; + if( tDATA ) { +#ifdef DEBUG_EXTRA + LOG( "CHECK CAMERA FOV" ); +#endif + if( inTheFOV( tDATA->global_target.lat, tDATA->global_target.lon, tDATA->global_target.alt ) ){ +#ifdef DEBUG_EXTRA + LOG("TARGET IN CAMERA FOV"); +#endif + + }; + }; + break; + }; + }; + break; + }; + case EVT_CLASS_CAMERA_CTRL:{ + /* + if( E->m_nDestinationUID == m_sCamData.node_id ) { + switch( E->m_eType ) { + case EVT_CAMERA_DM:{ + CAMERA_CTRL_DATA *tDATA = (CAMERA_CTRL_DATA *)E->m_pEvtData; + if( tDATA != NULL ) { + if( tDATA->moveMask & 0x08 == 0x08 ){ + //Relative Move cmd + if( tDATA->moveMask & 0x07 == 0 ){ + relativeStop(); + } else { + relativeMove( tDATA->spdPAN, tDATA->spdTILT, tDATA->spdZOOM ); + }; + } else { + if( tDATA->moveMask & 0xF0 != 0x00 ) { + absoluteMove( tDATA->absPAN, tDATA->absTILT, tDATA->absZOOM ); + }; + }; + }; + break; + }; + }; + } + ;*/ + break; + }; + }; +}; +bool ARGUS_CAM::validate(){ + //LOG("VALIDATE"); + if( m_bThreadStatus == TH_ENDED ) return false; + if( !argusNetNode::m_pDBC ) return false; + //Validate Node Settings + { + DBC_NODE_DATA *tDATA = argusNetNode::m_pDBC->getNodeData( m_nDBID ); + if( tDATA ) { + if( memcmp( &m_sNodeData, tDATA, sizeof(DBC_NODE_DATA)) != 0 ){ + free( tDATA ); + LOG("Node Settings Changed!"); + return false; + }; + free( tDATA ); + } else { + LOG("Node Deleted!"); + return false; + }; + } + // Validate Camera Settings + /*{ + DBC_CAM_DATA *tDATA = argusNetNode::m_pDBC->getCamData( m_sNodeData.aux_id ); + if( tDATA ) { + if( memcmp( &m_sCamData, tDATA, sizeof(DBC_CAM_DATA)) != 0 ){ + free( tDATA ); + LOG("Cam Settings Changed!"); + return false; + }; + free( tDATA ); + } else{ + LOG("Cam Deleted!"); + return false; + }; + }*/ + // Validate Stream + { + if( m_sNodeData.aux_parameter ) { // Has Choosed Stream + DBC_MEDIA_STREAM_DATA *tDATA = argusNetNode::m_pDBC->getMediaStreamData( m_sNodeData.aux_parameter ); + if( tDATA ){ + if( tDATA->valid ) { + if( !m_bSourceConnected ) { + if(!connectToStream( m_sNodeData.aux_parameter ) ) return false; + }; + } else { + if( m_bSourceConnected ) { + if( disconnectFromStream() ) return false; + }; + }; + free( tDATA ); + }; + }; + } + return true; +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/rgoose/rgooseNodeStaticCamControl.h b/lib/rgoose/rgooseNodeStaticCamControl.h new file mode 100644 index 00000000..caafe852 --- /dev/null +++ b/lib/rgoose/rgooseNodeStaticCamControl.h @@ -0,0 +1,47 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2017. All Rights Reserved. +// Version 2.0 6/11/2019 +// Last modification: 6/11/2019 +// PROJECT: +// SUBSYSTEM: +// FILE: rgooseIPCamera.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of rgooseIPCamera.h +//---------------------------------------------------------------------------- +// +#ifndef __ARGUS_STATIC_CAMERA_CTRL_HEADER__ +#define __ARGUS_STATIC_CAMERA_CTRL_HEADER__ + +#include "rgooseCamera.h" +#include "rgooseNode.h" +#include "../components/base/basicEventHandler.h" +#include "../components/base/basicEventHeap.h" + +//https://www.ebay.com/itm/Professional-Rolling-Makeup-Case-Bulb-Mirror-Cosmetic-Artist-Dressing-Train-Case/233264525474 + +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:print_format=json -f null - +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:measured_I=-30:measured_LRA=1.1:measured_tp=-11 04:measured_thresh=-40.21:offset=-0.47 -ar 48k -y output.mp4 + + + + + +class ARGUS_CAM: public ARGUS_Camera, public argusNetNode, public basicEventHandler { + private: + basicLogCollection * m_pLog; + protected: + CAMERA_CTRL_DATA m_sCtrlData; + public: + explicit ARGUS_CAM( uint32_t id ); + explicit ARGUS_CAM( DBC_NODE_DATA *Data = NULL ); + ~ARGUS_CAM(); + virtual void dispatchEvent( EVENT_CONTAINER *Evt ); + virtual bool startService(); + virtual bool stopService(); + virtual bool validate(); +}; + +#endif diff --git a/lib/rgoose/rgooseTypes.h b/lib/rgoose/rgooseTypes.h index 077feddf..f43ef3e6 100644 --- a/lib/rgoose/rgooseTypes.h +++ b/lib/rgoose/rgooseTypes.h @@ -10,6 +10,7 @@ #include #include #include + #include #else #include #include @@ -206,6 +207,7 @@ typedef struct S_DBC_MODULE_EMBED_VIDEO_DATA{ bool show_logo; uint16_t width; uint16_t height; + uint8_t compression_quality; int ts_x; int ts_y; uint8_t ts_font_face; diff --git a/prereqvisites.txt b/prereqvisites.txt index e53af2cb..6f709dac 100644 --- a/prereqvisites.txt +++ b/prereqvisites.txt @@ -9,3 +9,6 @@ libssl-dev libv4l-dev libhidapi-dev libgphoto2-dev + + +sudo apt-get install openssl libssl-dev \ No newline at end of file