Limit Decoder CPU Threads in FFmpeg
Restricting CPU thread usage for a specific decoder in FFmpeg is
essential for preventing system resource exhaustion and optimizing
multi-tasking during media processing. This guide explains how to
correctly target the decoding stage using the -threads
option, apply thread constraints to specific streams, and manage thread
types for individual decoders.
Parameter Placement Matters
FFmpeg interprets command-line options sequentially. Options placed
before an input file (-i) apply to the
demuxer and decoder (reading), whereas options placed
after an input file apply to the muxer and encoder
(writing).
To limit the threads used across all input decoders to a specific
number, specify the -threads flag before defining the
input:
ffmpeg -threads 2 -i input.mp4 -c:v libx264 output.mp4In this example, the decoding process is restricted to 2 CPU threads,
while the encoder (libx264) will use its default thread
allocation.
Restricting Threads for a Specific Stream Type
If a file contains multiple streams (such as video and audio) and you
only want to limit the CPU usage of the video decoder, apply a stream
specifier (:v for video, :a for audio):
ffmpeg -threads:v 4 -i input.mkv -c:v copy output.mp4This ensures that only the video decoder is restricted to 4 threads.
Target a Specific Decoder Directly
When forcing a specific decoder before reading the file, declare the
decoder name alongside the thread count before the -i
flag:
ffmpeg -c:v h264 -threads 2 -i input.mp4 output.mkvFor hardware-accelerated decoders or third-party libraries (such as
libdav1d for AV1), you can configure their internal
threading mechanisms directly as input options:
ffmpeg -c:v libdav1d -threads 4 -i input.av1 output.mp4Controlling Thread Types
Some software decoders support different threading architectures:
frame (decoding multiple frames simultaneously) and
slice (decoding multiple parts of a single frame
simultaneously). You can limit the thread behavior further by using the
-thread_type parameter:
ffmpeg -thread_type slice -threads 2 -i input.mp4 output.mp4Using slice instead of frame can
significantly reduce memory consumption and decoding latency at the cost
of slight CPU efficiency.