Configure FFmpeg to Release Unused Memory

FFmpeg is a powerful tool for processing audio and video, but it can sometimes retain large amounts of system memory after processing frames instead of returning it to the operating system. This article explains how to configure FFmpeg’s environment and memory allocator settings to force the immediate release of unused memory back to the OS, preventing memory bloat during long-running or batch-processing tasks.

Use Environment Variables to Tune glibc Memory Allocation

By default, FFmpeg on Linux uses the standard GNU C Library (glibc) allocator, which keeps freed memory in thread-specific pools (arenas) for future reuse rather than returning it to the OS. You can change this behavior by setting specific environment variables before running your FFmpeg command.

  1. MALLOC_MMAP_THRESHOLD_: This variable defines the threshold (in bytes) above which memory allocations are performed using mmap instead of brk. Memory allocated via mmap is returned directly to the operating system as soon as it is freed. Setting this to a lower value forces FFmpeg to use mmap for smaller video frame buffers:

    export MALLOC_MMAP_THRESHOLD_=131072
  2. MALLOC_TRIM_THRESHOLD_: This defines the amount of free space at the top of the heap that must exist before glibc performs a “trim” operation to release memory back to the OS. Setting this to a lower value forces more aggressive memory reclamation:

    export MALLOC_TRIM_THRESHOLD_=65536

Combine these variables when running your FFmpeg command:

MALLOC_MMAP_THRESHOLD_=131072 MALLOC_TRIM_THRESHOLD_=65536 ffmpeg -i input.mp4 output.mkv

Preload jemalloc for Efficient Memory Management

The standard glibc allocator suffers from high memory fragmentation under heavy multi-threaded workloads like video encoding. Replacing it with jemalloc, a memory allocator designed to actively release unused pages to the OS, is the most effective solution.

  1. Install jemalloc on your system:

    • Ubuntu/Debian: sudo apt-get install libjemalloc-dev
    • CentOS/RHEL: sudo dnf install jemalloc
  2. Run FFmpeg with jemalloc loaded via LD_PRELOAD, and configure it to aggressively decay (release) unused dirty memory immediately:

    LD_PRELOAD="/usr/lib/x86_64-linux-gnu/libjemalloc.so" \
    MALLOC_CONF="dirty_decay_ms:0,muzzy_decay_ms:0" \
    ffmpeg -i input.mp4 output.mkv

    (Note: Adjust the path to libjemalloc.so based on your Linux distribution’s library path).

Limit Thread Count to Reduce Arena Creation

FFmpeg automatically spawns multiple threads for decoding, encoding, and filtering. Each thread creates its own glibc memory arena, compounding memory retention issues.

You can restrict the maximum number of threads FFmpeg is allowed to spawn by using the -threads global option:

ffmpeg -threads 4 -i input.mp4 output.mkv

Reducing the thread count directly reduces the number of memory pools glibc manages, allowing the OS to reclaim unused memory much faster.