Search code examples
c++ffmpeglibavcodeclibav

How do I pre-allocate the memory for libavcodec to write decoded frame data?


I am trying to decode a video with libav by following the demo code: here

I need to be able to control where the frame data in pFrame->data[0] is stored. I have tried setting pFrame->data to my own buffer as follows:

// Determine required buffer size and allocate buffer 
int numBytes = av_image_get_buffer_size(pixFmt, width, height, 1); 
(uint8_t*) dataBuff = (uint8_t*) malloc (numBytes * sizeof(uint8_t)); 

// Assign buffer to image planes in pFrame
av_image_fill_arrays(frame->data, frame->linesize, dataBuff, pixFmt, width,
height, 1);

While this does set pFrame->data to be dataBuff (if I print their addresses, they are the same), this call ret = avcodec_receive_frame(pCodecContext, pFrame) to receive the decoded data always writes the data to a different address. It seems to manage its own memory somewhere in the underlying API and ignores the dataBuff that I assigned to pFrame right before.

So I'm stuck--how can I tell libav to write decoded frame data to memory that I pre-allocate? I've seen people ask similar questions online and in the libav forum but haven't been able to find an answer.

Many thanks~


Solution

  • I found that the proper way to do it is via the callback function get_buffer2 to create your own custom allocator as this answer demonstrates:

    FFMPEG: While decoding video, is possible to generate result to user's provided buffer?

    Further documentation is here!