diff --git a/lib/App/common/streamHandler.cpp b/lib/App/common/streamHandler.cpp new file mode 100644 index 00000000..f13f5f48 --- /dev/null +++ b/lib/App/common/streamHandler.cpp @@ -0,0 +1,3741 @@ +#include "streamHandler.h" +#include "kernelModuleEmbedVideo.h" + +#define DEBUG_EXTRA + +#ifndef LRF_PROXY_ONLY +// #include "rgooseHardwareResourceNetworkProvider.h" +// #include "mojoKernel.h" +#include "../alg/generic/base64.h" +#include "../data/media/video/videoAVLIBSource.h" +#include "../data/media/video/videoLive555AVLibSource.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include +#include +#include + +// #define DEBUG +// #undef DEBUG_EXTRA +// #define DEBUG_EXTRA + + +#ifndef STORAGE_DIR_MODE + #define STORAGE_DIR_MODE 0x1FF +#endif + +#ifndef STORAGE_FILE_MODE + #define STORAGE_FILE_MODE 0x1B6 +#endif + +#define LOG(X) streamHandler::m_pLog->Log("MEV_STR", this, X) +#ifdef DEBUG + #define LOG_ERROR(X) \ + { \ + char _tBfrErrMSG2w34[256]; \ + sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ + streamHandler::m_pLog->Log("MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34); \ + } +#else + #define LOG_ERROR(X) streamHandler::m_pLog->Log("MEV_STR", this, _LOG_ERROR, X); +#endif + +streamHandler::streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M, uint8_t flip_mode) : + basicMediaDestination(), +#ifdef EVE_ENABLE_VIDEO + basicThread(), +#endif + m_pMaster(ptr), + m_eWM(M) +{ + m_pLog = basicLogCollection::getInstance(); + memset(&m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA)); + m_pSource = NULL; + m_bEvtMarkerCounter = 0; + m_bCamMoveCounter = 0; + m_bFlipMode = flip_mode; + +#ifdef EVE_ENABLE_VIDEO + #ifdef EVE_SEQUENTAL_OUTPUT + m_nSegFrameCounter = 0; + m_nGlobalFrameCounter = 0; + m_nSegShiftFrames = 0; + m_nSegSkippedFrames = 0; + m_bSegActive = false; + m_bSegDelete = true; + m_bNSegDelete = true; + #else + m_nPreAlarmFrames = 0; + m_nPostAlarmFrames = 0; + m_nSegmentLimitFrames = 0; + m_nHardLimitFrames = 0; + m_nSegAFrameCounter = 0; + m_nSegBFrameCounter = 0; + m_nGlobalFrameCounter = 0; + + m_nSegAShiftFrames = 0; + m_nSegBShiftFrames = 0; + m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; + + m_bActiveEncoderStream = 0; + m_bSegAActive = false; + m_bSegADelete = true; + m_bSegBActive = false; + m_bSegBDelete = true; + #endif // !EVE_SEQUENTAL_OUTPUT + + m_bCOP = 0; + m_cSourceType = 'A'; + + //todo: must be writen helper function to clean VIDEO_SEGMENT_INFO + //that is not dynamicaly created by NEW operator + + //memset(&m_sStreamSegmentInfo[0], 0, sizeof(VIDEO_SEGMENT_INFO)); + //memset(&m_sStreamSegmentInfo[1], 0, sizeof(VIDEO_SEGMENT_INFO)); + #ifdef DIRECT_MJPEG_COMPOSING + #ifndef EVE_SEQUENTAL_OUTPUT + m_pOutputFD[0] = NULL; + m_pOutputFD[1] = NULL; + #else + m_pOutputFD = NULL; + #endif + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + #ifndef EVE_SEQUENTAL_OUTPUT + m_pEncoderA = NULL; + m_pEncoderB = NULL; + #else + m_pEncoder = NULL; + #endif + #endif + #endif +#endif // EVE_ENABLE_VIDEO + // if( M == MS_MODE_DECODE_FRAMES ) 1=1; +} + +streamHandler::~streamHandler() +{ + if (m_sStreamData.id) + { + if (m_pSource != NULL) + { + switch (m_cSourceType) + { // m_sStreamData.source_type[0] ) { + case 'D': delete((videoLIVE555Source *) m_pSource); break; + case 'A': delete((videoAVLIBSource *) m_pSource); break; + }; + }; +#ifdef EVE_ENABLE_VIDEO + closeAll(); +#endif // EVE_ENABLE_VIDEO + }; +} + +bool streamHandler::create(dataBinder * ptr, uint32_t stremID) +{ + if (ptr == NULL) + { + return false; + } + m_pDBC = ptr; + if (stremID) + { + DBC_MEDIA_STREAM_DATA * tData = m_pDBC->getMediaStreamData(stremID); + if (tData) + { + memcpy(&m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); + free(tData); + DBC_CAM_DATA * tCAM = m_pDBC->getCamData(m_sStreamData.source_id); + if (tCAM) + { + + m_sSourceDesc.mediaStreamId = stremID; + + m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; + uint32_t tNID = m_pDBC->getNodeIdByTypeAndAux(tCAM->type, m_sStreamData.source_id); + // ToDo: Check Camera Addition + // Just Work around to handle Wrong tyoe 12 instead of 13 + if (tNID == 0) + { + tNID = m_pDBC->getNodeIdByTypeAndAux(13, m_sStreamData.source_id); + }; + if (tNID) + { + CSTR tNAM = m_pDBC->getNodeName(tNID); + if (tNAM != NULL) + { + strncpy(m_sSourceDesc.mediaName, tNAM, 127); + m_sSourceDesc.mediaName[127] = (char) 0; + free(tNAM); + } + else + { + sprintf(m_sSourceDesc.mediaName, "No Name Cam"); + }; + } + else + { + sprintf(m_sSourceDesc.mediaName, "No-Name-Cam"); + }; + + m_cSourceType = m_sStreamData.source_type[0]; + + switch (m_cSourceType) + { + case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc); break; + case 'D': + { + // Check Auth mode if basic - Override and use AVLIB + // To Debug LIVE555 ONLY + if (1 || tCAM->auth_mode == 0) + { + m_cSourceType = 'A'; + m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc); + break; + } + else + { + m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sSourceDesc); + break; + }; + break; + }; + }; + if (m_pSource != NULL) + { + char tMRL[1024]; +#ifdef DEBUG_EXTRA + LOG("Source OK"); +#endif + int tW = m_pMaster->getWidh(); + int tH = m_pMaster->getHeight(); + int pix = -1; + bool in_16_9 = (((m_sStreamData.width * 100) / m_sStreamData.height) > 140); + bool out_16_9 = (((tW * 100) / tH) > 140); + // if( tW > 0 ){ + // //m_pSource->setProportionalByWidth( tW ); + // m_pSource->setSize( tW, tH ); + // }; + if (in_16_9 != out_16_9) + { + if (in_16_9) + { + tH = (((tW * 1000) / 16) * 9) / 1000; + } + else + { + tW = (((tH * 1000) / 3) * 4) / 1000; + }; + }; + // export PATH=/usr/sbin:$PATH + if (strncmp(m_sStreamData.mrl_proto, "v4l2", 4) == 0) + { + sprintf(tMRL, m_sStreamData.mrl); + pix = atoi(m_sStreamData.c_type); + } + else + { + sprintf(tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl); + }; + if (m_pSource->_open(tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH)) + { + if (! m_pSource->attachDestination(this)) + { + switch (m_cSourceType) + { + case 'D': delete((videoLIVE555Source *) m_pSource); break; + case 'A': delete((videoAVLIBSource *) m_pSource); break; + }; + m_pSource = NULL; + } + else + { +#ifdef DEBUG_EXTRA + LOG("Source is Connected to Output."); +#endif + }; + } + else + { + LOG_ERROR("Can not Open Video Source!"); + switch (m_cSourceType) + { + case 'D': delete((videoLIVE555Source *) m_pSource); break; + case 'A': delete((videoAVLIBSource *) m_pSource); break; + }; + m_pSource = NULL; + }; + } + else + { + LOG_ERROR("Video Source Stream Failure!"); + }; + free(tCAM); + } + else + { + LOG_ERROR("Error Getting CAM Data!"); + m_pSource = NULL; + return false; + }; + }; + }; + + if (m_pSource) + { +#ifdef EVE_ENABLE_VIDEO + return initVideoOutput(); +#else + return true; +#endif // EVE_ENABLE_VIDEO + }; + + return false; +} + +bool streamHandler::pushFrame(AVFrame * Frame, void * src) +{ + if( !Frame ) return false; + if( !m_pMaster )return false; + + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + if (tMD) + { + }; + return true; +} + +bool streamHandler::pushFrame(cv::Mat & Frame, void * src) +{ + + /// @todo Valgrind is reporting an important memory leak in this method. + if (m_pMaster == NULL) + { + return false; + } + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + char tBuffer[512]; + if (tMD) + { + float mK, oK; + cv::Rect ROI; + + m_pMaster->m_mPictureProtector.lock(); + + if (m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0) + { + LOG("First Frame Enqueued"); + sprintf(tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId); + LOG(tBuffer); + + m_pMaster->m_mapMATS[tMD->mediaStreamId].create(m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width, CV_8UC3); + cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(0, 0), cv::Point(m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width), cv::Scalar(0, 0, 0), cv::FILLED); + }; + +#ifdef USE_SCALING_IN + oK = ((float) m_pMaster->m_sEmbedVideoData.height) / ((float) m_pMaster->m_sEmbedVideoData.width); + mK = ((float) Frame.rows) / ((float) Frame.cols); + // sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); + if ((fabsf(mK - oK) < 0.1f) || (fabsf(oK - mK) < 0.1f)) + { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.x = (int) 0; + ROI.y = (int) 0; + } + else + { + if (mK < oK) + { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) (((float) m_pMaster->m_sEmbedVideoData.width) * mK); + ROI.x = (int) 0; + ROI.y = (int) (m_pMaster->m_sEmbedVideoData.height - ROI.height) >> 1; + } + else + { + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.width = (int) (((float) m_pMaster->m_sEmbedVideoData.height) / mK); + ROI.y = (int) 0; + ROI.x = (int) (m_pMaster->m_sEmbedVideoData.width - ROI.width) >> 1; + }; + }; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI); + #ifndef USE_CV_DENOISE + cv::resize(Frame, mROI, mROI.size(), 0, 0, cv::INTER_LINEAR); + #else + cv::Mat mDenoiser; + cv::resize(Frame, mDenoiser, mROI.size(), 0, 0, cv::INTER_LINEAR); + cv::fastNlMeansDenoisingColored(mDenoiser, mROI, 10, 10, 7, 17); + #endif + #ifdef USE_CV_TONEMAP + cv::Mat ldrReinhard; + cv::Ptr tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0); + tonemapReinhard->process(mROI, ldrReinhard); + ldrReinhard = ldrReinhard * 255; + ldrReinhard.copyTo(mROI); + #endif +#else + if ((m_pMaster->m_sEmbedVideoData.height == Frame.rows) && (m_pMaster->m_sEmbedVideoData.width == Frame.cols)) + { + Frame.copyTo(m_pMaster->m_mapMATS[tMD->mediaStreamId]); + } + else + { + // Mat dst_roi = dst(Rect(left, top, src.cols, src.rows)); + // src.copyTo(dst_roi); + + if (m_pMaster->m_sEmbedVideoData.width == Frame.cols) + { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = 0; + ROI.y = (m_pMaster->m_sEmbedVideoData.height - Frame.rows) >> 1; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI); + #ifdef USE_CV_DENOISE + cv::fastNlMeansDenoisingColored(Frame, mROI, 10, 10, 7, 17); + #else + Frame.copyTo(mROI); + #endif + #ifdef USE_CV_TONEMAP + cv::Mat ldrReinhard; + cv::Ptr tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0); + tonemapReinhard->process(mROI, ldrReinhard); + ldrReinhard = ldrReinhard * 255; + ldrReinhard.copyTo(mROI); + #endif + } + else + { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = (m_pMaster->m_sEmbedVideoData.width - Frame.cols) >> 1; + ROI.y = 0; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI); + #ifdef USE_CV_DENOISE + cv::fastNlMeansDenoisingColored(Frame, mROI, 10, 10, 7, 17); + #else + Frame.copyTo(mROI); + #endif + #ifdef USE_CV_TONEMAP + cv::Mat ldrReinhard; + cv::Ptr tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0); + tonemapReinhard->process(mROI, ldrReinhard); + ldrReinhard = ldrReinhard * 255; + ldrReinhard.copyTo(mROI); + #endif + }; + }; +#endif + // 0 - dis .. 1 - Hor ... 2 - vert 3 - both + if (m_bFlipMode) + { + // Flip Horizontally = 1 vertically = 0 both = -1 + cv::Mat mirroredImage; + cv::flip(m_pMaster->m_mapMATS[tMD->mediaStreamId], mirroredImage, 2 - m_bFlipMode); + mirroredImage.copyTo(m_pMaster->m_mapMATS[tMD->mediaStreamId]); + }; + +#ifdef EVE_ENABLE_DROP_OUTPUT_FPS + // LOG("T"); + m_mEncodingQueueProtector.lock(); + if (m_qEncodingQueue.size() > 10) + { + m_mEncodingQueueProtector.unlock(); + m_pMaster->m_mPictureProtector.unlock(); + // LOG("D"); + return true; + }; + m_mEncodingQueueProtector.unlock(); + // LOG("Q"); +#endif + + if (m_bCamMoveCounter > m_bEvtMarkerCounter) + { + cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(10, 10, 20, 20), cv::Scalar(m_bCamMoveCounter, 0, 0), cv::FILLED); + m_bCamMoveCounter -= 4; + if (m_bCamMoveCounter < 4) + { + m_bCamMoveCounter = 0; + } + } + else + { + if (m_bEvtMarkerCounter) + { + m_bCamMoveCounter = 0; + cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(10, 10, 20, 20), cv::Scalar(0, 0, m_bEvtMarkerCounter), cv::FILLED); + m_bEvtMarkerCounter -= 4; + if (m_bEvtMarkerCounter < 4) + { + m_bEvtMarkerCounter = 0; + } + }; + }; + if (m_pMaster->m_sEmbedVideoData.show_label) + { + time_t t = time(NULL); + // struct tm * tmp = gmtime( &t ); + struct tm * tmp = localtime(&t); + if (tmp) + { + char tsb[64]; + // if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ + if (strftime(tsb, sizeof(tsb), "%F %T", tmp) != 0) + { + + // sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); + sprintf(tBuffer, ">>>%s>%s>", tMD->mediaName, tsb); + int baseline = 0; + cv::Size textSize = cv::getTextSize(tBuffer, m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, m_pMaster->m_sEmbedVideoData.label_font_thickness, &baseline); + int x = m_pMaster->m_sEmbedVideoData.label_x; + int y = m_pMaster->m_sEmbedVideoData.label_y; + if (x < 0) + { + x = m_pMaster->m_sEmbedVideoData.width + x - textSize.width; + }; + if (y < 0) + { + y = m_pMaster->m_sEmbedVideoData.height + y - baseline; // + }; + if (! m_pMaster->m_sEmbedVideoData.label_transperant) + { + cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(x, y - textSize.height - 4, textSize.width, textSize.height + baseline + 4), cv::Scalar(0, 0, 0), cv::FILLED); + }; + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(x, y), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, cv::Scalar(0, 255, 0), + m_pMaster->m_sEmbedVideoData.label_font_thickness, m_pMaster->m_sEmbedVideoData.label_line_type); + }; + }; + } + else + { + if (m_pMaster->m_sEmbedVideoData.show_ts) + { + time_t t = time(NULL); + // struct tm * tmp = gmtime( &t ); + struct tm * tmp = localtime(&t); + if (tmp) + { + if (strftime(tBuffer, sizeof(tBuffer), "%F %T GMT", tmp) != 0) + { + uint8_t shift_x = 0; + uint8_t shift_y = 15; + if (! m_pMaster->m_sEmbedVideoData.ts_transperant) + { + if (m_pMaster->m_sEmbedVideoData.ts_font_face) + { + shift_y = 15; + cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y), cv::Point(490, 60), cv::Scalar(0, 0, 0), cv::FILLED); + } + else + { + shift_y = 23; + cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y), cv::Point(490, 60), cv::Scalar(0, 0, 0), cv::FILLED); + }; + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 255, 255), m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type); + } + else + { + if (m_pMaster->m_sEmbedVideoData.ts_font_face) + { + shift_y = 15; + } + else + { + shift_y = 23; + }; + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); + cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 255, 255), m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type); + } + }; + }; + }; + }; + if (m_pMaster->m_sEmbedVideoData.show_logo) + { + cv::Rect roi(cv::Point(m_pMaster->m_sEmbedVideoData.logo_x, m_pMaster->m_sEmbedVideoData.logo_y), cv::Size(m_pMaster->m_sEmbedVideoData.logo_w, m_pMaster->m_sEmbedVideoData.logo_h)); + cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](roi); + m_pMaster->m_mLogoPic.copyTo(destinationROI, m_pMaster->m_mLogoMask); + }; + + vector compression_params; + // compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + // compression_params.push_back(9); + compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); + compression_params.push_back(50); // m_pMaster->m_sEmbedVideoData.compression_quality ); + + m_pMaster->m_mEncodedProtector.lock(); + m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); + cv::imencode(".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params); + + // cv::Mat bw_dst; + // cv::cvtColor( m_pMaster->m_mapMATS[tMD->mediaStreamId], bw_dst, cv::COLOR_BGR2GRAY ); + // cv::imencode( ".jpg", bw_dst, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); + +#ifdef HAVE_SMAL_PREVIEW_STREAMS + // Make Small Preview Thumb + cv::Mat dst; + cv::resize(m_pMaster->m_mapMATS[tMD->mediaStreamId], dst, cv::Size(PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT)); + // cv::resize( bw_dst, dst, cv::Size( PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT )); + + m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId].clear(); + cv::imencode(".jpg", dst, m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId], compression_params); +#endif + m_pMaster->m_mEncodedProtector.unlock(); + +#ifdef EVE_ENABLE_VIDEO + // if only decode Video Stream -> Exit + // To handle video recording elsewhere (For Steph) + if (m_eWM == MS_MODE_DECODE_FRAMES) + { + m_pMaster->m_mPictureProtector.unlock(); + return true; + }; + // encode Video Stream + + // m_nPreAlarmFrames + // m_nPostAlarmFrames + // m_nNoAlarmSegmentFrames + // m_nSegmentLimitFrames + // m_nHardLimitFrames + #ifdef EVE_SEQUENTAL_OUTPUT + if ( m_bSegActive ) + { // The Open/Close is management ath Encoder Thread Procedure + #else // !EVE_SEQUENTAL_OUTPUT + if (m_bSegAActive || m_bSegBActive) + { + m_mFrameCounterProtector.lock(); + if( m_bSegAActive ) { + if (m_nSegAFrameCounter > m_nHardLimitFrames) { + #ifdef DEBUG_EXTRA + LOG("HardLimit Reached!(A)"); + #endif + closeSegmentA(); + // break; + }; + if (m_nSegAFrameCounter > (m_nSegmentLimitFrames - (m_nPostAlarmFrames + m_nPreAlarmFrames))){ + if (! m_bSegBActive){ + #ifdef DEBUG_EXTRA + LOG("Start Alt!(A)"); + #endif + openSegmentB(); + }; + }; + if (m_nSegAFrameCounter > (m_nSegmentLimitFrames - m_nPostAlarmFrames) && ! m_bActiveEncoderStream){ + #ifdef DEBUG_EXTRA + LOG("Swap Active!(A)"); + #endif + swapActiveStreams(); + }; + }; + + if( m_bSegBActive ){ + if (m_nSegBFrameCounter > m_nBHardLimitFrames){ + #ifdef DEBUG_EXTRA + LOG("HardLimit Reached!(B)"); + #endif + closeSegmentB(); + }; + if (m_nSegBFrameCounter > (m_nBSegmentLimitFrames - (m_nBPostAlarmFrames + m_nAPreAlarmFrames))){ + if (! m_bSegAActive){ + #ifdef DEBUG_EXTRA + LOG("Start Alt!(B)"); + #endif + openSegmentA(); + }; + }; + if (m_nSegBFrameCounter > (m_nBSegmentLimitFrames - m_nBPostAlarmFrames) && m_bActiveEncoderStream){ + #ifdef DEBUG_EXTRA + LOG("Swap Active!(B)"); + #endif + swapActiveStreams(); + }; + }; + m_mFrameCounterProtector.unlock(); + #endif // !EVE_SEQUENTAL_OUTPUT + + + // Transfer Data to Encoder Thread + + ENCODING_BUFFER * tData = (ENCODING_BUFFER *) malloc(sizeof(ENCODING_BUFFER)); + if (tData) + { + #ifdef DIRECT_MJPEG_COMPOSING + tData->size = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].size(); + tData->data = (uint8_t *) malloc(tData->size); + if (tData->data) + { + memcpy(tData->data, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(), tData->size); + // Aproach to reference and not copy data ... was not such a good idea + // tData->data = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(); + // if ( tData->data ) { + #else + #ifdef OPENCV_VIDEO_OUTPUT + tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; + tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols; + tData->size = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols * m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize() * tData->rows; + tData->data = (uint8_t *) malloc(tData->size); + if (tData->data) + { + memcpy(tData->data, m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size); + #else // OPENCV_VIDEO_OUTPUT + tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols * m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize(); + tData->linesize[1] = 0; + tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; + tData->size = tData->linesize[0] * tData->rows; + tData->data[1] = NULL; + tData->data[0] = (uint8_t *) malloc(tData->size); + if (tData->data[0]) + { + memcpy(tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size); + #endif // OPENCV_VIDEO_OUTPUT + #endif //! DIRECT_MJPEG_COMPOSING + m_mEncodingQueueProtector.lock(); + m_qEncodingQueue.push(tData); + m_mEncodingQueueProtector.unlock(); + } + else + { + LOG_ERROR("MAT_CPY malloc Error!"); + free(tData); + }; + } + else + { + LOG_ERROR("ENC_BUF malloc Error!"); + } + }; +#endif // EVE_ENABLE_VIDEO + m_pMaster->m_mPictureProtector.unlock(); + } + else + { + LOG_ERROR("No PayLoad!"); + }; + return true; +} + +#ifdef EVE_ENABLE_VIDEO + #ifdef EVE_SEQUENTAL_OUTPUT + /* + bool streamHandler::openSegment(void){ + if (!m_bSegActive) + { + CSTR tAM = getUniqID_MD5(); + if(tAM) + { + sprintf(m_sStreamSegmentInfo.scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); + strncpy(m_sStreamSegmentInfo.recordMD5, tAM, 32); + m_sStreamSegmentInfo.recordMD5[32] = (char) 0; + free(tAM); + m_sStreamSegmentInfo.stream_id = m_sStreamData.id; + PF_TIMESTAMP ts; + getPFTS(&ts); + m_sStreamSegmentInfo.streamTSS = ts.seconds; + m_sStreamSegmentInfo.streamTMS = ts.milliseconds; + #ifdef DEBUG_EXTRA + char tB[128]; + sprintf(tB, "A opened %d.%d", m_sStreamSegmentInfo.streamTSS, m_sStreamSegmentInfo.streamTMS); + LOG(tB); + #endif + strncpy(m_sStreamSegmentInfo.recordEXT, VIDEO_OUTPUT_CONTAINER, 6); + m_sStreamSegmentInfo.streamFPS = m_sStreamData.fps; + m_sStreamSegmentInfo.streamWidth = m_pMaster->getWidh(); + m_sStreamSegmentInfo.streamHeight = m_pMaster->getHeight(); + m_sStreamSegmentInfo.eventIDS.clear(); + m_sStreamSegmentInfo.eventTSS.clear(); + m_sStreamSegmentInfo.eventTMS.clear(); + m_sStreamSegmentInfo.eventFrames.clear(); + m_sStreamSegmentInfo.dataSize = 0; + m_sStreamSegmentInfo.db_id = 0; + #ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD = fopen(m_sStreamSegmentInfo.scratchPath, "wb+"); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderA) + { + // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + double fps = m_sStreamData.fps; + cv::String mn(m_sStreamSegmentInfo.scratchPath); + cv::Size fz(m_sStreamData.width, m_sStreamData.height); + // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if (! m_pEncoder->open(mn, fourcc, fps, fz)) + { + LOG_ERROR("Cannot Open Output Segment A!"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + char tB[256]; + sprintf(tB, "VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo.scratchPath, fps); + LOG(tB); + #endif + }; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + } + else + { + LOG_ERROR("No Encoder(A) Object!"); + return false; + }; + #else // !OPENCV_VIDEO_OUTPUT + // Check if Encoder is Ready + if (m_pFormat == NULL) + { + return false; + } + + #ifdef SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) + { + LOG_ERROR("Format CTX A alloc error!"); + return false; + } + else + { + av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoACodec); + if (m_pVideoStr == NULL) + { + avformat_free_context(m_pFormatCtx); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("VideoStream A is Created"); + #endif + }; + const AVRational dst_fps = {m_sStreamData.fps, 1}; + m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; + m_pVideoStr->time_base = m_pCodecCtx->time_base; + avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecACtx); + #ifdef DEBUG_EXTRA + LOG("Opening Stream A"); + LOG(m_cSegName); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration); + LOG(tB); + #endif + // if (avio_open(&m_pFormatCtx->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + if (avio_open(&m_pFormatCtx->pb, m_sStreamSegmentInfo.scratchPath, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + return m_bSegActive; + }; + if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegActive; + }; + // m_mFrameCounterProtector.lock(); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + // m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegSkippedFrames = m_pVideoStr->nb_frames + 1; + if (m_pVideoStr->nb_frames) + { + m_pVideoStr->nb_frames = 0; + m_pVideoStr->start_time = 0; + m_pVideoStr->first_dts = 0; + m_pFormatCtx->start_time = 0; + }; + #ifdef DEBUG_EXTRA + LOG("Opening Stream"); + LOG(m_cSegName); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration); + LOG(tB); + #endif + if (avio_open(&m_pFormatCtx->pb, m_cSegName, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + return m_bSegActive; + }; + if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegActive; + }; + // m_mFrameCounterProtector.lock(); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + // m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + }; + }; + return m_bSegActive; + } + void streamHandler::closeSegment(void){ + #ifdef DEBUG + LOG("Closing Stream"); + #endif + #ifdef DEBUG_EXTRA + LOG("Actual Closing Video Stream"); + LOG(m_sStreamSegmentInfo.scratchPath); + #endif + m_bSegActive = false; + if( !m_bSegDelete ){ + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD){ + fclose(m_pOutputFD); + m_pOutputFD = NULL; + }; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoder->isOpened()){ + m_pEncoder->release(); + #ifdef DEBUG_EXTRA + }else{ + LOG(" Encoder is NOT Opened!"); + #endif + }; + #else // !OpenCV + av_write_trailer(m_pFormatCtx); + avio_close(m_pFormatCtx->pb); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo); + if (bEVT){ + basicEventHeap::getInstance()->broadcast(bEVT); + }else{ + LOG_ERROR("Event Creation failure!"); + } + #ifdef DEBUG_EXTRA + LOG("Stream is Saved"); + #endif + } else { + #ifdef DIRECT_MJPEG_COMPOSING + if ( m_pOutputFD ){ + fclose(m_pOutputFD); + m_pOutputFD = NULL; + }; + #else + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoder->isOpened()) { + m_pEncoder->release(); + #ifdef DEBUG_EXTRA + } else { + LOG(" Encoder is NOT Opened!"); + #endif + }; + #else // !OPenCV + #ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer(m_pFormatCtx); + #endif + avio_close(m_pFormatCtx->pb); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + #ifndef EVE_DONT_DELETE_SEGMENTS + unlink(m_sStreamSegmentInfo.scratchPath); + #endif + #ifdef DEBUG_EXTRA + LOG("Stream is Closed!"); + #endif + }; + } + */ + // Final Closing All + Thread + void streamHandler::closeAll() + { + waitThreadEnd(true); + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoder){ + if (m_pEncoder->isOpened()){ + m_pEncoder->release(); + }; + delete(m_pEncoder); + }; + #else // !OPENCV_VIDEO_OUTPUT + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD ){ + fclose(m_pOutputFD); + m_pOutputFD = NULL; + }; + #else // ! DIRECT_MJPEG_COMPOSING + if(( m_pCodecCtx != NULL ) && m_bSegActive ){ + if (m_pCodecCtx != NULL){ + avcodec_send_frame(m_pCodecCtx, NULL); + int ret = 0; + AVPacket * avp = av_packet_alloc(); + if (avp){ + do{ + av_packet_unref(avp); + ret = avcodec_receive_packet(m_pCodecACtx, avp); + if (! ret){ + if (m_bSegActive){ + av_write_frame(m_pFormatCtxA, avp); + }; + }; + } while (! ret); + av_packet_unref(avp); + av_packet_free(&avp); + }; + }; + if (m_bSegActive){ + av_write_trailer(m_pFormatCtx); + avformat_close_input(&m_pFormatCtx); + m_bSegActive = false; + }; + }; + #endif // !DIRECT_MJPEG_COMPOSING + #endif // !OPENCV_VIDEO_OUTPUT + } + bool streamHandler::initVideoOutput() + { + + m_nPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000; + m_nPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000; + m_nSegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps) / 1000; + m_nHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps) / 1000; + + #ifndef DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + m_pEncoder = new cv::VideoWriter(); + if (m_pEncoder == NULL) + { + LOG_ERROR("Encoder A Create Failure!"); + return false; + }; + + m_pEncoder->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0); + m_pEncoder->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0); + + #else + if (! initLibAV()) + { + return false; + } + + m_pFormat = av_guess_format(VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL); + + if (m_pFormat == NULL) + { + LOG_ERROR("Out VideoFormat Not Found!"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Output video Format"); + LOG(VIDEO_OUTPUT_CONTAINER); + #endif + }; + + #ifdef SEPARATED_VIDEO_ENCODERS + /* Stream A */ + m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); + if (m_pVideoCodec == NULL) + { + LOG_ERROR("Encoder Video Codec Not Found!"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Video Encoder Created"); + #endif + }; + m_pCodecCtx = avcodec_alloc_context3(m_pVideoACodec); + if (m_pCodecCtx == NULL) + { + LOG_ERROR("Video Encoder Context Memory Allocation Error!"); + av_free(m_pVideoCodec); + avformat_free_context(m_pFormatCtx); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Video Encoder Context A Allocated"); + #endif + }; + m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + m_pCodecCtx->max_b_frames = 1; + m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecCtx->time_base.num = 1; + m_pCodecCtx->time_base.den = m_sStreamData.fps; + m_pCodecCtx->framerate.num = m_sStreamData.fps; + m_pCodecCtx->framerate.den = 1; + #if (LIBAVCODEC_VERSION_MAJOR > 54) + // m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); + #endif + m_pFormatOpts = NULL; + if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265)) + { + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0) + { + LOG_ERROR("av_dict_set movflags!"); + #ifdef DEBUG_EXTRA + } else { + LOG("MOV FLAG SET!"); + #endif + }; + // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + // }; + + // default brand is "isom", which fails on some devices + if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0) + { + LOG_ERROR("av_dict_set brand!"); + }; + // m_pCodecCtx->max_b_frames = 1; + // m_pCodecCtx->level = 31; + m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + // P-frames, generated by referencing data from prev and future frames. + // [Compression up, CPU usage up] + // [use 3/gop] + m_pCodecCtx->max_b_frames = 5; + // Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + // [use 3?5 ref per P] + m_pCodecCtx->refs = 3; + // Compression efficiency (slower -> better quality + higher cpu%) + // [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + // Set this option to "ultrafast" is critical for realtime encoding + av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + // Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + // Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0); + // Change settings based upon the specifics of input + // [psnr, ssim, grain, zerolatency, fastdecode, animation] + // This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0); + // Disable b-pyramid. CLI options for this is "-b-pyramid 0" + // Because Quicktime (ie. iOS) doesn't support this option + av_opt_set(m_pCodecACtx->priv_data, "b-pyramid", "0", 0); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif + } else { // codec is not AV_CODEC_ID_H264 || AV_CODEC_ID_H265 + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) + { + m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + } + }; + const AVRational dst_fps = {m_sStreamData.fps, 1}; + + #ifdef DEBUG_EXTRA + char TB[129]; + sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den); + LOG(TB); + sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den); + LOG(TB); + #endif + ////m_pVideoStr->time_base = m_pCodecCtx->time_base; + // avcodec_get_context_defaults3( m_pVideoStr->codec, m_pVideoCodec ); + + // m_pVideoStr->codec->width = m_pMaster->m_sEmbedVideoData.width; + // m_pVideoStr->codec->height = m_pMaster->m_sEmbedVideoData.height; + // m_pVideoStr->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStr->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + //// m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = + ////dst_fps; + + // if ( m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + //// avcodec_parameters_from_context( m_pVideoStr->codecpar, + ////m_pCodecCtx ); + // m_pVideoStr->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStr->codecpar->extradata = m_pCodecCtx->extradata; + // m_pVideoStr->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + if (avcodec_is_open(m_pCodecCtx) == 0) + { + LOG("output codec context is closed, opening"); + if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0) + { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is opened"); + #endif + }; + + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is already opened"); + #endif + }; + #else // !SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) + { + LOG_ERROR("Format CTX alloc error!"); + return false; + } else { + av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); + if (m_pVideoCodec == NULL) + { + LOG_ERROR("Output VideoCodec Not Found!"); + avformat_free_context(m_pFormatCtxA); + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Output Video Codec Found"); + #endif + }; + + m_pCodecCtx = avcodec_alloc_context3(m_pVideoCodec); + if (m_pCodecCtx == NULL) + { + LOG_ERROR("Out VideoCodec Context Memory Allocation Error"); + av_free(m_pVideoCodec); + avformat_free_context(m_pFormatCtx); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("Out Codec Context3 Allocated"); + #endif + }; + m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoCodec); + if (m_pVideoStr == NULL) + { + LOG_ERROR("VideoStream A Not Created!"); + avcodec_free_context(&m_pCodecCtx); + av_free(m_pCodecCtx); + av_free(m_pVideoCodec); + // avformat_close_input ( &m_pFormatCtx ); + avformat_free_context(m_pFormatCtx); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("VideoStream A is Created"); + #endif + }; + + m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + // m_pCodecCtx->thread_count = 1; + // m_pCodecCtx->bit_rate_tolerance = 1; + // m_pCodecCtx->global_quality = 100; + // m_pCodecCtx->compression_level = 2; + m_pCodecCtx->max_b_frames = 1; + m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecCtx->time_base.num = 1; + m_pCodecCtx->time_base.den = m_sStreamData.fps; + m_pCodecCtx->framerate.num = m_sStreamData.fps; + m_pCodecCtx->framerate.den = 1; + + #if (LIBAVCODEC_VERSION_MAJOR > 54) + m_pCodecCtx->codec_tag = av_codec_get_tag(m_pFormatCtx->oformat->codec_tag, VIDEO_OUTPUT_CODEC); + #endif + m_pFormatOpts = NULL; + + if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265)) + { + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0) + { + LOG_ERROR("av_dict_set movflags!"); + #ifdef DEBUG_EXTRA + } else { + LOG("MOV FLAG SET!"); + #endif + }; + + // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + // }; + + // default brand is "isom", which fails on some devices + if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0) + { + LOG_ERROR("av_dict_set brand!"); + }; + // m_pCodecCtx->max_b_frames = 1; + // m_pCodecCtx->level = 31; + + m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecCtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3?5 ref per P] + m_pCodecCtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set(m_pCodecCtx->priv_data, "b-pyramid", "0", 0); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif + } else { + if (m_pFormat->flags & AVFMT_GLOBALHEADER) + { + m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + } + }; + + const AVRational dst_fps = {m_sStreamData.fps, 1}; + + #ifdef DEBUG_EXTRA + char TB[129]; + sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den); + LOG(TB); + #endif + m_pVideoStr->time_base = m_pCodecCtx->time_base; + + // avcodec_get_context_defaults3( m_pVideoStr->codec, m_pVideoCodec ); + + // m_pVideoStr->codec->width = m_pMaster->m_sEmbedVideoData.width; + // m_pVideoStr->codec->height = m_pMaster->m_sEmbedVideoData.height; + // m_pVideoStr->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStr->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStr->r_frame_rate = dst_fps; + // if ( m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStr->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecCtx); + // m_pVideoStr->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStr->codecpar->extradata = m_pCodecCtx->extradata; + // m_pVideoStr->codecpar->extradata_size = m_pCodecCtx->extradata_size; + if (avcodec_is_open(m_pCodecCtx) == 0) + { + LOG("output codec context is closed, opening"); + if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0) + { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is opened"); + #endif + }; + #ifdef DEBUG_EXTRA + } else { + LOG("output codec context is already opened"); + #endif + }; + #endif // SEPARATED_VIDEO_ENCODERS + m_pConvertCtx = + sws_getContext(m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, NULL); + if (m_pConvertCtx == NULL) + { + return false; + } + m_pAVFrame = av_frame_alloc(); + if (m_pAVFrame == NULL) + { + return false; + }; + m_pOutBuffer = (uint8_t *) av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN)); + if (m_pOutBuffer == NULL) + { + return false; + }; + m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width; + m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height; + m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT; + // av_frame_get_buffer( m_pAVFrame, 0 ); + av_image_fill_arrays(m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1); + + // av_frame_make_writable( m_pAVFrame ); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + return init(); + } + #else // !EVE_SEQUENTAL_OUTPUT + void streamHandler::closeSegmentA(void) + { + m_mCurrentOperationProtector.lock(); + if (m_bCOP == 0) + { + m_bCOP = 0x01; + } + m_mCurrentOperationProtector.unlock(); + #ifdef DEBUG_EXTRA + LOG("Closing Stream A"); + #endif + } + + void streamHandler::closeSegmentB(void) + { + m_mCurrentOperationProtector.lock(); + if (m_bCOP == 0) + { + m_bCOP = 0x02; + } + m_mCurrentOperationProtector.unlock(); + #ifdef DEBUG_EXTRA + LOG("Closing Stream B"); + #endif + } + + void streamHandler::closeAll() + { + waitThreadEnd(true); + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderA) + { + if (m_pEncoderA->isOpened()) + { + m_pEncoderA->release(); + }; + delete(m_pEncoderA); + }; + if (m_pEncoderB) + { + if (m_pEncoderB->isOpened()) + { + m_pEncoderB->release(); + }; + delete(m_pEncoderB); + }; + #else // !OPENCV_VIDEO_OUTPUT + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD[0]) + { + fclose(m_pOutputFD[0]); + m_pOutputFD[0] = NULL; + }; + if (m_pOutputFD[1]) + { + fclose(m_pOutputFD[1]); + m_pOutputFD[1] = NULL; + }; + #else // ! DIRECT_MJPEG_COMPOSING + #ifdef SEPARATED_VIDEO_ENCODERS + if ((m_pCodecACtx != NULL || m_pCodecBCtx != NULL) && (m_bSegAActive || m_bSegBActive)) + { + if (m_pCodecACtx != NULL) + { + avcodec_send_frame(m_pCodecACtx, NULL); + int ret = 0; + AVPacket * avp = av_packet_alloc(); + if (avp) + { + do + { + av_packet_unref(avp); + ret = avcodec_receive_packet(m_pCodecACtx, avp); + if (! ret) + { + if (m_bSegAActive) + { + av_write_frame(m_pFormatCtxA, avp); + } + }; + } + while (! ret); + av_packet_unref(avp); + av_packet_free(&avp); + }; + }; + if (m_pCodecBCtx != NULL) + { + avcodec_send_frame(m_pCodecBCtx, NULL); + int ret = 0; + AVPacket * avp = av_packet_alloc(); + if (avp) + { + do + { + av_packet_unref(avp); + ret = avcodec_receive_packet(m_pCodecBCtx, avp); + if (! ret) + { + if (m_bSegBActive) + { + av_write_frame(m_pFormatCtxB, avp); + } + }; + } + while (! ret); + av_packet_unref(avp); + av_packet_free(&avp); + }; + }; + if (m_bSegAActive) + { + av_write_trailer(m_pFormatCtxA); + avformat_close_input(&m_pFormatCtxA); + m_bSegAActive = false; + }; + if (m_bSegBActive) + { + av_write_trailer(m_pFormatCtxB); + avformat_close_input(&m_pFormatCtxB); + m_bSegBActive = false; + }; + }; + #else // !SEPARATED_VIDEO_ENCODERS + if (m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive)) + { + avcodec_send_frame(m_pCodecCtx, NULL); + int ret = 0; + AVPacket * avp = av_packet_alloc(); + if (avp) + { + do + { + av_packet_unref(avp); + ret = avcodec_receive_packet(m_pCodecCtx, avp); + if (! ret) + { + if (m_bSegAActive) + { + av_write_frame(m_pFormatCtxA, avp); + } + if (m_bSegBActive) + { + av_write_frame(m_pFormatCtxB, avp); + } + }; + } + while (! ret); + av_packet_unref(avp); + av_packet_free(&avp); + }; + if (m_bSegAActive) + { + av_write_trailer(m_pFormatCtxA); + avformat_close_input(&m_pFormatCtxA); + m_bSegAActive = false; + }; + if (m_bSegBActive) + { + av_write_trailer(m_pFormatCtxB); + avformat_close_input(&m_pFormatCtxB); + m_bSegBActive = false; + }; + }; + #endif // !SEPARATED_VIDEO_ENCODERS + #endif // !DIRECT_MJPEG_COMPOSING + // if( m_pFormat != NULL ) { + // av_free( m_pFormat ); + //}; + #endif // OPENCV_VIDEO_OUTPUT + } + bool streamHandler::openSegmentA(void) + { + if (! m_bSegAActive) + { + CSTR tAM = getUniqID_MD5(); + if (tAM) + { + sprintf(m_sStreamSegmentInfo[0].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); + strncpy(m_sStreamSegmentInfo[0].recordMD5, tAM, 32); + m_sStreamSegmentInfo[0].recordMD5[32] = (char) 0; + free(tAM); + m_sStreamSegmentInfo[0].stream_id = m_sStreamData.id; + PF_TIMESTAMP ts; + getPFTS(&ts); + m_sStreamSegmentInfo[0].streamTSS = ts.seconds; + m_sStreamSegmentInfo[0].streamTMS = ts.milliseconds; + #ifdef DEBUG_EXTRA + char tB[128]; + sprintf(tB, "A opened %d.%d", m_sStreamSegmentInfo[0].streamTSS, m_sStreamSegmentInfo[0].streamTMS); + LOG(tB); + #endif + strncpy(m_sStreamSegmentInfo[0].recordEXT, VIDEO_OUTPUT_CONTAINER, 6); + m_sStreamSegmentInfo[0].streamFPS = m_sStreamData.fps; + m_sStreamSegmentInfo[0].streamWidth = m_pMaster->getWidh(); + m_sStreamSegmentInfo[0].streamHeight = m_pMaster->getHeight(); + m_sStreamSegmentInfo[0].eventIDS.clear(); + m_sStreamSegmentInfo[0].eventTSS.clear(); + m_sStreamSegmentInfo[0].eventTMS.clear(); + m_sStreamSegmentInfo[0].eventFrames.clear(); + m_sStreamSegmentInfo[0].dataSize = 0; + m_sStreamSegmentInfo[0].db_id = 0; + #ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD[0] = fopen(m_sStreamSegmentInfo[0].scratchPath, "wb+"); + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + m_bSegAActive = true; + m_bSegADelete = true; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderA) + { + // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + double fps = m_sStreamData.fps; + cv::String mn(m_sStreamSegmentInfo[0].scratchPath); + cv::Size fz(m_sStreamData.width, m_sStreamData.height); + // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if (! m_pEncoderA->open(mn, fourcc, fps, fz)) + { + LOG_ERROR("Cannot Open Output Segment A!"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + char tB[256]; + sprintf(tB, "VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps); + LOG(tB); + #endif + }; + m_bSegAActive = true; + m_bSegADelete = true; + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + } + else + { + LOG_ERROR("No Encoder(A) Object!"); + return false; + }; + #else // !OPENCV_VIDEO_OUTPUT + // Check if Encoder is Ready + if (m_pFormat == NULL) + { + return false; + } + + #ifdef SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) + { + LOG_ERROR("Format CTX A alloc error!"); + return false; + } + else + { + av_dict_set(&m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStrA = avformat_new_stream(m_pFormatCtxA, m_pVideoACodec); + if (m_pVideoStrA == NULL) + { + avformat_free_context(m_pFormatCtxA); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("VideoStream A is Created"); + #endif + }; + const AVRational dst_fps = {m_sStreamData.fps, 1}; + m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; + m_pVideoStrA->time_base = m_pCodecACtx->time_base; + avcodec_parameters_from_context(m_pVideoStrA->codecpar, m_pCodecACtx); + #ifdef DEBUG_EXTRA + LOG("Opening Stream A"); + LOG(m_cSegNameA); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration); + LOG(tB); + #endif + // if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + return m_bSegAActive; + }; + if (avformat_write_header(m_pFormatCtxA, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegAActive; + }; + // m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + m_bSegAActive = true; + m_bSegADelete = true; + // m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1; + if (m_pVideoStrA->nb_frames) + { + m_pVideoStrA->nb_frames = 0; + m_pVideoStrA->start_time = 0; + m_pVideoStrA->first_dts = 0; + m_pFormatCtxA->start_time = 0; + }; + #ifdef DEBUG_EXTRA + LOG("Opening Stream A"); + LOG(m_cSegNameA); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration); + LOG(tB); + #endif + if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + return m_bSegAActive; + }; + if (avformat_write_header(m_pFormatCtxA, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegAActive; + }; + // m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + m_bSegAActive = true; + m_bSegADelete = true; + // m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream A Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + }; + }; + return m_bSegAActive; + } + + bool streamHandler::openSegmentB(void) + { + if (! m_bSegBActive) + { + CSTR tAM = getUniqID_MD5(); + if (tAM) + { + sprintf(m_sStreamSegmentInfo[1].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); + strncpy(m_sStreamSegmentInfo[1].recordMD5, tAM, 32); + m_sStreamSegmentInfo[1].recordMD5[32] = (char) 0; + free(tAM); + m_sStreamSegmentInfo[1].stream_id = m_sStreamData.id; + PF_TIMESTAMP ts; + getPFTS(&ts); + m_sStreamSegmentInfo[1].streamTSS = ts.seconds; + m_sStreamSegmentInfo[1].streamTMS = ts.milliseconds; + #ifdef DEBUG_EXTRA + char tB[128]; + sprintf(tB, "B opened %d.%d", m_sStreamSegmentInfo[1].streamTSS, m_sStreamSegmentInfo[1].streamTMS); + LOG(tB); + #endif + strncpy(m_sStreamSegmentInfo[1].recordEXT, VIDEO_OUTPUT_CONTAINER, 6); + m_sStreamSegmentInfo[1].streamFPS = m_sStreamData.fps; + m_sStreamSegmentInfo[1].streamWidth = m_pMaster->getWidh(); + m_sStreamSegmentInfo[1].streamHeight = m_pMaster->getHeight(); + m_sStreamSegmentInfo[1].eventIDS.clear(); + m_sStreamSegmentInfo[1].eventTSS.clear(); + m_sStreamSegmentInfo[1].eventTMS.clear(); + m_sStreamSegmentInfo[1].eventFrames.clear(); + m_sStreamSegmentInfo[1].dataSize = 0; + m_sStreamSegmentInfo[1].db_id = 0; + + #ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD[1] = fopen(m_sStreamSegmentInfo[1].scratchPath, "wb+"); + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + m_bSegBActive = true; + m_bSegBDelete = true; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderB) + { + // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + double fps = m_sStreamData.fps; + cv::String mn(m_sStreamSegmentInfo[1].scratchPath); + cv::Size fz(m_sStreamData.width, m_sStreamData.height); + // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if (! m_pEncoderB->open(mn, fourcc, fps, fz)) + { + LOG_ERROR("Cannot Open Output Segment B!"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + char tB[256]; + sprintf(tB, "VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps); + LOG(tB); + #endif + }; + m_bSegBActive = true; + m_bSegBDelete = true; + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + } + else + { + LOG_ERROR("No Encoder(B) Object!"); + return false; + }; + #else // !OPENCV + // Check if Encoder is Ready + if (m_pFormat == NULL) + { + return false; + } + #ifdef SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) + { + LOG_ERROR("Format CTX B alloc error!"); + return false; + } + else + { + av_dict_set(&m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStrB = avformat_new_stream(m_pFormatCtxB, m_pVideoBCodec); + if (m_pVideoStrB == NULL) + { + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("VideoStream B is Created"); + #endif + }; + const AVRational dst_fps = {m_sStreamData.fps, 1}; + m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + m_pVideoStrB->time_base = m_pCodecBCtx->time_base; + avcodec_parameters_from_context(m_pVideoStrB->codecpar, m_pCodecBCtx); + #ifdef DEBUG_EXTRA + LOG("Opening Stream B"); + LOG(m_cSegNameB); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration); + LOG(tB); + #endif + + // if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ + if (avio_open(&m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + avformat_free_context(m_pFormatCtxB); + return false; + }; + if (avformat_write_header(m_pFormatCtxB, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + avio_close(m_pFormatCtxB->pb); + avformat_free_context(m_pFormatCtxB); + return false; + }; + // m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + m_bSegBActive = true; + m_bSegBDelete = true; + // m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1; + if (m_pVideoStrB->nb_frames) + { + m_pVideoStrB->nb_frames = 0; + m_pVideoStrB->start_time = 0; + m_pVideoStrB->first_dts = 0; + m_pFormatCtxB->start_time = 0; + }; + if (avio_open(&m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + return m_bSegBActive; + }; + if (avformat_write_header(m_pFormatCtxB, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegBActive; + }; + // m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + m_bSegBActive = true; + m_bSegBDelete = true; + // m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream B Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + }; + }; + return m_bSegBActive; + } + + bool streamHandler::initVideoOutput() + { + + m_nPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000; + m_nPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000; + m_nSegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps) / 1000; + m_nHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps) / 1000; + + #ifndef DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + m_pEncoderA = new cv::VideoWriter(); + if (m_pEncoderA == NULL) + { + LOG_ERROR("Encoder A Create Failure!"); + return false; + }; + + m_pEncoderA->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0); + m_pEncoderA->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0); + + m_pEncoderB = new cv::VideoWriter(); + if (m_pEncoderA == NULL) + { + LOG_ERROR("Encoder B Create Failure!"); + return false; + }; + + m_pEncoderB->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0); + m_pEncoderB->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0); + + #else + if (! initLibAV()) + { + return false; + } + + m_pFormat = av_guess_format(VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL); + + if (m_pFormat == NULL) + { + LOG_ERROR("Out VideoFormat Not Found!"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Output video Format"); + LOG(VIDEO_OUTPUT_CONTAINER); + #endif + }; + + #ifdef SEPARATED_VIDEO_ENCODERS + /* Stream A */ + m_pVideoACodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); + if (m_pVideoACodec == NULL) + { + LOG_ERROR("Encoder Video Codec Not Found!"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Video Encoder A Created"); + #endif + }; + m_pCodecACtx = avcodec_alloc_context3(m_pVideoACodec); + if (m_pCodecACtx == NULL) + { + LOG_ERROR("Video Encoder A Context Memory Allocation Error!"); + av_free(m_pVideoACodec); + avformat_free_context(m_pFormatCtxA); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Video Encoder Context A Allocated"); + #endif + }; + /* Stream B */ + m_pVideoBCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); + if (m_pVideoBCodec == NULL) + { + LOG_ERROR("Out VideoCodec Not Found!"); + av_free(m_pVideoACodec); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Video Encoder B Created"); + #endif + }; + m_pCodecBCtx = avcodec_alloc_context3(m_pVideoBCodec); + if (m_pCodecBCtx == NULL) + { + LOG_ERROR("Video Encoder B Context Memory Allocation Error!"); + av_free(m_pVideoACodec); + av_free(m_pVideoBCodec); + avformat_free_context(m_pFormatCtxA); + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Video Encoder Context B Allocated"); + #endif + }; + + m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE; + m_pCodecACtx->max_b_frames = 1; + m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecACtx->time_base.num = 1; + m_pCodecACtx->time_base.den = m_sStreamData.fps; + m_pCodecACtx->framerate.num = m_sStreamData.fps; + m_pCodecACtx->framerate.den = 1; + + m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + m_pCodecBCtx->max_b_frames = 1; + m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecBCtx->time_base.num = 1; + m_pCodecBCtx->time_base.den = m_sStreamData.fps; + m_pCodecBCtx->framerate.num = m_sStreamData.fps; + m_pCodecBCtx->framerate.den = 1; + + // https://pastebin.com/yG37YhWW + + // https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec + // G@ avcodec encode NALU mp4 + + #if (LIBAVCODEC_VERSION_MAJOR > 54) + ////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); + #endif + + #if (LIBAVCODEC_VERSION_MAJOR > 54) + ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); + #endif + m_pFormatOpts = NULL; + + // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + + if ((m_pCodecACtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecACtx->codec_id == AV_CODEC_ID_H265)) + { + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + // Set format's privater options, to be passed to avformat_write_header() + + /* + + mp4 muxer AVOptions: + -movflags E..... MOV muxer flags (default 0) + rtphint E..... Add RTP hint tracks + empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) + frag_keyframe E..... Fragment at video keyframes + separate_moof E..... Write separate moof/mdat atoms for each track + frag_custom E..... Flush fragments on caller requests + isml E..... Create a live smooth streaming feed (for pushing to a publishing point) + faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file + omit_tfhd_offset E..... Omit the base data offset in tfhd atoms + delay_moov ?? + -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) + -rtpflags E..... RTP muxer flags (default 0) + latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC + rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 + skip_rtcp E..... Don't send RTCP sender reports + h264_mode0 E..... Use mode 0 for H264 in RTP + send_bye E..... Send RTCP BYE packets when finishing + -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) + -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) + -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) + -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) + -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) + -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) + -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) + -use_editlist E..... use edit list (from -1 to 1) (default -1) + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ + if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0) + { + LOG_ERROR("av_dict_set movflags!"); + #ifdef DEBUG_EXTRA + } + else + { + LOG("MOV FLAG SET!"); + #endif + }; + + // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + // }; + + // default brand is "isom", which fails on some devices + if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0) + { + LOG_ERROR("av_dict_set brand!"); + }; + // m_pCodecCtx->max_b_frames = 1; + // m_pCodecCtx->level = 31; + + m_pCodecACtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecACtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3?5 ref per P] + m_pCodecACtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set(m_pCodecACtx->priv_data, "preset", "ultrafast", 0); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set(m_pCodecACtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set(m_pCodecACtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set(m_pCodecACtx->priv_data, "b-pyramid", "0", 0); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif + } + else + { + if (m_pFormat->flags & AVFMT_GLOBALHEADER) + { + m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + } + }; + + if ((m_pCodecBCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecBCtx->codec_id == AV_CODEC_ID_H265)) + { + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + // Set format's privater options, to be passed to avformat_write_header() + + /* + + mp4 muxer AVOptions: + -movflags E..... MOV muxer flags (default 0) + rtphint E..... Add RTP hint tracks + empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) + frag_keyframe E..... Fragment at video keyframes + separate_moof E..... Write separate moof/mdat atoms for each track + frag_custom E..... Flush fragments on caller requests + isml E..... Create a live smooth streaming feed (for pushing to a publishing point) + faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file + omit_tfhd_offset E..... Omit the base data offset in tfhd atoms + delay_moov ?? + -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) + -rtpflags E..... RTP muxer flags (default 0) + latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC + rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 + skip_rtcp E..... Don't send RTCP sender reports + h264_mode0 E..... Use mode 0 for H264 in RTP + send_bye E..... Send RTCP BYE packets when finishing + -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) + -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) + -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) + -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) + -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) + -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) + -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) + -use_editlist E..... use edit list (from -1 to 1) (default -1) + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ + // m_pCodecCtx->max_b_frames = 1; + // m_pCodecCtx->level = 31; + + m_pCodecBCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecBCtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3?5 ref per P] + m_pCodecBCtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set(m_pCodecBCtx->priv_data, "preset", "ultrafast", 0); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set(m_pCodecBCtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set(m_pCodecBCtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set(m_pCodecBCtx->priv_data, "b-pyramid", "0", 0); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif + } + else + { + if (m_pFormat->flags & AVFMT_GLOBALHEADER) + { + m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + } + }; + + const AVRational dst_fps = {m_sStreamData.fps, 1}; + + #ifdef DEBUG_EXTRA + char TB[129]; + sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den); + LOG(TB); + sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den); + LOG(TB); + #endif + + ////m_pVideoStrA->time_base = m_pCodecACtx->time_base; + ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base; + + // avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); + + // m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width; + // m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height; + // m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = + ////dst_fps; + + // avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec ); + + // m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width; + // m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height; + // m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + //// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = + ////dst_fps; + + // if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + // if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + //// avcodec_parameters_from_context( m_pVideoStrA->codecpar, + ////m_pCodecACtx ); + // m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata; + // m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + //// avcodec_parameters_from_context( m_pVideoStrB->codecpar, + ////m_pCodecBCtx ); + // m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata; + // m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + if (avcodec_is_open(m_pCodecACtx) == 0) + { + LOG("output codec context is closed, opening"); + if (avcodec_open2(m_pCodecACtx, m_pVideoACodec, NULL) < 0) + { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("output codec context is opened"); + #endif + }; + + #ifdef DEBUG_EXTRA + } + else + { + LOG("output codec context is already opened"); + #endif + }; + + if (avcodec_is_open(m_pCodecBCtx) == 0) + { + LOG("output codec context is closed, opening"); + if (avcodec_open2(m_pCodecBCtx, m_pVideoBCodec, NULL) < 0) + { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("output codec context is opened"); + #endif + }; + + #ifdef DEBUG_EXTRA + } + else + { + LOG("output codec context is already opened"); + #endif + }; + #else // SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) + { + LOG_ERROR("Format CTX A alloc error!"); + return false; + } + else + { + av_dict_set(&m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + if (avformat_alloc_output_context2(&m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) + { + LOG_ERROR("Format CTX B alloc error!"); + avformat_free_context(m_pFormatCtxA); + return false; + } + else + { + av_dict_set(&m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); + if (m_pVideoCodec == NULL) + { + LOG_ERROR("Output VideoCodec Not Found!"); + avformat_free_context(m_pFormatCtxA); + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Output Video Codec Found"); + #endif + }; + + m_pCodecCtx = avcodec_alloc_context3(m_pVideoCodec); + if (m_pCodecCtx == NULL) + { + LOG_ERROR("Out VideoCodec Context Memory Allocation Error"); + av_free(m_pVideoCodec); + avformat_free_context(m_pFormatCtxA); + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("Out Codec Context3 Allocated"); + #endif + }; + m_pVideoStrA = avformat_new_stream(m_pFormatCtxA, m_pVideoCodec); + if (m_pVideoStrA == NULL) + { + LOG_ERROR("VideoStream A Not Created!"); + avcodec_free_context(&m_pCodecCtx); + av_free(m_pCodecCtx); + av_free(m_pVideoCodec); + // avformat_close_input ( &m_pFormatCtxA ); + // avformat_close_input ( &m_pFormatCtxB ); + avformat_free_context(m_pFormatCtxA); + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("VideoStream A is Created"); + #endif + }; + + m_pVideoStrB = avformat_new_stream(m_pFormatCtxB, m_pVideoCodec); + if (m_pVideoStrB == NULL) + { + LOG_ERROR("VideoStream B Not Created!"); + + avcodec_free_context(&m_pCodecCtx); + av_free(m_pCodecCtx); + av_free(m_pVideoCodec); + // avformat_close_input ( &m_pFormatCtxA ); + // avformat_close_input ( &m_pFormatCtxB ); + avformat_free_context(m_pFormatCtxA); + avformat_free_context(m_pFormatCtxB); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("VideoStream B is Created"); + #endif + }; + m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + // m_pCodecCtx->thread_count = 1; + // m_pCodecCtx->bit_rate_tolerance = 1; + // m_pCodecCtx->global_quality = 100; + // m_pCodecCtx->compression_level = 2; + m_pCodecCtx->max_b_frames = 1; + m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecCtx->time_base.num = 1; + m_pCodecCtx->time_base.den = m_sStreamData.fps; + m_pCodecCtx->framerate.num = m_sStreamData.fps; + m_pCodecCtx->framerate.den = 1; + + // https://pastebin.com/yG37YhWW + + // https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec + // G@ avcodec encode NALU mp4 + + #if (LIBAVCODEC_VERSION_MAJOR > 54) + m_pCodecCtx->codec_tag = av_codec_get_tag(m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC); + #endif + m_pFormatOpts = NULL; + + // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + + if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265)) + { + #ifdef DEBUG_EXTRA + LOG("Begin Options!"); + #endif + // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + // Set format's privater options, to be passed to avformat_write_header() + + /* + + mp4 muxer AVOptions: + -movflags E..... MOV muxer flags (default 0) + rtphint E..... Add RTP hint tracks + empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) + frag_keyframe E..... Fragment at video keyframes + separate_moof E..... Write separate moof/mdat atoms for each track + frag_custom E..... Flush fragments on caller requests + isml E..... Create a live smooth streaming feed (for pushing to a publishing point) + faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file + omit_tfhd_offset E..... Omit the base data offset in tfhd atoms + delay_moov ?? + -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) + -rtpflags E..... RTP muxer flags (default 0) + latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC + rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 + skip_rtcp E..... Don't send RTCP sender reports + h264_mode0 E..... Use mode 0 for H264 in RTP + send_bye E..... Send RTCP BYE packets when finishing + -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) + -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) + -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) + -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) + -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) + -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) + -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) + -use_editlist E..... use edit list (from -1 to 1) (default -1) + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ + if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0) + { + LOG_ERROR("av_dict_set movflags!"); + #ifdef DEBUG_EXTRA + } + else + { + LOG("MOV FLAG SET!"); + #endif + }; + + // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + // }; + + // default brand is "isom", which fails on some devices + if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0) + { + LOG_ERROR("av_dict_set brand!"); + }; + // m_pCodecCtx->max_b_frames = 1; + // m_pCodecCtx->level = 31; + + m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecCtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3?5 ref per P] + m_pCodecCtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set(m_pCodecCtx->priv_data, "b-pyramid", "0", 0); + #ifdef DEBUG_EXTRA + LOG("End Options!"); + #endif + } + else + { + if (m_pFormat->flags & AVFMT_GLOBALHEADER) + { + m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + } + }; + + const AVRational dst_fps = {m_sStreamData.fps, 1}; + + #ifdef DEBUG_EXTRA + char TB[129]; + sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den); + LOG(TB); + #endif + + m_pVideoStrA->time_base = m_pCodecCtx->time_base; + m_pVideoStrB->time_base = m_pCodecCtx->time_base; + + // avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); + + // m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width; + // m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height; + // m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + // avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec ); + + // m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width; + // m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height; + // m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + // if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + // if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + avcodec_parameters_from_context(m_pVideoStrA->codecpar, m_pCodecCtx); + // m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata; + // m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + avcodec_parameters_from_context(m_pVideoStrB->codecpar, m_pCodecCtx); + // m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + // m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata; + // m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + if (avcodec_is_open(m_pCodecCtx) == 0) + { + LOG("output codec context is closed, opening"); + if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0) + { + LOG_ERROR("Error opening2 encoder"); + return false; + #ifdef DEBUG_EXTRA + } + else + { + LOG("output codec context is opened"); + #endif + }; + + #ifdef DEBUG_EXTRA + } + else + { + LOG("output codec context is already opened"); + #endif + }; + #endif // SEPARATED_VIDEO_ENCODERS + m_pConvertCtx = + sws_getContext(m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, NULL); + if (m_pConvertCtx == NULL) + { + return false; + } + m_pAVFrame = av_frame_alloc(); + if (m_pAVFrame == NULL) + { + return false; + }; + m_pOutBuffer = (uint8_t *) av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN)); + if (m_pOutBuffer == NULL) + { + return false; + }; + m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width; + m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height; + m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT; + // av_frame_get_buffer( m_pAVFrame, 0 ); + av_image_fill_arrays(m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1); + + // av_frame_make_writable( m_pAVFrame ); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + return init(); + } +#endif // !EVE_SEQUENTAL_OUTPUT + + // encoding thread + + void streamHandler::m_fThreadProc(void) + { + size_t nQueueSize; + #ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + AVPacket mPacket; + int bGotPacket; + int rVal = 0; + av_init_packet(&mPacket); + #endif + #endif + pthread_setname_np(pthread_self(), "VideoStream"); + while (m_bThreadStatus != TH_ENDED) + { + // At the begining All streams are closed --> try to Open + if (m_bThreadStatus < TH_WORKING){ + #ifdef EVE_SEQUENTAL_OUTPUT + CSTR tAM = getUniqID_MD5(); + if( tAM ){ + sprintf(m_sStreamSegmentInfo.scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); + strncpy(m_sStreamSegmentInfo.recordMD5, tAM, 32); + m_sStreamSegmentInfo.recordMD5[32] = (char) 0; + free(tAM); + m_sStreamSegmentInfo.stream_id = m_sStreamData.id; + PF_TIMESTAMP ts; + getPFTS(&ts); + m_sStreamSegmentInfo.streamTSS = ts.seconds; + m_sStreamSegmentInfo.streamTMS = ts.milliseconds; + #ifdef DEBUG_EXTRA + char tB[128]; + sprintf(tB, "First Time opened %d.%d", m_sStreamSegmentInfo.streamTSS, m_sStreamSegmentInfo.streamTMS); + LOG(tB); + #endif + strncpy(m_sStreamSegmentInfo.recordEXT, VIDEO_OUTPUT_CONTAINER, 6); + m_sStreamSegmentInfo.streamFPS = m_sStreamData.fps; + m_sStreamSegmentInfo.streamWidth = m_pMaster->getWidh(); + m_sStreamSegmentInfo.streamHeight = m_pMaster->getHeight(); + m_sStreamSegmentInfo.eventIDS.clear(); + m_sStreamSegmentInfo.eventTSS.clear(); + m_sStreamSegmentInfo.eventTMS.clear(); + m_sStreamSegmentInfo.eventFrames.clear(); + m_sStreamSegmentInfo.dataSize = 0; + m_sStreamSegmentInfo.db_id = 0; + #ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD = fopen(m_sStreamSegmentInfo.scratchPath, "wb+"); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if ( m_pEncoder ){ + // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + double fps = m_sStreamData.fps; + cv::String mn(m_sStreamSegmentInfo.scratchPath); + cv::Size fz(m_sStreamData.width, m_sStreamData.height); + // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if (! m_pEncoder->open(mn, fourcc, fps, fz) ) { + LOG_ERROR("Cannot Open Output VideoStream!"); + m_bThreadStatus = TH_ENDED; + continue; + #ifdef DEBUG_EXTRA + } else { + char tB[256]; + sprintf(tB, "VideoStream is Created [%s] %.2f fps", m_sStreamSegmentInfo.scratchPath, fps); + LOG(tB); + #endif + }; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + } else { + LOG_ERROR("No Encoder Object!"); + m_bThreadStatus = TH_ENDED; + continue; + }; + #else // !OPENCV_VIDEO_OUTPUT + // Check if Encoder is Ready + if (m_pFormat == NULL){ + m_bThreadStatus = TH_ENDED; + continue; + } + + #ifdef SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0){ + LOG_ERROR("Format CTX alloc error!"); + m_bThreadStatus = TH_ENDED; + continue; + } else { + av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoACodec); + if (m_pVideoStr == NULL){ + avformat_free_context(m_pFormatCtx); + m_bThreadStatus = TH_ENDED; + continue; + #ifdef DEBUG_EXTRA + } else { + LOG("VideoStream is Created"); + #endif + }; + const AVRational dst_fps = {m_sStreamData.fps, 1}; + m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; + m_pVideoStr->time_base = m_pCodecCtx->time_base; + avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecACtx); + #ifdef DEBUG_EXTRA + LOG("Opening Stream"); + LOG(m_cSegName); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration); + LOG(tB); + #endif + // if (avio_open(&m_pFormatCtx->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + if (avio_open(&m_pFormatCtx->pb, m_sStreamSegmentInfo.scratchPath, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + // m_mFrameCounterProtector.lock(); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + // m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegSkippedFrames = m_pVideoStr->nb_frames + 1; + if (m_pVideoStr->nb_frames) + { + m_pVideoStr->nb_frames = 0; + m_pVideoStr->start_time = 0; + m_pVideoStr->first_dts = 0; + m_pFormatCtx->start_time = 0; + }; + #ifdef DEBUG_EXTRA + LOG("Opening Stream"); + LOG(m_cSegName); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration); + LOG(tB); + #endif + if (avio_open(&m_pFormatCtx->pb, m_cSegName, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + // m_mFrameCounterProtector.lock(); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + // m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + }; + // If was not sucessfull - exit ?? + if( !m_bSegActive ){ + LOG_ERROR("Can not Open VideoStream for first time!"); + m_bThreadStatus = TH_ENDED; + continue; + }; + #else + if (! openSegmentA()){ + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Can not Open VideoStream A for first time!"); + continue; + }; + #endif + m_bThreadStatus = TH_WORKING; + continue; + }; + + m_mEncodingQueueProtector.lock(); + nQueueSize = m_qEncodingQueue.size(); + m_mEncodingQueueProtector.unlock(); + + if (nQueueSize) + { + m_mEncodingQueueProtector.lock(); + ENCODING_BUFFER * tData = m_qEncodingQueue.front(); + if (tData) + { + m_qEncodingQueue.pop(); + m_mEncodingQueueProtector.unlock(); + #ifdef DIRECT_MJPEG_COMPOSING + #ifdef EVE_SEQUENTAL_OUTPUT + if( m_pOutputFD ) + { + fwrite(tData->data, 1, tData->size, m_pOutputFD); + m_mFrameCounterProtector.lock(); + m_nSegFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + #else // ! EVE_SEQUENTAL_OUTPUT + + if (m_bSegAActive) + { + if (m_pOutputFD[0]) + { + fwrite(tData->data, 1, tData->size, m_pOutputFD[0]); + m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + } + + if (m_bSegBActive) + { + if (m_pOutputFD[1]) + { + fwrite(tData->data, 1, tData->size, m_pOutputFD[1]); + m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + } + #endif // ! EVE_SEQUENTAL_OUTPUT + // Don't free tData->data since is pointer on static data + free(tData->data); + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + + cv::Mat image(tData->rows, tData->cols, CV_8UC3); + memcpy(image.data, tData->data, tData->size); + free(tData->data); + if (m_bSegAActive) + { + if (m_pEncoderA->isOpened()) + { + m_pEncoderA->write(image); + m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + } + if (m_bSegBActive) + { + if (m_pEncoderB->isOpened()) + { + m_pEncoderB->write(image); + m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + } + #else //! OPENCV_VIDEO_OUTPUT + // av_frame_make_writable( m_pAVFrame ); + // m_qEncodingQueue.pop(); + // m_mEncodingQueueProtector.unlock(); + sws_scale(m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize); + free(tData->data[0]); + /* + + + AV_PICTURE_TYPE_NONE Undefined. + AV_PICTURE_TYPE_I Intra. + AV_PICTURE_TYPE_P Predicted. + AV_PICTURE_TYPE_B Bi-dir predicted. + AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4. + AV_PICTURE_TYPE_SI Switching Intra. + AV_PICTURE_TYPE_SP Switching Predicted. + AV_PICTURE_TYPE_BI BI type. + + + */ + if ((m_nGlobalFrameCounter % m_sStreamData.fps) == 0) + { + m_pAVFrame->key_frame = 1; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; + } + else + { + m_pAVFrame->key_frame = 0; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE; + }; + m_pAVFrame->pts = m_nGlobalFrameCounter + 1; + #ifdef SEPARATED_VIDEO_ENCODERS + if (m_bSegAActive) + { + rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame); + } + if (m_bSegBActive) + { + rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame); + } + #else //! SEPARATED_VIDEO_ENCODERS + rVal = avcodec_send_frame(m_pCodecCtx, m_pAVFrame); + #endif //! SEPARATED_VIDEO_ENCODERS + #endif //! OPENCV_VIDEO_OUTPUT + #endif //! DIRECT_MJPEG_COMPOSING + free(tData); + m_mFrameCounterProtector.lock(); + m_nGlobalFrameCounter++; + m_mFrameCounterProtector.unlock(); + } else { + m_mEncodingQueueProtector.unlock(); + }; + }; + #ifdef EVE_SEQUENTAL_OUTPUT + if ( m_bSegActive ) { + m_mFrameCounterProtector.lock(); + if ( m_nSegFrameCounter == m_nHardLimitFrames ) { + #ifdef DEBUG_EXTRA + LOG("Actual Closing Video Stream"); + LOG( m_sStreamSegmentInfo.scratchPath ); + #endif + m_bSegActive = false; + if( !m_bSegDelete ){ + #ifdef DIRECT_MJPEG_COMPOSING + if( m_pOutputFD ){ + fclose(m_pOutputFD); + m_pOutputFD = NULL; + }; + #else //! DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if( m_pEncoder->isOpened() ){ + m_pEncoder->release(); + #ifdef DEBUG_EXTRA + } else { + LOG("Encoder is NOT Opened!"); + #endif + }; + #else //! OPENCV_VIDEO_OUTPUT + av_write_trailer( m_pFormatCtx ); + avio_close( m_pFormatCtx->pb ); + #endif //! OPENCV_VIDEO_OUTPUT + #endif //! DIRECT_MJPEG_COMPOSING + VIDEO_SEGMENT_INFO *tData = (VIDEO_SEGMENT_INFO*) malloc( sizeof(VIDEO_SEGMENT_INFO)); + if( tData ){ + memcpy( tData, &m_sStreamSegmentInfo, sizeof( VIDEO_SEGMENT_INFO )); + EVENT_CONTAINER * bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, tData ); + if( bEVT ){ + basicEventHeap::getInstance()->broadcast(bEVT); + } else { + LOG_ERROR("Event Creation failure!"); + free(tData); + }; + }; + #ifdef DEBUG_EXTRA + LOG("Stream is Saved"); + #endif + } else { + #ifdef DIRECT_MJPEG_COMPOSING + if( m_pOutputFD ){ + fclose(m_pOutputFD); + m_pOutputFD = NULL; + }; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoder->isOpened()){ + m_pEncoder->release(); + #ifdef DEBUG_EXTRA + } else { + LOG("Encoder is NOT Opened!"); + #endif + }; + #else // !OPENCV + #ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer(m_pFormatCtx); + #endif + avio_close(m_pFormatCtx->pb); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + #ifndef EVE_DONT_DELETE_SEGMENTS + unlink(m_sStreamSegmentInfo.scratchPath); + #endif + #ifdef DEBUG_EXTRA + LOG("Stream is Closed and Deleted!"); + #endif + }; + #ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Del FCTX"); + #endif + avformat_free_context( m_pFormatCtx ); + m_pVideoStr = NULL; + #ifdef DEBUG_EXTRA + LOG("Del FCTX DONE"); + #endif + #endif // SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV + #endif // !DIRECT_MJPEG_COMPOSING + }; + m_mFrameCounterProtector.unlock(); + //If we closed Stream then open new + if (!m_bSegActive ) { + CSTR tAM = getUniqID_MD5(); + if( tAM ){ + sprintf(m_sStreamSegmentInfo.scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); + strncpy(m_sStreamSegmentInfo.recordMD5, tAM, 32); + m_sStreamSegmentInfo.recordMD5[32] = (char) 0; + free(tAM); + m_sStreamSegmentInfo.stream_id = m_sStreamData.id; + PF_TIMESTAMP ts; + getPFTS(&ts); + m_sStreamSegmentInfo.streamTSS = ts.seconds; + m_sStreamSegmentInfo.streamTMS = ts.milliseconds; + #ifdef DEBUG_EXTRA + char tB[128]; + sprintf(tB, "VideoStream opened %d.%d", m_sStreamSegmentInfo.streamTSS, m_sStreamSegmentInfo.streamTMS); + LOG(tB); + LOG( m_sStreamSegmentInfo.scratchPath ); + #endif + strncpy(m_sStreamSegmentInfo.recordEXT, VIDEO_OUTPUT_CONTAINER, 6); + m_sStreamSegmentInfo.streamFPS = m_sStreamData.fps; + m_sStreamSegmentInfo.streamWidth = m_pMaster->getWidh(); + m_sStreamSegmentInfo.streamHeight = m_pMaster->getHeight(); + m_sStreamSegmentInfo.eventIDS.clear(); + m_sStreamSegmentInfo.eventTSS.clear(); + m_sStreamSegmentInfo.eventTMS.clear(); + m_sStreamSegmentInfo.eventFrames.clear(); + m_sStreamSegmentInfo.dataSize = 0; + m_sStreamSegmentInfo.db_id = 0; + #ifdef DIRECT_MJPEG_COMPOSING + m_pOutputFD = fopen(m_sStreamSegmentInfo.scratchPath, "wb+"); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if ( m_pEncoder ){ + // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); + int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); + double fps = m_sStreamData.fps; + cv::String mn(m_sStreamSegmentInfo.scratchPath); + cv::Size fz(m_sStreamData.width, m_sStreamData.height); + // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) + if (! m_pEncoder->open(mn, fourcc, fps, fz) ) { + LOG_ERROR("Cannot Open Output VideoStream!"); + m_bThreadStatus = TH_ENDED; + continue; + #ifdef DEBUG_EXTRA + } else { + char tB[256]; + sprintf(tB, "VideoStream is Created [%s] %.2f fps", m_sStreamSegmentInfo.scratchPath, fps); + LOG(tB); + #endif + }; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + } else { + LOG_ERROR("No Encoder Object!"); + m_bThreadStatus = TH_ENDED; + continue; + }; + #else // !OPENCV_VIDEO_OUTPUT + // Check if Encoder is Ready + if (m_pFormat == NULL){ + m_bThreadStatus = TH_ENDED; + continue; + } + + #ifdef SEPARATED_VIDEO_ENCODERS + if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0){ + LOG_ERROR("Format CTX alloc error!"); + m_bThreadStatus = TH_ENDED; + continue; + } else { + av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0); + m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoACodec); + if (m_pVideoStr == NULL){ + avformat_free_context(m_pFormatCtx); + m_bThreadStatus = TH_ENDED; + continue; + #ifdef DEBUG_EXTRA + } else { + LOG("VideoStream is Created"); + #endif + }; + const AVRational dst_fps = {m_sStreamData.fps, 1}; + m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; + m_pVideoStr->time_base = m_pCodecCtx->time_base; + avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecACtx); + #ifdef DEBUG_EXTRA + LOG("Opening Stream"); + LOG(m_cSegName); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration); + LOG(tB); + #endif + // if (avio_open(&m_pFormatCtx->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + if (avio_open(&m_pFormatCtx->pb, m_sStreamSegmentInfo.scratchPath, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + // m_mFrameCounterProtector.lock(); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + // m_mFrameCounterProtector.unlock(); + #else // SEPARATED_VIDEO_ENCODERS + m_nSegSkippedFrames = m_pVideoStr->nb_frames + 1; + if (m_pVideoStr->nb_frames) + { + m_pVideoStr->nb_frames = 0; + m_pVideoStr->start_time = 0; + m_pVideoStr->first_dts = 0; + m_pFormatCtx->start_time = 0; + }; + #ifdef DEBUG_EXTRA + LOG("Opening Stream"); + LOG(m_cSegName); + char tB[128]; + sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts); + LOG(tB); + sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration); + LOG(tB); + #endif + if (avio_open(&m_pFormatCtx->pb, m_cSegName, AVIO_FLAG_WRITE) < 0) + { + LOG_ERROR("Could not open output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0) + { + LOG_ERROR("Error occurred when writing header to output file."); + m_bThreadStatus = TH_ENDED; + continue; + }; + // m_mFrameCounterProtector.lock(); + m_nSegFrameCounter = 0; + m_nSegShiftFrames = 0; + m_bSegActive = true; + m_bSegDelete = m_bNSegDelete; + m_bNSegDelete = true; + // m_mFrameCounterProtector.unlock(); + #endif // SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Stream Opened"); + #endif + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + }; + }; + }; + #else //! EVE_SEQUENTAL_OUTPUT + // Test Commands! + m_mCurrentOperationProtector.lock(); + switch (m_bCOP){ + case 0x01:{ + #ifdef DEBUG_EXTRA + LOG("Actual Closing Video Stream A!"); + LOG(m_sStreamSegmentInfo[0].scratchPath); + #endif + m_bSegAActive = false; + if (! m_bSegADelete) + { + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD[0]) + { + fclose(m_pOutputFD[0]); + m_pOutputFD[0] = NULL; + }; + #else //! DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderA->isOpened()) + { + m_pEncoderA->release(); + #ifdef DEBUG_EXTRA + } + else + { + LOG(" Encoder A is NOT Opened!"); + #endif + }; + #else //! OPENCV_VIDEO_OUTPUT + av_write_trailer(m_pFormatCtxA); + avio_close(m_pFormatCtxA->pb); + #endif //! OPENCV_VIDEO_OUTPUT + #endif //! DIRECT_MJPEG_COMPOSING + EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0]); + if (bEVT) + { + basicEventHeap::getInstance()->broadcast(bEVT); + } + else + { + LOG_ERROR("Event Creation failure!"); + } + #ifdef DEBUG_EXTRA + LOG("Stream A is Saved"); + #endif + } + else + { + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD[0]) + { + fclose(m_pOutputFD[0]); + m_pOutputFD[0] = NULL; + }; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderA->isOpened()) + { + m_pEncoderA->release(); + #ifdef DEBUG_EXTRA + } + else + { + LOG(" Encoder A is NOT Opened!"); + #endif + }; + #else // !OPENCV + #ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer(m_pFormatCtxA); + #endif + avio_close(m_pFormatCtxA->pb); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + #ifndef EVE_DONT_DELETE_SEGMENTS + unlink(m_sStreamSegmentInfo[0].scratchPath); + #endif + #ifdef DEBUG_EXTRA + LOG("Stream A is Closed!"); + #endif + }; + #ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS + #ifdef DEBUG_EXTRA + LOG("Del FCTX"); + #endif + avformat_free_context(m_pFormatCtxA); + m_pVideoStrA = NULL; + #ifdef DEBUG_EXTRA + LOG("Del FCTX DONE"); + #endif + #endif // SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV + #endif // !DIRECT_MJPEG_COMPOSING + break; + }; + case 0x02:{ + #ifdef DEBUG_EXTRA + LOG("Actual Closing Video Stream B!"); + LOG(m_sStreamSegmentInfo[1].scratchPath); + #endif + m_bSegBActive = false; + if (! m_bSegBDelete) + { + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD[1]) + { + fclose(m_pOutputFD[1]); + m_pOutputFD[1] = NULL; + }; + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderB->isOpened()) + { + m_pEncoderB->release(); + #ifdef DEBUG_EXTRA + } + else + { + LOG(" Encoder B is NOT Opened!"); + #endif + }; + #else // !OpenCV + av_write_trailer(m_pFormatCtxB); + avio_close(m_pFormatCtxB->pb); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1]); + if (bEVT) + { + basicEventHeap::getInstance()->broadcast(bEVT); + } + else + { + LOG_ERROR("Event Creation failure!"); + } + #ifdef DEBUG_EXTRA + LOG("Stream B is Saved"); + + #endif + } + else + { + #ifdef DIRECT_MJPEG_COMPOSING + if (m_pOutputFD[1]) + { + fclose(m_pOutputFD[1]); + m_pOutputFD[1] = NULL; + }; + #else + #ifdef OPENCV_VIDEO_OUTPUT + if (m_pEncoderB->isOpened()) + { + m_pEncoderB->release(); + #ifdef DEBUG_EXTRA + } + else + { + LOG(" Encoder B is NOT Opened!"); + #endif + }; + #else // !OPenCV + #ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer(m_pFormatCtxB); + #endif + avio_close(m_pFormatCtxB->pb); + #endif // !OPENCV_VIDEO_OUTPUT + #endif // !DIRECT_MJPEG_COMPOSING + #ifndef EVE_DONT_DELETE_SEGMENTS + unlink(m_sStreamSegmentInfo[1].scratchPath); + #endif + #ifdef DEBUG_EXTRA + LOG("Stream B is Closed!"); + #endif + }; + #ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS + avformat_free_context(m_pFormatCtxB); + m_pVideoStrB = NULL; + #endif // SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV + #endif // !DIRECT_MJPEG_COMPOSING + break; + }; + }; + m_bCOP = 0; + m_mCurrentOperationProtector.unlock(); + #endif // !EVE_SEQUENTAL_OUTPUT + +#ifndef DIRECT_MJPEG_COMPOSING + #ifndef OPENCV_VIDEO_OUTPUT + #ifdef SEPARATED_VIDEO_ENCODERS + do + { + mPacket.data = NULL; + mPacket.size = 0; + rVal = avcodec_receive_packet(m_pCodecACtx, &mPacket); + if (rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF) + { + break; + } + else if (rVal < 0) + { + LOG_ERROR("Error during encoding "); + m_bThreadStatus = TH_ENDED; + break; + }; + if (! rVal) + { + if (m_bSegAActive) + { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter++; + m_mFrameCounterProtector.unlock(); + mPacket.pts = av_rescale_q(m_nSegAFrameCounter, m_pCodecACtx->time_base, m_pVideoStrA->time_base); + // mPacket.pts = AV_NOPTS_VALUE; + // mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame(m_pFormatCtxA, &mPacket); + if (rc < 0) + { + // if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output A!"); + av_strerror(rc, tB, 128); + LOG_ERROR(tB); + break; // continue (changed since embed into do-while) + }; + }; + if (m_bSegBActive) + { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + mPacket.pts = av_rescale_q(m_nSegBFrameCounter, m_pCodecBCtx->time_base, m_pVideoStrB->time_base); + // mPacket.pts = AV_NOPTS_VALUE; + // mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame(m_pFormatCtxB, &mPacket); + if (rc < 0) + { + // if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output B!"); + av_strerror(rc, tB, 128); + LOG_ERROR(tB); + break; // continue (changed since embed into do-while) + }; + }; + av_packet_unref(&mPacket); + }; + } + while (rVal >= 0 && m_bThreadStatus != TH_ENDED); + #else // !SEPARATED_VIDEO_ENCODERS + do + { + mPacket.data = NULL; + mPacket.size = 0; + rVal = avcodec_receive_packet(m_pCodecCtx, &mPacket); + if (rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF) + { + break; + } + else if (rVal < 0) + { + LOG_ERROR("Error during encoding "); + m_bThreadStatus = TH_ENDED; + break; + }; + if (! rVal) + { + if (m_bSegAActive) + { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q(m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base); + // mPacket.pts = AV_NOPTS_VALUE; + // mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame(m_pFormatCtxA, &mPacket); + if (rc < 0) + { + // if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output A!"); + av_strerror(rc, tB, 128); + LOG_ERROR(tB); + break; // continue (changed since embed into do-while) + }; + }; + if (m_bSegBActive) + { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q(m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base); + // mPacket.pts = AV_NOPTS_VALUE; + // mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame(m_pFormatCtxB, &mPacket); + if (rc < 0) + { + // if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output B!"); + av_strerror(rc, tB, 128); + LOG_ERROR(tB); + break; // continue (changed since embed into do-while) + }; + }; + av_packet_unref(&mPacket); + }; + } + while (rVal >= 0 && m_bThreadStatus != TH_ENDED); + #endif // ! SEPARATED_VIDEO_ENCODERS + #endif // !OPENCV_VIDEO_OUTPUT +#endif // !DIRECT_MJPEG_COMPOSING + SLEEP(10); + }; +#ifdef DEBUG_EXTRA + LOG("Encoder Loop Ended!"); +#endif + } + + #ifndef EVE_SEQUENTAL_OUTPUT + void streamHandler::swapActiveStreams(void) + { + if (m_bSegDelete) + { + closeSegment(); + } + // m_mFrameCounterProtector.lock(); + m_bActiveEncoderStream = 1 - m_bActiveEncoderStream; + if (m_bActiveEncoderStream) + { + if (m_bSegADelete) + { + closeSegmentA(); + } + } + else + { + if (m_bSegBDelete) + { + closeSegmentB(); + } + }; + // m_mFrameCounterProtector.unlock(); + } + #endif // !EVE_SEQUENTAL_OUTPUT +#endif // EVE_ENABLE_VIDEO + +bool streamHandler::triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame) +{ + +#ifdef DEBUG_EXTRA + LOG("Trig Evt"); +#endif + +#ifdef EVE_ENABLE_VIDEO + m_mFrameCounterProtector.lock(); + // To Mark Events on the Frames + m_bEvtMarkerCounter = 255; + PF_TIMESTAMP ts; + getPFTS(&ts); + if ( dbid ) dbid = dbid; + #ifdef EVE_SEQUENTAL_OUTPUT + m_bSegDelete = false; + // Keep Also Next Segment if close to a end + if ( ( m_nSegmentLimitFrames - m_nSegFrameCounter ) < m_nPostAlarmFrames ) m_bNSegDelete = false; + m_nSegShiftFrames = frame = m_nSegFrameCounter; + m_sStreamSegmentInfo.eventIDS.push_back(eid); + m_sStreamSegmentInfo.eventTSS.push_back(ts.seconds); + m_sStreamSegmentInfo.eventTMS.push_back(ts.milliseconds); + m_sStreamSegmentInfo.eventFrames.push_back(frame); + // dbid = m_sStreamSegmentInfo.db_id;// = m_nVideoRegisteredDBID; + #else // !EVE_SEQUENTAL_OUTPUT + if (!m_bActiveEncoderStream) + { // Stream A is Active + m_bSegADelete = false; + m_nSegAShiftFrames = frame = m_nSegAFrameCounter; + } + else + { // Stream B is Active + m_bSegBDelete = false; + m_nSegBShiftFrames = frame = m_nSegBFrameCounter; + }; + m_sStreamSegmentInfo[m_bActiveEncoderStream].eventIDS.push_back(eid); + m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTSS.push_back(ts.seconds); + m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTMS.push_back(ts.milliseconds); + m_sStreamSegmentInfo[m_bActiveEncoderStream].eventFrames.push_back(frame); + // dbid = m_sStreamSegmentInfo[m_bActiveEncoderStream].db_id;// = m_nVideoRegisteredDBID; + #endif // !EVE_SEQUENTAL_OUTPUT + m_mFrameCounterProtector.unlock(); + // if ( dbid == 0 ) return false; + #ifdef DEBUG_EXTRA + LOG("Event Registered!"); + #endif +#endif // EVE_ENABLE_VIDEO + return true; +} + +bool streamHandler::triggerCamMove(void) +{ +#ifdef DEBUG_EXTRA + LOG("Trig Cammove"); +#endif + m_bCamMoveCounter = 255; + return true; +} + +bool streamHandler::validate(void) +{ + if (m_pSource) + { + if (m_pSource->getStatus() < MS_CLOSING) + { +#ifdef EVE_ENABLE_VIDEO + if (m_nGlobalFrameCounter) + { // Frames Received from a source + if (m_nGlobalFrameCounter == m_nValidatorFrameCounter) + { + // Video Stalled! + LOG_ERROR("Video Stalled"); + return false; // Try use System to recuperate + } + else + { + m_nValidatorFrameCounter = m_nGlobalFrameCounter; + } + }; + if (m_bThreadStatus < TH_ENDED) + { + return true; + } + else + { + LOG_ERROR("Thread Ended!"); + } +#endif + } + else + { + LOG_ERROR("Video Ended"); + } + }; + return false; +} + + +#undef LOG +#undef LOG_ERROR + +#endif // !LRF_PROXY_ONLY + +#undef DEBUG_EXTRA + diff --git a/lib/App/common/streamHandler.h b/lib/App/common/streamHandler.h new file mode 100644 index 00000000..e0eeed71 --- /dev/null +++ b/lib/App/common/streamHandler.h @@ -0,0 +1,366 @@ +#ifndef __STREAM_HANDLER_EMBED_VIDEO_HEADER__ +#define __STREAM_HANDLER_EMBED_VIDEO_HEADER__ + + +#include "../../components/base/basicDualThread.h" +#include "../../components/base/basicEventHeap.h" +#include "../../components/base/basicMutex.h" +#include "kernelModule.h" +#define EVE_SEQUENTAL_OUTPUT + +#ifndef EVE_SEQUENTAL_OUTPUT + //#define EVE_ENABLE_EASE_OUTPUT_FPS +#endif + +// #include "../../data/media/video/videoAVLIBDestination.h" +#include "../../components/base/basicMediaDestination.h" +#include "../../components/base/basicMediaSource.h" + +#define VIDEO_SCRATCHPAD_PATH (DB_SHMEM_POINT "/video_scratch") + + +//Predefine Classess +class kernelModuleEmbedVideo; +class streamHandler; + +#define FILESTREAMBUFFERSZ 1048576 + +#ifndef MEKOROT_PROJECT__ + #define EVE_ENABLE_VIDEO +#endif + +#define USE_SCALING_IN +// #define USE_CV_DENOISE +// #define USE_CV_TONEMAP + +#ifndef DB_SHMEM_POINT + #define DB_SHMEM_POINT "/dev/shm/argus" +#endif + +#ifdef EVE_ENABLE_VIDEO + #define VIDEO_OUTPUT_FPS 15 + + #ifndef EVE_SEQUENTAL_OUTPUT + // In case of sequental video files - no need two encoders + #define SEPARATED_VIDEO_ENCODERS + #endif + // #define EVE_DONT_DELETE_SEGMENTS + + /* 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 VO_MJPEG 1 + #define VO_MPEG4 2 + #define VO_H264 3 + #define VO_H265 4 + #define VO_FLV 5 + #define VO_DIRECT_MJPG 6 + + #define DIRECT_MJPEG_COMPOSING + + #ifdef DIRECT_MJPEG_COMPOSING + #define VIDEO_OUTPUT VO_DIRECT_MJPG + #else + #define OPENCV_VIDEO_OUTPUT + #define VIDEO_OUTPUT VO_DIRECT_MJPG + #ifndef OPENCV_VIDEO_OUTPUT + // #define VIDEO_OUTPUT VO_MJPEG + #define VIDEO_OUTPUT VO_MPEG4 + // #define VIDEO_OUTPUT VO_H264 + // #define VIDEO_OUTPUT VO_H265 + // #define VIDEO_OUTPUT VO_FLV + // #define VIDEO_OUTPUT_WIDTH 640 //1920 + // #define VIDEO_OUTPUT_HEIGHT 480 //1080 + // #define VIDEO_OUTPUT_FPS 10 + // #define VIDEO_OUTPUT_GOP 15 + #else // OPENCV_VIDEO_OUTPUT + #define VIDEO_OUTPUT VO_MJPEG // VO_CV_MP4 + #endif + #endif // DIRECT_MJPEG_COMPOSING + + #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_YUV420P // AV_PIX_FMT_YUVJ422P + #define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "mjpeg" + #elif 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 4000000 + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif 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 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_H265 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H265 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_FLV + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "flv" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "flv" + #elif VIDEO_OUTPUT == VO_CV_MP4 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_DIRECT_MJPG + #define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" + #define VIDEO_OUTPUT_CONTAINER "mjpeg" + #endif + #endif +#endif // EVE_ENABLE_VIDEO + +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 + +#define PRE_ALARM_TIME_MILSECONDS 5000 // 5 sec +#define POST_ALARM_TIME_MILSECONDS 5000 // 5 sec +#define ENCODING_SEGMENT_MILSECONDS 50000 // 50 sec +#define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute +// #define ENCODING_SEGMENT_LIMIT_MILSECONDS 900000 // 15 minutes + + +// #define ENCODER_DISABLED 0 +// #define ENCODER_ENABLED 1 + +#define EVE_ENABLE_DROP_OUTPUT_FPS + +#ifdef EVE_ENABLE_VIDEO + #ifdef DIRECT_MJPEG_COMPOSING + typedef struct S_ENCODING_BUFFER + { + uint8_t * data; + size_t size; + } ENCODING_BUFFER; + #else //! DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + typedef struct S_ENCODING_BUFFER + { + int cols; + int rows; + uint8_t * data; + size_t size; + } ENCODING_BUFFER; + #else //! OPENCV_VIDEO_OUTPUT + typedef struct S_ENCODING_BUFFER + { + int linesize[2]; + int rows; + uint8_t * data[2]; + size_t size; + } ENCODING_BUFFER; + #endif //! OPENCV_VIDEO_OUTPUT + #endif //! DIRECT_MJPEG_COMPOSING + +typedef std::queue Q_ENCODING_BUFFER; +#endif // EVE_ENABLE_VIDEO + +class streamHandler : + public basicMediaDestination +#ifdef EVE_ENABLE_VIDEO + , public basicThread +#endif +{ + private: + + basicLogCollection * m_pLog; + basicMediaSource * m_pSource; + MEDIA_SOURCE_DESC m_sSourceDesc; + char m_cSourceType; + DBC_MEDIA_STREAM_DATA m_sStreamData; + basicMutex m_mProtector; + kernelModuleEmbedVideo * m_pMaster; + uint8_t m_bEvtMarkerCounter; + uint8_t m_bCamMoveCounter; + + dataBinder * m_pDBC; + MS_WORK_MODE m_eWM; + basicMutex m_mEvtIDS_Protector; + +#ifdef EVE_ENABLE_VIDEO + + #ifdef EVE_SEQUENTAL_OUTPUT + basicMutex m_mEventBindingBlocker; + #endif + + uint32_t m_nPreAlarmFrames; + uint32_t m_nPostAlarmFrames; + uint32_t m_nSegmentLimitFrames; + uint32_t m_nHardLimitFrames; + + basicMutex m_mFrameCounterProtector; + uint64_t m_nGlobalFrameCounter; + uint64_t m_nValidatorFrameCounter; + #ifndef EVE_SEQUENTAL_OUTPUT + uint32_t m_nSegAFrameCounter; + uint32_t m_nSegBFrameCounter; + uint32_t m_nSegAShiftFrames; + uint32_t m_nSegBShiftFrames; + uint32_t m_nSegASkippedFrames; + uint32_t m_nSegBSkippedFrames; + + uint8_t m_bActiveEncoderStream; + bool m_bSegAActive; + bool m_bSegADelete; + bool m_bSegBActive; + bool m_bSegBDelete; + VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; + #else + uint32_t m_nSegFrameCounter; + uint32_t m_nSegShiftFrames; + uint32_t m_nSegSkippedFrames; + bool m_bSegActive; + bool m_bSegDelete; + bool m_bNSegDelete; + VIDEO_SEGMENT_INFO m_sStreamSegmentInfo; + #endif + uint8_t m_bFlipMode; + basicMutex m_mCurrentOperationProtector; + uint8_t m_bCOP; + + + #ifdef DIRECT_MJPEG_COMPOSING + #ifndef EVE_SEQUENTAL_OUTPUT + FILE * m_pOutputFD[2]; + #else + FILE * m_pOutputFD; + #endif + #else // !DIRECT_MJPEG_COMPOSING + #ifdef OPENCV_VIDEO_OUTPUT + #ifndef EVE_SEQUENTAL_OUTPUT + cv::VideoWriter * m_pEncoderA; + cv::VideoWriter * m_pEncoderB; + #else + cv::VideoWriter * m_pEncoder; + #endif + #else //! OPENCV_VIDEO_OUTPUT + // char m_pVideoScratchPath[PATH_MAX]; + #ifdef SEPARATED_VIDEO_ENCODERS + // LibAV encoding video stuff + #ifndef EVE_SEQUENTAL_OUTPUT + // Stream A + AVCodec * m_pVideoACodec; + AVCodecContext * m_pCodecACtx; + AVFrame * m_pAVAFrame; + uint8_t * m_pOutABuffer; + // Stream B + AVCodec * m_pVideoBCodec; + AVCodecContext * m_pCodecBCtx; + AVFrame * m_pAVBFrame; + uint8_t * m_pOutBBuffer; + #else + AVCodec * m_pVideoCodec; + AVCodecContext * m_pCodecCtx; + AVFrame * m_pAVFrame; + uint8_t * m_pOutBuffer; + #endif + #else //! SEPARATED_VIDEO_ENCODERS + // LibAV encoding video stuff + AVCodec * m_pVideoCodec; + AVCodecContext * m_pCodecCtx; + AVFrame * m_pAVFrame; + uint8_t * m_pOutBuffer; + #endif //! SEPARATED_VIDEO_ENCODERS + // Common Pix Converter ( for both streams ) + SwsContext * m_pConvertCtx; + #endif //! OPENCV_VIDEO_OUTPUT + + // char m_cSegNameA[128]; + // char m_cSegMD5A[33]; + // char m_cSegNameB[128]; + // char m_cSegMD5B[33]; + + AVOutputFormat * m_pFormat; + #ifdef SEPARATED_VIDEO_ENCODERS + // File Context 2 units + AVFormatContext * m_pFormatCtxA; + AVFormatContext * m_pFormatCtxB; + AVStream * m_pVideoStrA; + AVStream * m_pVideoStrB; + #else + // File Context 1 units + AVFormatContext * m_pFormatCtx; + AVStream * m_pVideoStr; + #endif + // common output options + AVDictionary * m_pFormatOpts; + #endif //! DIRECT_MJPEG_COMPOSING + basicMutex m_mEncodingQueueProtector; + Q_ENCODING_BUFFER m_qEncodingQueue; + #ifndef EVE_SEQUENTAL_OUTPUT + bool openSegmentA(void); + void closeSegmentA(void); + bool openSegmentB(void); + void closeSegmentB(void); + void swapActiveStreams(void); + #endif + void closeAll(); + bool initVideoOutput(); + + protected: + + void m_fThreadProc(void); +#endif //! EVE_ENABLE_VIDEO + + public: + + explicit streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M = MS_MODE_DECODE_FRAMES, uint8_t flip_mode = 0); + virtual ~streamHandler(); + bool create(dataBinder * ptr, uint32_t stremID); + /* from Media Destination */ + virtual bool pushFrame(AVFrame * Frame, void * src = NULL); + // virtual void pushFrame( cv::Mat* Frame, void* src = NULL); + virtual bool pushFrame(cv::Mat & Frame, void * src = NULL); + bool triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame); + bool triggerCamMove(void); + bool validate(void); +}; + +typedef map mapSTREAMHANDLERS; + +#endif diff --git a/lib/data/bosch_rcp/bosch_rcp.cpp b/lib/data/bosch_rcp/bosch_rcp.cpp new file mode 100644 index 00000000..74b31b5b --- /dev/null +++ b/lib/data/bosch_rcp/bosch_rcp.cpp @@ -0,0 +1,2449 @@ +#include "bosch_rcp.h" + +#include +#include +#include +#include +#include /* See NOTES */ +#include + +#define LOG(X) m_pLog->Log("pBRCP", this, X) +#define TLOG(X) basicLogCollection::getInstance()->Log("pBRCP_T", NULL, X) +#ifdef DEBUG + #define LOG_ERROR(X) \ + { \ + char _tBfrErrMSG2w34[512]; \ + sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ + m_pLog->Log("pBRCP", this, _LOG_ERROR, _tBfrErrMSG2w34); \ + } +#else + #define LOG_ERROR(X) m_pLog->Log("pBRCP", this, _LOG_ERROR, X); +#endif + +inline bool checkBool(const char * A) +{ + if (A == NULL) + { + return false; + } + return (A[0] == 'T' || A[0] == 't' || A[0] == '1'); +} + +inline bool checkOnOff(const char * A) +{ + if (A == NULL) + { + return false; + } + return (A[1] == 'N' || A[1] == 'n' || A[0] == '1'); +} + +inline onvifOnOffAuto checkOnOffAuto(const char * A) +{ + if (A == NULL) + { + return AUTO; + } + if (A[1] == 'N' || A[1] == 'n' || A[0] == '1') + { + return ON; + } + return OFF; +} + +boschRCP::boschRCP() +{ + m_pLog = basicLogCollection::getInstance(); + m_pIpAddress = NULL; + m_pUsername = NULL; + m_pPassword = NULL; + m_pMediaURI = NULL; + m_pSnapshotURI = NULL; + m_pDeviceURI = NULL; + m_pPTZURI = NULL; + m_pBaseURI = NULL; + m_nDeltaTime = 0; + m_pCURL = NULL; + m_pProxyHost = NULL; + m_nProxyPort = 0; + m_pProxyUsername = NULL; + m_pProxyPassword = NULL; + m_pLastResponse = NULL; + m_bIntransingent = true; + m_nDiscoveryTimeout = 30;//PONVIF_DEFAULT_DISCOVERYTIMEOUT; + m_pDiscoveryBindIP = NULL; // PONVIF_DEFAULT_DISCOVERYBINDIP; + m_pDiscoveryMCastIP = NULL; // PONVIF_DEFAULT_DISCOVERYMCASTIP; + m_nDiscoveryMCastPort = 30;//PONVIF_DEFAULT_DISCOVERYMCASTPORT; + m_bDiscoveryHideDuplicates = true; + m_pHttpAccessManager = NULL; + m_sCapabilities.Analytics = NULL; + m_sCapabilities.Device = NULL; + m_sCapabilities.Events = NULL; + m_sCapabilities.Imaging = NULL; + m_sCapabilities.Media = NULL; + m_sCapabilities.PTZ = NULL; + m_sCapabilities.Extension = NULL; + m_bAuthMode = 0; + LOG("Constructor Done!"); +} + +boschRCP::~boschRCP() +{ +#ifdef DEBUG + LOG("Destructor begin"); +#endif + if (m_pIpAddress) + { + free(m_pIpAddress); + } + if (m_pUsername) + { + free(m_pUsername); + } + if (m_pPassword) + { + free(m_pPassword); + } + if (m_pMediaURI) + { + free(m_pMediaURI); + } + if (m_pSnapshotURI) + { + free(m_pSnapshotURI); + } + if (m_pDeviceURI) + { + free(m_pDeviceURI); + } + if (m_pPTZURI) + { + free(m_pPTZURI); + } + if (m_pBaseURI) + { + free(m_pBaseURI); + } + if (m_pProxyHost) + { + free(m_pProxyHost); + } + if (m_pProxyUsername) + { + free(m_pProxyUsername); + } + if (m_pProxyPassword) + { + free(m_pProxyPassword); + } + if (m_pLastResponse) + { + free(m_pLastResponse); + } + if (m_pDiscoveryBindIP) + { + free(m_pDiscoveryBindIP); + } + if (m_pDiscoveryMCastIP) + { + free(m_pDiscoveryMCastIP); + } + if (m_sCapabilities.Analytics) + { + free(m_sCapabilities.Analytics); + } + if (m_sCapabilities.Device) + { + free(m_sCapabilities.Device); + } + if (m_sCapabilities.Events) + { + free(m_sCapabilities.Events); + } + if (m_sCapabilities.Imaging) + { + free(m_sCapabilities.Imaging); + } + if (m_sCapabilities.Media) + { + free(m_sCapabilities.Media); + } + if (m_sCapabilities.PTZ) + { + free(m_sCapabilities.PTZ); + } + if (m_sCapabilities.Extension) + { + free(m_sCapabilities.Extension); + } + if (m_pCURL) + { +#ifdef DEBUG + LOG("Try Cleanup CURL!"); +#endif + curl_easy_cleanup(m_pCURL); + m_pCURL = NULL; + }; +#ifdef DEBUG + LOG("Destructor Done!"); +#endif +} + +bool boschRCP::setProxyHost(CSTR proxyHost) +{ + if (m_pProxyHost != NULL) + { + free(m_pProxyHost); + } + if (proxyHost == NULL || strlen(proxyHost) == 0) + { + m_pProxyHost = NULL; + return true; + }; + m_pProxyHost = (CSTR) malloc(strlen(proxyHost) + 1); + if (m_pProxyHost == NULL) + { + return false; + } + memcpy(m_pProxyHost, proxyHost, strlen(proxyHost) + 1); + return true; +} + +CSTR boschRCP::getProxyHost() +{ + return m_pProxyHost; +} + +bool boschRCP::setProxyPort(int proxyPort) +{ + m_nProxyPort = proxyPort; + return true; +} + +int boschRCP::getProxyPort(void) +{ + return m_nProxyPort; +} + +bool boschRCP::setProxyUsername(CSTR proxyUsername) +{ + if (m_pProxyUsername != NULL) + { + free(m_pProxyUsername); + } + if (proxyUsername == NULL || strlen(proxyUsername) == 0) + { + m_pProxyUsername = NULL; + return true; + }; + m_pProxyUsername = (CSTR) malloc(strlen(proxyUsername) + 1); + if (m_pProxyUsername == NULL) + { + return false; + } + memcpy(m_pProxyUsername, proxyUsername, strlen(proxyUsername) + 1); + return true; +} + +CSTR boschRCP::getProxyUsername(void) +{ + return m_pProxyUsername; +} + +bool boschRCP::setProxyPassword(CSTR proxyPassword) +{ + if (m_pProxyPassword != NULL) + { + free(m_pProxyPassword); + } + if (proxyPassword == NULL || strlen(proxyPassword) == 0) + { + m_pProxyPassword = NULL; + return true; + }; + m_pProxyPassword = (CSTR) malloc(strlen(proxyPassword) + 1); + if (m_pProxyPassword == NULL) + { + return false; + } + memcpy(m_pProxyPassword, proxyPassword, strlen(proxyPassword) + 1); + return true; +} + +CSTR boschRCP::getProxyPassword() +{ + return m_pProxyPassword; +} + +bool boschRCP::setUsername(CSTR username) +{ + if (m_pUsername != NULL) + { + free(m_pUsername); + } + if (username == NULL || strlen(username) == 0) + { + m_pUsername = NULL; + return true; + }; + m_pUsername = (CSTR) malloc(strlen(username) + 1); + if (m_pUsername == NULL) + { + return false; + } + memcpy(m_pUsername, username, strlen(username) + 1); + return true; +} + +CSTR boschRCP::getUsername(void) +{ + return m_pUsername; +} + +bool boschRCP::setPassword(CSTR password) +{ + if (m_pPassword != NULL) + { + free(m_pPassword); + } + if (password == NULL || strlen(password) == 0) + { + m_pPassword = NULL; + return true; + }; + m_pPassword = (CSTR) malloc(strlen(password) + 1); + if (m_pPassword == NULL) + { + return false; + } + memcpy(m_pPassword, password, strlen(password) + 1); + return true; +} + +CSTR boschRCP::getPassword(void) +{ + return m_pPassword; +} + +CSTR boschRCP::getDeviceUri(void) +{ + return m_pDeviceURI; +} + +bool boschRCP::setDeviceUri(CSTR deviceUri) +{ + if (deviceUri == NULL || strlen(deviceUri) == 0) + { + m_pDeviceURI = NULL; + 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)); + 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; +} + +CSTR boschRCP::getIPAddress(void) +{ + return m_pIpAddress; +} + +bool boschRCP::setIPAddress(CSTR ipAddress) +{ + if (ipAddress == NULL || strlen(ipAddress) == 0) + { + m_pIpAddress = NULL; + 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)); + 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; +} + +videoSources * boschRCP::getSources(void) +{ + return &m_vVideoSources; +} + +videoSourceProfiles * boschRCP::getProfiles(void) +{ + return &m_vVideoProfiles; +} + +videoSourceProfiles * boschRCP::getActiveProfiles(void) +{ + return &m_vActiveSources; +} + +CSTR boschRCP::getMediaUri(void) +{ + return m_pMediaURI; +} + +CSTR boschRCP::getPTZUri(void) +{ + return m_pPTZURI; +} + +CSTR boschRCP::getBaseUrl(void) +{ + return m_pBaseURI; +} + +void boschRCP::getSupportedVersion(void) {} + +nodeCapability * boschRCP::getCapabilities(void) +{ + return &m_sCapabilities; +} + +bool boschRCP::setBreakOnError(bool intransingent) +{ + m_bIntransingent = intransingent; + return true; +} + +CSTR boschRCP::getLastResponse(void) +{ + return m_pLastResponse; +} + +bool boschRCP::setDiscoveryTimeout(int discoverytimeout) +{ + m_nDiscoveryTimeout = discoverytimeout; + return true; +} + +bool boschRCP::setDiscoveryBindIp(CSTR discoverybindip) +{ + if (m_pDiscoveryBindIP != NULL) + { + free(m_pDiscoveryBindIP); + } + if (discoverybindip == NULL || strlen(discoverybindip) == 0) + { + m_pDiscoveryBindIP = NULL; + return true; + }; + m_pDiscoveryBindIP = (CSTR) malloc(strlen(discoverybindip) + 1); + if (m_pDiscoveryBindIP == NULL) + { + return false; + } + memcpy(m_pDiscoveryBindIP, discoverybindip, strlen(discoverybindip) + 1); + return true; +} + +bool boschRCP::setDiscoveryMcastIp(CSTR discoverymcastip) +{ + if (m_pDiscoveryMCastIP != NULL) + { + free(m_pDiscoveryMCastIP); + } + if (discoverymcastip == NULL || strlen(discoverymcastip) == 0) + { + m_pDiscoveryMCastIP = NULL; + return true; + }; + m_pDiscoveryMCastIP = (CSTR) malloc(strlen(discoverymcastip) + 1); + if (m_pDiscoveryMCastIP == NULL) + { + return false; + } + memcpy(m_pDiscoveryMCastIP, discoverymcastip, strlen(discoverymcastip) + 1); + return true; +} + +bool boschRCP::setDiscoveryMcastPort(int discoverymcastport) +{ + m_nDiscoveryMCastPort = discoverymcastport; + return true; +} + +bool boschRCP::setDiscoveryHideDuplicates(bool discoveryhideduplicates) +{ + m_bDiscoveryHideDuplicates = discoveryhideduplicates; + return true; +} + +CSTR boschRCP::getSnapshotUri(void) +{ + return m_pSnapshotURI; +} + +/* + WS-Discovery + + https://www.geeksforgeeks.org/udp-server-client-implementation-c/ + +*/ +discoveryResults boschRCP::discover(void) +{ + discoveryResults RetVal; + time_t tTimeout = time(NULL) + m_nDiscoveryTimeout; + 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 + { + // SOL_UDP = 17 + tSocket = socket(AF_INET, SOCK_DGRAM, 0); + if (tSocket < 0) + { + LOG_ERROR("ERROR creating socket"); + return RetVal; + }; + LOG("Socket Created!"); + 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)!"); + return RetVal; + }; + LOG("Host Found!"); + //***************************************** + //* there we building our network address * + //***************************************** + 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); + + RetCode = bind(tSocket, (const sockaddr *) &tSockAddr, sizeof(struct sockaddr_in)); + if (RetCode != 0) + { + LOG_ERROR("Error Binding to Port/Address"); + return RetVal; + }; + LOG("Binding Done!"); + +#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); + 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); + if (tVal > 0) + { + Response[tVal] = '\0'; + // if( FALSE !== socket_recvfrom( $sock, $response, 9999, 0, $from, $this->discoverymcastport )){ + // if( Response != NULL && $response != $post_string){ + LOG(Response); + XMLNode node = XMLNode::parseString(Response, "root"); + //$response = $this->_xml2array($response); + // if(!isFault( node )){ + //$response['Envelope']['Body']['ProbeMatches']['ProbeMatch']['IPAddr'] = $from; + if (m_bDiscoveryHideDuplicates) + { + // $result[$from] = $response['Envelope']['Body']['ProbeMatches']['ProbeMatch']; + } + else + { + // $result[] = $response['Envelope']['Body']['ProbeMatches']['ProbeMatch']; + }; + // }; + //}; + //}; + }; + }; +#ifdef __linux__ + close(tSocket); +#else + closesocket(tSocket); +#endif + } + catch ( const std::exception& e) + { + LOG_ERROR("Communication at Discovery Exception Catched!"); + }; + return RetVal; +} + +/* + Public functions (basic initialization method and other collaterals) +*/ +bool boschRCP::create(void) +{ +#ifdef DEBUG_EXTRA + LOG("Get Instance m_pHttpAccessManager"); +#endif + m_pHttpAccessManager = curlRequestsManager::getInstance(); + if (m_pHttpAccessManager == NULL) + { + return false; + } +#ifdef DEBUG_EXTRA + LOG("CURL MANAGER OK"); +#endif + try + { + struct tm * tTS; + tTS = core_GetSystemDateAndTime(); + // This is UTS DTS + + if (tTS != NULL) + { +#ifdef DEBUG + char tB[128]; + sprintf(tB, "TS from dev: %04d-%02d-%02d %02d:%02d:%02d", tTS->tm_year, tTS->tm_mon, tTS->tm_mday, tTS->tm_hour, tTS->tm_min, tTS->tm_sec); + LOG(tB); +#endif + // WTF ??!! + tTS->tm_year -= 1900; + tTS->tm_mon -= 1; + + time_t tTimeStamp = timegm(tTS); // mktime( tTS ); + + m_nDeltaTime = time(NULL) - tTimeStamp; +#ifdef DEBUG + sprintf(tB, "TS:[%ld] D:[%ld]", tTimeStamp, m_nDeltaTime); + LOG(tB); +#endif + free(tTS); + } + else + { + return false; + } + } + catch (const std::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); + // m_pBaseURI = $matches[0]; + + if (media_GetVideoSources()) + { + if (media_GetProfiles()) + { + //_getActiveSources( m_vVideoSources, m_vVideoProfiles); + return true; + }; + }; + LOG_ERROR("Error Profiles!"); + return false; +} + +/* + Public wrappers for a subset of ONVIF primitives +*/ +struct tm * boschRCP::core_GetSystemDateAndTime(void) +{ + struct tm * RetVal = NULL; + char tURL[CTEXT]; + 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; + }; + }; +#ifdef DEBUG_EXTRA + LOG("Before REQ"); +#endif + if (_send_request(tURL, PONVIF_PACK_GET_SYS_DTS, true)) + { + XMLResults tParseResults; + XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); +#ifdef DEBUG_EXTRA + LOG("core_GetSystemDateAndTime"); +#endif + if (tParseResults.error) + { + char tBuffer[CTEXT]; + sprintf(tBuffer, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); + LOG_ERROR(tBuffer); + } + else + { + RetVal = (struct tm *) malloc(sizeof(struct tm)); + if (RetVal != NULL) + { + memset(RetVal, 0, sizeof(struct tm)); + XMLNode zNode = response.getChildNode("Body", 0); + if (! zNode.isEmpty()) + { + XMLNode fNode = zNode.getChildNode("GetSystemDateAndTimeResponse", 0); + if (! fNode.isEmpty()) + { + XMLNode hNode = fNode.getChildNode("SystemDateAndTime", 0); + if (! hNode.isEmpty()) + { + XMLNode tNode = hNode.getChildNode("UTCDateTime", 0); + if (! tNode.isEmpty()) + { + RetVal->tm_isdst = 0; + XMLNode ttNode = tNode.getChildNode("Time", 0); + XMLNode dtNode = tNode.getChildNode("Date", 0); + { + XMLNode t = ttNode.getChildNode("Hour", 0); + RetVal->tm_hour = atoi(t.getText(0)); + } + { + XMLNode t = ttNode.getChildNode("Minute", 0); + RetVal->tm_min = atoi(t.getText(0)); + } + { + XMLNode t = ttNode.getChildNode("Second", 0); + RetVal->tm_sec = atoi(t.getText(0)); + } + { + XMLNode t = dtNode.getChildNode("Year", 0); + RetVal->tm_year = atoi(t.getText(0)); + } + { + XMLNode t = dtNode.getChildNode("Month", 0); + RetVal->tm_mon = atoi(t.getText(0)); + } + { + XMLNode t = dtNode.getChildNode("Day", 0); + RetVal->tm_mday = atoi(t.getText(0)); + } + } + else + { + LOG_ERROR("UTCDateTime is Not Found!"); + }; + } + else + { + LOG_ERROR("SystemDateAndTime is Not Found!"); + }; + } + else + { + LOG_ERROR("GetSystemDateAndTimeResponse is Not Found!"); + }; + } + else + { + LOG_ERROR("Body is Not Found!"); + LOG(m_pLastResponse); + }; + }; + return RetVal; + }; + } + else + { + LOG_ERROR("GetSystemDateAndTime: Communication error"); + } + return NULL; +} + +// Based on https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl + +bool boschRCP::core_GetCapabilities(void) +{ + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + char tURL[CTEXT]; + 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 ); + // build_package( tBuffer, PONVIF_ENVELOPE_SIM, tSTR ); + if (_send_request(tURL, tBuffer)) + { + XMLResults tParseResults; + XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); +#ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES + LOG("RCPT:"); + printf(m_pLastResponse); +#endif + if (tParseResults.error != eXMLErrorNone) + { + char tBuf[CTEXT]; + sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); + LOG_ERROR(tBuf); + } + else + { + XMLNode zNode = response.getChildNode("Body", 0); + if (zNode.isEmpty()) + { + return false; + } + XMLNode tNode = zNode.getChildNode("GetCapabilitiesResponse", 0); + if (! tNode.isEmpty()) + { + XMLNode tCaps = tNode.getChildNode("Capabilities", 0); + if (! tCaps.isEmpty()) + { + { + XMLNode t = tCaps.getChildNode("Analytics", 0); + if (! t.isEmpty()) + { + m_sCapabilities.Analytics = (onvifAnalyticsCapabilities *) malloc(sizeof(onvifAnalyticsCapabilities)); + if (m_sCapabilities.Analytics != NULL) + { + memset(m_sCapabilities.Analytics, 0, sizeof(onvifAnalyticsCapabilities)); + { + XMLNode c = t.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Analytics->XAddr, "%s", c.getText(0)); + } + { + XMLNode c = t.getChildNode("RuleSupport", 0); + m_sCapabilities.Analytics->RuleSupport = checkBool(c.getText(0)); + } + { + XMLNode c = t.getChildNode("AnalyticsModuleSupport", 0); + m_sCapabilities.Analytics->AnalyticsModuleSupport = checkBool(c.getText(0)); + } + }; + }; + } + { + XMLNode t = tCaps.getChildNode("Device", 0); + if (! t.isEmpty()) + { + m_sCapabilities.Device = (onvifDeviceCapabilities *) malloc(sizeof(onvifDeviceCapabilities)); + if (m_sCapabilities.Device != NULL) + { + memset(m_sCapabilities.Device, 0, sizeof(onvifDeviceCapabilities)); + { + XMLNode c = t.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Device->XAddr, "%s", c.getText(0)); + } + { + XMLNode c = t.getChildNode("Network", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Device->Network = (onvifNetworkCapabilities *) malloc(sizeof(onvifNetworkCapabilities)); + if (m_sCapabilities.Device->Network != NULL) + { + memset(m_sCapabilities.Device->Network, 0, sizeof(onvifNetworkCapabilities)); + { + XMLNode n = c.getChildNode("IPFilter", 0); + m_sCapabilities.Device->Network->IPFilter = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("ZeroConfiguration", 0); + m_sCapabilities.Device->Network->ZeroConfiguration = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("IPVersion6", 0); + m_sCapabilities.Device->Network->IPVersion6 = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("DynDNS", 0); + m_sCapabilities.Device->Network->DynDNS = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("Extension", 0); + if (! n.isEmpty()) + { + m_sCapabilities.Device->Network->Extension = (onvifNetworkCapabilitiesExtension *) malloc(sizeof(onvifNetworkCapabilitiesExtension)); + if (m_sCapabilities.Device->Network->Extension != NULL) + { + memset(m_sCapabilities.Device->Network->Extension, 0, sizeof(onvifNetworkCapabilitiesExtension)); + { + XMLNode x = n.getChildNode("Dot11Configuration", 0); + m_sCapabilities.Device->Network->Extension->Dot11Configuration = checkBool(x.getText(0)); + } + }; + }; + } + }; + }; + } + { + XMLNode c = t.getChildNode("System", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Device->System = (onvifSystemCapabilities *) malloc(sizeof(onvifSystemCapabilities)); + if (m_sCapabilities.Device->System != NULL) + { + memset(m_sCapabilities.Device->System, 0, sizeof(onvifSystemCapabilities)); + { + XMLNode n = c.getChildNode("DiscoveryResolve", 0); + m_sCapabilities.Device->System->DiscoveryResolve = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("DiscoveryBye", 0); + m_sCapabilities.Device->System->DiscoveryBye = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RemoteDiscovery", 0); + m_sCapabilities.Device->System->RemoteDiscovery = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("SystemBackup", 0); + m_sCapabilities.Device->System->SystemBackup = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("SystemLogging", 0); + m_sCapabilities.Device->System->SystemLogging = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("FirmwareUpgrade", 0); + m_sCapabilities.Device->System->FirmwareUpgrade = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("SupportedVersions", 0); + if (! n.isEmpty()) + { + m_sCapabilities.Device->System->SupportedVersions = (onvifSupportedVersions *) malloc(sizeof(onvifSupportedVersions)); + if (m_sCapabilities.Device->System->SupportedVersions != NULL) + { + memset(m_sCapabilities.Device->System->SupportedVersions, 0, sizeof(onvifSupportedVersions)); + { + XMLNode x = n.getChildNode("Major", 0); + m_sCapabilities.Device->System->SupportedVersions->Major = atoi(x.getText(0)); + } + { + XMLNode x = n.getChildNode("Minor", 0); + m_sCapabilities.Device->System->SupportedVersions->Minor = atoi(x.getText(0)); + } + }; + }; + } + { + XMLNode n = c.getChildNode("Extension", 0); + if (! n.isEmpty()) + { + m_sCapabilities.Device->System->Extension = (onvifSystemCapabilitiesExtension *) malloc(sizeof(onvifSystemCapabilitiesExtension)); + if (m_sCapabilities.Device->System->Extension != NULL) + { + memset(m_sCapabilities.Device->System->Extension, 0, sizeof(onvifSystemCapabilitiesExtension)); + { + XMLNode x = n.getChildNode("HttpFirmwareUpgrade", 0); + m_sCapabilities.Device->System->Extension->HttpFirmwareUpgrade = checkBool(x.getText(0)); + } + { + XMLNode x = n.getChildNode("HttpSystemBackup", 0); + m_sCapabilities.Device->System->Extension->HttpSystemBackup = checkBool(x.getText(0)); + } + { + XMLNode x = n.getChildNode("HttpSystemLogging", 0); + m_sCapabilities.Device->System->Extension->HttpSystemLogging = checkBool(x.getText(0)); + } + { + XMLNode x = n.getChildNode("HttpSupportInformation", 0); + m_sCapabilities.Device->System->Extension->HttpSupportInformation = checkBool(x.getText(0)); + } + }; + }; + } + }; + }; + } + { + XMLNode c = t.getChildNode("IO", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Device->IO = (onvifIOCapabilities *) malloc(sizeof(onvifIOCapabilities)); + if (m_sCapabilities.Device->IO != NULL) + { + memset(m_sCapabilities.Device->IO, 0, sizeof(onvifIOCapabilities)); + { + XMLNode n = c.getChildNode("InputConnectors", 0); + m_sCapabilities.Device->IO->InputConnectors = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RelayOutputs", 0); + m_sCapabilities.Device->IO->RelayOutputs = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("Extension", 0); + if (! n.isEmpty()) + { + m_sCapabilities.Device->IO->Extension = (onvifIOCapabilitiesExtension *) malloc(sizeof(onvifIOCapabilitiesExtension)); + if (m_sCapabilities.Device->IO->Extension != NULL) + { + memset(m_sCapabilities.Device->IO->Extension, 0, sizeof(onvifIOCapabilitiesExtension)); + { + XMLNode x = n.getChildNode("Auxiliary", 0); + m_sCapabilities.Device->IO->Extension->Auxiliary = checkBool(x.getText(0)); + } + }; + }; + } + }; + }; + } + { + XMLNode c = t.getChildNode("Security", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Device->Security = (onvifSecurityCapabilities *) malloc(sizeof(onvifSecurityCapabilities)); + if (m_sCapabilities.Device->Security != NULL) + { + memset(m_sCapabilities.Device->Security, 0, sizeof(onvifSecurityCapabilities)); + { + XMLNode n = c.getChildNode("TLS1.1", 0); + m_sCapabilities.Device->Security->TLS1_1 = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("TLS1.2", 0); + m_sCapabilities.Device->Security->TLS1_2 = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("OnboardKeyGeneration", 0); + m_sCapabilities.Device->Security->OnboardKeyGeneration = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("AccessPolicyConfig", 0); + m_sCapabilities.Device->Security->AccessPolicyConfig = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("X.509Token", 0); + m_sCapabilities.Device->Security->X_509Token = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("SAMLToken", 0); + m_sCapabilities.Device->Security->SAMLToken = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("KerberosToken", 0); + m_sCapabilities.Device->Security->KerberosToken = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RELToken", 0); + m_sCapabilities.Device->Security->RELToken = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("Extension", 0); + if (! n.isEmpty()) + { + m_sCapabilities.Device->Security->Extension = (onvifSecurityCapabilitiesExtension *) malloc(sizeof(onvifSecurityCapabilitiesExtension)); + if (m_sCapabilities.Device->Security->Extension != NULL) + { + memset(m_sCapabilities.Device->Security->Extension, 0, sizeof(onvifSecurityCapabilitiesExtension)); + { + XMLNode x = n.getChildNode("TLS1.0", 0); + m_sCapabilities.Device->Security->Extension->TLS1_0 = checkBool(x.getText(0)); + } + }; + }; + } + }; + }; + } + }; + }; + } + { + XMLNode t = tCaps.getChildNode("Events", 0); + if (! t.isEmpty()) + { + m_sCapabilities.Events = (onvifEventCapabilities *) malloc(sizeof(onvifEventCapabilities)); + if (m_sCapabilities.Events != NULL) + { + memset(m_sCapabilities.Events, 0, sizeof(onvifEventCapabilities)); + { + XMLNode c = t.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Events->XAddr, "%s", c.getText(0)); + } + { + XMLNode c = t.getChildNode("WSSubscriptionPolicySupport", 0); + m_sCapabilities.Events->WSSubscriptionPolicySupport = checkBool(c.getText(0)); + } + { + XMLNode c = t.getChildNode("WSPullPointSupport", 0); + m_sCapabilities.Events->WSPullPointSupport = checkBool(c.getText(0)); + } + { + XMLNode c = t.getChildNode("WSPausableSubscriptionManagerInterfaceSupport", 0); + m_sCapabilities.Events->WSPausableSubscriptionManagerInterfaceSupport = checkBool(c.getText(0)); + } + }; + }; + } + { + XMLNode t = tCaps.getChildNode("Imaging", 0); + if (! t.isEmpty()) + { + m_sCapabilities.Imaging = (onvifImagingCapabilities *) malloc(sizeof(onvifImagingCapabilities)); + if (m_sCapabilities.Imaging != NULL) + { + memset(m_sCapabilities.Imaging, 0, sizeof(onvifImagingCapabilities)); + { + XMLNode c = t.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Imaging->XAddr, "%s", c.getText(0)); + } + }; + }; + } + { + XMLNode t = tCaps.getChildNode("Media", 0); + if (! t.isEmpty()) + { + m_sCapabilities.Media = (onvifMediaCapabilities *) malloc(sizeof(onvifMediaCapabilities)); + if (m_sCapabilities.Media != NULL) + { + memset(m_sCapabilities.Media, 0, sizeof(onvifMediaCapabilities)); + { + XMLNode c = t.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Media->XAddr, "%s", c.getText(0)); + } + { + XMLNode c = t.getChildNode("StreamingCapabilities", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Media->StreamingCapabilities = (onvifRealTimeStreamingCapabilities *) malloc(sizeof(onvifRealTimeStreamingCapabilities)); + if (m_sCapabilities.Media->StreamingCapabilities != NULL) + { + memset(m_sCapabilities.Media->StreamingCapabilities, 0, sizeof(onvifRealTimeStreamingCapabilities)); + { + XMLNode n = c.getChildNode("RTPMulticast", 0); + m_sCapabilities.Media->StreamingCapabilities->RTPMulticast = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RTP_TCP", 0); + m_sCapabilities.Media->StreamingCapabilities->RTP_TCP = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RTP_RTSP_TCP", 0); + m_sCapabilities.Media->StreamingCapabilities->RTP_RTSP_TCP = checkBool(n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("Extension", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Media->Extension = (onvifMediaCapabilitiesExtension *) malloc(sizeof(onvifMediaCapabilitiesExtension)); + if (m_sCapabilities.Media->Extension != NULL) + { + memset(m_sCapabilities.Media->Extension, 0, sizeof(onvifMediaCapabilitiesExtension)); + { + XMLNode n = c.getChildNode("ProfileCapabilities", 0); + if (! n.isEmpty()) + { + m_sCapabilities.Media->Extension->ProfileCapabilities = (onvifProfileCapabilities *) malloc(sizeof(onvifProfileCapabilities)); + if (m_sCapabilities.Media->Extension->ProfileCapabilities != NULL) + { + memset(m_sCapabilities.Media->Extension->ProfileCapabilities, 0, sizeof(onvifProfileCapabilities)); + { + XMLNode x = n.getChildNode("MaximumNumberOfProfiles", 0); + m_sCapabilities.Media->Extension->ProfileCapabilities->MaximumNumberOfProfiles = atoi(x.getText(0)); + } + }; + }; + } + }; + }; + } + }; + }; + } + { + XMLNode t = tCaps.getChildNode("PTZ", 0); + if (! t.isEmpty()) + { + m_sCapabilities.PTZ = (onvifPTZCapabilities *) malloc(sizeof(onvifPTZCapabilities)); + if (m_sCapabilities.PTZ != NULL) + { + memset(m_sCapabilities.PTZ, 0, sizeof(onvifPTZCapabilities)); + { + XMLNode c = t.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.PTZ->XAddr, "%s", c.getText(0)); + } + }; + }; + } + { + XMLNode t = tCaps.getChildNode("Extension", 0); + if (! t.isEmpty()) + { + m_sCapabilities.Extension = (onvifCapabilitiesExtension *) malloc(sizeof(onvifCapabilitiesExtension)); + if (m_sCapabilities.Extension != NULL) + { + memset(m_sCapabilities.Extension, 0, sizeof(onvifCapabilitiesExtension)); + { + XMLNode c = t.getChildNode("DeviceIO", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->DeviceIO = (onvifDeviceIOCapabilities *) malloc(sizeof(onvifDeviceIOCapabilities)); + if (m_sCapabilities.Extension->DeviceIO != NULL) + { + memset(m_sCapabilities.Extension->DeviceIO, 0, sizeof(onvifDeviceIOCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->DeviceIO->XAddr, "%s", n.getText(0)); + } + { + XMLNode n = c.getChildNode("VideoSources", 0); + m_sCapabilities.Extension->DeviceIO->VideoSources = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("VideoOutputs", 0); + m_sCapabilities.Extension->DeviceIO->VideoOutputs = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("AudioSources", 0); + m_sCapabilities.Extension->DeviceIO->AudioSources = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("AudioOutputs", 0); + m_sCapabilities.Extension->DeviceIO->AudioOutputs = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RelayOutputs", 0); + m_sCapabilities.Extension->DeviceIO->RelayOutputs = atoi(n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("Display", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->Display = (onvifDisplayCapabilities *) malloc(sizeof(onvifDisplayCapabilities)); + if (m_sCapabilities.Extension->Display != NULL) + { + memset(m_sCapabilities.Extension->Display, 0, sizeof(onvifDisplayCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->Display->XAddr, "%s", n.getText(0)); + } + { + XMLNode n = c.getChildNode("FixedLayout", 0); + m_sCapabilities.Extension->Display->FixedLayout = checkBool(n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("Recording", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->Recording = (onvifRecordingCapabilities *) malloc(sizeof(onvifRecordingCapabilities)); + if (m_sCapabilities.Extension->Recording != NULL) + { + memset(m_sCapabilities.Extension->Recording, 0, sizeof(onvifRecordingCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->Recording->XAddr, "%s", n.getText(0)); + } + { + XMLNode n = c.getChildNode("ReceiverSource", 0); + m_sCapabilities.Extension->Recording->ReceiverSource = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("MediaProfileSource", 0); + m_sCapabilities.Extension->Recording->MediaProfileSource = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("DynamicRecordings", 0); + m_sCapabilities.Extension->Recording->DynamicRecordings = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("DynamicTracks", 0); + m_sCapabilities.Extension->Recording->DynamicTracks = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("MaxStringLength", 0); + m_sCapabilities.Extension->Recording->MaxStringLength = atoi(n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("Search", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->Search = (onvifSearchCapabilities *) malloc(sizeof(onvifSearchCapabilities)); + if (m_sCapabilities.Extension->Search != NULL) + { + memset(m_sCapabilities.Extension->Search, 0, sizeof(onvifSearchCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->Search->XAddr, "%s", n.getText(0)); + } + { + XMLNode n = c.getChildNode("MetadataSearch", 0); + m_sCapabilities.Extension->Search->MetadataSearch = checkBool(n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("Replay", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->Replay = (onvifReplayCapabilities *) malloc(sizeof(onvifReplayCapabilities)); + if (m_sCapabilities.Extension->Replay != NULL) + { + memset(m_sCapabilities.Extension->Replay, 0, sizeof(onvifReplayCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->Replay->XAddr, "%s", n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("Receiver", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->Receiver = (onvifReceiverCapabilities *) malloc(sizeof(onvifReceiverCapabilities)); + if (m_sCapabilities.Extension->Receiver != NULL) + { + memset(m_sCapabilities.Extension->Receiver, 0, sizeof(onvifReceiverCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->Receiver->XAddr, "%s", n.getText(0)); + } + { + XMLNode n = c.getChildNode("RTP_Multicast", 0); + m_sCapabilities.Extension->Receiver->RTP_Multicast = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RTP_TCP", 0); + m_sCapabilities.Extension->Receiver->RTP_TCP = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("RTP_RTSP_TCP", 0); + m_sCapabilities.Extension->Receiver->RTP_RTSP_TCP = checkBool(n.getText(0)); + } + { + XMLNode n = c.getChildNode("SupportedReceivers", 0); + m_sCapabilities.Extension->Receiver->SupportedReceivers = atoi(n.getText(0)); + } + { + XMLNode n = c.getChildNode("MaximumRTSPURILength", 0); + m_sCapabilities.Extension->Receiver->MaximumRTSPURILength = atoi(n.getText(0)); + } + }; + }; + } + { + XMLNode c = t.getChildNode("AnalyticsDevice", 0); + if (! c.isEmpty()) + { + m_sCapabilities.Extension->AnalyticsDevice = (onvifAnalyticsDeviceCapabilities *) malloc(sizeof(onvifAnalyticsDeviceCapabilities)); + if (m_sCapabilities.Extension->AnalyticsDevice != NULL) + { + memset(m_sCapabilities.Extension->AnalyticsDevice, 0, sizeof(onvifAnalyticsDeviceCapabilities)); + { + XMLNode n = c.getChildNode("XAddr", 0); + sprintf(m_sCapabilities.Extension->AnalyticsDevice->XAddr, "%s", n.getText(0)); + } + { + XMLNode n = c.getChildNode("RuleSupport", 0); + m_sCapabilities.Extension->AnalyticsDevice->RuleSupport = checkBool(n.getText(0)); + } + }; + }; + } + }; + }; + } + return true; + } + else + { + LOG("Capabilities is Empty!"); + }; + } + else + { + LOG("GetCapabilitiesResponse is Empty!"); + }; + }; + } + return false; +} + +// based on https://www.onvif.org/ver20/imaging/wsdl/imaging.wsdl + +bool boschRCP::media_GetVideoSources(void) +{ + if (m_pMediaURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_VIDEO_SOURCES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + if (_send_request(m_pMediaURI, tBuffer)) + { + XMLResults tParseResults; + XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); +#ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES + LOG("RCPT:"); + printf(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 + { + XMLNode zNode = response.getChildNode("Body", 0); + if (zNode.isEmpty()) + { + return false; + } + XMLNode tNode = zNode.getChildNode("GetVideoSourcesResponse", 0); + if (! tNode.isEmpty()) + { + for (int index = 0; index < tNode.nChildNode(); index++) + { + XMLNode cNode = tNode.getChildNode("VideoSources", index); + if (! cNode.isEmpty()) + { + videoSource * tPtr; + tPtr = (videoSource *) malloc(sizeof(videoSource)); + if (tPtr != NULL) + { + sprintf(tPtr->token, "%s", cNode.getAttribute("token", 0)); + { + XMLNode nNode = cNode.getChildNode("Framerate", 0); + tPtr->Framerate = (float) atof(nNode.getText(0)); + } + { + XMLNode nNode = cNode.getChildNode("Resolution", 0); + if (! nNode.isEmpty()) + { + { + XMLNode xNode = nNode.getChildNode("Width", 0); + tPtr->Resolution.Width = atoi(xNode.getText(0)); + } + { + XMLNode xNode = nNode.getChildNode("Height", 0); + tPtr->Resolution.Height = atoi(xNode.getText(0)); + } + }; + } + { + XMLNode nNode = cNode.getChildNode("Imaging", 0); + if (! nNode.isEmpty()) + { + tPtr->Imaging = (onvifImagingSettings *) malloc(sizeof(onvifImagingSettings)); + if (tPtr->Imaging != NULL) + { + memset(tPtr->Imaging, 0, sizeof(onvifImagingSettings)); + { + XMLNode xNode = nNode.getChildNode("BacklightCompensation", 0); + if (! xNode.isEmpty()) + { + tPtr->Imaging->BacklightCompensation = (onvifBacklightCompensation *) malloc(sizeof(onvifBacklightCompensation)); + if (tPtr->Imaging->BacklightCompensation != NULL) + { + memset(tPtr->Imaging->BacklightCompensation, 0, sizeof(onvifBacklightCompensation)); + { + XMLNode rNode = xNode.getChildNode("Mode", 0); + tPtr->Imaging->BacklightCompensation->Mode = checkOnOff(rNode.getText(0)); + } + { + XMLNode rNode = xNode.getChildNode("Level", 0); + tPtr->Imaging->BacklightCompensation->Level = (float) atof(rNode.getText(0)); + } + }; + }; + } + { + XMLNode xNode = nNode.getChildNode("Brightness", 0); + tPtr->Imaging->Brightness = (float) atoi(xNode.getText(0)); + } + { + XMLNode xNode = nNode.getChildNode("ColorSaturation", 0); + tPtr->Imaging->ColorSaturation = (float) atoi(xNode.getText(0)); + } + { + XMLNode xNode = nNode.getChildNode("Contrast", 0); + tPtr->Imaging->Contrast = (float) atoi(xNode.getText(0)); + } + { + XMLNode xNode = nNode.getChildNode("Sharpness", 0); + tPtr->Imaging->Sharpness = (float) atoi(xNode.getText(0)); + } + { + XMLNode xNode = nNode.getChildNode("IrCutFilter", 0); + tPtr->Imaging->IrCutFilter = checkOnOffAuto(xNode.getText(0)); + } + }; + }; + } + m_vVideoSources.push_back(tPtr); + }; + }; + }; + return true; + } + else + { + LOG_ERROR("GetVideoSourcesResponse EMPTY!"); + }; + }; + } + else + { + LOG_ERROR("_send_request Failure!"); + }; + return false; +} + +bool boschRCP::media_GetProfiles(void) +{ + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_PROFILES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + if (_send_request(m_pMediaURI, tBuffer)) + { + XMLResults tParseResults; + XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); +#ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES + LOG("RCPT:"); + printf(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 + { + XMLNode zNode = response.getChildNode("Body", 0); + if (zNode.isEmpty()) + { + return false; + } + XMLNode tNode = zNode.getChildNode("GetProfilesResponse", 0); + if (! tNode.isEmpty()) + { + for (int index = 0; index < tNode.nChildNode(); index++) + { + XMLNode cNode = tNode.getChildNode("Profiles", index); + if (! cNode.isEmpty()) + { + videoSourceProfile * tPtr; + tPtr = (videoSourceProfile *) malloc(sizeof(videoSourceProfile)); + if (tPtr != NULL) + { + memset(tPtr, 0, sizeof(videoSourceProfile)); + sprintf(tPtr->profiletoken, "%s", cNode.getAttribute("token", 0)); + { + XMLNode nNode = cNode.getChildNode("Name", 0); + sprintf(tPtr->profilename, "%s", nNode.getText(0)); + } + { + XMLNode nNode = cNode.getChildNode("VideoSourceConfiguration", 0); + if (! nNode.isEmpty()) + { + XMLNode zNode = nNode.getChildNode("SourceToken", 0); + sprintf(tPtr->sourcetoken, "%s", zNode.getText(0)); + }; + } + { + XMLNode nNode = cNode.getChildNode("VideoEncoderConfiguration", 0); + if (! nNode.isEmpty()) + { + { + XMLNode zNode = nNode.getChildNode("Encoding", 0); + sprintf(tPtr->encoding, "%s", zNode.getText(0)); + } + { + XMLNode zNode = nNode.getChildNode("Resolution", 0); + { + XMLNode jNode = zNode.getChildNode("Width", 0); + tPtr->width = atoi(jNode.getText(0)); + } + { + XMLNode jNode = zNode.getChildNode("Height", 0); + tPtr->height = atoi(jNode.getText(0)); + } + } + { + XMLNode zNode = nNode.getChildNode("RateControl", 0); + { + XMLNode jNode = zNode.getChildNode("FrameRateLimit", 0); + tPtr->fps = atoi(jNode.getText(0)); + } + { + XMLNode jNode = zNode.getChildNode("BitrateLimit", 0); + tPtr->bitrate = atoi(jNode.getText(0)); + } + } + }; + } + m_vVideoProfiles.push_back(tPtr); + }; + }; + }; + return true; + }; + }; + }; + return false; +} + +bool boschRCP::media_GetServices(void) +{ + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_SERVICES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + if (_send_request(m_pMediaURI, 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 false; +} + +bool boschRCP::core_GetDeviceInformation() +{ + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_DEV_INFO, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + if (_send_request(m_pMediaURI, 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 $response['Envelope']['Body']['GetDeviceInformationResponse']; + }; + }; + return false; +} + +CSTR boschRCP::media_GetStreamUri(CSTR profileToken, CSTR stream, CSTR protocol) +{ + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_STREAM_URI, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, stream, protocol, profileToken); + if (_send_request(m_pMediaURI, 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 + { + // Parse + // return $response['Envelope']['Body']['GetStreamUriResponse']['MediaUri']['Uri']; + }; + }; + return NULL; +} + +CSTR boschRCP::media_GetSnapshotUri(CSTR profileToken) +{ + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_PICTURE_URI, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); + if (_send_request(m_pMediaURI, 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 + { + // Parse + // return $response['Envelope']['Body']['GetSnapshotUriResponse']['MediaUri']['Uri']; + }; + }; + return NULL; +} + +bool boschRCP::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(); + memset(tStatus, 0, sizeof(ptzStatus)); + sprintf(tBuffer, PONVIF_PACK_GET_PTZ_STATUS, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); + if (_send_request(m_pPTZURI, tBuffer, true)) + { + 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 + { + XMLNode aNode = response.getChildNode("Body", 0); + if (aNode.isEmpty()) + { + return NULL; + } + XMLNode bNode = aNode.getChildNode("GetStatusResponse", 0); + if (! bNode.isEmpty()) + { + XMLNode cNode = bNode.getChildNode("PTZStatus", 0); + if (! cNode.isEmpty()) + { + XMLNode dNode = cNode.getChildNode("Position", 0); + if (! dNode.isEmpty()) + { + XMLNode eNode = dNode.getChildNode("PanTilt", 0); + if (! eNode.isEmpty()) + { + // XMLAttribute ZZ = eNode.getAttribute(1); + // LOG( ZZ.lpszName ); + tStatus->pan = atof(eNode.getAttribute("x")); // ZZ.lpszValue ); + // ZZ = eNode.getAttribute(2); + // LOG( ZZ.lpszName ); + tStatus->tilt = atof(eNode.getAttribute("y")); // ZZ.lpszValue ); + }; + XMLNode fNode = dNode.getChildNode("Zoom", 0); + if (! fNode.isEmpty()) + { + // XMLAttribute ZZ = eNode.getAttribute(1); + // LOG( ZZ.lpszName ); + tStatus->zoom = atof(fNode.getAttribute("x")); // ZZ.lpszValue ); + }; + }; + if (tStatus->pan != .0f || tStatus->tilt != .0f || tStatus->zoom != .0f) + { + XMLNode gNode = cNode.getChildNode("MoveStatus", 0); + if (! gNode.isEmpty()) + { + tStatus->hasMoveStatus = true; + XMLNode hNode = gNode.getChildNode("PanTilt", 0); + if (! hNode.isEmpty()) + { + if (strstr(hNode.getText(0), "IDLE") != NULL) + { + tStatus->PanTiltIdle = true; + } + }; + XMLNode iNode = gNode.getChildNode("Zoom", 0); + if (! iNode.isEmpty()) + { + if (strstr(iNode.getText(0), "IDLE") != NULL) + { + tStatus->ZoomIdle = true; + } + }; + }; + } + return true; + }; + }; + }; + }; + return false; +} + +bool boschRCP::ptz_GetPresets(CSTR profileToken) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_PRESETS, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); + if (_send_request(m_pPTZURI, tBuffer)) + { + // XMLResults tParseResults; + // XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); + // LOG("RCPT:"); + // LOG( 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 { + //$getpresetsresponse=$response['Envelope']['Body']['GetPresetsResponse']['Preset']; + //$presets=array(); + // foreach ($getpresetsresponse as $preset) { + // $presets[]=array('Token'=>$preset['@attributes']['token'], + // 'Name'=>$preset['Name'], + // 'PTZPosition'=>$preset['PTZPosition']); + // } + // return $presets; + return true; + //}; + }; + return false; +} + +bool boschRCP::ptz_GetNode(CSTR ptzNodeToken) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_GET_PTZ_NODE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, ptzNodeToken); + 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 $response['Envelope']['Body']['GetNodeResponse']; + }; + }; + return false; +} + +bool boschRCP::ptz_GotoPreset(CSTR profileToken, CSTR presetToken, float speed_pantilt_x, float speed_pantilt_y, float speed_zoom_x) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + 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); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_RemovePreset(CSTR profileToken, CSTR presetToken) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_REMOVE_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetToken); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_SetPreset(CSTR profileToken, CSTR presetName) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_SET_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetName); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_RelativeMove(CSTR profileToken, float translation_pantilt_x, float translation_pantilt_y, float speed_pantilt_x, float speed_pantilt_y) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + 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); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_RelativeMoveZoom(CSTR profileToken, float zoom, float speedZoom) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_RELATIVE_ZOOM, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, zoom, speedZoom); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float position_pantilt_y, float zoom) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + 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); + return _send_request(m_pPTZURI, tBuffer, false); +} + +bool boschRCP::ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + 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); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_ContinuousMoveZoom(CSTR profileToken, float zoom) +{ + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + accessToken tTOKEN; + tTOKEN = _makeToken(); + sprintf(tBuffer, PONVIF_PACK_CONTINUOUS_ZOOM, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, zoom); + return _send_request(m_pPTZURI, tBuffer, true); +} + +bool boschRCP::ptz_Stop(CSTR profileToken, bool pantilt, bool zoom) +{ + if ( pantilt || zoom ) profileToken = profileToken; + if (m_pPTZURI == NULL) + { + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + 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, true); +} + +/* + Internal functions +*/ +accessToken boschRCP::_makeToken(void) +{ + time_t tTS = time(NULL) - m_nDeltaTime; + return _passwordDigest(m_pUsername, m_pPassword, tTS); +} + +void boschRCP::_getOnvifVersion(nodeCapability & caps) +{ + if (caps.Device != NULL) + { + if (caps.Device->System != NULL) + { + if (caps.Device->System->SupportedVersions != NULL) + { + m_sOnvifVersion.Major = caps.Device->System->SupportedVersions->Major; + m_sOnvifVersion.Minor = caps.Device->System->SupportedVersions->Minor; + }; + }; + }; + if (caps.PTZ != NULL) + { + m_pPTZURI = caps.PTZ->XAddr; + }; + if (caps.Media != NULL) + { + m_pMediaURI = caps.Media->XAddr; + }; + if (caps.Device != NULL) + { + m_pDeviceURI = caps.Device->XAddr; + }; +} + +/* + protected function _getActiveSources($videoSources,$profiles) { + $sources=array(); + + if (isset($videoSources['@attributes'])) { + // NVT is a camera + $sources[0]['sourcetoken']=$videoSources['@attributes']['token']; + $this->_getProfileData($sources,0,$profiles); + } + else { + // NVT is an encoder + for ($i=0;$i_getProfileData($sources,$i,$profiles); + } + } // for + } + + return $sources; + } + +void pOnvif::_getProfileData( sources,$i, XMLNode profiles ){ + //$inprofile=0; + videoSourceProfile *tPtr; + for( $y=0; $y < count($profiles); $y++ ){ + if ($profiles[$y]['VideoSourceConfiguration']['SourceToken']==$sources[$i]['sourcetoken']) { + $sources[$i][$inprofile]['profilename']=$profiles[$y]['Name']; + $sources[$i][$inprofile]['profiletoken']=$profiles[$y]['@attributes']['token']; + if ( isset($profiles[$y]['VideoEncoderConfiguration'])) { + $sources[$i][$inprofile]['encoding']=$profiles[$y]['VideoEncoderConfiguration']['Encoding']; + $sources[$i][$inprofile]['width']=$profiles[$y]['VideoEncoderConfiguration']['Resolution']['Width']; + $sources[$i][$inprofile]['height']=$profiles[$y]['VideoEncoderConfiguration']['Resolution']['Height']; + $sources[$i][$inprofile]['fps']=$profiles[$y]['VideoEncoderConfiguration']['RateControl']['FrameRateLimit']; + $sources[$i][$inprofile]['bitrate']=$profiles[$y]['VideoEncoderConfiguration']['RateControl']['BitrateLimit']; + } + if ( isset($profiles[$y]['PTZConfiguration'])) { + $sources[$i][$inprofile]['ptz']['name']=$profiles[$y]['PTZConfiguration']['Name']; + $sources[$i][$inprofile]['ptz']['nodetoken']=$profiles[$y]['PTZConfiguration']['NodeToken']; + } + $inprofile++; + } + } +}; +*/ +/* +protected function _xml2array($response) { + $sxe = new SimpleXMLElement($response); + $dom_sxe = dom_import_simplexml($sxe); + $dom = new DOMDocument('1.0'); + $dom_sxe = $dom->importNode($dom_sxe, true); + $dom_sxe = $dom->appendChild($dom_sxe); + $element = $dom->childNodes->item(0); + foreach ($sxe->getDocNamespaces() as $name => $uri) { + $element->removeAttributeNS($uri, $name); + } + $xmldata=$dom->saveXML(); + $xmldata=substr($xmldata,strpos($xmldata,"")); + $xmldata=substr($xmldata,0,strpos($xmldata,"")+strlen("")); + $xml=simplexml_load_string($xmldata); + $data=json_decode(json_encode((array)$xml),1); + $data=array($xml->getName()=>$data); + return $data; +} +*/ + +accessToken boschRCP::_passwordDigest(CSTR username, CSTR password, time_t timestamp, uint32_t nonce) +{ + accessToken RetVal; + char tTS[CTEXT]; + unsigned char * tPDIGEST; + if (timestamp == 0) + { + time_t t; + struct tm * tmp; + t = time(NULL); + tmp = gmtime(&t); + if (tmp == NULL) + { + LOG_ERROR("gmtime Error!"); + }; + if (strftime(tTS, 200, "%FT%TZ", tmp) == 0) + { + LOG_ERROR("strftime returned 0!"); + }; + } + else + { + struct tm * tmp; + tmp = gmtime(×tamp); + if (tmp == NULL) + { + LOG_ERROR("gmtime Error!"); + }; + if (strftime(tTS, 200, "%FT%TZ", tmp) == 0) + { + LOG_ERROR("strftime returned 0!"); + }; + }; + if (nonce == 0) + { + nonce = (uint32_t) rand(); + }; + unsigned char tBuff[CTEXT]; + int cp = 0; + int index = 0; + for (; index < 4; index++) + { + tBuff[cp++] = ((unsigned char *) (&nonce))[index]; + }; + index = 0; + while (tTS[index] != '\0') + { + tBuff[cp++] = (unsigned char) tTS[index]; + index++; + }; + index = 0; + while (password[index] != '\0') + { + tBuff[cp++] = (unsigned char) password[index]; + index++; + }; + size_t baseOutLen; + unsigned char tSHA[SHA_DIGEST_LENGTH]; + SHA1(tBuff, cp, tSHA); + // tPDIGEST = base64_encode(pack('H*', sha1(pack('H*', $nonce) . pack('a*',$timestamp).pack('a*',$password)))); + tPDIGEST = base64_encode(tSHA, SHA_DIGEST_LENGTH, &baseOutLen); + // free( tSHA ); + //$passdigest=base64_encode(sha1($nonce.$timestamp.$password,true)); // alternative + strncpy(RetVal.USERNAME, username, CTEXT); + strncpy(RetVal.TIMESTAMP, tTS, CTEXT); + strncpy(RetVal.PASSDIGEST, (const char *) tPDIGEST, CTEXT); + free(tPDIGEST); + tPDIGEST = base64_encode((unsigned char *) &nonce, 4, &baseOutLen); + strncpy(RetVal.NONCE, (const char *) tPDIGEST, baseOutLen); + RetVal.NONCE[baseOutLen] = '\0'; + free(tPDIGEST); + //$REQ['NONCE']=base64_encode($nonce); // alternative + return RetVal; +} + +void * boschRCP::parser(void * obj, void * ptr) +{ + boschRCP * ME = (boschRCP *) 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 boschRCP::_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, m_bAuthMode); + 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 + while (! RetVal && cnt--) + { + RetVal = parser_done; + SLEEP(10); + }; + }; + } + else + { + RetVal = m_pHttpAccessManager->accomplish(tRC); + }; + } + else + { + LOG_ERROR("Cannot Create curlRequest!"); + } + m_mResponseProtector.unlock(); + }; + return RetVal; +#else + char tBuffer[CTEXT]; + if (m_pCURL == NULL) + { + if (m_pLastResponse == NULL) + { + m_pLastResponse = (CSTR) malloc(DEFAULT_BUFFER_SIZE); + }; + m_pCURL = curl_easy_init(); + if (m_pProxyHost != NULL && m_nProxyPort != 0) + { + curl_easy_setopt(m_pCURL, CURLOPT_PROXY, m_pProxyHost); + curl_easy_setopt(m_pCURL, CURLOPT_PROXYPORT, m_nProxyPort); + if (m_pProxyUsername != NULL && m_pProxyPassword != NULL) + { + sprintf(tBuffer, "%s:%s", m_pProxyUsername, m_pProxyPassword); + curl_easy_setopt(m_pCURL, CURLOPT_PROXYUSERPWD, tBuffer); + }; + }; + 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_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_WRITEFUNCTION, pOnvif::_writer); + curl_easy_setopt(m_pCURL, CURLOPT_WRITEDATA, this); + }; + if (m_pCURL != NULL) + { + curl_easy_setopt(m_pCURL, CURLOPT_URL, url); + struct curl_slist * sList = NULL; + // Content-Type: application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver20/ptz/wsdl/ContinuousMove" + // Connection: Close + sList = curl_slist_append(sList, "Content-Type: text/xml; charset=utf-8"); + sprintf(tBuffer, "Content-Length: %d", strlen(post_string)); + sList = curl_slist_append(sList, tBuffer); + curl_easy_setopt(m_pCURL, CURLOPT_HTTPHEADER, sList); + 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); + switch (m_bAuthMode) + { + case 0: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); break; + case 1: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); break; + case 2: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST_IE); break; + case 3: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); break; + case 4: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_NEGOTIATE); break; + case 5: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); break; + case 6: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_NTLM_WB); break; + case 7: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANY); break; + case 8: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE); break; + case 9: + curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_ONLY); + break; + // case 10: curl_easy_setopt( m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_AWS_SIGV4 ); break; + }; + #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; + }; + m_pLastIndex = 0; + }; + return false; +#endif +} + +#ifndef CURL_MANAGER +int boschRCP::_writer(char * data, size_t size, size_t nmemb, boschRCP * Ptr) +{ + if (Ptr == NULL) + { + return 0; + } + // TLOG("*"); + memcpy(Ptr->m_pLastResponse + Ptr->m_pLastIndex, data, size * nmemb); + Ptr->m_pLastIndex += size * nmemb; + return size * nmemb; +} +#endif + +bool boschRCP::setAuthMode(uint8_t Mode) +{ + m_bAuthMode = Mode; +#ifdef DEBUG + switch (m_bAuthMode) + { + case 0 : LOG("Set Auth CURLAUTH_BASIC"); break; + case 1 : LOG("Set Auth CURLAUTH_DIGEST"); break; + case 2 : LOG("Set Auth CURLAUTH_DIGEST_IE"); break; + case 3 : LOG("Set Auth CURLAUTH_BEARER"); break; + case 4 : LOG("Set Auth CURLAUTH_NEGOTIATE"); break; + case 5 : LOG("Set Auth CURLAUTH_NTLM"); break; + case 6 : LOG("Set Auth CURLAUTH_NTLM_WB"); break; + case 7 : LOG("Set Auth CURLAUTH_ANY"); break; + case 8 : LOG("Set Auth CURLAUTH_ANYSAFE"); break; + case 9 : LOG("Set Auth CURLAUTH_ONLY"); break; + case 10: LOG("Set Auth CURLAUTH_AWS_SIGV4"); break; + }; +#endif + return true; +} + +#undef LOG +#undef TLOG +#undef LOG_ERROR diff --git a/lib/data/bosch_rcp/bosch_rcp.h b/lib/data/bosch_rcp/bosch_rcp.h new file mode 100644 index 00000000..033b7bec --- /dev/null +++ b/lib/data/bosch_rcp/bosch_rcp.h @@ -0,0 +1,606 @@ +#ifndef __BOSCH_RCP_CLASS_HEADER__ +#define __BOSCH_RCP_CLASS_HEADER__ + +#include +#include +#include + +#ifdef __linux__ + #include + #include + #include + #include + #include + #include +#endif + +#include "../../alg/generic/base64.h" +#include "../../components/base/basicLogCollection.h" +#include "../../components/base/basicTypes.h" +#include "../curl/curlRequestsManager.h" +#include "../protocol/xmlParser.h" + +#define CURL_MANAGER +// #define DEBUG_BRCP_PRINTOUT_MESSAGES +// #define DEBUG_BRCP_TRAFFIC + + +#define BRCP_PACK_GET_SYS_DTS \ + (CSTR)"" +#define BRCP_PACK_GET_CAPABILITIES \ + (CSTR)"%s%s%s%sAll" +#define BRCP_PACK_GET_VIDEO_SOURCES \ + (CSTR)"%s%s%s%s" +#define BRCP_PACK_GET_PROFILES \ + (CSTR)"%s%s%s%s" +#define BRCP_PACK_GET_SERVICES \ + (CSTR)"%s%s%s%sfalse" +#define BRCP_PACK_GET_DEV_INFO \ + (CSTR)"%s%s%s%s" +#define BRCP_PACK_GET_STREAM_URI \ + (CSTR)"%s%s%s%s%s%s%s" +#define BRCP_PACK_GET_PICTURE_URI \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_GET_PRESETS \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_GET_PTZ_NODE \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_GET_PTZ_STATUS \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_GOTO_PRESET \ + (CSTR)"%s%s%s%s%s%s" +#define BRCP_PACK_REMOVE_PRESET \ + (CSTR)"%s%s%s%s%s%s" +#define BRCP_PACK_SET_PRESET \ + (CSTR)"%s%s%s%s%s%s" +#define BRCP_PACK_RELATIVE_MOVE \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_RELATIVE_ZOOM \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_ABSOLUTE_MOVE \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_CONTINUOUS_MOVE \ + (CSTR)"%s%s%s%s%s" +// #define BRCP_PACK_CONTINUOUS_MOVE_A (CSTR)"Profile_1" +#define BRCP_PACK_CONTINUOUS_ZOOM \ + (CSTR)"%s%s%s%s%s" +#define BRCP_PACK_PTZ_STOP \ + (CSTR)"%s%s%s%s%struetrue" + +#define BRCP_ENVELOPE_EXT \ + (CSTR)"%s%s" +#define PONVIF_ENVELOPE_SIM (CSTR) "%s%s" +#define PONVIF_BODY (CSTR) "%s" +#define BRCP_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 BRCP_HEADER_SECUR \ + (CSTR)"%s%s%s%s" + +#define BRCP_PCK_GET_CAPABILITIES (CSTR) "All" + +typedef struct S_accessToken +{ + char USERNAME[CTEXT]; + char PASSDIGEST[CTEXT]; // SHA_DIGEST_LENGTH]; + char NONCE[CTEXT]; // SHA_DIGEST_LENGTH]; + char TIMESTAMP[CTEXT]; +} accessToken; + +typedef struct S_videoSourceProfile +{ + char sourcetoken[CTEXT]; + char profiletoken[CTEXT]; + char profilename[CTEXT]; + char encoding[16]; + int width; + int height; + int fps; + int bitrate; +} videoSourceProfile; + +typedef struct S_onvifVideoResolution +{ + int Width; + int Height; +} onvifVideoResolution; + +typedef struct S_onvifBacklightCompensation +{ + bool Mode; + float Level; +} onvifBacklightCompensation; + +typedef enum E_onvifExposurePriority +{ + LowNoise = 0, + FrameRate +} onvifExposurePriority; + +typedef struct S_onvifRectangle +{ + int x; + int y; + int width; + int height; +} onvifRectangle; + +typedef struct S_onvifExposure +{ + bool Mode; + onvifExposurePriority Priority; + onvifRectangle Window; + float MinExposureTime; + float MaxExposureTime; + float MinGain; + float MaxGain; + float MinIris; + float MaxIris; + float ExposureTime; + float Gain; + float Iris; +} onvifExposure; + +typedef enum E_onvifOnOffAuto +{ + ON = 0, + OFF, + AUTO +} onvifOnOffAuto; + +typedef struct S_onvifFocusConfiguration +{ + bool AutoFocusMode; + float DefaultSpeed; + float NearLimit; + float FarLimit; +} onvifFocusConfiguration; + +typedef struct S_onvifWideDynamicRange +{ + bool Mode; + float Level; +} onvifWideDynamicRange; + +typedef struct S_onvifWhiteBalanceExtension +{ +} onvifWhiteBalanceExtension; + +typedef struct S_onvifWhiteBalance +{ + bool Mode; + float CrGain; + float CbGain; + onvifWhiteBalanceExtension * Extension; +} onvifWhiteBalance; + +typedef struct S_onvifImagingSettingsExtension +{ +} onvifImagingSettingsExtension; + +typedef struct S_onvifImagingSettings +{ + onvifBacklightCompensation * BacklightCompensation; + float Brightness; + float ColorSaturation; + float Contrast; + onvifExposure * Exposure; + onvifFocusConfiguration * Focus; + onvifOnOffAuto IrCutFilter; + float Sharpness; + onvifWideDynamicRange * WideDynamicRange; + onvifWhiteBalance * WhiteBalance; + onvifImagingSettingsExtension * Extension; +} onvifImagingSettings; + +typedef struct S_onvifVideoSourceExtension +{ + onvifImagingSettings * Imaging; +} onvifVideoSourceExtension; + +typedef struct S_onvifVideoSource +{ + char token[CTEXT]; + float Framerate; + onvifVideoResolution Resolution; + onvifImagingSettings * Imaging; + onvifVideoSourceExtension * Extension; +} videoSource; + +typedef struct S_onvifSupportedVersions +{ + int Major; + int Minor; +} onvifSupportedVersions; + +typedef struct S_onvifNetworkCapabilitiesExtension2 +{ +} onvifNetworkCapabilitiesExtension2; + +typedef struct S_onvifNetworkCapabilitiesExtension +{ + bool Dot11Configuration; + onvifNetworkCapabilitiesExtension2 * Extension; +} onvifNetworkCapabilitiesExtension; + +typedef struct S_onvifNetworkCapabilities +{ + bool IPFilter; + bool ZeroConfiguration; + bool IPVersion6; + bool DynDNS; + onvifNetworkCapabilitiesExtension * Extension; +} onvifNetworkCapabilities; + +typedef struct S_onvifIOCapabilitiesExtension2 +{ +} onvifIOCapabilitiesExtension2; + +typedef struct S_onvifIOAuxiliaryData +{ +} onvifIOAuxiliaryData; + +typedef struct S_onvifIOCapabilitiesExtension +{ + bool Auxiliary; + onvifIOAuxiliaryData * AuxiliaryCommands; + onvifIOCapabilitiesExtension2 * Extension; +} onvifIOCapabilitiesExtension; + +typedef struct S_onvifIOCapabilities +{ + int InputConnectors; + int RelayOutputs; + onvifIOCapabilitiesExtension * Extension; +} onvifIOCapabilities; + +typedef struct S_onvifSecurityCapabilitiesExtension2 +{ + bool Dot1X; + int SupportedEAPMethod; + bool RemoteUserHandling; +} onvifSecurityCapabilitiesExtension2; + +typedef struct S_onvifSecurityCapabilitiesExtension +{ + bool TLS1_0; + onvifSecurityCapabilitiesExtension2 * Extension; +} onvifSecurityCapabilitiesExtension; + +typedef struct S_onvifSecurityCapabilities +{ + bool TLS1_1; + bool TLS1_2; + bool OnboardKeyGeneration; + bool AccessPolicyConfig; + bool X_509Token; + bool SAMLToken; + bool KerberosToken; + bool RELToken; + onvifSecurityCapabilitiesExtension * Extension; +} onvifSecurityCapabilities; + +typedef struct S_onvifSystemCapabilitiesExtension2 +{ +} onvifSystemCapabilitiesExtension2; + +typedef struct S_onvifSystemCapabilitiesExtension +{ + bool HttpFirmwareUpgrade; + bool HttpSystemBackup; + bool HttpSystemLogging; + bool HttpSupportInformation; + onvifSystemCapabilitiesExtension2 * Extension; +} onvifSystemCapabilitiesExtension; + +typedef struct S_onvifSystemCapabilities +{ + bool DiscoveryResolve; + bool DiscoveryBye; + bool RemoteDiscovery; + bool SystemBackup; + bool SystemLogging; + bool FirmwareUpgrade; + onvifSupportedVersions * SupportedVersions; + onvifSystemCapabilitiesExtension * Extension; +} onvifSystemCapabilities; + +typedef struct S_onvifDeviceCapabilitiesExtension +{ +} onvifDeviceCapabilitiesExtension; + +typedef struct S_onvifAnalyticsCapabilities +{ + char XAddr[CTEXT]; + bool RuleSupport; + bool AnalyticsModuleSupport; +} onvifAnalyticsCapabilities; + +typedef struct S_onvifDeviceCapabilities +{ + char XAddr[CTEXT]; + onvifNetworkCapabilities * Network; + onvifSystemCapabilities * System; + onvifIOCapabilities * IO; + onvifSecurityCapabilities * Security; + onvifDeviceCapabilitiesExtension * Extension; +} onvifDeviceCapabilities; + +typedef struct S_onvifEventCapabilities +{ + char XAddr[CTEXT]; + bool WSSubscriptionPolicySupport; + bool WSPullPointSupport; + bool WSPausableSubscriptionManagerInterfaceSupport; +} onvifEventCapabilities; + +typedef struct S_onvifImagingCapabilities +{ + char XAddr[CTEXT]; +} onvifImagingCapabilities; + +typedef struct S_onvifRealTimeStreamingCapabilitiesExtension +{ +} onvifRealTimeStreamingCapabilitiesExtension; + +typedef struct S_onvifRealTimeStreamingCapabilities +{ + bool RTPMulticast; + bool RTP_TCP; + bool RTP_RTSP_TCP; + onvifRealTimeStreamingCapabilitiesExtension * Extension; +} onvifRealTimeStreamingCapabilities; + +typedef struct S_onvifProfileCapabilities +{ + int MaximumNumberOfProfiles; +} onvifProfileCapabilities; + +typedef struct S_onvifMediaCapabilitiesExtension +{ + onvifProfileCapabilities * ProfileCapabilities; +} onvifMediaCapabilitiesExtension; + +typedef struct S_onvifMediaCapabilities +{ + char XAddr[CTEXT]; + onvifRealTimeStreamingCapabilities * StreamingCapabilities; + onvifMediaCapabilitiesExtension * Extension; +} onvifMediaCapabilities; + +typedef struct S_onvifPTZCapabilities +{ + char XAddr[CTEXT]; +} onvifPTZCapabilities; + +typedef struct S_onvifDeviceIOCapabilities +{ + char XAddr[CTEXT]; + int VideoSources; + int VideoOutputs; + int AudioSources; + int AudioOutputs; + int RelayOutputs; +} onvifDeviceIOCapabilities; + +typedef struct S_onvifDisplayCapabilities +{ + char XAddr[CTEXT]; + bool FixedLayout; +} onvifDisplayCapabilities; + +typedef struct S_onvifRecordingCapabilities +{ + char XAddr[CTEXT]; + bool ReceiverSource; + bool MediaProfileSource; + bool DynamicRecordings; + bool DynamicTracks; + int MaxStringLength; +} onvifRecordingCapabilities; + +typedef struct S_onvifSearchCapabilities +{ + char XAddr[CTEXT]; + bool MetadataSearch; +} onvifSearchCapabilities; + +typedef struct S_onvifReplayCapabilities +{ + char XAddr[CTEXT]; +} onvifReplayCapabilities; + +typedef struct S_onvifReceiverCapabilities +{ + char XAddr[CTEXT]; + bool RTP_Multicast; + bool RTP_TCP; + bool RTP_RTSP_TCP; + int SupportedReceivers; + int MaximumRTSPURILength; +} onvifReceiverCapabilities; + +typedef struct S_onvifAnalyticsDeviceExtension +{ +} onvifAnalyticsDeviceExtension; + +typedef struct S_onvifAnalyticsDeviceCapabilities +{ + char XAddr[CTEXT]; + bool RuleSupport; + onvifAnalyticsDeviceExtension * Extension; +} onvifAnalyticsDeviceCapabilities; + +typedef struct S_onvifCapabilitiesExtension2 +{ +} onvifCapabilitiesExtension2; + +typedef struct S_onvifCapabilitiesExtension +{ + onvifDeviceIOCapabilities * DeviceIO; + onvifDisplayCapabilities * Display; + onvifRecordingCapabilities * Recording; + onvifSearchCapabilities * Search; + onvifReplayCapabilities * Replay; + onvifReceiverCapabilities * Receiver; + onvifAnalyticsDeviceCapabilities * AnalyticsDevice; + onvifCapabilitiesExtension2 * Extensions; +} onvifCapabilitiesExtension; + +typedef struct S_nodeCapability +{ + onvifAnalyticsCapabilities * Analytics; + onvifDeviceCapabilities * Device; + onvifEventCapabilities * Events; + onvifImagingCapabilities * Imaging; + onvifMediaCapabilities * Media; + onvifPTZCapabilities * PTZ; + onvifCapabilitiesExtension * Extension; +} nodeCapability; + +typedef struct S_discoveryNodeInfo +{ + char endpoint_uid[64]; + char types[CTEXT]; + char scopes[CTEXT]; + char x_addrs[CTEXT]; + char meta_version[10]; + char ip_addrs[32]; +} discoveryNodeInfo; + +typedef struct S_ptzStatus +{ + float pan; + float tilt; + float zoom; + bool hasMoveStatus; + bool PanTiltIdle; + bool ZoomIdle; +} ptzStatus; + +class boschRCP; + +typedef std::vector videoSourceProfiles; +typedef std::vector videoSources; +typedef std::vector discoveryResults; + +class boschRCP{ + private: + curlRequestsManager * m_pHttpAccessManager; + basicMutex m_mResponseProtector; + CURL * m_pCURL; + basicLogCollection * m_pLog; + CSTR m_pIpAddress; + CSTR m_pUsername; + CSTR m_pPassword; + CSTR m_pDeviceURI; + int m_pLastIndex; + CSTR m_pMediaURI; + CSTR m_pSnapshotURI; + + CSTR m_pPTZURI; + CSTR m_pBaseURI; + onvifSupportedVersions m_sOnvifVersion; + time_t m_nDeltaTime; + videoSources m_vVideoSources; + videoSourceProfiles m_vVideoProfiles; + videoSourceProfiles m_vActiveSources; + nodeCapability m_sCapabilities; + CSTR m_pProxyHost; + int m_nProxyPort; + CSTR m_pProxyUsername; + CSTR m_pProxyPassword; + CSTR m_pLastResponse; + bool m_bIntransingent; + time_t m_nDiscoveryTimeout; + CSTR m_pDiscoveryBindIP; + CSTR m_pDiscoveryMCastIP; + int m_nDiscoveryMCastPort; + bool m_bDiscoveryHideDuplicates; + bool parser_done; + uint8_t m_bAuthMode; +#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: + + boschRCP(); + ~boschRCP(); + bool setProxyHost(CSTR proxyHost); + CSTR getProxyHost(void); + bool setProxyPort(int proxyPort); + int getProxyPort(void); + bool setProxyUsername(CSTR proxyUsername); + CSTR getProxyUsername(void); + bool setProxyPassword(CSTR proxyPassword); + CSTR getProxyPassword(void); + bool setUsername(CSTR username); + CSTR getUsername(void); + bool setPassword(CSTR password); + bool setAuthMode(uint8_t Mode); + CSTR getPassword(void); + CSTR getDeviceUri(void); + bool setDeviceUri(CSTR deviceUri); + CSTR getIPAddress(void); + bool setIPAddress(CSTR ipAddress); + videoSources * getSources(void); + videoSourceProfiles * getProfiles(void); + videoSourceProfiles * getActiveProfiles(void); + CSTR getMediaUri(void); + CSTR getPTZUri(void); + CSTR getBaseUrl(void); + void getSupportedVersion(void); + nodeCapability * getCapabilities(void); + bool setBreakOnError(bool intransingent); + CSTR getLastResponse(void); + bool setDiscoveryTimeout(int discoverytimeout); + bool setDiscoveryBindIp(CSTR discoverybindip); + bool setDiscoveryMcastIp(CSTR discoverymcastip); + bool setDiscoveryMcastPort(int discoverymcastport); + bool setDiscoveryHideDuplicates(bool discoveryhideduplicates); + CSTR getSnapshotUri(void); + + discoveryResults discover(void); + bool create(void); + + struct tm * core_GetSystemDateAndTime(void); + bool core_GetCapabilities(); + bool core_GetDeviceInformation(); + + bool media_GetVideoSources(); + bool media_GetProfiles(); + bool media_GetServices(); + CSTR media_GetStreamUri(CSTR profileToken, CSTR stream = (CSTR) "RTP-Unicast", CSTR protocol = (CSTR) "RTSP"); + CSTR media_GetSnapshotUri(CSTR profileToken); + + bool ptz_GetPresets(CSTR profileToken); + bool ptz_GetNode(CSTR ptzNodeToken); + bool ptz_GetStatus(CSTR profileToken, ptzStatus * tStatus); + bool ptz_GotoPreset(CSTR profileToken, CSTR presetToken, float speed_pantilt_x, float speed_pantilt_y, float speed_zoom_x); + bool ptz_RemovePreset(CSTR profileToken, CSTR presetToken); + bool ptz_SetPreset(CSTR profileToken, CSTR presetName); + bool ptz_RelativeMove(CSTR profileToken, float translation_pantilt_x, float translation_pantilt_y, float speed_pantilt_x, float speed_pantilt_y); + bool ptz_RelativeMoveZoom(CSTR profileToken, float zoom, float speedZoom); + bool ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float position_pantilt_y, float zoom); + bool ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y); + bool ptz_ContinuousMoveZoom(CSTR profileToken, float zoom); + bool ptz_Stop(CSTR profileToken, bool pantilt, bool zoom); + /* + Internal functions + */ + private: + + accessToken _makeToken(void); + void _getBRCPVersion(nodeCapability & capabilities); + void _getActiveSources(videoSourceProfiles & videoSources, videoSourceProfiles profiles); + 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 mr = true); + bool _post_request(CSTR url, CSTR post_string); +}; + +#endif diff --git a/lib/data/protocol/protocolPTZ_BRCP.cpp b/lib/data/protocol/protocolPTZ_BRCP.cpp new file mode 100644 index 00000000..0bdff292 --- /dev/null +++ b/lib/data/protocol/protocolPTZ_BRCP.cpp @@ -0,0 +1,513 @@ +#include "protocolPTZ_BRCP.h" + +#include "../../hardware/uart/serialPort.h" + +#define LOG(X) m_pLog->Log("BRCP", this, X) +#define LOG_ERROR(X) m_pLog->Log("BRCP", this, _LOG_ERROR, X) + +protocolPTZ_BRCP::protocolPTZ_BRCP(config_setting_t * Settings) : + protocolPTZ(), + m_mInquiryMutex() +{ + m_pLog = basicLogCollection::getInstance(); + m_bLastCommandIssued = CMD_PTZ_NOOP; + m_pSettings = Settings; + m_bAuthMode = 0; + boschRCP = NULL; + m_pProfile = NULL; + memset(m_pDeviceURI, 0, MAX_PATH_LEN); + memset(m_pUser, 0, MAX_CRED_LEN); + memset(m_pPassword, 0, MAX_CRED_LEN); +} + +protocolPTZ_BRCP::protocolPTZ_BRCP(CSTR ip, uint16_t port, CSTR username, CSTR password, uint8_t AuthMode) : + protocolPTZ(), + m_mInquiryMutex() +{ + m_pLog = basicLogCollection::getInstance(); + m_bLastCommandIssued = CMD_PTZ_NOOP; + m_pSettings = NULL; + boschRCP = NULL; + m_pProfile = NULL; + LOG(ip); + LOG(username); + LOG(password); + m_bAuthMode = AuthMode; + sprintf(m_pDeviceURI, "Auth Mode: [%d]", m_bAuthMode); + LOG(m_pDeviceURI); + if (port == 80) + { + sprintf(m_pDeviceURI, "http://%s/onvif/device_service", ip); + } + else + { + sprintf(m_pDeviceURI, "http://%s:%d/onvif/device_service", ip, port); + } + LOG(m_pDeviceURI); + strncpy(m_pUser, username, MAX_CRED_LEN); + strncpy(m_pPassword, password, MAX_CRED_LEN); +} + +protocolPTZ_BRCP::protocolPTZ_BRCP(CSTR ctl_url, CSTR username, CSTR password, uint8_t AuthMode) : + protocolPTZ(), + m_mInquiryMutex() +{ + m_pLog = basicLogCollection::getInstance(); + m_bLastCommandIssued = CMD_PTZ_NOOP; + m_pSettings = NULL; + boschRCP = NULL; + m_pProfile = NULL; + LOG(ctl_url); + LOG(username); + LOG(password); + m_bAuthMode = AuthMode; + sprintf(m_pDeviceURI, "Auth Mode: [%d]", m_bAuthMode); + LOG(m_pDeviceURI); + strncpy(m_pDeviceURI, ctl_url, 250); + strncpy(m_pUser, username, MAX_CRED_LEN); + strncpy(m_pPassword, password, MAX_CRED_LEN); +} + +protocolPTZ_BRCP::~protocolPTZ_BRCP() {} + +bool protocolPTZ_BRCP::setIPAddress(CSTR ip) +{ + if (ip == NULL) + { + return false; + } + if (strlen(ip) == 0) + { + return false; + } + sprintf(m_pDeviceURI, "http://%s/onvif/device_service", ip); + // strncpy( m_pDeviceURI, ip, MAX_PATH_LEN ); + return true; +} + +bool protocolPTZ_BRCP::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_BRCP::setPassword(CSTR password) +{ + if (password == NULL) + { + return false; + } + if (strlen(password) == 0) + { + return false; + } + strncpy(m_pPassword, password, MAX_CRED_LEN); + return true; +} + +bool protocolPTZ_BRCP::setAuthMode(uint8_t Mode) +{ + m_bAuthMode = Mode; + return true; +} + +bool protocolPTZ_BRCP::create(void) +{ + if (! protocolPTZ::create()) + { + return false; + } + if (m_pSettings != NULL) + { + config_setting_t * pSetting; + pSetting = config_setting_get_member(m_pSettings, PPTZ_TAG_ONVIF_USER); + if (pSetting == NULL) + { + return false; + } + sprintf(m_pUser, "%s", config_setting_get_string(pSetting)); + pSetting = config_setting_get_member(m_pSettings, PPTZ_TAG_ONVIF_PASS); + if (pSetting == NULL) + { + return false; + } + sprintf(m_pPassword, "%s", config_setting_get_string(pSetting)); + pSetting = config_setting_get_member(m_pSettings, PPTZ_TAG_ONVIF_DEV_URI); + 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 + boschRCP = new boschRCP(); + if (boschRCP == NULL) + { + LOG_ERROR("boschRCP NEW FAILURE!"); + m_bStatus = 0; + return false; + }; + boschRCP->setDeviceUri(m_pDeviceURI); + boschRCP->setUsername(m_pUser); + boschRCP->setPassword(m_pPassword); + boschRCP->setAuthMode(m_bAuthMode); + LOG("PROTOCREATE"); + if (boschRCP->create()) + { + m_pProfile = boschRCP->getProfiles()->at(0); + LOG("DONE"); + m_bStatus = 1; + return true; + } else { + LOG_ERROR("pOnvif CREATE FAILURE!"); + delete(m_pOnVif); + m_pOnVif = NULL; + m_bStatus = 0; + return false; + }; +#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_BRCP::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_BRCP::move(uint32_t MoveMatrix) +{ + // 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; + if (MoveMatrix > 0) + { + if ((MoveMatrix & PTZ_DRIVE_PAN_MASK) == 0) + { + Speed_x = 0.0f; + } + else if ((MoveMatrix & PTZ_DRIVE_PAN_LEFT) != 0) + { + Speed_x = -m_dPanSpeed; + } + else + { + Speed_x = m_dPanSpeed; + }; + if ((MoveMatrix & PTZ_DRIVE_TILT_MASK) == 0) + { + Speed_y = 0.0; + } + else if ((MoveMatrix & PTZ_DRIVE_TILT_UP) != 0) + { + Speed_y = m_dTiltSpeed; + } + else + { + Speed_y = -m_dTiltSpeed; + }; + if ((MoveMatrix & PTZ_DRIVE_ZOOM_MASK) == 0) + { + Speed_z = 0.0; + } + else if ((MoveMatrix & PTZ_DRIVE_ZOOM_WIDE) != 0) + { + Speed_z = m_dZoomSpeed; + } + else + { + Speed_z = -m_dZoomSpeed; + }; + bool res = true; + if ((MoveMatrix & (PTZ_DRIVE_PAN_MASK | PTZ_DRIVE_TILT_MASK)) != 0) + { + res = m_pOnVif->ptz_ContinuousMove(m_pProfile->profiletoken, Speed_x, Speed_y); + }; + if (res) + { + if ((MoveMatrix & PTZ_DRIVE_ZOOM_MASK) != 0) + { + res = m_pOnVif->ptz_ContinuousMoveZoom(m_pProfile->profiletoken, Speed_z); + }; + }; + m_bStatus = (res) ? 1 : 0; + } + else + { + + m_bStatus = (m_pOnVif->ptz_Stop(m_pProfile->profiletoken, true, true)) ? 1 : 0; + }; + return (m_bStatus > 0); +#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_BRCP::waitMoveIsDone(void) +{ + ptzStatus tVal; + uint8_t TO = 12; // 3.6 second max + while (m_pOnVif->ptz_GetStatus(m_pProfile->profiletoken, &tVal) && TO) + { + if (tVal.hasMoveStatus) + { + if (tVal.PanTiltIdle && tVal.ZoomIdle) + { + break; + } + } + else + { + // if( ( fabs(tVal.pan - dPan) < 0.0005 ) && ( fabs( tVal.tilt - dTilt) < 0.0005 ) ) break;//&& ( fabs( tVal.zoom - dZoom ) < 0.05 ) ) break; + }; + SLEEP(333); + TO--; + }; + if (TO) + { +#ifdef DEBUG_EXTRA + LOG("Finished Move!"); +#endif + return true; +#ifdef DEBUG_EXTRA + } + else + { + LOG_ERROR("Error Fetching PTZ Status!"); +#endif + }; + return false; +} + +bool protocolPTZ_BRCP::goAbsolute(float dPan, float dTilt, float dZoom) +{ +#ifdef USE_PONVIF + // if (m_bStatus == 0) return false; + #ifdef DEBUG_EXTRA + LOG("ABS Move"); + #endif + if (m_pProfile == NULL) + { + LOG_ERROR("No PTZ Profile!!"); + return false; + }; + if (dZoom < 0.0f) + { + dZoom = 0.0f; + } + + if (m_pOnVif->ptz_AbsoluteMove(m_pProfile->profiletoken, dPan, dTilt, dZoom)) + { + }; + return true; +#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 +} + +bool protocolPTZ_BRCP::getCameraPresets(void) +{ + LOG("GET PRESETS!"); + return m_pOnVif->ptz_GetPresets(m_pProfile->profiletoken); +} + +bool protocolPTZ_BRCP::goPreset(char * PresetToken) +{ +#ifdef USE_PONVIF + // if (m_bStatus == 0) return false; + #ifdef DEBUG_EXTRA + LOG("Preset Move"); + #endif + if (m_pProfile == NULL) + { + LOG_ERROR("No PTZ Profile!!"); + return false; + }; + if (! m_pOnVif->ptz_GotoPreset(m_pProfile->profiletoken, PresetToken, 1.0f, 1.0f, 1.0f)) + { + m_bStatus = 0; + } + return (m_bStatus > 0); +#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 +} + +bool protocolPTZ_BRCP::validate() +{ + return (m_bStatus > 0); +} + +#undef LOG +#undef LOG_ERROR diff --git a/lib/data/protocol/protocolPTZ_BRCP.h b/lib/data/protocol/protocolPTZ_BRCP.h new file mode 100644 index 00000000..274b4f12 --- /dev/null +++ b/lib/data/protocol/protocolPTZ_BRCP.h @@ -0,0 +1,46 @@ +#ifndef __PROTOCOL_PTZ_BRCP_HEADER__ +#define __PROTOCOL_PTZ_BRCP_HEADER__ + +#include "protocolPTZ.h" + +#include "../bosch_rcp/bosch_rcp.h" + + +class protocolPTZ_BRCP : public protocolPTZ +{ + private: + + basicLogCollection * m_pLog; + char m_pUser[MAX_CRED_LEN]; + char m_pPassword[MAX_CRED_LEN]; + char m_pDeviceURI[MAX_PATH_LEN]; + uint8_t m_bAuthMode; + boschRCP * m_pBRCP; + videoSourceProfile * m_pProfile; + config_setting_t * m_pSettings; + basicMutex m_mInquiryMutex; + + public: + + explicit protocolPTZ_BRCP(config_setting_t * Settings = NULL); + protocolPTZ_BRCP(CSTR ip, uint16_t port, CSTR username, CSTR password, uint8_t AuthMode = 0); + protocolPTZ_BRCP(CSTR ctl_url, CSTR username, CSTR password, uint8_t AuthMode = 0); + virtual ~protocolPTZ_BRCP(); + 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); + virtual bool goPreset(char * PresetToken); + virtual bool getCameraPresets(void); + + bool setIPAddress(CSTR ip); + bool setUsername(CSTR username); + bool setPassword(CSTR password); + bool setAuthMode(uint8_t Mode); + virtual bool waitMoveIsDone(void); + virtual bool validate(); +}; + +#endif