Question

The code bellow creates mp4 video file from jpeg images. When number of images is greater than GOP size the encoding success and after 10th image gotPacket that returned by avcodec_encode_video2 is > 0.

BUT when number of images is smaller than GOP size gotPacket is always = 0 and therefore no images written to the file.

My guess is that avcodec_encode_video2 allocates buffer with length equals to GOP size and until it won't be full gotPacket will be 0.

My question is how to force avcodec_encode_video2 to encode even if it's buffer is not full?

...
_outStream->codec.gop_size = 10;
_outStream->codec.keyint_min = 10;
...

AVFrame* frame = getFrame();


AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;

int gotPacket = 0;
if (avcodec_encode_video2(_outStream->codec, &packet, frame, &gotPacket) < 0)
    throw std::runtime_error("failed to encode frame");

if (gotPacket)
{
    ...
    if (av_write_frame(_outContainer.get(), &packet) < 0)
        throw std::runtime_error("failed to write frame");      
    av_free_packet(&packet);
}
Was it helpful?

Solution

I found the solution. If we'll pass NULL as raw video data to be encoded(3rd param) it will cause the encoder to flush the buffer

if (avcodec_encode_video2(_outStream->codec, &packet, NULL, &gotPacket)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top