【问题标题】:Custom Reading Function for FFMPEG I/OFFMPEG I/O 的自定义读取功能
【发布时间】:2023-03-31 20:40:01
【问题描述】:

我需要创建一个自定义读取回调函数,该函数可以将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();

}

【问题讨论】:

    标签: c++ c audio casting ffmpeg


    【解决方案1】:

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

    这里是sn-p的代码:

    //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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-02
      • 2017-03-26
      • 2021-08-10
      • 2011-09-20
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2016-01-03
      相关资源
      最近更新 更多