從記憶中讀書
libavformat 通常接受檔名並直接從檔案系統讀取媒體。如果要從記憶體中讀取(例如流),請執行以下操作:
// Define your buffer size
const int FILESTREAMBUFFERSZ = 8192;
// A IStream - you choose where it comes from
IStream* fileStreamData;
// Alloc a buffer for the stream
unsigned char* fileStreamBuffer = (unsigned char*)av_malloc(FILESTREAMBUFFERSZ);
if (fileStreamBuffer == nullptr){
// out of memory
}
// Get a AVContext stream
AVIOContext* ioContext = avio_alloc_context(
fileStreamBuffer, // Buffer
FILESTREAMBUFFERSZ, // Buffer size
0, // Buffer is only readable - set to 1 for read/write
fileStreamData, // User (your) specified data
FileStreamRead, // Function - Reading Packets (see example)
0, // Function - Write Packets
FileStreamSeek // Function - Seek to position in stream (see example)
);
if(ioContext == nullptr){
// out of memory
}
// Allocate a AVContext
AVFormatContext *formatContext = avformat_alloc_context();
// Set up the Format Context
formatContext->pb = ioContext;
formatContext->flags |= AVFMT_FLAG_CUSTOM_IO; // we set up our own IO
// Open "file" (open our custom IO)
// Empty string is where filename would go. Doesn't matter since we aren't reading a file
// NULL params are format and demuxer settings, respectively
if (avformat_open_input(&formatContext, "", nullptr, nullptr) < 0){
// Error opening file
}
// Do something with the formatContext
// Free resources!
avformat_close_input(&formatContext);
av_free(ioContext);