gpt4 book ai didi

c++ - FFMPEG I/O 的自定义读取功能

转载 作者:行者123 更新时间:2023-11-30 19:15:23 25 4
gpt4 key购买 nike

我需要创建一个自定义读取回调函数,该函数可以将 std::string 形式的文件内容读取到 uint8_t * buf 中。我尝试了在互联网和 stackoverflow 上找到的多种不同方法,但有时它可以工作,而其他程序会无限循环或中途停止执行。

我对 amr/3gp 文件没有任何问题,但所有 wav/pcm 文件由于某种原因都会导致一些问题。我所知道的一切都与我目前拥有的阅读功能有关。

理想情况下,我希望能够为程序提供任何类型的文件,然后将其转换。

这就是我从代码中调用 readCallback 函数的方式:

//create the buffer
uint8_t * avio_ctx_buffer = NULL;

//allocate space for the buffer using ffmpeg allocation method
avio_ctx_buffer = (uint8_t *) av_malloc(avio_ctx_buffer_size);

//Allocate and initialize an AVIOContext for buffered I/O.
//audio variable contains the contents of the audio file
avio_ctx = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size,0, &audio, &readCallback, NULL, NULL);

以下是适用于某些类型文件的回调函数:

static int readCallback(void* opaque, uint8_t * buf, int buf_size){  
std::string * file =static_cast<std::string *>(opaque);
if(file->length() == 0){
return AVERROR_EOF; //if we reach to the end of the string, return
// return End of file
}

// Creating a vector of the string size
std::vector<uint8_t> array(file->length());

//Copying the contents of the string into the vector
std::copy(file->begin(),file->end(),array.begin());

//Copying the vector into buf
std::copy(array.begin(),array.end(),buf);


return file->length();

}

最佳答案

在尝试了一段时间之后,我得到了一个使用 std::stringstream 的解决方案,它与我迄今为止测试过的几种格式配合得很好:3gp/amr、wav/pcm、mp3。

这里是代码片段:

//Create a string stream that contains the audio
std::stringstream audio_stream(audio);

//create the buffer
uint8_t * avio_ctx_buffer = NULL;

//allocate space for the buffer using ffmpeg allocation method
avio_ctx_buffer = (uint8_t *) av_malloc(avio_ctx_buffer_size);


//Allocate and initialize an AVIOContext for buffered I/O.
//Pass the stringstream audio_stream
avio_ctx = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size,0,&audio_stream, &readCallback, NULL, NULL);

回调函数:

static int readFunction1(void* opaque, uint8_t * buf, int buf_size){
//Cast the opaque pointer to std::stringstream
std::stringstream * me =static_cast<std::stringstream *>(opaque);

//If we are at the end of the stream return FFmpeg's EOF
if(me->tellg() == buf_size){
return AVERROR_EOF;
}
// Read the stream into the buf and cast it to char *
me->read((char*)buf, buf_size);

//return how many characters extracted
return me->tellg();
}

关于c++ - FFMPEG I/O 的自定义读取功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663570/

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