Select Specific NVIDIA GPU for FFmpeg Encoding

When running a system with multiple graphics cards, you may want to dedicate a specific NVIDIA GPU to handle your FFmpeg video encoding tasks to balance system resources. This article provides a straightforward guide on how to identify your GPUs and select a specific card for hardware-accelerated NVENC encoding in FFmpeg using command-line arguments and environment variables.

Step 1: Identify Your GPU Index

Before configuring FFmpeg, you need to find the index number of the NVIDIA GPU you want to use. Open your terminal or command prompt and run:

nvidia-smi

This command displays a list of all connected NVIDIA GPUs. Note the ID number (usually 0, 1, 2, etc.) next to the GPU you wish to target.

Step 2: Select the GPU in FFmpeg

There are three primary methods to force FFmpeg to use your selected GPU.

The most direct way to specify a GPU is by passing the -gpu flag directly to the NVENC encoder (h264_nvenc or hevc_nvenc).

To use the GPU with index 1, format your command like this:

ffmpeg -i input.mp4 -c:v h264_nvenc -gpu 1 output.mp4

Method B: Using the -hwaccel_device parameter

If you are decoding and encoding on the same hardware using CUDA, you can specify the target device at the hardware acceleration level using -hwaccel cuda and -hwaccel_device.

To run the entire pipeline on GPU index 1:

ffmpeg -hwaccel cuda -hwaccel_device 1 -i input.mp4 -c:v h264_nvenc output.mp4

Method C: Using the CUDA_VISIBLE_DEVICES Environment Variable

If you want to completely hide other GPUs from FFmpeg, you can set the CUDA_VISIBLE_DEVICES environment variable before running the command. This forces FFmpeg to only see the specified GPU, which it will then treat as device 0.

On Linux/macOS:

CUDA_VISIBLE_DEVICES=1 ffmpeg -i input.mp4 -c:v h264_nvenc output.mp4

On Windows (Command Prompt):

set CUDA_VISIBLE_DEVICES=1
ffmpeg -i input.mp4 -c:v h264_nvenc output.mp4

On Windows (PowerShell):

$env:CUDA_VISIBLE_DEVICES="1"
ffmpeg -i input.mp4 -c:v h264_nvenc output.mp4