[Libav-user] How to close the release resources of a video decoding session properlly?

Shupeng Lai shupenglai at gmail.com
Wed Jun 8 18:14:47 CEST 2016


I use the following code to open a MP4 file. Each time the MP4 file is
opened successfully by calling `QVideoDecoder::openFile(QString filename)`.

I close the content and release the resources by calling close();

However, each time I run the `openFile(QString filename)` function on the
same file. There are some memory leak.


 What is wrong with my code?

    void QVideoDecoder::InitVars()
    {
    ok = false;
    pFormatCtx = 0;
    pCodecCtx = 0;
    pCodec = 0;
    pFrame = 0;
    pFrameRGB = 0;
    buffer = 0;
    img_convert_ctx = 0;
    th = 0;
    }

    void QVideoDecoder::close()
    {
       if(buffer)
          delete [] buffer;

       if(pFrame)
          av_free(pFrame);

       if(pFrameRGB)
          av_free(pFrameRGB);

       if(pCodecCtx)
          avcodec_close(pCodecCtx);

       if(pFormatCtx)
      avformat_close_input(&pFormatCtx);

       if (th)
      delete th;

       InitVars();
    }

    bool QVideoDecoder::openFile(QString filename)
    {
    // Close the last video first
    //----------------------------------------------
    close();

    ffmpeg::AVInputFormat *iformat = NULL;

    pFormatCtx = ffmpeg::avformat_alloc_context();

    avformat_open_input(&pFormatCtx, filename.toStdString().c_str(),
iformat, &opts) != 0)
    av_dict_free(&opts);


    avformat_find_stream_info(pFormatCtx, NULL);

    av_dump_format(pFormatCtx, 0, filename.toStdString().c_str(), false);

    for (unsigned i = 0; i < pFormatCtx->nb_streams; i++)
    {
    if (pFormatCtx->streams[i]->codec->codec_type ==
ffmpeg::AVMEDIA_TYPE_VIDEO)
    {
    videoStream = i;
    break;
    }
    }

    pCodecCtx = pFormatCtx->streams[videoStream]->codec;

    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);

    pCodecCtx->thread_type = 0;

avcodec_open2(pCodecCtx, pCodec, NULL);

pFrame = ffmpeg::avcodec_alloc_frame();

pFrameRGB = ffmpeg::avcodec_alloc_frame();

numBytes = ffmpeg::avpicture_get_size(ffmpeg::PIX_FMT_RGB24,
pCodecCtx->width, pCodecCtx->height);
buffer = new uint8_t[numBytes];

avpicture_fill((ffmpeg::AVPicture *)pFrameRGB, buffer,
ffmpeg::PIX_FMT_RGB24,
pCodecCtx->width, pCodecCtx->height);

return true;
    }
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://ffmpeg.org/pipermail/libav-user/attachments/20160609/fbb720c7/attachment.html>


More information about the Libav-user mailing list