title: Custom Reading Function for FFMPEG I/O
body: <p>I need to create a custom reading callback function that can read contents of a file in the form of a  <code>std::string</code> into a <code>uint8_t * buf</code>. I tried multiple different methods found around the internet and on stackoverflow but sometimes it works and other the the program infinitely loops or stops execution half way.</p>
  
  <p>I have no problems with amr/3gp files but all wav/pcm files are causing some problems for some reason. All I know its something to do with the reading function I have so far.</p>
  
  <p>Ideally I would like to be able to give the program any type of file and then it converts it.  </p>
  
  <p>This is how I am calling the <code>readCallback</code> function from the code:</p>
  
  <pre><code>//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, &amp;audio, &amp;readCallback, NULL, NULL);
  </code></pre>
  
  <p>Here is the callback function that works on some types of files: </p>
  
  <pre><code>static int readCallback(void* opaque, uint8_t * buf, int buf_size){  
    std::string * file =static_cast&lt;std::string *&gt;(opaque);
    if(file-&gt;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&lt;uint8_t&gt; array(file-&gt;length());
  
    //Copying the contents of the string into the vector
    std::copy(file-&gt;begin(),file-&gt;end(),array.begin());
  
    //Copying the vector into buf
    std::copy(array.begin(),array.end(),buf);
  
  
    return file-&gt;length();
  
  }
  </code></pre>