我最近也有类似的需求。我在 OpenCV 中寻找一种方法来播放已经在内存中的视频,但不必将视频文件写入磁盘。我发现 FFMPEG 接口已经通过av_open_input_stream 支持这个。与 OpenCV 中用于打开文件的 av_open_input_file 调用相比,需要做更多的准备工作。
在以下两个网站之间,我能够使用 ffmpeg 调用拼凑出一个可行的解决方案。详情请参阅这些网站上的信息:
http://ffmpeg.arrozcru.org/forum/viewtopic.php?f=8&t=1170
http://cdry.wordpress.com/2009/09/09/using-custom-io-callbacks-with-ffmpeg/
为了让它在 OpenCV 中运行,我最终在 CvCapture_FFMPEG 类中添加了一个新函数:
virtual bool openBuffer( unsigned char* pBuffer, unsigned int bufLen );
我通过 highgui DLL 中的新 API 调用提供了对它的访问,类似于 cvCreateFileCapture。新的openBuffer函数与open( const char* _filename )函数基本相同,区别如下:
err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
替换为:
ic = avformat_alloc_context();
ic->pb = avio_alloc_context(pBuffer, bufLen, 0, pBuffer, read_buffer, NULL, NULL);
if(!ic->pb) {
// handle error
}
// Need to probe buffer for input format unless you already know it
AVProbeData probe_data;
probe_data.buf_size = (bufLen < 4096) ? bufLen : 4096;
probe_data.filename = "stream";
probe_data.buf = (unsigned char *) malloc(probe_data.buf_size);
memcpy(probe_data.buf, pBuffer, probe_data.buf_size);
AVInputFormat *pAVInputFormat = av_probe_input_format(&probe_data, 1);
if(!pAVInputFormat)
pAVInputFormat = av_probe_input_format(&probe_data, 0);
// cleanup
free(probe_data.buf);
probe_data.buf = NULL;
if(!pAVInputFormat) {
// handle error
}
pAVInputFormat->flags |= AVFMT_NOFILE;
err = av_open_input_stream(&ic , ic->pb, "stream", pAVInputFormat, NULL);
此外,在这种情况下,请确保在 CvCapture_FFMPEG::close() 函数中调用 av_close_input_stream 而不是 av_close_input_file。
现在传入avio_alloc_context的read_buffer回调函数我定义为:
static int read_buffer(void *opaque, uint8_t *buf, int buf_size)
{
// This function must fill the buffer with data and return number of bytes copied.
// opaque is the pointer to private_data in the call to avio_alloc_context (4th param)
memcpy(buf, opaque, buf_size);
return buf_size;
}
此解决方案假定整个视频都包含在内存缓冲区中,并且可能需要进行调整才能处理流数据。
原来如此!顺便说一句,我使用的是 OpenCV 2.1 版所以 YMMV。