Select Specific NVIDIA GPU for FFmpeg Decoding
When running FFmpeg on a system with multiple NVIDIA graphics cards,
hardware-accelerated video decoding defaults to the primary GPU (GPU 0).
This guide covers how to direct FFmpeg to a specific NVIDIA GPU for
decoding using the modern -hwaccel_device flag,
decoder-specific arguments, or the CUDA_VISIBLE_DEVICES
environment variable, ensuring efficient workload distribution across
multiple cards.
Step 1: Identify Your GPU Index
Before specifying a device, determine the index assigned to each NVIDIA card on your system. Run the following command in your terminal:
nvidia-smiLook at the leftmost column labeled GPU. The indices are
zero-based (e.g., 0, 1, 2). Note
the index number of the GPU you intend to use for hardware decoding.
Method 1: Use
the -hwaccel_device Flag (Recommended)
The modern, standard method for selecting an NVIDIA GPU in FFmpeg
uses the CUDA hardware acceleration framework paired with the
-hwaccel_device parameter.
Place -hwaccel cuda and
-hwaccel_device <index> before the
input file (-i):
ffmpeg -hwaccel cuda -hwaccel_device 1 -i input.mp4 -c:v libx264 output.mp4In this command:
-hwaccel cudaactivates NVIDIA CUDA-based hardware decoding (NVDEC).-hwaccel_device 1routes the decoding workload specifically to GPU 1.-i input.mp4specifies the source file.
Method 2: Use
the -gpu Option with CUVID Decoders
If you are using legacy CUVID decoders directly (such as
h264_cuvid or hevc_cuvid), you can specify the
target card using the -gpu flag prior to the input:
ffmpeg -c:v h264_cuvid -gpu 1 -i input.mp4 -c:v libx264 output.mp4In this command:
-c:v h264_cuvidforces the use of the NVIDIA CUVID H.264 decoder.-gpu 1forces the decoder to run on GPU 1.
Method
3: Use the CUDA_VISIBLE_DEVICES Environment Variable
You can restrict FFmpeg’s visibility to a specific GPU at the operating system level. When set, FFmpeg will only see the specified card and treat it as GPU 0.
On Linux/macOS:
CUDA_VISIBLE_DEVICES=1 ffmpeg -hwaccel cuda -i input.mp4 -c:v libx264 output.mp4On Windows (PowerShell):
$env:CUDA_VISIBLE_DEVICES="1"; ffmpeg -hwaccel cuda -i input.mp4 -c:v libx264 output.mp4On Windows (Command Prompt):
set CUDA_VISIBLE_DEVICES=1 && ffmpeg -hwaccel cuda -i input.mp4 -c:v libx264 output.mp4Complete Pipeline: Decoding and Encoding on the Same GPU
To avoid copying frames back and forth across the PCIe bus, maintain the video frames in the VRAM of the designated GPU for both decoding and encoding:
ffmpeg -hwaccel cuda -hwaccel_output_format cuda -hwaccel_device 1 -i input.mp4 -c:v h264_nvenc -gpu 1 output.mp4-hwaccel_output_format cudakeeps the decoded frames in GPU memory.-c:v h264_nvenc -gpu 1ensures the encoder also uses GPU 1 to process the stored frames directly.