You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1189 lines
34 KiB

#include "videoAVLIBSource.h"
#ifndef LRF_PROXY_ONLY
//#define DEBUG_EXTRA
#include "libavutil/error.h"
#define LOG(X) m_pLog->Log("LibAV_SRC", this, X)
#ifdef DEBUG
#define LOG_ERROR(X) \
{ \
char _tBfrErrMSG2w34[4096]; \
sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
m_pLog->Log("LIBAV_SRC", this, _LOG_ERROR, _tBfrErrMSG2w34); \
}
#else
#define LOG_ERROR(X) m_pLog->Log("LIBAV_SRC", this, _LOG_ERROR, X);
#endif
static int interrupt_cb(void * ctx)
{
if ( ctx != NULL ) {
basicLogCollection::getInstance()->Log("LibAV_CB", NULL, "INTERUPT!");
}
// do something
return 0;
}
static const AVIOInterruptCB int_cb = {interrupt_cb, NULL};
// https://ffmpeg.org/doxygen/3.4/ffplay_8c_source.html#l02732
videoAVLIBSource::videoAVLIBSource(void * opaque) :
basicMediaSource(),
basicThread()
{
m_pLog = basicLogCollection::getInstance();
m_bStreamingSource = true;
m_bSizeIsAutomatic = false;
m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1;
m_bSrcType = AVLIB_SOURCE_NOTDEF;
if (opaque)
{
m_pOpaque = opaque;
}
else
{
m_pOpaque = (void *) this;
};
if (! initLibAV())
{
return;
}
m_pVideoState = (VideoState *) av_mallocz(sizeof(VideoState));
if (m_pVideoState == NULL)
{
LOG_ERROR("VideoState Memory Allocation Error");
return;
};
m_eMediaStatus = m_pVideoState->m_bStatus = MS_UNDEFINED;
m_pVideoState->m_iVideoStreamID = -1;
#ifndef _NOAUDIO_
m_pVideoState->m_iAudioStreamID = -1;
#endif
m_pVideoState->m_bStatus = MS_INIT;
}
videoAVLIBSource::videoAVLIBSource(char * Source, void * opaque) :
basicMediaSource(),
basicThread()
{
m_pLog = basicLogCollection::getInstance();
m_bStreamingSource = true;
m_bSizeIsAutomatic = false;
m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1;
m_bSrcType = AVLIB_SOURCE_NOTDEF;
if (opaque)
{
m_pOpaque = opaque;
}
else
{
m_pOpaque = (void *) this;
};
if (! initLibAV())
{
return;
}
m_pVideoState = (VideoState *) av_mallocz(sizeof(VideoState));
if (m_pVideoState == NULL)
{
LOG_ERROR("VideoState Memory Allocation Error");
return;
};
m_eMediaStatus = m_pVideoState->m_bStatus = MS_UNDEFINED;
m_pVideoState->m_pFormatCtx = avformat_alloc_context();
if (m_pVideoState->m_pFormatCtx == NULL)
{
LOG_ERROR("Video Format Context Memory Allocation Error");
return;
};
m_pVideoState->m_iVideoStreamID = -1;
#ifndef _NOAUDIO_
m_pVideoState->m_iAudioStreamID = -1;
#endif
m_pVideoState->m_bStatus = MS_INIT;
_open(Source);
}
videoAVLIBSource::~videoAVLIBSource()
{
LOG("Destructor");
if (m_pVideoState != NULL)
{
_close();
av_free(m_pVideoState);
m_pVideoState = NULL;
};
}
bool videoAVLIBSource::setOutputSize(int Width, int Height)
{
if (m_pVideoState)
{
if (m_pVideoState->m_bStatus == MS_INIT)
{
if (Width && Height)
{
m_bSizeIsAutomatic = false;
m_nOutWidth = Width;
m_nOutHeight = Height;
return true;
};
};
};
return false;
}
bool videoAVLIBSource::setProportionalByWidth(int Width)
{
if (m_pVideoState)
{
if (m_pVideoState->m_bStatus == MS_INIT)
{
if (Width > 0)
{
m_bSizeIsAutomatic = true;
m_nOutWidth = Width;
return true;
};
};
};
return false;
}
bool videoAVLIBSource::setProportionalByHeight(int Height)
{
if (m_pVideoState)
{
if (m_pVideoState->m_bStatus == MS_INIT)
{
if (Height > 0)
{
m_bSizeIsAutomatic = true;
m_nOutHeight = Height;
return true;
};
};
};
return false;
}
bool videoAVLIBSource::setFrameAspectRatio(FrameAspectRatio AspectRatio)
{
if( AspectRatio ) AspectRatio = AspectRatio;
return true;
}
bool videoAVLIBSource::_close(void)
{
LOG("CLOSE");
// set Close Status - to prevent continue
m_eMediaStatus = m_pVideoState->m_bStatus = MS_CLOSED;
if (m_pVideoState == NULL)
{
return true;
}
m_pMediaDestination = NULL; //??
//_stop(); //stops the Thread
basicThread::waitThreadEnd(true);
if (m_pVideoState->m_pFormatOpts)
{
av_dict_free(&m_pVideoState->m_pFormatOpts);
m_pVideoState->m_pFormatOpts = NULL;
};
if (m_pVideoState->m_pFormatCtx)
{
avformat_close_input(&m_pVideoState->m_pFormatCtx);
m_pVideoState->m_iVideoStreamID = -1;
};
if (m_pVideoState->m_bStatus > MS_INIT)
{
#if (LIBAVCODEC_VERSION_MAJOR < 58) // && ( LIBAVCODEC_VERSION_MINOR < 50 )
#ifndef _NOAUDIO_
if (m_pVideoState->m_pAudioCtx != NULL)
{
avcodec_close(m_pVideoState->m_pAudioCtx);
avcodec_free_context(&m_pVideoState->m_pAudioCtx);
};
#endif
if (m_pVideoState->m_pCodecCtx != NULL)
{
avcodec_close(m_pVideoState->m_pCodecCtx);
m_pVideoState->m_iVideoStreamID = -1;
};
#else
#ifndef _NOAUDIO_
if (m_pVideoState->m_pAudioCtx != NULL)
{
avcodec_close(m_pVideoState->m_pAudioCtx);
avcodec_free_context(&m_pVideoState->m_pAudioCtx);
};
#endif
if (m_pVideoState->m_pCodecCtx != NULL)
{
avcodec_close(m_pVideoState->m_pCodecCtx);
avcodec_free_context(&m_pVideoState->m_pCodecCtx);
};
#endif
m_eMediaStatus = m_pVideoState->m_bStatus = MS_INIT;
};
sws_freeContext(m_pVideoState->m_pSwsCtx);
return true;
}
bool videoAVLIBSource::_continue(void)
{
if (m_pVideoState->m_bStatus == MS_STOPED)
{
return basicThread::init();
};
return false;
}
bool videoAVLIBSource::_stop(void)
{
LOG("STOP");
return basicThread::uninit();
}
// https://www.youtube.com/watch?v=Lu3LZmhC_DY
bool videoAVLIBSource::_restart(void)
{
if (m_pVideoState == NULL)
{
return false;
}
if (m_pVideoState->m_bStatus < MS_OPENED)
{
return false;
}
if (m_pVideoState->m_pFormatCtx == NULL)
{
LOG_ERROR("Video Format Context Memory Allocation Error");
return false;
};
// Stop Thread
basicThread::uninit();
int RetVal;
switch (m_bSrcType)
{
case AVLIB_SOURCE_DDSHOW:
{
//const added for ffmpeg 60
const AVInputFormat * iformat = av_find_input_format("dshow");
if ((RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, iformat, &m_pVideoState->m_pFormatOpts)) != 0)
{
char tB[2048];
// av_free( iformat );
char tBuffer[128];
av_strerror(RetVal, tBuffer, 128);
sprintf(tB, "VideoSource Couldn't open input device[%s](Code:%d): %s", tBuffer, RetVal, m_pVideoState->m_pFileName);
LOG_ERROR(tB);
m_eMediaStatus = m_pVideoState->m_bStatus = MS_INIT;
return false;
};
break;
};
case AVLIB_SOURCE_V4L2:
case AVLIB_SOURCE_IPSTREAM:
{
if ((RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts)) != 0)
{
// av_dict_free(&options);
char tB[2048];
char tBuffer[128];
av_strerror(RetVal, tBuffer, 128);
sprintf(tB, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, RetVal, m_pVideoState->m_pFileName);
LOG_ERROR(tB);
m_eMediaStatus = m_pVideoState->m_bStatus = MS_INIT;
return false;
};
break;
};
};
#ifdef DEBUG
LOG("DataStream Opened");
#endif
m_eMediaStatus = m_pVideoState->m_bStatus = MS_OPENED;
if (avformat_find_stream_info(m_pVideoState->m_pFormatCtx, NULL) < 0)
{
char tB[2048];
sprintf(tB, "Couldn't find stream information: %s", m_pVideoState->m_pFileName);
LOG_ERROR(tB);
return false;
};
#if (LIBAVCODEC_VERSION_MAJOR < 58) // && ( LIBAVCODEC_VERSION_MINOR < 50 )
for (unsigned int i = 0; i < m_pVideoState->m_pFormatCtx->nb_streams; i++)
{
// if( m_pVideoState->m_pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){
if (m_pVideoState->m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
LOG("VIDEO stream detected.");
if (m_pVideoState->m_iVideoStreamID < 0)
{
LOG("VIDEO stream assigned.");
m_pVideoState->m_iVideoStreamID = i;
};
};
#ifndef _NOAUDIO_
if (m_pVideoState->m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
LOG("AUDIO stream detected.");
if (m_pVideoState->m_iAudioStreamID < 0)
{
LOG("AUDIO stream assigned.");
m_pVideoState->m_iAudioStreamID = i;
}
};
#endif
};
if (m_pVideoState->m_iVideoStreamID == -1)
{
LOG_ERROR("Didn't find a video stream.");
return false;
};
#ifndef _NOAUDIO_
if (m_pVideoState->m_iAudioStreamID == -1)
{
LOG_ERROR("Didn't find a audio stream.");
return false;
};
#endif
// Stream found
m_pVideoState->m_pCodecCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID]->codec;
// m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID]->codecpar->codec_id
m_pVideoState->m_pVideoCodec = avcodec_find_decoder(m_pVideoState->m_pCodecCtx->codec_id);
#else
#ifdef DEBUG_EXTRA
LOG("YABABA-2!");
#endif
/* find the video stream information */
//cast ffmpeg 60
m_pVideoState->m_iVideoStreamID = av_find_best_stream(m_pVideoState->m_pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, const_cast<const AVCodec**>(&m_pVideoState->m_pVideoCodec), 0);
if (m_pVideoState->m_iVideoStreamID == -1)
{
LOG_ERROR("Didn't find a video stream.");
return false;
};
#ifndef _NOAUDIO_
if (m_pVideoState->m_iAudioStreamID == -1)
{
LOG_ERROR("Didn't find a audio stream.");
return false;
};
#endif
if (! (m_pVideoState->m_pCodecCtx = avcodec_alloc_context3(m_pVideoState->m_pVideoCodec)))
{
LOG_ERROR("Can not create decoder context!");
return false;
};
m_pVideoState->m_pVideoStr = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID];
if (avcodec_parameters_to_context(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoStr->codecpar) < 0)
{
LOG_ERROR("Can not set Context parameters!");
return false;
};
#endif
if (m_pVideoState->m_pVideoCodec == NULL)
{
char tB[2048];
// sprintf(Buffer, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, m_pVideoState->m_pFileName);
sprintf(tB, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, m_pVideoState->m_pFileName);
LOG_ERROR(tB);
return false;
};
/*
End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2())
and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE).
Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool.
*/
m_pVideoState->m_pCodecCtx->thread_count = 4;
// m_pVideoState->m_pCodecCtx->thread_type = FF_THREAD_FRAME;
// if (is_live)
m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE;
// else
// m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE | FF_THREAD_FRAME;
#ifdef DEBUG_EXTRA
LOG("Before Open2");
#endif
if (avcodec_open2(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoCodec, NULL) < 0)
{
char tB[2048];
sprintf(tB, "Could not open Video codec[%d] for %s", m_pVideoState->m_pCodecCtx->codec_id, m_pVideoState->m_pFileName);
LOG_ERROR(tB);
return false;
};
/* we do not send complete frames */
// if( m_pVideoState->m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_pVideoState->m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED;
#ifndef _NOAUDIO_
m_pVideoState->m_pAudioCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iAudioStreamID]->codec;
m_pVideoState->m_pAudioCodec = avcodec_find_decoder(m_pVideoState->m_pAudioCtx->codec_id);
if (! m_pVideoState->m_pAudioCodec)
{
LOG_ERROR("Unsupported Audio codec!");
return false;
};
if (avcodec_open2(m_pVideoState->m_pAudioCtx, m_pVideoState->m_pAudioCodec, NULL) < 0)
{
// SDL_LogError( SDL_LOG_CATEGORY_AUDIO, "Could not open Audio codec[%d].", m_pVideoState->m_pAudioCtx->codec_id );
LOG_ERROR("Could not open Audio codec.");
return false;
};
#endif
return basicThread::init();
}
bool videoAVLIBSource::_open(char * URI, bool ShowDeviceMenu, float framerate, int inputPin, int width, int height, int s_width, int s_height)
{
if (URI == NULL)
{
return false;
}
if (m_pVideoState == NULL)
{
return false;
}
if (m_bThreadStatus > TH_PRE_INIT)
{
return false;
}
m_pVideoState->m_pFormatCtx = avformat_alloc_context();
if (m_pVideoState->m_pFormatCtx == NULL)
{
LOG_ERROR("Video Format Context Memory Allocation Error");
return false;
};
if (m_pVideoState->m_bStatus == MS_INIT)
{
char Buffer[1248] = {0};
char tChar[128] = {0};
strncpy(m_pVideoState->m_pFileName, URI, MAX_PATH_LEN);
CSTR tMD5 = MD5String(m_pVideoState->m_pFileName);
if (tMD5)
{
sprintf(m_pCookie, "%s", tMD5);
free(tMD5);
}
else
{
sprintf(m_pCookie, "some-random-id");
}
m_eMediaStatus = m_pVideoState->m_bStatus = MS_OPENING;
if (strncmp(m_pVideoState->m_pFileName, "video=", 6) == 0)
{
m_bSrcType = AVLIB_SOURCE_DDSHOW;
#ifdef DEBUG
LOG("MS-Video Device");
#endif
// AVDictionary *options = NULL;
if (width != -1 && height != -1)
{
m_bSizeIsAutomatic = false;
char tChar[10];
sprintf(tChar, "%dx%d", width, height);
av_dict_set(&m_pVideoState->m_pFormatOpts, "video_size", tChar, 0);
}
else
{
// m_bSizeIsAutomatic = true;
};
// av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "yuyv422", 0 );
av_dict_set(&m_pVideoState->m_pFormatOpts, "video_codec", "mjpeg", 0);
if (inputPin != -1)
{
sprintf(tChar, "%d", inputPin);
av_dict_set(&m_pVideoState->m_pFormatOpts, "crossbar_video_input_pin_number", tChar, 0);
};
if (framerate != -1)
{
sprintf(tChar, "%f", framerate);
av_dict_set(&m_pVideoState->m_pFormatOpts, "framerate", tChar, 0);
};
av_dict_set(&m_pVideoState->m_pFormatOpts, "rtbufsize", "500000k", 0);
if (ShowDeviceMenu)
{
av_dict_set(&m_pVideoState->m_pFormatOpts, "show_video_device_dialog", "true", 0);
av_dict_set(&m_pVideoState->m_pFormatOpts, "show_video_crossbar_connection_dialog", "true", 0);
// sprintf(Buffer, "data/%s.settings", m_pCookie);
// av_dict_set(&options, "video_device_save", Buffer, 0);
#ifndef _NOAUDIO_
av_dict_set(&m_pVideoState->m_pFormatOpts, "show_audio_crossbar_connection_dialog", "true", 0);
sprintf(Buffer, "%s-a.settings", URI);
av_dict_set(&m_pVideoState->m_pFormatOpts, "audio_device_save", Buffer, 0);
#endif
}
else
{
sprintf(Buffer, "data/%s.settings", m_pCookie);
// if (!fileExist(Buffer)) av_dict_set(&m_pVideoState->m_pFormatOpts, "video_device_load", Buffer, 0);
};
// av_dict_set(&m_pVideoState->m_pFormatOpts, "crossbar_video_input_pin_number", "1", 0);
// av_dict_set(&m_pVideoState->m_pFormatOpts, "show_audio_crossbar_connection_dialog", "true", 0);
// av_dict_set(&m_pVideoState->m_pFormatOpts, "show_video_crossbar_connection_dialog", "true", 0);
// AVInputFormat * is Internal Const in CoDec Lib
const AVInputFormat * iformat = av_find_input_format("dshow");
// av_dict_set(&options, "pixel_format", "bgr24", 0);
av_dict_set(&m_pVideoState->m_pFormatOpts, "timeout", "5000", 0);
// AVDeviceInfoList *device_list;
// m_pVideoState->m_pFormatCtx->iformat = iformat;
// avdevice_list_devices(m_pVideoState->m_pFormatCtx, &device_list);
// avdevice_free_list_devices(&device_list);
if (avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, iformat, &m_pVideoState->m_pFormatOpts) != 0)
{
av_dict_free(&m_pVideoState->m_pFormatOpts);
m_pVideoState->m_pFormatOpts = NULL;
sprintf(Buffer, "VideoSource Couldn't open input device: %s", URI);
LOG_ERROR(Buffer);
m_eMediaStatus = m_pVideoState->m_bStatus = MS_INIT;
return false;
};
/*AVDictionaryEntry *e;
if (e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
sprintf(Buffer, "Option %s not recognized by the demuxer", e->key);
LOG_ERROR(Buffer);
};*/
// if (iformat!=NULL)
// if (iformat->priv_class != NULL){
// const AVOption *cOption = NULL;
// while((cOption = av_opt_next(&iformat->priv_class, cOption))!= NULL )
// serializeOption(cOption);
// };
// av_dict_free(&options);
// AVOption *mpOption = NULL;
}
else
{
if (strncmp(URI, "/dev/video", 10) == 0)
{
m_bSrcType = AVLIB_SOURCE_V4L2;
}
else
{
m_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(&m_pVideoState->m_pFormatOpts, "rtsp_transport", "tcp", 0);
av_dict_set(&m_pVideoState->m_pFormatOpts, "stimeout", "5000000", 0);
av_dict_set(&m_pVideoState->m_pFormatOpts, "buffer_size", "4096000", 0);
/*
av_dict_set_int(&opts, "rw_timeout", 5000000, 0);
av_dict_set_int(&opts, "tcp_nodelay", 1, 0);
av_dict_set_int(&opts, "stimeout", 10000000, 0);
av_dict_set(&opts, "user_agent", "Mozilla/5.0", 0);
av_dict_set(&opts, "rtsp_transport", "tcp", 0);
av_dict_set(&opts, "rtsp_flags", "prefer_tcp", 0);
av_dict_set_int(&opts, "buffer_size", BUFSIZE, 0);
pFormatCtx->flags |= AVFMT_FLAG_NONBLOCK;
pFormatCtx->flags |= AVFMT_FLAG_DISCARD_CORRUPT;
pFormatCtx->flags |= AVFMT_FLAG_NOBUFFER;
*/
}
else
{
#ifdef DEBUG
LOG("Linux Video Device");
#endif
if (width != -1 && height != -1)
{
m_bSizeIsAutomatic = false;
sprintf(tChar, "%dx%d", width, height);
av_dict_set(&m_pVideoState->m_pFormatOpts, "video_size", tChar, 0);
switch (inputPin)
{
case 0:
LOG("PIX YUYV");
av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "yuv420p", 0);
break;
case 1:
LOG("PIX MJPG");
av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "mjpeg", 0);
break;
default: av_dict_set(&m_pVideoState->m_pFormatOpts, "pixel_format", "rgb24", 0); break;
};
}
else
{
// m_bSizeIsAutomatic = true;
};
av_dict_set(&m_pVideoState->m_pFormatOpts, "fflags", "nobuffer", 0);
};
av_dict_set(&m_pVideoState->m_pFormatOpts, "max_delay", "100", 0);
// av_dict_set(&options, "analyzeduration", "1000000", 0);
if (framerate != -1)
{
sprintf(tChar, "%0.2f", framerate);
// sprintf(tChar, "120" );
av_dict_set(&m_pVideoState->m_pFormatOpts, "framerate", tChar, 0);
// av_dict_set(&options, "frame_rate", tChar, 0);
};
// av_dict_set(&options, "timeout", "8000", 0);
int RetVal = 0;
// LOG("Before Open1");
if ((RetVal = avformat_open_input(&m_pVideoState->m_pFormatCtx, m_pVideoState->m_pFileName, NULL, &m_pVideoState->m_pFormatOpts)) != 0)
{
av_dict_free(&m_pVideoState->m_pFormatOpts);
m_pVideoState->m_pFormatOpts = NULL;
char tBuffer[128];
av_strerror(RetVal, tBuffer, 128);
sprintf(Buffer, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, RetVal, m_pVideoState->m_pFileName);
LOG_ERROR(Buffer);
return false;
};
// LOG("After Open1");
AVDictionaryEntry * e;
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);
};
// e is pointer to entry!
// av_dict_free( &e );
};
#ifdef DEBUG
LOG("DataStream Opened");
#endif
m_eMediaStatus = m_pVideoState->m_bStatus = MS_OPENED;
if (avformat_find_stream_info(m_pVideoState->m_pFormatCtx, NULL) < 0)
{
sprintf(Buffer, "Couldn't find stream information: %s", URI);
LOG_ERROR(Buffer);
return false;
};
#if (LIBAVCODEC_VERSION_MAJOR < 58) // && ( LIBAVCODEC_VERSION_MINOR < 50 )
for (unsigned int i = 0; i < m_pVideoState->m_pFormatCtx->nb_streams; i++)
{
// if( m_pVideoState->m_pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){
if (m_pVideoState->m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
LOG("VIDEO stream detected.");
if (m_pVideoState->m_iVideoStreamID < 0)
{
LOG("VIDEO stream assigned.");
m_pVideoState->m_iVideoStreamID = i;
};
};
#ifndef _NOAUDIO_
if (m_pVideoState->m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
{
LOG("AUDIO stream detected.");
if (m_pVideoState->m_iAudioStreamID < 0)
{
LOG("AUDIO stream assigned.");
m_pVideoState->m_iAudioStreamID = i;
}
};
#endif
};
if (m_pVideoState->m_iVideoStreamID == -1)
{
LOG_ERROR("Didn't find a video stream.");
return false;
};
// Video Stream found
m_pVideoState->m_pCodecCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID]->codec;
// Static pointer
m_pVideoState->m_pVideoCodec = avcodec_find_decoder(m_pVideoState->m_pCodecCtx->codec_id);
#ifndef _NOAUDIO_
if (m_pVideoState->m_iAudioStreamID == -1)
{
LOG_ERROR("Didn't find a audio stream.");
return false;
};
// ToDo: Bind Audio Codec
#endif
#else
#ifdef DEBUG_EXTRA
LOG("YABABA-2!");
#endif
/* find the video stream information */
m_pVideoState->m_iVideoStreamID = av_find_best_stream(m_pVideoState->m_pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, const_cast<const AVCodec**>(&m_pVideoState->m_pVideoCodec), 0);
if (m_pVideoState->m_iVideoStreamID == -1)
{
LOG_ERROR("Didn't find a video stream.");
return false;
};
#ifndef _NOAUDIO_
if (m_pVideoState->m_iAudioStreamID == -1)
{
LOG_ERROR("Didn't find a audio stream.");
return false;
};
#endif
if (! (m_pVideoState->m_pCodecCtx = avcodec_alloc_context3(m_pVideoState->m_pVideoCodec)))
{
LOG_ERROR("Can not create decoder context!");
return false;
};
m_pVideoState->m_pVideoStr = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID];
if (avcodec_parameters_to_context(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoStr->codecpar) < 0)
{
LOG_ERROR("Can not set Context parameters!");
return false;
};
#endif
if (m_pVideoState->m_pVideoCodec == NULL)
{
// sprintf(Buffer, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, URI);
sprintf(Buffer, "Codec [%d] not found for %s", m_pVideoState->m_pCodecCtx->codec_id, URI);
LOG_ERROR(Buffer);
return false;
};
/*
End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2())
and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE).
Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool.
*/
m_pVideoState->m_pCodecCtx->thread_count = 4;
// m_pVideoState->m_pCodecCtx->thread_type = FF_THREAD_FRAME;
// if (is_live)
m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE;
// else
// m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE | FF_THREAD_FRAME;
#ifdef DEBUG_EXTRA
LOG("Before Open2");
#endif
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);
LOG_ERROR(Buffer);
return false;
};
//ffmpeg 6 removes AV_CODEC_CAP_TRUNCATED and AV_CODEC_FLAG_TRUNCATED
#if (LIBAVCODEC_VERSION_MAJOR >= 60 )
#else
/* we do not send complete frames */
if (m_pVideoState->m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED)
{
m_pVideoState->m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED;
}
#endif // LIBAVCODEC_VERSION_MAJOR 60
#ifndef _NOAUDIO_
m_pVideoState->m_pAudioCtx = m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iAudioStreamID]->codec;
m_pVideoState->m_pAudioCodec = avcodec_find_decoder(m_pVideoState->m_pAudioCtx->codec_id);
if (! m_pVideoState->m_pAudioCodec)
{
LOG_ERROR("Unsupported Audio codec!");
return false;
};
if (avcodec_open2(m_pVideoState->m_pAudioCtx, m_pVideoState->m_pAudioCodec, NULL) < 0)
{
// SDL_LogError( SDL_LOG_CATEGORY_AUDIO, "Could not open Audio codec[%d].", m_pVideoState->m_pAudioCtx->codec_id );
LOG_ERROR("Could not open Audio codec.");
return false;
};
#endif
#ifdef DEBUG_EXTRA
char tB[256];
sprintf(tB, "Setting Frame [%dx%d]", s_width, s_height);
LOG(tB);
sprintf(tB, "Source Frame [%dx%d]", m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height);
LOG(tB);
#endif
if ((s_width > 0) && (s_height > 0))
{
m_nOutWidth = s_width;
m_nOutHeight = s_height;
}
else
{
if (m_bSizeIsAutomatic)
{
#ifdef DEBUG_EXTRA
LOG("Size is Automatic");
#endif
if ((m_nOutWidth == -1) && (m_nOutHeight == -1))
{
m_nOutWidth = m_pVideoState->m_pCodecCtx->width;
m_nOutHeight = m_pVideoState->m_pCodecCtx->height;
}
else
{
// Proportional
if (m_nOutHeight == -1)
{
float k = ((float) m_pVideoState->m_pCodecCtx->height) / ((float) m_pVideoState->m_pCodecCtx->width);
m_nOutHeight = (int) (((float) m_nOutWidth) * k);
}
else
{
float k = ((float) m_pVideoState->m_pCodecCtx->width) / ((float) m_pVideoState->m_pCodecCtx->height);
m_nOutWidth = (int) (((float) m_nOutHeight) * k);
};
};
}
else
{
#ifdef DEBUG_EXTRA
LOG("Size is Manual");
#endif
if ((width > 0) && (height > 0))
{
m_nOutWidth = width;
m_nOutHeight = height;
}
else
{
m_nOutWidth = m_pVideoState->m_pCodecCtx->width;
m_nOutHeight = m_pVideoState->m_pCodecCtx->height;
};
};
};
#ifdef DEBUG_EXTRA
sprintf(tB, "Using Size [%dx%d]", m_nOutWidth, m_nOutHeight);
LOG(tB);
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_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, SWS_BICUBIC);
LOG(tB);
#endif
if ( m_pVideoState->m_pCodecCtx->pix_fmt < 0 ) {
LOG_ERROR("Error Detectin Pixel Format of the stream!!");
return false;
};
m_pVideoState->m_pSwsCtx = sws_getContext(m_pVideoState->m_pCodecCtx->width, m_pVideoState->m_pCodecCtx->height, m_pVideoState->m_pCodecCtx->pix_fmt, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24,
SWS_BICUBIC, // SWS_FAST_BILINEAR,// | SWS_ACCURATE_RND,//SWS_BILINEAR,//SWS_BICUBIC,
NULL, NULL, NULL);
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;
}
void videoAVLIBSource::m_fThreadProc(void)
{
//AVPacket * pPacket = NULL;
cv::Mat mRGB(m_nOutHeight, m_nOutWidth, CV_8UC3, cv::Scalar(255, 0, 255));
AVFrame * pFrame = NULL;
AVFrame * pFrameBGR = NULL;
uint8_t * pBGRbuffer = NULL;
int dec_ret;
char tB[2048];
/** @todo Valgrind is reporting several important memory leaks in this method.
*
* The first one has to do with @p av_frame_alloc():
* The next one has to do with @p av_image_alloc():
*/
m_bThreadStatus = TH_WORKING;
pthread_setname_np(pthread_self(), "AVLib Source");
//AVPacket Packet;
//av_init_packet(&Packet); // Optional in newer API
AVPacket *Packet = av_packet_alloc();
if (!Packet) {
m_bThreadStatus = TH_ENDED;
LOG_ERROR("Error allocating SRC AVFrame!");
} else {
Packet->data = NULL;
Packet->size = 0;
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 {
dec_ret = av_image_alloc(pFrameBGR->data, pFrameBGR->linesize, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, BUFFER_ALIGN);
sprintf(tB, "Allocated: %d bytes to Frame", dec_ret);
LOG(tB);
if (dec_ret < 0) {
m_bThreadStatus = TH_ENDED;
LOG_ERROR("Error allocating BGR AVFrame Buffer!");
} 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;
#ifdef DEBUG
LOG("Video Reader Thread Started.");
#endif
};
};
};
};// Packet allocation
// cv::setBreakOnError( true );
m_eMediaStatus = m_pVideoState->m_bStatus = MS_STOPED;
while (m_pMediaDestination == NULL && m_bThreadStatus == TH_WORKING)
{
SLEEP(20);
#ifdef DEBUG_EXTRA
LOG("Waiting Destination");
#endif
};
m_eMediaStatus = 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
while (m_pVideoState->m_bStatus < MS_CLOSING && m_bThreadStatus != TH_ENDED)
{
if (m_pMediaDestination != NULL)
{
dec_ret = av_read_frame(m_pVideoState->m_pFormatCtx, Packet);
if (dec_ret >= 0)
{
if (Packet->stream_index == m_pVideoState->m_iVideoStreamID)
{
m_pVideoState->m_bStatus = MS_PRESENT;
dec_ret = avcodec_send_packet(m_pVideoState->m_pCodecCtx, Packet);
if (dec_ret < 0 && dec_ret != AVERROR(EAGAIN) /* && dec_ret != AVERROR_EOF */)
{
LOG_ERROR("Error sending video package to decoder");
m_eMediaStatus = 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, pFrame);
if (dec_ret == AVERROR(EAGAIN) || dec_ret == AVERROR_EOF)
{
break; // Skip to next data
}
else if (dec_ret < 0)
{
LOG_ERROR("Error decoding video frame");
m_eMediaStatus = m_pVideoState->m_bStatus = MS_CLOSING;
m_bThreadStatus = TH_ENDED;
break;
};
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
{
if (m_pMediaDestination)
{
memcpy(mRGB.data, pFrameBGR->data[0], pFrameBGR->linesize[0] * m_nOutHeight);
if (! m_pMediaDestination->pushFrame(mRGB, m_pOpaque))
{
m_pMediaDestination = NULL;
LOG_ERROR("Error Consume Frame by Media Destination!");
m_eMediaStatus = m_pVideoState->m_bStatus = MS_CLOSING;
m_bThreadStatus = TH_ENDED;
};
};
}
catch (cv::Exception & e)
{
LOG_ERROR(e.msg.c_str());
m_eMediaStatus = m_pVideoState->m_bStatus = MS_CLOSING;
m_pMediaDestination = NULL;
m_bThreadStatus = TH_ENDED;
break;
};
};
};
};
av_packet_unref( Packet );
}
else if (dec_ret != AVERROR(EAGAIN) && dec_ret != AVERROR_EOF)
{
LOG_ERROR("Error reading video package");
char tBuffer[128];
av_strerror(dec_ret, tBuffer, 128);
LOG_ERROR(tBuffer);
m_eMediaStatus = 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[128];
av_strerror(dec_ret, tBuffer, 128);
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;
};
};
};
SLEEP(5);
}
else
{
SLEEP(5);
}
};
#ifdef DEBUG
LOG("Video Source Ended!");
#endif
if ( Packet ) {
av_packet_free( &Packet );
};
if (pFrame != NULL)
{
av_frame_free(&pFrame);
};
if (pFrameBGR)
{
if (pFrameBGR->data[0])
{
av_freep(&pFrameBGR->data[0]);
}
av_frame_free(&pFrameBGR);
};
if (pBGRbuffer != NULL)
{
av_free(pBGRbuffer);
};
m_bThreadStatus = TH_ENDED;
m_eMediaStatus = m_pVideoState->m_bStatus = MS_STOPED;
#ifdef DEBUG
LOG("Video Structures Cleared!");
#endif
}
/*
JPEG2000 isn't jpeg. To encode JPEG images, use AV_CODEC_ID_MJPEG. MJPEG stands for "motion JPEG", which is how a sequence of JPEG pictures making up a video stream is typically called.
int save_frame_as_jpeg( AVCodecContext *pCodecCtx, AVFrame *pFrame, int FrameNo) {
AVCodec *jpegCodec = avcodec_find_encoder(AV_CODEC_ID_JPEG2000);
if (!jpegCodec) {
return -1;
}
AVCodecContext *jpegContext = avcodec_alloc_context3(jpegCodec);
if (!jpegContext) {
return -1;
}
jpegContext->pix_fmt = pCodecCtx->pix_fmt;
jpegContext->height = pFrame->height;
jpegContext->width = pFrame->width;
if (avcodec_open2(jpegContext, jpegCodec, NULL) < 0) {
return -1;
}
FILE *JPEGFile;
char JPEGFName[256];
AVPacket packet = {.data = NULL, .size = 0};
av_init_packet(&packet);
int gotFrame;
if (avcodec_encode_video2(jpegContext, &packet, pFrame, &gotFrame) < 0) {
return -1;
}
sprintf(JPEGFName, "dvr-%06d.jpg", FrameNo);
JPEGFile = fopen(JPEGFName, "wb");
fwrite(packet.data, 1, packet.size, JPEGFile);
fclose(JPEGFile);
av_free_packet(&packet);
avcodec_close(jpegContext);
return 0;
}
*/
MediaStateStatus videoAVLIBSource::getStatus(void)
{
if (m_pVideoState)
{
return m_pVideoState->m_bStatus;
}
return MS_UNDEFINED;
}
bool videoAVLIBSource::isFinished(void)
{
if (m_pVideoState)
{
if (m_pVideoState->m_bStatus < MS_CLOSING)
{
return false;
}
}
return true;
}
#undef LOG
#undef LOG_ERROR
//#undef DEBUG_EXTRA
#endif //! LRF_PROXY_ONLY