Configure libx264 Thread Count in FFmpeg
This article explains how to configure and optimize the thread count
for the libx264 video encoder in FFmpeg. You will learn how
to use the global -threads option as well as
libx264-specific parameters to control CPU utilization,
improve encoding speeds, or limit resource consumption during video
compression.
Using the Global Threads Option
The simplest way to control the thread count in FFmpeg is by using
the generic -threads flag. By default, libx264
automatically determines the optimal number of threads based on your
CPU’s available logical cores (equivalent to setting
-threads 0).
To restrict or force FFmpeg to use a specific number of threads,
place the -threads option after your input file and before
the output file:
ffmpeg -i input.mp4 -c:v libx264 -threads 4 output.mp4In this example, FFmpeg limits the libx264 encoder (and
other multithreaded filters/demuxers in the pipeline) to exactly 4
threads.
Using libx264-Specific Threading Parameters
While the global -threads flag is sufficient for most
use cases, libx264 offers finer control over its internal
threading model via the -x264-params option. You can
configure two primary threading mechanisms: frame threads and sliced
threads.
1. Frame-Based Threading
Frame-based threading encodes multiple frames in parallel. This is highly efficient for throughput but introduces a small amount of latency. You can set this directly in the x264 parameters:
ffmpeg -i input.mp4 -c:v libx264 -x264-params threads=4 output.mp42. Sliced Threading
Sliced threading divides a single frame into multiple “slices” and encodes those slices in parallel. This is ideal for low-latency streaming because it does not delay frame output, though it can slightly reduce compression efficiency.
To enable sliced threading, you must define the number of slices or
force sliced-threads=1 in the parameters:
ffmpeg -i input.mp4 -c:v libx264 -x264-params threads=4:sliced-threads=1 output.mp4Alternatively, you can specify the exact number of slices:
ffmpeg -i input.mp4 -c:v libx264 -slices 4 -x264-params sliced-threads=1 output.mp4Choosing the Right Thread Count
- For Maximum Speed: Leave the setting at
-threads 0(default).libx264will automatically scale, usually spawning 1.5 times the number of logical CPU cores to keep the pipeline saturated. - For Resource Saving: If you are running FFmpeg on a
shared server and want to prevent it from hogging the entire CPU, limit
the count to a specific number (e.g.,
-threads 2or-threads 4). - Diminishing Returns: Note that
libx264scaling begins to degrade slightly beyond 16 threads due to synchronization overhead. If you have a high-core-count CPU (e.g., 32+ threads), manually limiting the thread count to 8 or 12 per process and running multiple encoding jobs in parallel is often more efficient than running a single job with maximum threads.