golstar
golstar

Reputation: 56

Libav - how to correctly free memory leaking with av_write_frame

I am using LIBAV on Ubuntu to save user's video stream(RTP VP8) on server in WebM format. The problem is, memory is leaking when using av_write_frame. Memory usage is constantly growing (equally with the webm file size) and is never freed after finishing the video recording. The only way to free the memory(RAM) is deleting the WebM file from the storage (HD) afterwards.

I have 2 questions:

  1. Is it possible to free the memory consumed by av_write_frame during runtime? I am freeing the packet.data correctly. Memory usage is not growing when av_write_frame line is commented.
  2. What is the correct way to close the file? This is what I'm doing (it does not free the memory):

    av_write_trailer(fctx); avcodec_close(vStream->codec); avio_close(fctx->pb); avformat_free_context(fctx);

Upvotes: 0

Views: 4847

Answers (3)

Niko
Niko

Reputation: 672

If your memory gets freed when you delete the file, this would indicate that you might be writing your data on a RAM disk or to a folder that is a symbolic link to a RAM disk. In some Linux systems for example, the /tmp folder is a separate partition on the RAM.

  • You might want to check if the file still exists after a reboot. If not, you probably never wrote the file to disk.

Writing your data onto RAM can be a good idea when measuring execution time, as you are free from the latency introduced by writing to disk. Just be aware of it cause they are non-persistent.

(Would have made this a comment to another answer, but I cannot comment yet due to insufficient reputation)

Upvotes: 1

golstar
golstar

Reputation: 56

This is Linux kernel memory management thing. As I am a Linux newbie, I didn't know. Memory is not leaking, Linux is just caching file content into RAM.

For better explanation take a look at: https://askubuntu.com/questions/155768/how-do-i-clean-or-disable-the-memory-cache/155771#155771

Upvotes: 0

George Y.
George Y.

Reputation: 11779

  1. Please make sure you use the latest ffmpeg and VP8 libraries. av_write_frame should not allocate any memory which should be freed. You can confirm by writing one frame and then closing the stream, and running this program under Valgrind. There are many other things to free, but since you are sure commenting out av_write_frame stops the leak, this does not apply to you.

  2. I assume somewhere in your code you have:

    stream = avformat_new_stream( fctx, codecCtx->codec );
    

right? Then you also also need to free the streams:

    for ( unsigned int i = 0; i < fctx->nb_streams; i++ )
    {
        av_freep(&fctx->streams[i]->codec);
        av_freep(&fctx->streams[i]);
    }

Upvotes: 0

Related Questions