Question

I'm using libavcodec for Windows and avformat_open_input() appears to have a significant memory leak. If I open 5,000 videos, the OS reports 2 GB of RAM consumed that is not freed when the application exits. Here is the code:

AVFormatContext *pFormatCtx = NULL;
AVDictionary *dict = NULL;
int result = 0;

av_register_all();

// open the input video file
IntPtr ip = Marshal::StringToHGlobalAnsi(videoFilename);
const char* filename = static_cast<const char*>(ip.ToPointer());
result = avformat_open_input(&pFormatCtx, filename, NULL, &dict);
if (result < 0) {
    Marshal::FreeHGlobal(ip);
    return result;
}

Marshal::FreeHGlobal(ip);
avformat_close_input(&pFormatCtx);
return result;

The above code is in a class library that is called from C#. I'm using managed C++ to call the libavcodec libraries. The flow is C# -> Managed C++ -> libavcodec. I'm using DLL's and dynamic linking. This is a single threaded application. When I use threads, as expected, the leak increases.

I've tried the following:

  • I've tried a couple of the 32-bit builds and the memory leak is consistent.
  • Using NULL instead of &dict.
  • Calling avformat_open_input() with the same file name 5,000+ times which does not leak memory.
  • Using combinations avformat_alloc_context() and avformat_free_context(). I can't find a combination that frees memory.
Was it helpful?

Solution

Getting back to this in case someone finds this useful.

As it turns out, if I just open and close a file, there is a memory leak. However, if I do functions like (read, seek, etc.), there isn't a memory leak.

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