diff --git a/Projects/argus/test/runme b/Projects/argus/test/runme new file mode 100755 index 00000000..d88dae1e --- /dev/null +++ b/Projects/argus/test/runme @@ -0,0 +1,3 @@ + + +gcc scaling_video.c -Wno-write-strings `pkg-config libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -lpthread -lmysqlclient -lssl -lcurl -lm -lz -lv4l1 -lv4l2 `pkg-config libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --libs` -latomic -o scaling_video \ No newline at end of file diff --git a/Projects/argus/test/scaling_video b/Projects/argus/test/scaling_video new file mode 100755 index 00000000..d6b9f5b6 Binary files /dev/null and b/Projects/argus/test/scaling_video differ diff --git a/Projects/argus/test/scaling_video.c b/Projects/argus/test/scaling_video.c new file mode 100644 index 00000000..4ce9df94 --- /dev/null +++ b/Projects/argus/test/scaling_video.c @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2012 Stefano Sabatini + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * @file + * libswscale API use example. + * @example scaling_video.c + */ + +#include +#include +#include + +static void fill_yuv_image(uint8_t *data[4], int linesize[4], + int width, int height, int frame_index) +{ + int x, y; + + /* Y */ + for (y = 0; y < height; y++) + for (x = 0; x < width; x++) + data[0][y * linesize[0] + x] = x + y + frame_index * 3; + + /* Cb and Cr */ + for (y = 0; y < height / 2; y++) { + for (x = 0; x < width / 2; x++) { + data[1][y * linesize[1] + x] = 128 + y + frame_index * 2; + data[2][y * linesize[2] + x] = 64 + x + frame_index * 5; + } + } +} + +int main(int argc, char **argv) +{ + uint8_t *src_data[4], *dst_data[4]; + int src_linesize[4], dst_linesize[4]; + int src_w = 320, src_h = 240, dst_w, dst_h; + enum AVPixelFormat src_pix_fmt = AV_PIX_FMT_YUV420P, dst_pix_fmt = AV_PIX_FMT_BGR24; + const char *dst_size = NULL; + const char *dst_filename = NULL; + FILE *dst_file; + int dst_bufsize; + struct SwsContext *sws_ctx; + int i, ret; + + if (argc != 3) { + fprintf(stderr, "Usage: %s output_file output_size\n" + "API example program to show how to scale an image with libswscale.\n" + "This program generates a series of pictures, rescales them to the given " + "output_size and saves them to an output file named output_file\n" + "\n", argv[0]); + exit(1); + } + dst_filename = argv[1]; + dst_size = argv[2]; + + if (av_parse_video_size(&dst_w, &dst_h, dst_size) < 0) { + fprintf(stderr, + "Invalid size '%s', must be in the form WxH or a valid size abbreviation\n", + dst_size); + exit(1); + } + + dst_file = fopen(dst_filename, "wb"); + if (!dst_file) { + fprintf(stderr, "Could not open destination file %s\n", dst_filename); + exit(1); + } + + /* create scaling context */ + sws_ctx = sws_getContext(src_w, src_h, src_pix_fmt, + dst_w, dst_h, dst_pix_fmt, + SWS_BILINEAR, NULL, NULL, NULL); + if (!sws_ctx) { + fprintf(stderr, + "Impossible to create scale context for the conversion " + "fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n", + av_get_pix_fmt_name(src_pix_fmt), src_w, src_h, + av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h); + ret = AVERROR(EINVAL); + goto end; + } + + /* allocate source and destination image buffers */ + if ((ret = av_image_alloc(src_data, src_linesize, + src_w, src_h, src_pix_fmt, 16)) < 0) { + fprintf(stderr, "Could not allocate source image\n"); + goto end; + } + + /* buffer is going to be written to rawvideo file, no alignment */ + if ((ret = av_image_alloc(dst_data, dst_linesize, + dst_w, dst_h, dst_pix_fmt, 1)) < 0) { + fprintf(stderr, "Could not allocate destination image\n"); + goto end; + } + dst_bufsize = ret; + + for (i = 0; i < 100; i++) { + /* generate synthetic video */ + fill_yuv_image(src_data, src_linesize, src_w, src_h, i); + + /* convert to destination format */ + sws_scale(sws_ctx, (const uint8_t * const*)src_data, + src_linesize, 0, src_h, dst_data, dst_linesize); + + /* write scaled image to file */ + fwrite(dst_data[0], 1, dst_bufsize, dst_file); + } + + fprintf(stderr, "Scaling succeeded. Play the output file with the command:\n" + "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n", + av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h, dst_filename); + +end: + fclose(dst_file); + av_freep(&src_data[0]); + av_freep(&dst_data[0]); + sws_freeContext(sws_ctx); + return ret < 0; +} diff --git a/Projects/argus/test/tutu.jpg b/Projects/argus/test/tutu.jpg new file mode 100644 index 00000000..5f249747 Binary files /dev/null and b/Projects/argus/test/tutu.jpg differ diff --git a/lib/components/base/basicLIBAV.cpp b/lib/components/base/basicLIBAV.cpp index 23a68ea6..825800a4 100644 --- a/lib/components/base/basicLIBAV.cpp +++ b/lib/components/base/basicLIBAV.cpp @@ -46,8 +46,8 @@ bool initLibAV(void){ LOG(Buffer); sprintf(Buffer, "LibAV SWScale: %d.%d.%d", LIBSWSCALE_VERSION_MAJOR, LIBSWSCALE_VERSION_MINOR, LIBSWSCALE_VERSION_MICRO); LOG(Buffer); - //av_register_all(); - //avcodec_register_all(); + av_register_all(); + avcodec_register_all(); avdevice_register_all(); avformat_network_init(); }; diff --git a/lib/components/base/basicLIBAV.h b/lib/components/base/basicLIBAV.h index 4af19394..e7488f21 100644 --- a/lib/components/base/basicLIBAV.h +++ b/lib/components/base/basicLIBAV.h @@ -162,10 +162,6 @@ typedef struct VideoState { AVCodecContext *m_pCodecCtx; AVCodec *m_pVideoCodec; SwsContext *m_pSwsCtx; - //VideoPicture m_mPictQ[VIDEO_PICTURE_QUEUE_SIZE]; - //int m_iPictQSize; - //int m_iPictQ_rindex; - //int m_iPictQ_windex; char m_pFileName[MAX_PATH_LEN]; MediaStateStatus m_bStatus; } VideoState; diff --git a/lib/data/media/video/videoAVLIBSource.cpp b/lib/data/media/video/videoAVLIBSource.cpp index 07a8be10..aa4e7d78 100644 --- a/lib/data/media/video/videoAVLIBSource.cpp +++ b/lib/data/media/video/videoAVLIBSource.cpp @@ -12,52 +12,34 @@ #define LOG_ERROR( X ) m_pLog->Log( "LIBAV_SRC", this, _LOG_ERROR, X ); #endif -#define TLOG( X ) basicLogCollection::getInstance()->Log( "LIBAV_SRC_T", NULL, X ) -#ifdef DEBUG - #define TLOG_ERROR( X ) {\ - char _tBfrErrMSG2w34[256];\ - sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ - basicLogCollection::getInstance()->Log( "LIBAV_SRC_T", NULL, _LOG_ERROR, _tBfrErrMSG2w34 );\ - } -#else - #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "LIBAV_SRC_T", NULL, _LOG_ERROR, X ); -#endif - videoAVLIBSource::videoAVLIBSource( void *opaque ): basicMediaSource(), basicThread() { m_pLog = basicLogCollection::getInstance(); - m_bSizeIsAutomatic = true; - m_nWidth = -1; - m_nHeight = -1; - + m_bStreamingSource = true; + m_bSizeIsAutomatic = false; + m_nWidth = 640; + m_nHeight = 524; + m_bSrcType = AVLIB_SOURCE_NOTDEF; if( opaque ) { m_pOpaque = opaque; } else { m_pOpaque = (void *)this; }; - if (!initLibAV()) return; + if( !initLibAV() ) return; m_pVideoState = (VideoState*)av_mallocz(sizeof(VideoState)); - if( m_pVideoState == NULL ){ + if (m_pVideoState == NULL){ LOG_ERROR("VideoState Memory Allocation Error"); return; }; m_pVideoState->m_bStatus = MS_UNDEFINED; m_pVideoState->m_pFormatCtx = avformat_alloc_context(); - if( m_pVideoState->m_pFormatCtx == NULL ){ - LOG_ERROR("VideoFormat Context Memory Allocation Error"); + + if (m_pVideoState->m_pFormatCtx == NULL){ + LOG_ERROR("VideoCodec Context Memory Allocation Error"); return; }; - - m_pFrame = NULL; -#ifdef PROCESS_YUV420P - m_pFrameYUV = NULL; -#else - m_pFrameBGR = NULL; -#endif - img_convert_ctx = NULL; - m_pVideoState->m_iVideoStreamID = -1; #ifndef _NOAUDIO_ m_pVideoState->m_iAudioStreamID = -1; @@ -65,12 +47,13 @@ videoAVLIBSource::videoAVLIBSource( void *opaque ): basicMediaSource(), basicThr m_pVideoState->m_bStatus = MS_INIT; }; -videoAVLIBSource::videoAVLIBSource(char *Source, void *opaque ) : basicMediaSource(){ +videoAVLIBSource::videoAVLIBSource( char *Source, void *opaque ) : basicMediaSource(), basicThread() { m_pLog = basicLogCollection::getInstance(); m_bStreamingSource = true; - m_bSizeIsAutomatic = true; - m_nWidth = -1; - m_nHeight = -1; + m_bSizeIsAutomatic = false; + m_nWidth = 640; + m_nHeight = 524; + m_bSrcType = AVLIB_SOURCE_NOTDEF; if( opaque ) { m_pOpaque = opaque; } else { @@ -91,7 +74,6 @@ videoAVLIBSource::videoAVLIBSource(char *Source, void *opaque ) : basicMediaSour LOG_ERROR("VideoCodec Context Memory Allocation Error"); return; }; - m_pVideoState->m_pFormatCtx->video_codec_id = AV_CODEC_ID_MJPEG; m_pVideoState->m_iVideoStreamID = -1; #ifndef _NOAUDIO_ m_pVideoState->m_iAudioStreamID = -1; @@ -121,18 +103,10 @@ videoAVLIBSource::~videoAVLIBSource(){ avformat_close_input(&m_pVideoState->m_pFormatCtx); //avformat_free_context(m_pVideoState->m_pFormatCtx); }; - + if( m_pVideoState->m_pSwsCtx != NULL ){ + sws_freeContext( m_pVideoState->m_pSwsCtx ); + }; av_free(m_pVideoState); - - if( m_pFrame!= NULL ) av_frame_free(&m_pFrame); -#ifdef PROCESS_YUV420P - av_frame_free( &m_pFrameYUV ); -#endif -#ifdef PROCESS_BGR24 - if (m_pFrameBGR != NULL) av_frame_free(&m_pFrameBGR); -#endif - //av_free( m_pOut_buffer ); - if( img_convert_ctx != NULL ) sws_freeContext(img_convert_ctx); }; }; }; @@ -187,20 +161,9 @@ bool videoAVLIBSource::_close(void){ if (m_pVideoState->m_bStatus < MS_OPENED) return true; if (m_pVideoState->m_bStatus == MS_CLOSED) return true; - - m_pVideoState->m_bStatus = MS_CLOSING; - - while( m_pVideoState->m_bStatus != MS_CLOSED ) SLEEP(10); - + _stop(); if (m_pVideoState->m_bStatus > MS_ALOCATED){ - av_frame_free(&m_pFrame); -#ifdef PROCESS_YUV420P - av_frame_free(&m_pFrameYUV); -#else - av_frame_free(&m_pFrameBGR); -#endif - sws_freeContext(img_convert_ctx); #ifndef _NOAUDIO_ if (m_pVideoState->m_pAudioCtx != NULL){ avcodec_close(m_pVideoState->m_pAudioCtx); @@ -222,8 +185,7 @@ bool videoAVLIBSource::_close(void){ }; bool videoAVLIBSource::_stop(void){ - if ( _close() ) basicThread::waitThreadEnd(); - else return false; + basicThread::waitThreadEnd( true ); return true; }; //https://www.youtube.com/watch?v=Lu3LZmhC_DY @@ -236,10 +198,9 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in char tChar[128] = {0}; sprintf( m_pCookie, "%s", MD5String(URI) ); m_pVideoState->m_bStatus = MS_OPENING; - uint8_t bSrcType = AVLIB_SOURCE_NOTDEF; if( strncmp( URI, "video=", 6 ) == 0 ){ - bSrcType = AVLIB_SOURCE_DDSHOW; + m_bSrcType = AVLIB_SOURCE_DDSHOW; #ifdef DEBUG LOG("MS-Video Device"); #endif @@ -315,18 +276,18 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in } else { if( strncmp( URI, "/dev/video", 10 ) == 0 ) { - bSrcType = AVLIB_SOURCE_V4L2; + m_bSrcType = AVLIB_SOURCE_V4L2; } else { - bSrcType = AVLIB_SOURCE_IPSTREAM; + m_bSrcType = AVLIB_SOURCE_IPSTREAM; }; - AVDictionary *options = NULL; - //av_dict_set(&options, "movflags", "faststart", 0); - if( bSrcType == AVLIB_SOURCE_IPSTREAM ) { + //AVDictionary *options = NULL; + //av_dict_set(&m_pVideoState->m_pFormatOpts, "movflags", "faststart", 0); + if( m_bSrcType == AVLIB_SOURCE_IPSTREAM ) { #ifdef DEBUG LOG("IP Stream Source"); #endif - av_dict_set(&options, "rtsp_transport", "tcp", 0); - av_dict_set(&options, "stimeout", "1000000", 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "rtsp_transport", "tcp", 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "stimeout", "5000000", 0); } else { #ifdef DEBUG LOG("Linux Video Device"); @@ -334,37 +295,39 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in if( width != -1 && height != -1 ){ m_bSizeIsAutomatic = false; sprintf(tChar, "%dx%d", width, height); - av_dict_set(&options, "video_size", tChar, 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "video_size", tChar, 0); } else { m_bSizeIsAutomatic = true; }; }; - av_dict_set(&options, "max_delay", "300000", 0); - av_dict_set(&options, "fflags", "nobuffer", 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "buffer_size", "1024000", 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "max_delay", "100", 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "fflags", "nobuffer", 0); //av_dict_set(&options, "analyzeduration", "1000000", 0); if( framerate != -1 ){ sprintf(tChar, "%0.2f", framerate); //sprintf(tChar, "120" ); - av_dict_set(&options, "framerate", tChar, 0); + av_dict_set(&m_pVideoState->m_pFormatOpts, "framerate", tChar, 0); //av_dict_set(&options, "frame_rate", tChar, 0); }; //av_dict_set(&options, "pixel_format", "mjpeg", 0); //av_dict_set(&options, "timeout", "8000", 0); int RetVal = 0; - if( ( RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, URI, NULL, &options) ) != 0 ){ - av_dict_free(&options); + strncpy( m_pVideoState->m_pFileName, URI, MAX_PATH_LEN ); + if( ( RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts) ) != 0 ){ + //av_dict_free(&options); char tBuffer[1024]; av_strerror( RetVal, tBuffer, 1024 ); - sprintf(Buffer, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, RetVal, URI); + sprintf(Buffer, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, RetVal, m_pVideoState->m_pFileName ); LOG_ERROR(Buffer); return false; }; AVDictionaryEntry *e; - if( e = av_dict_get( options, "", NULL, AV_DICT_IGNORE_SUFFIX )){ + if( e = av_dict_get( m_pVideoState->m_pFormatOpts, "", NULL, AV_DICT_IGNORE_SUFFIX )){ sprintf(Buffer, "Option %s not recognized by the demuxer", e->key); LOG_ERROR(Buffer); }; - av_dict_free(&options); + //av_dict_free( &e ); }; //DataStream Opened ! m_pVideoState->m_bStatus = MS_OPENED; @@ -453,8 +416,8 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE). Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool. */ - m_pVideoState->m_pCodecCtx->thread_count = 2; - m_pVideoState->m_pCodecCtx->thread_type = FF_THREAD_FRAME; + //m_pVideoState->m_pCodecCtx->thread_count = 2; + //m_pVideoState->m_pCodecCtx->thread_type = FF_THREAD_FRAME; if( avcodec_open2( m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoCodec, NULL ) < 0 ){ sprintf(Buffer, "Could not open Video codec[%d] for %s", m_pVideoState->m_pCodecCtx->codec_id, URI ); @@ -478,25 +441,24 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in return false; }; #endif - m_pFrame = av_frame_alloc(); -#ifdef PROCESS_YUV420P - m_pFrameYUV = av_frame_alloc(); -#endif -#ifdef PROCESS_BGR24 - m_pFrameBGR = av_frame_alloc(); -#endif - char tB[128]; +#ifdef DEBUG + char tB[256]; sprintf( tB, "Setting Frame [%dx%d]", m_nWidth, m_nHeight ); LOG( tB ); sprintf( tB, "Source Frame [%dx%d]", m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height ); LOG( tB ); +#endif if( scaled ){ +#ifdef DEBUG LOG("Size is Scaled"); +#endif m_nWidth = s_width; m_nHeight = s_height; } else { if( m_bSizeIsAutomatic ){ +#ifdef DEBUG LOG("Size is Automatic"); +#endif if(( m_nWidth == -1 )&&( m_nHeight == -1 )){ m_nWidth = m_pVideoState->m_pCodecCtx->width; m_nHeight = m_pVideoState->m_pCodecCtx->height; @@ -511,7 +473,9 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in }; }; } else { +#ifdef DEBUG LOG("Size is Manual"); +#endif if( width > 0 ){ m_nWidth = width; }; @@ -520,90 +484,87 @@ bool videoAVLIBSource::_open(char *URI, bool ShowDeviceMenu, float framerate, in }; }; }; - sprintf( tB, "Actual Frame [%dx%d]", m_nWidth, m_nHeight ); +#ifdef DEBUG + sprintf( tB, "Using Size [%dx%d]", m_nWidth, m_nHeight ); LOG( tB ); -#ifdef PROCESS_YUV420P - m_pOut_buffer = (uint8_t *) av_malloc( av_image_get_buffer_size( AV_PIX_FMT_YUV420P, m_nWidth , m_nHeight , BUFFER_ALIGN )); - //avpicture_fill((AVPicture *) m_pFrameYUV, m_pOut_buffer, AV_PIX_FMT_YUV420P, m_nWidth, m_nHeight ); - av_image_fill_arrays( m_pFrameYUV->data, m_pFrameYUV->linesize, m_pOut_buffer, AV_PIX_FMT_YUV420P, m_nWidth, m_nHeight, BUFFER_ALIGN); - m_pFrameYUV->width = m_nWidth; - m_pFrameYUV->height = m_nHeight; -#endif -#ifdef PROCESS_BGR24 - m_pOut_buffer = (uint8_t *) av_malloc( av_image_get_buffer_size( AV_PIX_FMT_BGR24, m_nWidth , m_nHeight , BUFFER_ALIGN )); - if( m_pOut_buffer == NULL ) return false; - //avpicture_fill((AVPicture *)m_pFrameBGR, m_pOut_buffer, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight); - av_image_fill_arrays ( m_pFrameBGR->data, m_pFrameBGR->linesize, m_pOut_buffer, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, BUFFER_ALIGN); - m_pFrameBGR->width = m_nWidth; - m_pFrameBGR->height = m_nHeight; - //m_pMat = cv::Mat( m_nHeight, m_nWidth, CV_8UC3, cv::Scalar(255) ); - //m_pOMat = cv::Mat( m_nHeight, m_nWidth, CV_8UC3, cv::Scalar(255) ); -#endif - m_pPacket = (AVPacket *) av_malloc( sizeof(AVPacket) ); - if ( m_pPacket == NULL ) return false; - // Printout FF - //av_dump_format(m_pFormatCtx,0,filepath,0); -#ifdef PROCESS_YUV420P - //Col Depth 12bpp - img_convert_ctx = sws_getContext(m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, m_pVideoState->m_pCodecCtx->pix_fmt, m_nWidth, m_nHeight, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL ); - if ( img_convert_ctx == NULL ) return false; - //Col Depth 16bpp - //img_convert_ctx = sws_getContext(m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, m_pVideoState->m_pCodecCtx->pix_fmt, m_nWidth, m_nHeight, AV_PIX_FMT_YUYV422, SWS_BICUBIC, NULL, NULL, NULL); -#endif -#ifdef PROCESS_BGR24 - img_convert_ctx = sws_getContext( + sprintf(tB,"swsPar: IN: %dx%d [%d] OUT: %dx%d [%d] {%d}", m_pVideoState->m_pCodecCtx->width, + m_pVideoState->m_pCodecCtx->height, + m_pVideoState->m_pCodecCtx->pix_fmt, + m_nWidth, + m_nHeight, + AV_PIX_FMT_BGR24, + SWS_BILINEAR ); + LOG( tB ); +#endif + m_pVideoState->m_pSwsCtx = sws_getContext( m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, m_pVideoState->m_pCodecCtx->pix_fmt, m_nWidth, m_nHeight, AV_PIX_FMT_BGR24, - SWS_BICUBIC, + SWS_FAST_BILINEAR | SWS_ACCURATE_RND,//SWS_BILINEAR,//SWS_BICUBIC, NULL, NULL, NULL ); - if ( img_convert_ctx == NULL ) return false; - //img_convert_ctx = sws_getContext(m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, m_pVideoState->m_pCodecCtx->pix_fmt, m_nWidth, m_nHeight, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL); -#endif - m_pVideoState->m_bStatus = MS_ALOCATED; // All seems to be good -> allocating mem + if ( m_pVideoState->m_pSwsCtx == NULL ){ + LOG_ERROR("Error Allocating SwsCtx!"); + return false; + }; +#ifdef DEBUG LOG("Allocation Done->Start Thread!"); +#endif return init(); }; return false; }; -#if !(( LIBAVCODEC_VERSION_MAJOR < 58 ) /* && ( LIBAVCODEC_VERSION_MINOR < 50 ) */ ) -// The flush packet is a non-NULL packet with size 0 and data NULL -int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt){ - int ret; - *got_frame = 0; - if (pkt){ - ret = avcodec_send_packet(avctx, pkt); - // In particular, we don't expect AVERROR(EAGAIN), because we read all - // decoded frames with avcodec_receive_frame() until done. - if (ret < 0) return ret == AVERROR_EOF ? 0 : ret; - }; - - ret = avcodec_receive_frame(avctx, frame); - if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) return ret; - if (ret >= 0) *got_frame = 1; - return 0; -}; -#endif - void videoAVLIBSource::m_fThreadProc( void ){ - int RetVal; - int bGotPicture = 0; -#ifdef _OPENCV_ - cv::Mat mRGB(m_nHeight, m_nWidth, CV_8UC3); -#endif - m_bThreadStatus = TH_WORKING; + AVPacket * pPacket = NULL; + cv::Mat mRGB( m_nHeight, m_nWidth, CV_8UC3 ); + AVFrame * pFrame = NULL; + AVFrame * pFrameBGR = NULL; + uint8_t * pBGRbuffer = NULL; + int dec_ret; + char tB[256]; + + pPacket = (AVPacket *) av_malloc( sizeof(AVPacket) ); + av_init_packet( pPacket ); + if ( pPacket == NULL ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Error allocating AVPacket!"); + } else { + pFrame = av_frame_alloc(); + if ( pFrame == NULL ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Error allocating SRC AVFrame!"); + } else { + pFrameBGR = av_frame_alloc(); + if ( pFrameBGR == NULL ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Error allocating BGR AVFrame!"); + } else { + pBGRbuffer = (uint8_t *) av_malloc( av_image_get_buffer_size( AV_PIX_FMT_BGR24, m_nWidth , m_nHeight , BUFFER_ALIGN )); + if ( pBGRbuffer == NULL ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Error allocating BGR AVFrame Buffer!"); + } else { + av_image_fill_arrays ( pFrameBGR->data, pFrameBGR->linesize, pBGRbuffer, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, BUFFER_ALIGN ); + pFrameBGR->width = m_nWidth; + pFrameBGR->height = m_nHeight; + m_pVideoState->m_bStatus = MS_ALOCATED; + m_bThreadStatus = TH_WORKING; #ifdef DEBUG_EXTRA - LOG("Reader Thread Started."); + LOG("Video Reader Thread Started."); #endif - //cv::setBreakOnError( true ); + }; + }; + }; + }; + + //cv::setBreakOnError( true ); m_pVideoState->m_bStatus = MS_STOPED; while( m_pMediaDestination == NULL && m_bThreadStatus == TH_WORKING ){ SLEEP(20); @@ -611,90 +572,91 @@ void videoAVLIBSource::m_fThreadProc( void ){ LOG("Waiting Destination"); #endif }; + m_pVideoState->m_bStatus = MS_PRESENT; + if( m_bSrcType == AVLIB_SOURCE_IPSTREAM ){ + //av_read_play( m_pVideoState->m_pFormatCtx ); + }; #ifdef DEBUG LOG("Presentation Started."); #endif - m_pVideoState->m_bStatus = MS_PRESENT; - av_read_play( m_pVideoState->m_pFormatCtx ); - while( m_pVideoState->m_bStatus < MS_CLOSING && m_bThreadStatus != TH_ENDED ){ if ( m_pMediaDestination != NULL ){ - if( av_read_frame( m_pVideoState->m_pFormatCtx, m_pPacket ) >= 0 ){ - if( m_pPacket->stream_index == m_pVideoState->m_iVideoStreamID ){ - int dec_ret = avcodec_send_packet( m_pVideoState->m_pCodecCtx, m_pPacket ); - if( dec_ret < 0 ){ - LOG_ERROR( "Error decoding video frame" ); + dec_ret = av_read_frame( m_pVideoState->m_pFormatCtx, pPacket ); + if( dec_ret >= 0 ){ + if( pPacket->stream_index == m_pVideoState->m_iVideoStreamID ){ + m_pVideoState->m_bStatus = MS_PRESENT; + dec_ret = avcodec_send_packet( m_pVideoState->m_pCodecCtx, pPacket ); + if( dec_ret < 0 && dec_ret != AVERROR(EAGAIN) /* && dec_ret != AVERROR_EOF */ ){ + LOG_ERROR( "Error sending video package to decoder" ); m_pVideoState->m_bStatus = MS_CLOSING; m_bThreadStatus = TH_ENDED; } else { while( dec_ret >= 0 && m_bThreadStatus != TH_ENDED ) { - dec_ret = avcodec_receive_frame( m_pVideoState->m_pCodecCtx, m_pFrame ); + dec_ret = avcodec_receive_frame( m_pVideoState->m_pCodecCtx, pFrame ); if( dec_ret == AVERROR(EAGAIN) || dec_ret == AVERROR_EOF ){ - continue;//Skip to next data + break;//Skip to next data } else if( dec_ret < 0 ){ - LOG_ERROR("Error in video decoding"); - m_pVideoState->m_bStatus = MS_STOPED; + LOG_ERROR("Error decoding video frame"); + m_pVideoState->m_bStatus = MS_CLOSING; m_bThreadStatus = TH_ENDED; break; }; - - #ifdef PROCESS_YUV420P - sws_scale( img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameYUV->data, m_pFrameYUV->linesize ); - //SDL_UpdateYUVTexture(m_pTexture, &m_oRect, m_pFrameYUV->data[0], m_pFrameYUV->linesize[0], m_pFrameYUV->data[1], m_pFrameYUV->linesize[1], m_pFrameYUV->data[2], m_pFrameYUV->linesize[2]); - m_pMediaDestination->pushFrame( m_pFrameYUV, m_pOpaque ); - #else // PROCESS_BGR24 - sws_scale( img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, m_pFrameBGR->data, m_pFrameBGR->linesize ); + sws_scale( m_pVideoState->m_pSwsCtx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, m_pVideoState->m_pCodecCtx->height, pFrameBGR->data, pFrameBGR->linesize ); try{ - #ifdef USE_QVideoFrame - QVideoFrame *tFrame; - tFrame = new QVideoFrame(m_pFrameBGR->linesize[0] * m_nHeight, QSize(m_nHeight, m_nWidth), m_pFrameBGR->linesize[0], QVideoFrame::Format_BGR24); - memcpy(tFrame->bits(), m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight); - if (m_pMediaDestination != NULL) m_pMediaDestination->pushFrame(tFrame, m_pOpaque ); - #else - #ifdef _OPENCV_ - memcpy( mRGB.data, m_pFrameBGR->data[0], m_pFrameBGR->linesize[0] * m_nHeight ); - #endif - #ifdef _SDL_ - SDL_Surface* mRGB = SDL_CreateRGBSurfaceFrom( m_pFrameBGR->data[0], m_nHeight, m_nWidth, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask ); - #endif + memcpy( mRGB.data, pFrameBGR->data[0], pFrameBGR->linesize[0] * m_nHeight ); m_pMediaDestination->pushFrame( mRGB, m_pOpaque ); - #ifdef _SDL_ - SDL_FreeSurface(mRGB); - #endif - #ifdef _OPENCV_ - //delete(mRGB); - #endif - #endif // !USE_QVideoFrame } catch (cv::Exception & e) { - LOG_ERROR(e.msg.c_str()); // output exception message + LOG_ERROR( e.msg.c_str() ); }; - #endif - //Unref Frame - //av_freep( m_pFrame->data[0] ); - //av_frame_unref( m_pFrame ); }; }; }; - } else { - m_pVideoState->m_bStatus = MS_CLOSED; + } else if( dec_ret != AVERROR(EAGAIN) && dec_ret != AVERROR_EOF ){ + LOG_ERROR( "Error reading video package" ); + char tBuffer[1024]; + av_strerror( dec_ret, tBuffer, 1024 ); + LOG_ERROR( tBuffer ); + m_pVideoState->m_bStatus = MS_CLOSING; m_bThreadStatus = TH_ENDED; + } else { + if( dec_ret == AVERROR_EOF ){ + avformat_close_input( &m_pVideoState->m_pFormatCtx ); + if( ( dec_ret = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts) ) != 0 ){ + char tBuffer[1024]; + av_strerror( dec_ret, tBuffer, 1024 ); + sprintf( tB, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, dec_ret, m_pVideoState->m_pFileName ); + LOG_ERROR( tB ); + m_pVideoState->m_bStatus = MS_CLOSING; + m_bThreadStatus = TH_ENDED; + }; + }; + //m_pVideoState->m_bStatus = MS_STOPED; + SLEEP( 5 ); }; -#if ( LIBAVCODEC_VERSION_MAJOR < 58 ) //&& ( LIBAVCODEC_VERSION_MINOR < 50 ) - av_free_packet( m_pPacket ); -#else - av_packet_unref( m_pPacket ); -#endif + av_packet_unref( pPacket ); } else SLEEP( 20 ); }; - m_pVideoState->m_bStatus = MS_CLOSED; + if ( pFrame != NULL ) { + av_frame_free( &pFrame ); + }; + if ( pPacket != NULL ) { + av_free( pPacket ); + }; + if( pBGRbuffer != NULL ) { + av_free( pBGRbuffer ); + }; + m_pVideoState->m_bStatus = MS_CLOSED; m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG("Video Source Ended!"); +#endif }; /* JPEG2000 isn't jpeg. To encode JPEG images, use AV_CODEC_ID_MJPEG. MJPEG stands for "motion JPEG", which is how a sequence of JPEG pictures making up a video stream is typically called. -int save_frame_as_jpeg(AVCodecContext *pCodecCtx, AVFrame *pFrame, int FrameNo) { +int save_frame_as_jpeg( AVCodecContext *pCodecCtx, AVFrame *pFrame, int FrameNo) { AVCodec *jpegCodec = avcodec_find_encoder(AV_CODEC_ID_JPEG2000); if (!jpegCodec) { return -1; @@ -733,21 +695,16 @@ int save_frame_as_jpeg(AVCodecContext *pCodecCtx, AVFrame *pFrame, int FrameNo) } */ +MediaStateStatus videoAVLIBSource::getStatus( void ){ + if( m_pVideoState ) return m_pVideoState->m_bStatus; + return MS_UNDEFINED; +}; + bool videoAVLIBSource::isFinished( void ){ - if ( m_pVideoState ) { - char tT[64]; - LOG("VideoState OK"); - sprintf( tT, "VS=%d ? 8", m_pVideoState->m_bStatus ); - LOG( tT ); - return (m_pVideoState->m_bStatus == MS_CLOSED); - } else { - LOG("No VideoState Object!"); - }; + if( m_pVideoState ) if( m_pVideoState->m_bStatus < MS_CLOSING ) return false; return true; }; -#undef TLOG -#undef TLOG_ERROR #undef LOG #undef LOG_ERROR diff --git a/lib/data/media/video/videoAVLIBSource.h b/lib/data/media/video/videoAVLIBSource.h index 89c144f3..7c9d0637 100644 --- a/lib/data/media/video/videoAVLIBSource.h +++ b/lib/data/media/video/videoAVLIBSource.h @@ -19,34 +19,28 @@ class videoAVLIBSource : public basicMediaSource, public basicThread { config_setting_t * m_pConfig; char m_pCookie[33]; VideoState * m_pVideoState; - AVFrame * m_pFrame; void * m_pOpaque; -#ifdef PROCESS_YUV420P - AVFrame * m_pFrameYUV; -#else - AVFrame * m_pFrameBGR; -#endif - uint8_t * m_pOut_buffer; - AVPacket * m_pPacket; + uint8_t m_bSrcType; + //uint8_t * m_pOut_buffer; int m_nWidth; int m_nHeight; int m_iY_size; - struct SwsContext * img_convert_ctx; - void m_fThreadProc( void ); #ifndef _NOAUDIO_ mediaBus * m_pAudioBus; static void * m_tAudioProc( void *args ); #endif bool m_bSizeIsAutomatic; + protected: + void m_fThreadProc( void ); public: bool _open( CSTR URI, bool ShowDeviceMenu = false, float framerate=-1.f, int inputPin = -1, int width = -1, int height = -1 , bool scaled=false, int s_width=-1, int s_height=-1 ); bool _close( void ); virtual bool _stop( void ); bool isFinished( void ); - uint8_t getStatus( void ){ if( m_pVideoState ){ return m_pVideoState->m_bStatus; }; return 0; }; + MediaStateStatus getStatus( void ); videoAVLIBSource( void *opaque=NULL ); videoAVLIBSource( CSTR URI, void *opaque=NULL ); - videoAVLIBSource( config_setting_t *CFG, void *opaque=NULL ); + //videoAVLIBSource( config_setting_t *CFG, void *opaque=NULL ); virtual ~videoAVLIBSource(); bool setSize( int Width, int Height ); diff --git a/lib/rgoose/rgooseCamera.cpp b/lib/rgoose/rgooseCamera.cpp index 4a86a787..9ebfc4b1 100644 --- a/lib/rgoose/rgooseCamera.cpp +++ b/lib/rgoose/rgooseCamera.cpp @@ -54,7 +54,7 @@ ARGUS_Camera::ARGUS_Camera(): basicThread(){ ARGUS_Camera::~ARGUS_Camera(){ LOG("Destruct"); - m_mQPROTECTOR.unlock(); + //m_mQPROTECTOR.unlock(); waitThreadEnd( true ); LOG("Thread Del OK"); if( m_pTransport!= NULL ) { @@ -338,9 +338,9 @@ bool ARGUS_Camera::absoluteMove( uint32_t TargetRefID, float PanPOS, float TiltP tTask->CMD->ZOOM = ZoomPOS; tTask->movemet_needed = true; tTask->source_evt_id = TargetRefID; - m_mQPROTECTOR.lock(); + //m_mQPROTECTOR.lock(); m_qCAM_TASK.push( tTask ); - m_mQPROTECTOR.unlock(); + //m_mQPROTECTOR.unlock(); return true; } else { free( tTask ); @@ -351,14 +351,15 @@ bool ARGUS_Camera::absoluteMove( uint32_t TargetRefID, float PanPOS, float TiltP }; void ARGUS_Camera::m_fThreadProc( void ){ + DBC_PUSHED_CMD * PUSHED = NULL; m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ) { //Local Recorder if( m_bSourceConnected ) { }; - DBC_PUSHED_CMD * PUSHED = m_pDBC->getNodePushedCMD( m_sCamData.node_id ); - if( PUSHED ) { + PUSHED = m_pDBC->getNodePushedCMD( m_sCamData.node_id ); + if( PUSHED != NULL ) { if( ( PUSHED->CMD & ARGUS_CAM_PCMD_CMD_MASK ) == ARGUS_CAM_PCMD_CMD_MASK ) { switch( PUSHED->CMD ) { case 0x80:{ @@ -373,7 +374,7 @@ void ARGUS_Camera::m_fThreadProc( void ){ break; }; }; - } else { + } else if ( m_bState == CAM_WS_READY || m_bState == CAM_WS_AUTOMATED_MOVE ){ //Direct Movment Mode if( PUSHED->CMD == ARGUS_CAM_PCMD_STOP ) { m_bState = CAM_WS_STOP_MOVE; @@ -385,45 +386,52 @@ void ARGUS_Camera::m_fThreadProc( void ){ }; }; free( PUSHED ); + PUSHED = NULL; }; switch( m_bState ) { case CAM_WS_INIT:{ #ifdef DEBUG LOG("Init Camera - PowerMode"); #endif + setBusy( true ); if( m_pProtocol->initCamera() ) m_bState = CAM_WS_WHITE_BALLANCE; + setBusy( false ); break; }; case CAM_WS_WHITE_BALLANCE:{ #ifdef DEBUG LOG("Set WB"); #endif + setBusy( true ); if( m_pProtocol->setWhiteBalanceMode( WB_AUTO ) ) m_bState = CAM_WS_BACKLIGHT; + setBusy( false ); break; }; case CAM_WS_BACKLIGHT:{ #ifdef DEBUG LOG("Set BLC"); #endif + setBusy( true ); if( m_pProtocol->setBackLightMode( true ) ) m_bState = CAM_WS_AUTO_FOCUS; - //if( m_pProtocol->goHomePosition() ) m_bState++; + setBusy( false ); break; }; case CAM_WS_AUTO_FOCUS:{ #ifdef DEBUG LOG("Set AF"); #endif + setBusy( true ); if( m_pProtocol->setAutoFocus( true ) ) m_bState = CAM_WS_INIT_GO_HOME; + setBusy( false ); break; }; case CAM_WS_INIT_GO_HOME:{ #ifdef DEBUG LOG("INIT GO -1 -1 -1"); #endif - if( m_pProtocol->goAbsolute( -1, -1, -1 ) ){ - m_bState = CAM_WS_READY; + setBusy( true ); + if( m_pProtocol->goAbsolute( -1, -1, -1 ) ) m_bState = CAM_WS_READY; setBusy( false ); - }; break; }; case CAM_WS_AUTOMATED_MOVE:{ @@ -461,10 +469,11 @@ void ARGUS_Camera::m_fThreadProc( void ){ if( m_fRM_Zoom < -1.0f ) m_fRM_Zoom = -1.0f; if( m_fRM_Zoom > 1.0f ) m_fRM_Zoom = 1.0f; setBusy( true ); - if( !relativeMove( m_fRM_Pan, m_fRM_Tilt, m_fRM_Zoom ) ){ + if( !relativeMove( m_fRM_Pan, m_fRM_Tilt, m_fRM_Zoom ) ) m_bState = CAM_WS_READY; + setBusy( false ); + if( m_nRelativeMoveCounter > 10 ) { m_bState = CAM_WS_READY; }; - setBusy( false ); break; }; case CAM_WS_STOP_MOVE:{ @@ -475,15 +484,13 @@ void ARGUS_Camera::m_fThreadProc( void ){ m_fRM_Zoom = .0f; m_fRM_Zoom = .0f; setBusy( true ); - if( relativeStop() ){ - m_bState = CAM_WS_READY; - }; + if( relativeStop() ) m_bState = CAM_WS_READY; setBusy( false ); break; } case CAM_WS_READY:{ uint32_t tSLEEP = DEFAULT_THREAD_SLEEP_TIME; - m_mQPROTECTOR.lock(); + //m_mQPROTECTOR.lock(); if( m_qCAM_TASK.size() ){ #ifdef DEBUG char tB[128]; @@ -491,14 +498,13 @@ void ARGUS_Camera::m_fThreadProc( void ){ LOG( tB ); #endif CAM_TASK *tTASK = m_qCAM_TASK.front(); - if ( tTASK ) { - m_qCAM_TASK.pop(); - m_mQPROTECTOR.unlock(); + if ( tTASK != NULL ) { if( tTASK->movemet_needed ){ CAM_PTZ_CMD *tCMD = tTASK->CMD; if( tCMD ) { switch( tCMD->CMD ) { case PTZ_STOP:{ + setBusy( true ); m_pProtocol->goStop(); setBusy( false ); break; @@ -506,8 +512,10 @@ void ARGUS_Camera::m_fThreadProc( void ){ case PTZ_MOVE:{ uint32_t MoveMatrix = 0; if( m_pProtocol->setPTZSpeed( tCMD->PAN, tCMD->TILT, tCMD->ZOOM ) ){ - tSLEEP = 5; + tSLEEP = 15; + setBusy( true ); m_pProtocol->move( MoveMatrix ); + setBusy( false ); }; break; }; @@ -515,7 +523,7 @@ void ARGUS_Camera::m_fThreadProc( void ){ setBusy( true ); if( !m_pProtocol->goAbsolute( tCMD->PAN, tCMD->TILT, tCMD->ZOOM ) ) { LOG_ERROR("Cannot Issue goAbsolute Command!"); - //tSLEEP= 1000; + tSLEEP= 100; }; setBusy( false ); if( m_pBEH ){ @@ -534,18 +542,18 @@ void ARGUS_Camera::m_fThreadProc( void ){ case PTZ_RELOAD_CAMERA:{ LOG("Exit Command Rcpt"); m_bThreadStatus = TH_ENDED; - setBusy( true ); }; }; free( tCMD ); tTASK->CMD = NULL; }; }; + m_qCAM_TASK.pop(); free( tTASK ); } else { - m_mQPROTECTOR.unlock(); LOG_ERROR("Error Fetching TASK from Queue"); }; + //m_mQPROTECTOR.unlock(); }; if( tSLEEP ) { SLEEP( tSLEEP ); @@ -745,9 +753,9 @@ bool ARGUS_Camera::makeSnap( uint32_t TargetRefID ){ if( tTask->CMD ){ tTask->CMD->CMD = PTZ_CAPTURE_ONLY; tTask->source_evt_id = TargetRefID; - m_mQPROTECTOR.lock(); + //m_mQPROTECTOR.lock(); m_qCAM_TASK.push( tTask ); - m_mQPROTECTOR.unlock(); + //m_mQPROTECTOR.unlock(); return true; } else { free( tTask ); @@ -810,12 +818,19 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ }; }; LOG( tMRL ); - if( m_pSource->_open( tMRL ) ) { - m_pSource->attachDestination( (argusModuleEmbedVideo*) tKM ); + //m_pSource = new videoAVLIBSource( tMRL, &m_sMediaSource ); + if( m_pSource->_open( tMRL ) ) { + m_bSourceConnected = m_pSource->attachDestination( (argusModuleEmbedVideo*) tKM ); + if ( !m_bSourceConnected ) { + delete( m_pSource ); + m_pSource = NULL; + } #ifdef DEBUG - LOG("Finish!"); + else { + LOG("Source is Connected to Output."); + } #endif - m_bSourceConnected = true; + ; } else { LOG_ERROR("Can not Open Video Source!"); delete( m_pSource ); @@ -823,7 +838,7 @@ bool ARGUS_Camera::connectToStream( uint32_t id ){ }; } else { LOG_ERROR("Video Source Stream Failure!"); - }; + }; free( tDATA ); }; } @@ -847,12 +862,12 @@ bool ARGUS_Camera::disconnectFromStream( void ){ }; bool ARGUS_Camera::validateStream( void ){ - LOG("Stream Validation"); if( m_bSourceConnected ) { - LOG("Source is Connected"); if( m_pSource ) { - LOG("Source is Created"); - return !(m_pSource->isFinished()); + if( !m_pSource->isFinished() ){ + return true; + }; + LOG("Source is Finished!"); } else { LOG_ERROR("No Source Object! Set Disconnected!"); m_bSourceConnected = false; diff --git a/lib/rgoose/rgooseCamera.h b/lib/rgoose/rgooseCamera.h index 94e3ba39..0c69c6cc 100644 --- a/lib/rgoose/rgooseCamera.h +++ b/lib/rgoose/rgooseCamera.h @@ -102,7 +102,7 @@ class ARGUS_Camera: public basicThread { basicTransport * m_pTransport; CAM_TASK_QUEUE m_qCAM_TASK; - basicMutex m_mQPROTECTOR; + //basicMutex m_mQPROTECTOR; videoAVLIBSource * m_pSource; uint32_t m_nRelativeMoveCounter; diff --git a/lib/rgoose/rgooseDBConnector.cpp b/lib/rgoose/rgooseDBConnector.cpp index fca7e51a..0cc519fb 100644 --- a/lib/rgoose/rgooseDBConnector.cpp +++ b/lib/rgoose/rgooseDBConnector.cpp @@ -2833,28 +2833,31 @@ uint32_t argusDBC::addLocalUART( uint32_t ResID, uint8_t utype, uint32_t speed, return RetVal; }; -uint32_t argusDBC::addLocalNetInterface( CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ +uint32_t argusDBC::addLocalNetInterface( CSTR device, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ uint32_t RetVal = 0; if( m_bIsConnected ) { char tQBuf[MAX_PATH_LEN]; - - sprintf( tQBuf, "%s:%s:xxx:%s", address, mask, broadcast ); - char * tKey = MD5String( tQBuf ); + char * tKey = MD5String( device ); if( tKey != NULL ) { - sprintf( tQBuf, "INSERT INTO `network_interfaces` SET `key`='%s', `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s' ON DUPLICATE KEY UPDATE `id`=`id`", + sprintf( tQBuf, "INSERT INTO `network_interfaces` SET `key`='%s', `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s' ON DUPLICATE KEY UPDATE `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s'", tKey, address, gateway, mask, + broadcast, + address, + gateway, + mask, broadcast ); #ifdef DEBUG_ALL LOG(tQBuf); #endif RetVal = m_pDatabase->QueryID( tQBuf ); - if( RetVal == 0 ) { - RetVal = getNetworkInterfaceID( tKey ); - }; + // On Update IF data no need to return ID + //if( RetVal == 0 ) { + // RetVal = getNetworkInterfaceID( tKey ); + //}; free( tKey ); }; }; diff --git a/lib/rgoose/rgooseDBConnector.h b/lib/rgoose/rgooseDBConnector.h index 3c0bdb93..5b8606bd 100644 --- a/lib/rgoose/rgooseDBConnector.h +++ b/lib/rgoose/rgooseDBConnector.h @@ -38,7 +38,7 @@ class argusDBC{ uint32_t addLocalMediaSource( uint32_t SiteID, CSTR path, uint32_t width, uint32_t height ); uint32_t addLocalDCB( uint32_t SiteID, CSTR PATH, CSTR SERIAL, uint8_t CNT, uint32_t status ); uint32_t addLocalUART( uint32_t ResID, uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode=0, uint16_t port=0 ); - uint32_t addLocalNetInterface( CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ); + uint32_t addLocalNetInterface( CSTR device, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ); //uint32_t addNodeSocket( uint32_t NodeID, uint32_t auxID, uint8_t SocketType, uint8_t SocketMode, bool multidrop, CSTR path, CSTR name ); bool addNotification( uint32_t MSG_ID, uint8_t DIS_LVL = 0, uint32_t OBJ_ID=0 ); uint32_t addPicture( uint32_t streamID, CSTR md5, CSTR ext ); diff --git a/lib/rgoose/rgooseHardwareManager.cpp b/lib/rgoose/rgooseHardwareManager.cpp index f2e53ebc..fddafd50 100644 --- a/lib/rgoose/rgooseHardwareManager.cpp +++ b/lib/rgoose/rgooseHardwareManager.cpp @@ -55,9 +55,11 @@ argusHardwareManager::argusHardwareManager( bool cold_start ){ enumerateHardware(); } else { //enumerateHardware( !cold_start ); + enumerateNIFS(); #ifdef DEBUG LOG("Loading Ressources..."); #endif + loadResources(); }; }; @@ -213,31 +215,18 @@ int xioctl(int fh, int request, void *arg){ #include #include - -void argusHardwareManager::enumerateHardware( void ){ - char tBuffer[CTEXT]; - DIR * dFD = NULL; - struct dirent * pDR = NULL; - struct ifaddrs * ifaddr = NULL; - //ToDo: Check Ability to work without Kernel and DBC +void argusHardwareManager::enumerateNIFS( void ){ + struct ifaddrs * ifaddr = NULL; + char tBuffer[128]; + bool ETHNIF = true; if( m_pKernel == NULL ) return; if( m_pDBC == NULL ) return; -#ifdef DEBUG - LOG("HW Enumeration Started!"); -#endif - // Moved to a constructor!! - //m_nServerNodeID = m_pKernel->getServerNodeId(); - //m_nServerID = m_pKernel->getServerId(); - //m_nSiteID = m_pKernel->getSiteId(); - /* Add Network Interfaces */ - - m_pDBC->cleanResources( m_nServerNodeID, true ); if( -1 == getifaddrs(&ifaddr)) { LOG_ERROR("No NET INTERFACES?!"); } else { -#ifdef DEBUG_EXTRA - LOG("NETWORK!"); +#ifdef DEBUG + LOG("Enumerating Network Interfaces"); #endif struct ifaddrs * ifa; char addr[INET6_ADDRSTRLEN]; @@ -249,11 +238,13 @@ void argusHardwareManager::enumerateHardware( void ){ LOG("NIF ***"); LOG( ifa->ifa_name ); #endif + ETHNIF = true; // Filter Loopback if if( strstr( ifa->ifa_name, "lo" ) != NULL ) continue; // Filter vpn TUN if if( strstr( ifa->ifa_name, "tun" ) != NULL ) continue; - if( ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6 ) continue; + if( ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6 ) continue; + if( strstr( ifa->ifa_name, "wlan" ) != NULL ) ETHNIF = false; if( ifa->ifa_addr->sa_family == AF_INET ){ // create IPv4 string struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr; @@ -271,11 +262,11 @@ void argusHardwareManager::enumerateHardware( void ){ (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5] ); sprintf( gw, "" ); - //sprintf( tBuffer, "NET4:%s", ifa->ifa_name ); - //m_pDBC->addNodeSocket( m_nServerNodeID, m_nServerID, ARGUS_NODE_SOCK_TYPE_NETWORK_IPV4, ARGUS_NODE_SOCK_MODE_INOUT, true, ifa->ifa_name, addr ); - uint32_t tID = m_pDBC->addLocalNetInterface( addr, mask, gw, bc ); + int RTYP = (ETHNIF)?ARGUS_HARDWARE_NETWORK_IPV4:ARGUS_HARDWARE_NETWORK_WIFI_IPV4; + sprintf( tBuffer, "RES[%d]:%s", RTYP, ifa->ifa_name ); + uint32_t tID = m_pDBC->addLocalNetInterface( tBuffer, addr, mask, gw, bc ); if( tID ) { - m_pDBC->addResource( m_nServerNodeID, ARGUS_HARDWARE_NETWORK_IPV4, addr, tID ); + m_pDBC->addResource( m_nServerNodeID, RTYP, addr, tID ); }; } else { // AF_INET6 // create IPv6 string @@ -322,20 +313,42 @@ void argusHardwareManager::enumerateHardware( void ){ sprintf( bc, "" ); }; sprintf( gw, "" ); - //sprintf( tBuffer, "NET6:%s", ifa->ifa_name ); - //m_pDBC->addNodeSocket( m_nServerNodeID, m_nServerID, ARGUS_NODE_SOCK_TYPE_NETWORK_IPV6, ARGUS_NODE_SOCK_MODE_INOUT, true, ifa->ifa_name, addr ); - uint32_t tID = m_pDBC->addLocalNetInterface( addr, mask, gw, bc ); + int RTYP = (ETHNIF)?ARGUS_HARDWARE_NETWORK_IPV6:ARGUS_HARDWARE_NETWORK_WIFI_IPV6; + sprintf( tBuffer, "RES[%d]:%s", RTYP, ifa->ifa_name ); + uint32_t tID = m_pDBC->addLocalNetInterface( tBuffer, addr, mask, gw, bc ); if( tID ) { - m_pDBC->addResource( m_nServerNodeID, ARGUS_HARDWARE_NETWORK_IPV6, addr, tID ); + m_pDBC->addResource( m_nServerNodeID, RTYP, addr, tID ); }; }; -#ifdef DEBUG_EXTRA - sprintf( tBuffer, "Network Interface: %s [%s]", ifa->ifa_name, addr ); +#ifdef DEBUG + sprintf( tBuffer, "Detected Network Interface: %s [%s]", ifa->ifa_name, addr ); LOG(tBuffer); #endif }; freeifaddrs( ifaddr ); }; +}; + +void argusHardwareManager::enumerateHardware( void ){ + char tBuffer[CTEXT]; + DIR * dFD = NULL; + struct dirent * pDR = NULL; + + //ToDo: Check Ability to work without Kernel and DBC + if( m_pKernel == NULL ) return; + if( m_pDBC == NULL ) return; +#ifdef DEBUG + LOG("HW Enumeration Started!"); +#endif + // Moved to a constructor!! + //m_nServerNodeID = m_pKernel->getServerNodeId(); + //m_nServerID = m_pKernel->getServerId(); + //m_nSiteID = m_pKernel->getSiteId(); + /* Add Network Interfaces */ + + m_pDBC->cleanResources( m_nServerNodeID, true ); + + enumerateNIFS(); /* Check HID Devices */ struct hid_device_info * pDevs; diff --git a/lib/rgoose/rgooseHardwareManager.h b/lib/rgoose/rgooseHardwareManager.h index 7ad0345a..e2aefa77 100644 --- a/lib/rgoose/rgooseHardwareManager.h +++ b/lib/rgoose/rgooseHardwareManager.h @@ -27,6 +27,7 @@ class argusHardwareManager{ uint32_t createResourceVIDEO( CSTR devName ); uint32_t createResourceUDCB( CSTR devName ); uint32_t createResourceNETWORK( CSTR devName ); + void enumerateNIFS( void ); public: virtual ~argusHardwareManager(); static argusHardwareManager * getInstance( bool cold_start = true ); diff --git a/lib/rgoose/rgooseModuleOnvifObserver.cpp b/lib/rgoose/rgooseModuleOnvifObserver.cpp index cbd9c492..beb71fe7 100644 --- a/lib/rgoose/rgooseModuleOnvifObserver.cpp +++ b/lib/rgoose/rgooseModuleOnvifObserver.cpp @@ -67,16 +67,14 @@ #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_ONVIF", this, _LOG_ERROR, X ); #endif -#define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_ONVIF_T", me, X ) -#define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_ONVIF_T", me, _LOG_ERROR, X ) argusModuleOnvifObserver::argusModuleOnvifObserver( uint32_t ModuleID ): argusKernelModule( ModuleID, ARGUS_MODULE_ONVIF_OBSERVER ), basicThread(){ m_bEnabled = false; m_pEventHeap = basicEventHeap::getInstance(); - m_pIpAddresses = NULL; - m_vResultPool.clear(); - m_nFinishedProbesCount = 0; - m_nNIFsCount = 0; + + m_bCurrentNIF = 0; + m_bProbeIsActive = false; + m_bDetached = false; #ifdef __linux__ m_bWSAOK = true; #else @@ -99,155 +97,155 @@ argusModuleOnvifObserver::~argusModuleOnvifObserver(){ bool argusModuleOnvifObserver::startService(){ LOG("Starting Service!"); if( !m_bWSAOK ) return false; - m_bEnabled = init(); - return m_bEnabled; + m_bEnabled = reloadSettings(); + return init(); }; bool argusModuleOnvifObserver::stopService( bool force ){ m_bEnabled = false; - waitThreadEnd( true ); - if( m_vThreads.size() ) { // Kill-Wait Started Probes -#ifdef DEBUG - char tB[128]; - sprintf( tB, "Have to Wait %d Probe(s)!", m_vThreads.size() ); - LOG( tB ); -#endif - for( vectorOBSERVER_CTX::iterator index = m_vThreads.begin(); index < m_vThreads.end(); index++ ) { - if( force ){ -#ifdef DEBUG - LOG("Force Cancel Probe!"); -#endif - pthread_cancel( (*index)->m_hThreadHandle ); - } else{ -#ifdef DEBUG - LOG("Wait Probe Exits!"); -#endif - pthread_join( (*index)->m_hThreadHandle, NULL ); + if( !m_bDetached ) m_bDetached = uninit(); + if( m_bDetached ) { + //Clear Results + m_mResultProtector.lock(); + if (m_vResultPool.size()){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ + free(*index); }; - free((*index)->context); - free((*index)); + m_vResultPool.clear(); }; - m_vThreads.clear(); + m_mResultProtector.unlock(); }; -#ifdef DEBUG - LOG("No More Probes!"); -#endif - m_mResultProtector.lock(); - if (m_vResultPool.size()){ // Clear structures - for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ - free(*index); - }; - m_vResultPool.clear(); - }; - m_mResultProtector.unlock(); -#ifdef DEBUG - LOG("Data is Cleared!"); -#endif - m_bDetached = true; return m_bDetached; }; void argusModuleOnvifObserver::m_fThreadProc(){ - m_bThreadStatus = TH_WORKING; - if( !m_bEnabled ) { - m_bThreadStatus = TH_ENDED; -#ifdef DEBUG - LOG("Module is Disabled!"); -#endif - }; + int socketFD; + int RetVal; + struct sockaddr_in r_address; + bool bOptVal; + int bOptLen; + int iOptLen; + uint8_t bCounterTO = 100; // 1 second + char rBuffer[MAX_BUFF_SIZE]; #ifdef DEBUG + char tB[128]; LOG("Module Started!"); #endif - + m_bDetached = false; + m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ) { - LOG("...Loop..."); - if( m_pKernel != NULL ){ + if ( m_bEnabled ) { + if ( m_bProbeIsActive ) { + if( socketFD > -1 ){ + if( bCounterTO-- ){ + memset( rBuffer, 0, MAX_BUFF_SIZE ); #ifdef DEBUG - LOG("Check IPS"); + struct sockaddr src_addr; + socklen_t addrlen = sizeof( src_addr ); + RetVal = recvfrom( socketFD, rBuffer, MAX_BUFF_SIZE, 0, &src_addr, &addrlen ); + sprintf( tB, "(%d){%d}MSG[%d] from %s", bCounterTO, socketFD, RetVal, inet_ntoa(((struct sockaddr_in *)&src_addr)->sin_addr) ); + LOG( tB ); +#else + RetVal = recvfrom( socketFD, rBuffer, MAX_BUFF_SIZE, 0, NULL, NULL ); #endif - argusHardwareManager *tHWM = m_pKernel->getHardwareManager(); - if( tHWM != NULL ) { - LOG("...HWM..."); - DBC_INT_LIST *rIDS = tHWM->requestResourcesByType( ARGUS_HARDWARE_PROVIDER_NETWORK ); - if( rIDS != NULL ) { - bool ProbeIsStarted = false; - for( DBC_INT_LIST::iterator idx = rIDS->begin(); idx < rIDS->end(); idx++ ){ - argusHardwareResourceNetwork *tRES = (argusHardwareResourceNetwork *) tHWM->requestResource( ARGUS_HARDWARE_PROVIDER_NETWORK, *idx ); - if( tRES != NULL ) { - CSTR BC = tRES->getBroadcast(); - if( BC!= NULL ) { + if ((RetVal == -1) && /*(errno != EAGAIN) &&*/ (errno != EINTR) && (errno != EWOULDBLOCK)) { + LOG_ERROR("Error acures while reading UDP package"); + close( socketFD ); + m_bProbeIsActive = false; + continue; // Error ocured but continue to next address + }; + if( RetVal < 1 ){ + SLEEP(DEFAULT_THREAD_SLEEP_TIME); + continue; // No Data - wait to next time + }; + OBSERVER_RESULT *tResult = parseXML( rBuffer ); + if ( tResult ) { + m_mResultProtector.lock(); + m_vResultPool.push_back( tResult ); + m_mResultProtector.unlock(); #ifdef DEBUG - LOG("Have BC Address"); - LOG(BC); + LOG("Probe Finished!"); #endif - startProbe( BC, m_nNIFsCount ); - ProbeIsStarted = true; + } else { #ifdef DEBUG - LOG("Probe Started"); + LOG("Probe Finished with unrecognized data!"); #endif - m_nNIFsCount++; - free( BC ); - } + }; + } else { #ifdef DEBUG - else { - LOG("NO BC Address"); - } + LOG("Probe Finished By Timeout!"); #endif - ; - } else { - LOG_ERROR("Cannot Get Resource!"); - }; - }; - delete( rIDS ); - if(ProbeIsStarted == false ){ - LOG("No Networks Detected!"); - m_bEnabled = false; }; - } else { - LOG("No Networks Detected!"); - m_bEnabled = false; +#ifdef __linux__ + close(socketFD); +#else + closesocket(socketFD); +#endif + }; + m_bProbeIsActive = false; + //Sleep 5 minutes if done all scans + if ( m_bCurrentNIF == 0 ){ + LOG("Going to sleep!"); + for( int i=30000; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + LOG("Waked Up!"); }; } else { - LOG_ERROR("No HW Manager"); - }; - } else { - LOG_ERROR("Kernel Not Assigned!" ); - }; + // start new probe; + LOG("Before Mutex"); + m_mNIFMUTEX.lock(); + LOG("After Mutex"); + if ( m_vNIFIPS.size() ) { +#ifdef DEBUG + sprintf( tB, "Starting probe on %s address", m_vNIFIPS.at(m_bCurrentNIF) ); + LOG( tB ); +#endif + socketFD = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); + if( socketFD > -1 ){ + CSTR send_buff = (CSTR)SEARCH_REQUEST_STRING; + r_address.sin_family = AF_INET; + r_address.sin_port = htons(HTTPMU_HOST_PORT); + r_address.sin_addr.s_addr = inet_addr(m_vNIFIPS.at(m_bCurrentNIF)); + bOptVal = true; #ifdef DEBUG - LOG("Start Default Probe"); - LOG( HTTPMU_HOST_ADDRESS ); + LOG("Sending Probe Request"); #endif - startProbe(HTTPMU_HOST_ADDRESS, m_nNIFsCount ); - m_nNIFsCount++; - while ( ( m_nFinishedProbesCount < m_nNIFsCount ) && ( m_bThreadStatus < TH_ENDED ) ) { - // Whait Till All Probes Finished - m_mThreadProtector.lock(); - for( vectorOBSERVER_CTX::iterator index = m_vThreads.begin(); index < m_vThreads.end(); index++ ) { - if( (*index)->context->isFinished ){ -#ifdef DEBUG_EXTRA - LOG("Probe Ended!"); + RetVal = setsockopt( socketFD, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen ); + RetVal = sendto( socketFD, send_buff, strlen(send_buff), 0, (struct sockaddr*)&r_address, sizeof(struct sockaddr_in)); + if ( RetVal > -1 ) { +#ifdef DEBUG + sprintf( tB, "Sent %d Bytes of %d", RetVal, strlen(send_buff) ); + LOG( tB ); #endif - pthread_join( (*index)->m_hThreadHandle, NULL ); +#ifdef __linux__ + fcntl( socketFD, F_SETFL, fcntl( socketFD, F_GETFL, 0) | O_NONBLOCK ); +#else + u_long val = 1; + ioctlsocket( socketFD, FIONBIO, &val );//none block +#endif + bCounterTO = 100; + m_bProbeIsActive = true; + } else { + // Failure to send probe package + LOG("Error in sending Probe Request"); +#ifdef __linux__ + close(socketFD); +#else + closesocket(socketFD); +#endif + }; + }; + m_bCurrentNIF++; + if ( m_bCurrentNIF == m_vNIFIPS.size() ) m_bCurrentNIF = 0; }; - free((*index)->context); - free((*index)); - m_vThreads.erase( index ); - m_nFinishedProbesCount++; + m_mNIFMUTEX.unlock(); }; - m_mThreadProtector.unlock(); - - for( int i=300; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( 100 ); -#ifdef DEBUG - char tT[128]; - sprintf( tT, "Finished %d Probes of %d ",m_nFinishedProbesCount, m_nNIFsCount ); - LOG( tT ); -#endif + } else { + //Sleep 3 Sec. + for( int i=300; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); }; - m_nNIFsCount = 0; - m_nFinishedProbesCount = 0; }; - LOG("---LOOP-FINISHED----"); + m_bDetached = true; }; void argusModuleOnvifObserver::dispatchEvent(EVENT_CONTAINER *Evt){ @@ -260,139 +258,118 @@ void argusModuleOnvifObserver::dispatchEvent(EVENT_CONTAINER *Evt){ }; bool argusModuleOnvifObserver::reloadSettings(){ - return true; -}; - -PROBE_CTX *argusModuleOnvifObserver::init_PROBE_CTX(CSTR ADR, int ID ){ - PROBE_CTX *RetVal; - RetVal = (PROBE_CTX*)malloc(sizeof(PROBE_CTX)); - if (RetVal == NULL) return NULL; - sprintf(RetVal->IpAddress, "%s", ADR); - RetVal->Port = HTTPMU_HOST_PORT; - RetVal->socketFD = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if( RetVal->socketFD !=-1 ){ - RetVal->send_buff = (CSTR)SEARCH_REQUEST_STRING; - RetVal->r_address.sin_family = AF_INET; - RetVal->r_address.sin_port = htons(RetVal->Port); - RetVal->r_address.sin_addr.s_addr = inet_addr(RetVal->IpAddress); - RetVal->bOptVal = true; - RetVal->bOptLen = sizeof(bool); - RetVal->iOptLen = sizeof(int); - RetVal->AddressID = ID; - RetVal->isFinished = false; - RetVal->observer = this; - return RetVal; - } else { - free( RetVal ); + m_mNIFMUTEX.lock(); + if( m_vNIFIPS.size() ) { + for ( vectorCSTR::iterator idx=m_vNIFIPS.begin(); idx < m_vNIFIPS.end(); idx++ ) free(*idx); + m_vNIFIPS.clear(); }; - return NULL; -}; - -void *argusModuleOnvifObserver::probeThreadProc( void *ptr ){ - PROBE_CTX *me; - if (ptr == NULL) return NULL; - me = (PROBE_CTX *)ptr; - if (me->observer == NULL ){ -#ifdef __linux__ - close(me->socketFD); -#else - closesocket(me->socketFD); -#endif + m_mNIFMUTEX.unlock(); + if( m_pKernel != NULL ){ #ifdef DEBUG - TLOG_ERROR("No Observer OBJ -> Probe Finished"); -#endif - me->isFinished = true; - return NULL; - }; - //Detach Self! - //pthread_detach( pthread_self() ); + LOG("Check IPS"); +#endif + argusHardwareManager *tHWM = m_pKernel->getHardwareManager(); + if( tHWM != NULL ) { + DBC_INT_LIST *rIDS = tHWM->requestResourcesByType( ARGUS_HARDWARE_PROVIDER_NETWORK ); + if( rIDS != NULL ) { + for( DBC_INT_LIST::iterator idx = rIDS->begin(); idx < rIDS->end(); idx++ ){ + argusHardwareResourceNetwork *tRES = (argusHardwareResourceNetwork *) tHWM->requestResource( ARGUS_HARDWARE_PROVIDER_NETWORK, *idx ); + if( tRES != NULL ) { + CSTR BC = tRES->getBroadcast(); + if( BC!= NULL ) { #ifdef DEBUG - //TLOG("Probe Request Sent"); + LOG("Have BC Address"); + LOG(BC); #endif - me->RetVal = setsockopt(me->socketFD, SOL_SOCKET, SO_BROADCAST, (char*)&me->bOptVal, me->bOptLen ); - me->RetVal = sendto(me->socketFD, me->send_buff, strlen(me->send_buff), 0, (struct sockaddr*)&me->r_address, sizeof(struct sockaddr_in)); + m_mNIFMUTEX.lock(); + m_vNIFIPS.push_back( BC ); + m_mNIFMUTEX.unlock(); #ifdef DEBUG - //sprintf(me->buff, "Sent %d Bytes", me->RetVal ); - //TLOG(me->buff); + LOG("NIF defined"); #endif -#ifdef __linux__ - fcntl( me->socketFD, F_SETFL, fcntl(me->socketFD, F_GETFL, 0) | O_NONBLOCK ); -#else - u_long val = 1; - ioctlsocket(me->socketFD, FIONBIO, &val);//none block -#endif - for( me->index = 1; me->index <= 10; me->index++ ){ - memset(me->buff, 0, sizeof(me->buff)); + } #ifdef DEBUG - struct sockaddr src_addr; - socklen_t addrlen = sizeof( src_addr ); - me->RetVal = recvfrom( me->socketFD, me->buff, MAX_BUFF_SIZE, 0, &src_addr, &addrlen ); - char TT[64]; - sprintf( TT, "{%d}MSG[%d] from %s", me->socketFD, me->RetVal, inet_ntoa(((struct sockaddr_in *)&src_addr)->sin_addr) ); - TLOG( TT ); -#else - me->RetVal = recvfrom( me->socketFD, me->buff, MAX_BUFF_SIZE, 0, NULL, NULL ); + else { + LOG("NO BC Address"); + } #endif - if( me->RetVal < 0 ){//SOCKET_ERROR){ - SLEEP(10); - continue; - }; - if( me->RetVal == 0 ) continue; // No Data + ; + } else { + LOG_ERROR("Cannot Get Resource!"); + }; + }; + delete( rIDS ); + } else { + LOG("No Networks Detected!"); + m_bEnabled = false; + }; + } else { + LOG_ERROR("No HW Manager"); + }; + } else { + LOG_ERROR("Kernel Not Assigned!" ); + }; +#ifdef DEBUG + LOG("Default Probe"); + LOG( HTTPMU_HOST_ADDRESS ); +#endif + CSTR tBC = (CSTR) malloc(16); + if ( tBC ) { + strncpy(tBC, HTTPMU_HOST_ADDRESS, 16); + m_mNIFMUTEX.lock(); + m_vNIFIPS.push_back( tBC ); + m_mNIFMUTEX.unlock(); + } else { + LOG_ERROR("Malloc Error!"); + }; + return true; +}; - me->recv_buff = me->buff; - XMLResults tParseResults; - XMLNode response = XMLNode::parseString( me->buff, "root", &tParseResults ); -#ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES - FILE *fd; - fd = fopen("ONVIF_MSGS.txt","a+"); - fprintf(fd,"++++++++++++++++++++\r\n"); - fprintf(fd,me->buff); - fprintf(fd,"--------------------\r\n"); - fclose(fd); -#endif +OBSERVER_RESULT *argusModuleOnvifObserver::parseXML( CSTR data ){ + OBSERVER_RESULT *retVal = NULL; + if( data!=NULL ){ + XMLResults tParseResults; + XMLNode response = XMLNode::parseString( data, "root", &tParseResults ); if( tParseResults.error ){ char tBuffer[CTEXT]; sprintf( tBuffer, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); - TLOG_ERROR( tBuffer ); + LOG_ERROR( tBuffer ); } else { if( response.isEmpty() ){ - TLOG_ERROR("The device descripe XML file is not a valid XML file. Cann't find root element."); - continue; + LOG_ERROR("The device descripe XML file is not a valid XML file. Cann't find root element."); } else { #ifdef DEBUG - TLOG_ERROR("Probe XML parsed"); + LOG("Probe XML parsed"); #endif XMLNode Body = response.getChildNode( "Body", 0 ); if(!Body.isEmpty()){ - TLOG("Have Body elm"); + LOG("Have Body elm"); XMLNode ProbeMatches = Body.getChildNode("ProbeMatches", 0);//EndpointReference if(!ProbeMatches.isEmpty()) { - TLOG("Have ProbeMathes elm"); + LOG("Have ProbeMathes elm"); int matches = ProbeMatches.nChildNode(); for(int index=0;indexresultID = me->AddressID; + retVal = (OBSERVER_RESULT *)malloc(sizeof(OBSERVER_RESULT)); + if( retVal != NULL ){ + memset( retVal, 0, sizeof(OBSERVER_RESULT)); if(!ProbeMatch.isEmpty()) { - TLOG("Have ProbeMatch elm"); + LOG("Have ProbeMatch elm"); { XMLNode node = ProbeMatch.getChildNode("EndpointReference", 0); if(!node.isEmpty()) { - TLOG("Have ProbeMatch EndpointReference"); + LOG("Have ProbeMatch EndpointReference"); XMLNode nod = node.getChildNode("Address", 0); if(!nod.isEmpty()){ char tBuf[CLOG]; sprintf(tBuf,"%s", nod.getText(0)); CArray *tArr; - TLOG("Before Explode"); + LOG("Before Explode"); tArr = explode(':',tBuf); - TLOG("After Explode"); + LOG("After Explode"); for(int j=0; jsize(); j++) { if( strlen(tArr->at(j)) > 10 ) { - sprintf(tRecord->RefID,"%s",tArr->at(j)); + sprintf(retVal->RefID,"%s",tArr->at(j)); break; }; }; @@ -409,7 +386,7 @@ void *argusModuleOnvifObserver::probeThreadProc( void *ptr ){ sprintf(tBuf,"%s", node.getText(0)); CArray *tArr; tArr = explode(' ',tBuf); - sprintf(tRecord->Type,"%s",tArr->at(0)); + sprintf(retVal->Type,"%s",tArr->at(0)); tArr->clear(); delete(tArr); } @@ -417,29 +394,28 @@ void *argusModuleOnvifObserver::probeThreadProc( void *ptr ){ { XMLNode node = ProbeMatch.getChildNode("Scopes", 0); char tBuf[CLOG]; - sprintf(tBuf,"%s", node.getText(0)); - CArray *tArr; - tArr = explode(' ',tBuf); + sprintf( tBuf,"%s", node.getText(0) ); + CArray *tArr = explode(' ',tBuf); if( tArr->size() > 0 ) { for( int index = 0; index < tArr->size(); index++){ char *tPtr; if( tPtr = strstr( tArr->at(index), "mac/" ) ){ - sprintf(tRecord->MAC,"%s",tPtr+4); + sprintf(retVal->MAC,"%s",tPtr+4); }; if( tPtr = strstr( tArr->at(index), "hardware/" ) ){ - sprintf(tRecord->Hardware,"%s",tPtr+9); + sprintf(retVal->Hardware,"%s",tPtr+9); }; if( tPtr = strstr( tArr->at(index), "name/" ) ){ - sprintf(tRecord->Name,"%s",tPtr+5); + sprintf(retVal->Name,"%s",tPtr+5); }; if (tPtr = strstr(tArr->at(index), "MAC/")) { - sprintf(tRecord->MAC, "%s", tPtr + 4); + sprintf(retVal->MAC, "%s", tPtr + 4); }; if (tPtr = strstr(tArr->at(index), "HARDWARE/")) { - sprintf(tRecord->Hardware, "%s", tPtr + 9); + sprintf(retVal->Hardware, "%s", tPtr + 9); }; if (tPtr = strstr(tArr->at(index), "NAME/")) { - sprintf(tRecord->Name, "%s", tPtr + 5); + sprintf(retVal->Name, "%s", tPtr + 5); }; }; tArr->clear(); @@ -458,7 +434,7 @@ void *argusModuleOnvifObserver::probeThreadProc( void *ptr ){ // IPv6 } else{ // IPv4 - sprintf(tRecord->XAddrs,"%s",tArr->at(0)); + sprintf(retVal->XAddrs,"%s",tArr->at(0)); }; }; tArr->clear(); @@ -466,100 +442,36 @@ void *argusModuleOnvifObserver::probeThreadProc( void *ptr ){ delete(tArr); } }; - me->observer->m_mResultProtector.lock(); - TLOG("FF"); - me->observer->m_vResultPool.push_back(tRecord); - me->observer->m_mResultProtector.unlock(); - TLOG("FA"); }; }; }; }; }; }; - }; - TLOG("BB"); -#ifdef __linux__ - close(me->socketFD); -#else - closesocket(me->socketFD); -#endif -#ifdef DEBUG - TLOG("Probe Finished"); -#endif - me->isFinished = true; - return NULL; -}; - -bool argusModuleOnvifObserver::startProbe( CSTR IP, int ID ){ -#ifdef DEBUG_EXTRA - LOG("Starting Probe!"); - LOG( IP ); -#endif - PROBE_CTX *tVal = init_PROBE_CTX( IP, ID ); - if( tVal == NULL ) return false; - - OBSERVER_CTX *tThread; - tThread = (OBSERVER_CTX *) malloc(sizeof(OBSERVER_CTX)); - if( tThread != NULL ){ - memset( tThread, 0, sizeof(OBSERVER_CTX)); -#ifdef __linux__ - int RetVal = pthread_create( &tThread->m_hThreadHandle, NULL, probeThreadProc, ( void * ) tVal ); - if( RetVal == -1 ) { - LOG_ERROR("Thread Creation Faled."); - free(tVal); - free(tThread); - return false; - }; -#else - tThread->m_hThreadHandle = CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE)probeThreadProc, - (LPVOID)tVal, - 0, - &tThread->m_dwThreadID); - if( tThread->m_hThreadHandle==NULL ){ - LOG_ERROR("Thread Creation Faled."); - free(tVal); - free(tThread); - return false; - }; -#endif - tThread->context = tVal; - m_mThreadProtector.lock(); - m_vThreads.push_back(tThread); - m_mThreadProtector.unlock(); -#ifdef DEBUG_EXTRA - LOG("Probe Created"); -#endif - return true; - } else { - LOG_ERROR("Can not allocate Memory for Probe CTX"); - free(tVal); }; - return false; + return retVal; }; + bool argusModuleOnvifObserver::validate(){ m_mResultProtector.lock(); if( m_vResultPool.size() ){ // Clear structures for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ -#ifdef DEBUG_EXTRA +#ifdef DEBUG char tBuffer[256]; sprintf( tBuffer, "Found Camwera [%s] %s", (*index)->XAddrs, (*index)->RefID ); LOG( tBuffer ); #endif uint32_t cid = m_pDBC->getCamId( (*index)->RefID ); //isCameraListed( DiscoverResults->at(index)->RefID ); if( cid ) { -#ifdef DEBUG_EXTRA +#ifdef DEBUG sprintf( tBuffer, "Camera is Listed as %d", cid ); LOG( tBuffer ); #endif m_pDBC->updateIPCam( m_pKernel->getSiteId(), cid, (*index)->XAddrs );// DiscoverResults->at(index)); } else { // Uncknown camera - no checking -#ifdef DEBUG_EXTRA +#ifdef DEBUG LOG("Camera is Not Listed"); #endif m_pDBC->addIPCam( m_pKernel->getSiteId(), (*index) ); @@ -583,6 +495,4 @@ bool argusModuleOnvifObserver::validate(){ #undef LOG #undef LOG_ERROR -#undef TLOG -#undef TLOG_ERROR diff --git a/lib/rgoose/rgooseModuleOnvifObserver.h b/lib/rgoose/rgooseModuleOnvifObserver.h index dacd10b0..bfae3834 100644 --- a/lib/rgoose/rgooseModuleOnvifObserver.h +++ b/lib/rgoose/rgooseModuleOnvifObserver.h @@ -56,23 +56,22 @@ typedef std::vector vectorOBSERVER_CTX; class argusModuleOnvifObserver: public argusKernelModule, public basicThread { private: basicEventHeap * m_pEventHeap; - enumeratorInfo m_vLocalDevices; + //enumeratorInfo m_vLocalDevices; + //localIpAddresses m_vIpAddresses; - localIpAddresses * m_pIpAddresses; - sourcePool m_vUsedDevices; - basicMutex m_mResultProtector; vectorOBSERVER_RESULT m_vResultPool; - basicMutex m_mThreadProtector; - vectorOBSERVER_CTX m_vThreads; - + basicMutex m_mResultProtector; + basicMutex m_mNIFMUTEX; + vectorCSTR m_vNIFIPS; + bool m_bProbeIsActive; bool m_bWSAOK; - int m_nFinishedProbesCount; - int m_nNIFsCount; + uint8_t m_bCurrentNIF; - PROBE_CTX * init_PROBE_CTX( CSTR ADR, int ID ); - bool loadAssignedSources(void); - bool startProbe( CSTR IP, int ID ); - static void * probeThreadProc(void *); + //PROBE_CTX * init_PROBE_CTX( CSTR ADR, int ID ); + //bool loadAssignedSources(void); + //bool startProbe( CSTR IP, int ID ); + //static void * probeThreadProc(void *); + OBSERVER_RESULT * parseXML( CSTR data ); protected: virtual void m_fThreadProc( void ); diff --git a/lib/rgoose/rgooseNodeFactory.cpp b/lib/rgoose/rgooseNodeFactory.cpp index b72c910b..93c70102 100644 --- a/lib/rgoose/rgooseNodeFactory.cpp +++ b/lib/rgoose/rgooseNodeFactory.cpp @@ -539,7 +539,7 @@ void argusNodeFactory::m_fThreadProc( void ){ LOG( MEM_MSG ); #endif #endif - for( int i = ( 5000 / DEFAULT_THREAD_SLEEP_TIME ); i && ( m_bThreadStatus < TH_ENDED ); i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + for( int i = ( 15000 / DEFAULT_THREAD_SLEEP_TIME ); i && ( m_bThreadStatus < TH_ENDED ); i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); }; }; LOG("EXIT FROM CTRL THREAD"); diff --git a/lib/rgoose/rgooseNodePTZCamControl.cpp b/lib/rgoose/rgooseNodePTZCamControl.cpp index 7bfd8fa8..c74d180e 100644 --- a/lib/rgoose/rgooseNodePTZCamControl.cpp +++ b/lib/rgoose/rgooseNodePTZCamControl.cpp @@ -185,22 +185,18 @@ bool ARGUS_PTZCAM::validate(){ }*/ // Validate Stream { -#ifdef DEBUG - LOG("Validation Stage 2"); -#endif + LOG("VALIDATE Stream"); + if( m_sNodeData.aux_parameter ) { // Has Choosed Stream if( !m_bSourceConnected ) { - if( m_sNodeData.aux_parameter ) { // Has Choosed Stream - if( connectToStream( m_sNodeData.aux_parameter ) ){ - //DBC_MEDIA_STREAM_DATA *tDATA = argusNetNode::m_pDBC->getMediaStreamData( m_sNodeData.aux_parameter ); - m_bSourceConnected = true; - return argusNetNode::m_pDBC->setStreamValid( m_sNodeData.aux_parameter ); + LOG("Not Connected->Connecting"); + if( connectToStream( m_sNodeData.aux_parameter ) ) { + argusNetNode::m_pDBC->setStreamValid( m_sNodeData.aux_parameter ); + } else return false; + } else { + LOG("Connected->Check Stream"); + if (!validateStream()) return false; + LOG("Stream Checked!"); }; - }; - } else { -#ifdef DEBUG - LOG("Validation Stage 3"); -#endif - return validateStream(); }; } return true; diff --git a/lib/rgoose/rgooseNodeStaticCamControl.cpp b/lib/rgoose/rgooseNodeStaticCamControl.cpp index c9bf6034..01a74b40 100644 --- a/lib/rgoose/rgooseNodeStaticCamControl.cpp +++ b/lib/rgoose/rgooseNodeStaticCamControl.cpp @@ -41,6 +41,7 @@ ARGUS_CAM::ARGUS_CAM( DBC_NODE_DATA *Data ): basicEventHandler(), argusNetNode( ARGUS_CAM::ARGUS_CAM( uint32_t id ): basicEventHandler(), argusNetNode( id ), ARGUS_Camera(){ m_pLog = basicLogCollection::getInstance(); m_sMediaSource.mediaSourceId = m_sNodeData.aux_id; + memset( &m_sCtrlData, 0, sizeof( CAMERA_CTRL_DATA )); }; ARGUS_CAM::~ARGUS_CAM(){ diff --git a/lib/rgoose/rgooseTypes.h b/lib/rgoose/rgooseTypes.h index a7def9a8..e8ff2176 100644 --- a/lib/rgoose/rgooseTypes.h +++ b/lib/rgoose/rgooseTypes.h @@ -120,6 +120,8 @@ typedef enum E_ARGUS_HARDWARE_PROVIDERS{ ARGUS_HARDWARE_PROVIDER_DRY_CONTACT = 4 } ARGUS_HARDWARE_PROVIDERS; +typedef std::vector vectorCSTR; + typedef enum E_ARGUS_HARDWARE_TYPE{ ARGUS_HARDWARE_UNKNOWN = 0, ARGUS_HARDWARE_UART = 1, @@ -130,7 +132,9 @@ typedef enum E_ARGUS_HARDWARE_TYPE{ ARGUS_HARDWARE_DIGITAL_VIDEO_IN = 33, ARGUS_HARDWARE_NETWORK_IPV4 = 100, ARGUS_HARDWARE_NETWORK_IPV6 = 101, - ARGUS_HARDWARE_NETWORK_WIFI_AP = 120, + ARGUS_HARDWARE_NETWORK_WIFI_IPV4 = 120, + ARGUS_HARDWARE_NETWORK_WIFI_IPV6 = 121, + ARGUS_HARDWARE_NETWORK_WIFI_AP = 125, ARGUS_HARDWARE_IP_UART = 129, ARGUS_HARDWARE_IP_VIDEO_OUT = 130, ARGUS_HARDWARE_IP_VIDEO_IN = 131