gpt4 book ai didi

c++ - 使用 libavformat 读取位于内存中的文件

转载 作者:IT老高 更新时间:2023-10-28 12:52:55 25 4
gpt4 key购买 nike

我目前正在尝试读取从服务器发送的小视频文件

为了使用 libavformat 读取文件,您应该调用

av_open_input_file(&avFormatContext, "C:\\path\\to\\video.avi", 0, 0, 0);

问题是在这种情况下文件不在磁盘上,而是在内存中。

我目前正在做的是下载文件,使用临时名称将其写入磁盘,然后使用临时文件名调用 av_open_input_file,这不是一个非常干净的解决方案.

其实我想要的是一个类似 av_open_custom(&avFormatContext, &myReadFunction, &mySeekFunction); 的函数,但我在文档中没有找到。我想这在技术上是可行的,因为文件名并不能帮助库确定它使用的格式。

那么有没有这样的函数,或者 av_open_input_file 的替代方法?

最佳答案

有趣的是,我在这个网站上发布问题后总是自己找到解决方案,即使我已经解决这个问题几个小时了。

事实上你必须在调用av_open_input之前初始化avFormatContext->pb,并传递一个假文件名给它。这不是写在文档中,而是直接在库的源代码中的注释中。

如果您想从 istream 加载示例代码(未经测试,以便有相同问题的人可以理解)

static int readFunction(void* opaque, uint8_t* buf, int buf_size) {
auto& me = *reinterpret_cast<std::istream*>(opaque);
me.read(reinterpret_cast<char*>(buf), buf_size);
return me.gcount();
}

std::ifstream stream("file.avi", std::ios::binary);

const std::shared_ptr<unsigned char> buffer(reinterpret_cast<unsigned char*>(av_malloc(8192)), &av_free);
const std::shared_ptr<AVIOContext> avioContext(avio_alloc_context(buffer.get(), 8192, 0, reinterpret_cast<void*>(static_cast<std::istream*>(&stream)), &readFunction, nullptr, nullptr), &av_free);

const auto avFormat = std::shared_ptr<AVFormatContext>(avformat_alloc_context(), &avformat_free_context);
auto avFormatPtr = avFormat.get();
avFormat->pb = avioContext.get();
avformat_open_input(&avFormatPtr, "dummyFilename", nullptr, nullptr);

关于c++ - 使用 libavformat 读取位于内存中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com