Qimage: out of memory , returning null image , av_codec_lib

179 Views Asked by At

here's my code to render the image in FFmpeg format, I am able to render the images but after some time due to memory leakage I got an error, QImage: out of memory, returning null image, and my application crashes.

SwsContext* img_convert_ctx;
img_convert_ctx = sws_getContext(codecCtx->width,
                                 codecCtx->height,
                                 codecCtx->pix_fmt,
                                 codecCtx->width,
                                 codecCtx->height,
                                 AV_PIX_FMT_RGB24,
                                 SWS_BICUBIC, NULL, NULL, NULL);

AVFrame* frameRGB ;

frameRGB = av_frame_alloc();

avpicture_alloc((AVPicture*)frameRGB,
                AV_PIX_FMT_RGB24,
                codecCtx->width,
                codecCtx->height);

sws_scale(img_convert_ctx,
          frame->data,
          frame->linesize, 0,
          codecCtx->height,
          frameRGB->data,
          frameRGB->linesize);

QImage image(frameRGB->data[0],
        codecCtx->width,
        codecCtx->height,
        frameRGB->linesize[0],
        QImage::Format_RGB888);

How can I free the memory? I tried using av_frame_free, av_frame_unref which are specified to deallocate the memory located

1

There are 1 best solutions below

1
Osyotr On

You are using QImage constructor that does not take ownership of buffer and you don't clean memory allocated by av_frame_alloc. Instead, let QImage manage it's buffer so that you can cleanup AVFrame * memory.

frameRGB = av_frame_alloc();
...
QImage image(
        codecCtx->width,
        codecCtx->height,
        frameRGB->linesize[0],
        QImage::Format_RGB888);
std::memcpy(image.bits(), frameRGB->data[0], image.sizeInBytes());
av_frame_free(&frameRGB);