The Complete Guide to Hardware Accelerated Encoding in FFmpeg
Learn FFmpeg 7.1 hardware encoding end to end: NVENC, VAAPI, Quick Sync and VideoToolbox, memory models, rate control, pipelines, measurement and failures.

A modern machine can encode video on a circuit built for the job instead of on the cores you are paying for. Every vendor ships one: NVIDIA calls it NVENC, Intel calls it Quick Sync Video, AMD's engine is reached through VAAPI on Linux and AMF on Windows, and Apple's is behind VideoToolbox. FFmpeg 7.1 can drive all of them, and the commands look deceptively simple until the first one fails with "Function not implemented" or produces a file that is twice the size you expected. This guide covers the whole subject in one place: what hardware encoding is and when it pays off, how FFmpeg models the device and its memory, how to find out what a machine can do, a complete recipe for each of the four main APIs, rate control, pipelines that keep frames on the GPU, quality measurement, a wrapper script that picks an encoder for you and a field manual of the errors you will meet. Each section carries commands you can adapt, written for FFmpeg 7.1, and every claim about options comes from the official documentation.
What hardware encoding is, and when it is worth it
A video encoder compresses a sequence of pictures into a stream. The work is a search: for each block of each frame the encoder looks for a way to describe the block cheaply, using motion from earlier frames, prediction from neighbouring pixels and a transform and quantisation step that throws away detail the eye is least likely to miss. A software encoder such as x264 runs that search on general-purpose cores, and its presets decide how much of the search it performs. A hardware encoder is a fixed-function block, a piece of silicon that performs a particular search at a fixed cost. It lives next to the GPU's shader cores but is a separate circuit, so a card can encode video while it renders a game or runs a neural network at full speed.
The consequences are the same on every vendor's hardware:
Speed. A hardware encoder is much faster than a software encoder of comparable quality settings, and its speed barely depends on the content.
Efficiency. The CPU is nearly idle during an encode, and the energy per encoded frame is much lower. On a laptop that means battery life, and in a data centre it means more streams per rack.
Compression. At the same bitrate, a slow software preset usually looks better, because the software search can try more options. The gap depends on the codec and on the GPU generation, and it narrows with newer hardware.
Features. Hardware encoders implement a fixed list of codecs, profiles, bit depths and chroma formats. Software encoders implement whatever the code supports.
These trade-offs make the decision a matter of what the file is for. The table below sorts common jobs.
| Job | Lean towards | Why |
|---|---|---|
| Live stream or screen capture | Hardware | Real-time guarantee and a free CPU |
| Many parallel transcodes on one server | Hardware | Cores run out long before encoder blocks do |
| Proxy or preview files | Hardware | Quality is secondary |
| Master archive or a file delivered to millions | Software, slow preset | Every saved bit multiplies |
| Strict bitrate cap with two-pass accuracy | Software | Precise rate control |
| HEVC or AV1 on a recent GPU | Measure | The gap to software is smaller |
When the answer is "measure", the section on measuring quality gives the method. The guide treats the decision as an engineering question and not as a belief, because the numbers differ between machines.
How FFmpeg models hardware: devices, frames and formats
Hardware encoding in FFmpeg runs on three ideas, and understanding them makes every error message readable.
A device is a handle to the hardware: a CUDA context, a VAAPI display opened on a DRM render node, a QSV session or a VideoToolbox session. FFmpeg calls it an AVHWDeviceContext. Commands create it with -hwaccel, which makes one for the decoder, or with -init_hw_device, which makes a named one that you can hand to filters with -filter_hw_device.
A hardware frame is a picture that lives in the device's memory. FFmpeg tags it with a hardware pixel format such as cuda, vaapi, qsv or videotoolbox_vld, and the frame carries an underlying software layout, usually nv12 for 8-bit 4:2:0 and p010le for 10-bit. A software filter cannot read a hardware frame, because the pointers refer to memory the CPU cannot address directly. Hardware frames come from a pool, an AVHWFramesContext, with a fixed number of surfaces.
A transfer moves a frame between system memory and device memory. hwupload copies upward and hwdownload copies downward. Each is a full-frame copy that costs bandwidth, and the central performance question in every hardware pipeline is how many of them it performs.
The encoders divide into two groups by the frames they accept:
| Encoder family | Accepts system frames | Needs GPU frames |
|---|---|---|
*_nvenc | Yes, it copies them in | Also accepts cuda frames |
*_videotoolbox | Yes | Also accepts videotoolbox_vld frames |
*_vaapi | No | Yes, vaapi surfaces |
*_qsv | Sometimes, via an implicit upload | Yes, qsv surfaces |
NVENC and VideoToolbox take ordinary frames, which makes them the easiest to start with. VAAPI insists on surfaces, so every VAAPI command contains an upload, either an explicit hwupload or a decoder that produces VAAPI frames. QSV sits between them, and an explicit upload makes its behaviour predictable.
Decoding is a separate switch
Hardware decoding and hardware encoding are independent, and a command can use one, both or neither. -hwaccel is an input option that accelerates decoding. An encoder is chosen by name with -c:v. The explainer on hardware decoding versus hardware encoding in this cluster covers the distinction at length. For this guide, the point is that decoding on the GPU and encoding on the GPU only avoid copies when the decoded frames stay in video memory, which needs -hwaccel_output_format and GPU filters. The section on pipelines returns to this.
Find out what a machine can do
Never write a pipeline without checking the machine. Three layers of evidence exist, and each answers a different question.
The first layer is the FFmpeg binary. It lists the acceleration methods and encoders compiled in:
ffmpeg -hide_banner -hwaccelsHardware acceleration methods:
cuda
vaapi
qsv
drm
opencl
vulkanffmpeg -hide_banner -encoders | grep -E "nvenc|vaapi|qsv|videotoolbox|amf" V....D h264_nvenc NVIDIA NVENC H.264 encoder (codec h264)
V....D hevc_nvenc NVIDIA NVENC hevc encoder (codec hevc)
V....D av1_nvenc NVIDIA NVENC av1 encoder (codec av1)
V....D h264_vaapi H.264/AVC (VAAPI) (codec h264)
V....D hevc_vaapi H.264/HEVC (VAAPI) (codec hevc)
V..... h264_qsv H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (Intel Quick Sync Video acceleration) (codec h264)The exact list depends on the platform and the build, and the wording of descriptions changes between releases. A missing name means the binary cannot use that encoder, whatever the hardware could do.
The second layer is the driver, which describes the hardware. On Intel and AMD under Linux, vainfo lists the profiles and their entrypoints, where VAEntrypointVLD is decode and VAEntrypointEncSlice or VAEntrypointEncSliceLP is encode. On NVIDIA, nvidia-smi names the GPU and driver, and NVIDIA's Video Encode and Decode GPU Support Matrix lists what each model can do. On a Mac, every Apple silicon chip has the engines, and the options differ by generation.
The third layer is a test encode, which is the only proof that the stack works. Generate a synthetic source with the lavfi input, encode one second and discard the output:
ffmpeg -hide_banner -f lavfi -i testsrc2=size=1280x720:rate=30 -t 1 -c:v h264_nvenc -f null -Output #0, null, to 'pipe:':
Stream #0:0: Video: h264 (h264_nvenc), yuv420p(tv, progressive), 1280x720, q=2-31, 2000 kb/s, 30 fps, 30 tbn
[out#0/null @ 0x55f8a3c0d640] video:61KiB audio:0KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknownIf the encoder opens and produces packets, the stack works for that codec and format. Test every codec, bit depth and chroma format that you plan to use, because a GPU that passes the 8-bit H.264 test can fail 10-bit HEVC.
NVENC on NVIDIA GPUs
NVENC needs an NVIDIA GPU with an encode block, the proprietary driver and an FFmpeg built against the nv-codec-headers. It loads libnvidia-encode at run time, so the machine running FFmpeg does not need the CUDA toolkit. The encoders are h264_nvenc, hevc_nvenc and, on Ada generation GPUs and later, av1_nvenc.
The minimal command takes ordinary frames:
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p5 -rc vbr -cq 23 -b:v 0 -c:a copy out.mp4The options carry the encoder's character. -preset runs from p1 (fastest, lowest compression) to p7 (slowest, best), and the difference between p6 and p7 is usually small. -rc vbr with -cq 23 and -b:v 0 is constant quality, the equivalent of x264's CRF, though the numbers do not match. -tune hq allows look-ahead and B-frames, and -tune ll or ull remove them for low latency. -multipass fullres adds a first analysis pass at full resolution for better rate control. -spatial-aq 1 moves bits towards flat areas where blocking is visible, and -rc-lookahead 20 looks at upcoming frames before spending bits. A dedicated post in this cluster tunes these in detail.
Limits to plan around: the number of simultaneous encode sessions on consumer GPUs, which NVIDIA documents and has changed between driver releases; the codecs each generation supports; and the fact that 10-bit support depends on the codec. A session failure appears as OpenEncodeSessionEx failed: out of memory (10), which means the session cap was reached and not that video memory ran out.
VAAPI on Intel and AMD under Linux
VAAPI is the Linux interface to video engines from Intel and AMD, and it needs a driver (iHD or i965 for Intel, Mesa's radeonsi for AMD) and a render node. Frames must be VAAPI surfaces, so the command uploads them:
ffmpeg -vaapi_device /dev/dri/renderD128 -i input.mp4 \
-vf "format=nv12,hwupload" -c:v h264_vaapi -qp 23 -c:a copy out.mp4-vaapi_device opens the device for filters. format=nv12 puts the frame in the surface layout, hwupload copies it, and -qp selects constant quantisation. Bitrate modes use -b:v, with -maxrate for constant bitrate. The error that every newcomer meets is Format yuv420p not supported for hardware encoding, which means the encoder received a software frame, and the fix is the format=nv12,hwupload pair.
HEVC uses hevc_vaapi with the same pattern, 10-bit uses format=p010le and -profile:v main10 where the hardware supports it, and AV1 uses av1_vaapi on GPUs with the engine. A full-hardware path decodes with -hwaccel vaapi -hwaccel_output_format vaapi and scales with scale_vaapi.
Quick Sync Video on Intel
Quick Sync is the same silicon as VAAPI on Intel hardware, reached through a different API. FFmpeg 7.1 talks to it through libvpl, the oneVPL dispatcher, and the encoders are h264_qsv, hevc_qsv, vp9_qsv, av1_qsv and mjpeg_qsv. The reason to choose QSV over VAAPI is control: it exposes intelligent constant quality and look-ahead rate control.
ffmpeg -init_hw_device qsv=hw:/dev/dri/renderD128 -filter_hw_device hw \
-i input.mp4 -vf "hwupload=extra_hw_frames=64,format=qsv" \
-c:v h264_qsv -global_quality 23 -preset slow -c:a copy out.mp4-global_quality sets the ICQ level, -preset runs from veryfast to veryslow, and -look_ahead 1 enables the look-ahead variant where supported. The extra_hw_frames value prevents the surface pool from running dry when the encoder holds frames. On Windows, the device uses Direct3D 11 and the driver ships with Intel's graphics package.
VideoToolbox on macOS
VideoToolbox is Apple's framework, and it needs no driver install. The encoders are h264_videotoolbox, hevc_videotoolbox and prores_videotoolbox:
ffmpeg -i input.mov -c:v hevc_videotoolbox -q:v 60 -tag:v hvc1 -c:a aac -b:a 160k out.mp4-q:v is a quality target from 0 to 100 on hardware that supports it, and -b:v is the bitrate alternative. The -tag:v hvc1 option matters, because FFmpeg writes hev1 for HEVC in MP4 by default, and Apple's players accept only hvc1. Add -hwaccel videotoolbox before the input to decode on the hardware too.
Other encoders you will meet
Windows with AMD GPUs uses AMF, with h264_amf, hevc_amf and av1_amf, which follow the same shape as the others. Embedded Linux boards often expose a V4L2 memory-to-memory device that FFmpeg wraps as h264_v4l2m2m, whose availability and options depend on the board's driver, so read the board's documentation and test with the one-second encode. Vulkan video encoders exist in recent FFmpeg versions and track the Vulkan driver's support. The test encode is the way to find out.
Rate control across the APIs
Every encoder has to answer the same question: how many bits should each frame get. Four strategies recur, with different names.
Constant quantiser holds the quantisation parameter fixed. Quality is uniform in terms of the quantiser and the bitrate follows the content. NVENC calls it -rc constqp -qp N, VAAPI uses -qp N, and QSV and VideoToolbox have their own forms.
Constant quality (also called CRF-like) lets the encoder vary the quantiser to hold perceived quality steady. NVENC uses -rc vbr -cq N -b:v 0, QSV uses -global_quality N, and VideoToolbox uses -q:v N. This is the right mode for files that you will keep.
Average bitrate (VBR) targets a mean rate and lets the instantaneous rate vary. All encoders take -b:v, and a -maxrate caps the peaks.
Constant bitrate (CBR) holds the rate nearly flat with a small buffer, which streaming services and fixed uplinks prefer. NVENC uses -rc cbr, and VAAPI and QSV use -b:v with -maxrate equal to it and a matching -bufsize.
| Goal | NVENC | VAAPI | QSV | VideoToolbox |
|---|---|---|---|---|
| Constant quality | -rc vbr -cq 23 -b:v 0 | -qp 23 | -global_quality 23 | -q:v 60 |
| Average bitrate | -b:v 6M | -b:v 6M | -b:v 6M | -b:v 6M |
| Constant bitrate | -rc cbr -b:v 6M | -b:v 6M -maxrate 6M | -b:v 6M -maxrate 6M | -b:v 6M |
The numbers in the first row are not comparable between encoders, so you pick each by looking at your footage. A good procedure is to encode a thirty second clip with three values, look at a dark scene and a fast scene at full size, and take the least generous value that looks right.
Check what your build supports with ffmpeg -h encoder=NAME, which prints every option with its range and default. Options vary with the FFmpeg version, the driver and the hardware generation, and an option that the hardware does not support is usually ignored with a warning, so read the log.
Structure: GOP, B-frames and keyframes
The encoder's frame structure affects both compression and delivery. A GOP is the group of frames between keyframes. -g 60 sets a keyframe interval of 60 frames, which is two seconds at 30 frames per second. Streaming protocols need regular keyframes because a viewer can only join at one, and adaptive formats such as HLS cut segments at them. B-frames are predicted from both earlier and later frames, which compresses well and requires reordering, so each B-frame adds delay. -bf 3 sets up to three consecutive B-frames, and -bf 0 removes them for low latency. Some hardware encoders limit B-frames or reference frames, and some set B-frames as references with an option such as NVENC's -b_ref_mode.
For MP4 files that will be served over HTTP, add -movflags +faststart so that the index sits at the start of the file and playback begins before the whole file downloads:
ffmpeg -i in.mp4 -c:v h264_nvenc -preset p5 -rc vbr -cq 23 -b:v 0 -g 60 -movflags +faststart -c:a aac out.mp4Pixel formats, 10-bit and HDR
Hardware encoders take specific pixel formats. For 8-bit 4:2:0 that is nv12 or yuv420p. For 10-bit it is p010le, with the Main10 profile for HEVC. Most consumer hardware encoders do not support 4:2:2 or 4:4:4 for H.264 and HEVC, and some GPU generations do not support 10-bit H.264 at all, so a professional 4:2:2 source needs a software encoder or a conversion step.
HDR needs more than a bit depth. An HDR10 stream carries PQ transfer, BT.2020 primaries and mastering metadata, and FFmpeg passes the tags along when you encode with a 10-bit HEVC encoder and keep the source's colour properties. If the target is an SDR device, you tone map instead, which is a separate chain of software filters described in the post on tone mapping with zscale and tonemap. Do not encode HDR to 8-bit H.264 without tone mapping, because players then show a grey, washed-out picture.
Pipelines: three patterns and what they cost
Every hardware encode fits one of three shapes, and the shape sets the cost.
Pattern 1: software decode, hardware encode. The CPU decodes and filters, and each frame is uploaded to the encoder. It is the simplest, it works with every encoder, and it is fine when decoding is cheap:
ffmpeg -i input.mp4 -vf "scale=1280:720" -c:v h264_nvenc -preset p5 -cq 23 -rc vbr -b:v 0 out.mp4Pattern 2: hardware decode, software filter, hardware encode. Decoding is accelerated, frames come down to system memory for filters and go back up for the encode. It helps when decoding is the heavy part, such as 4K HEVC input, and it adds two copies:
ffmpeg -hwaccel cuda -i input.mp4 -vf "scale=1280:720" -c:v h264_nvenc -preset p5 -cq 23 -rc vbr -b:v 0 out.mp4Pattern 3: all on the GPU. Decode, filter and encode share video memory, and nothing crosses the bus. It is the fastest and needs GPU versions of every filter:
ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i input.mp4 \
-vf "scale_cuda=w=1280:h=720" -c:v h264_nvenc -preset p5 -cq 23 -rc vbr -b:v 0 out.mp4The equivalent for VAAPI replaces cuda with vaapi and scale_cuda with scale_vaapi, and for QSV it uses -hwaccel qsv -hwaccel_output_format qsv with vpp_qsv. When you need a software filter inside pattern 3, you download, filter and upload with hwdownload,format=nv12 and hwupload, which restores the copies. A separate post covers mixed chains and hwmap, which can share memory between APIs without a copy.
Read the log to see which pattern ran. The line Stream #0:0 -> #0:0 (h264 (native) -> h264 (h264_nvenc)) says that the decoder is the native software one. A hardware decoder shows (h264 (h264_cuvid)... or a note about the hwaccel. In verbose mode, fmt:cuda or fmt:vaapi on filter links proves frames are on the device.
Measure quality, speed and throughput
Three measurements decide whether a hardware recipe is acceptable.
Quality is measured with VMAF through the libvmaf filter, if your build has it. Encode a representative clip at matching bitrates with software and hardware, then score each against the source:
ffmpeg -i hw.mp4 -i clip.mp4 -lavfi "[0:v][1:v]libvmaf=log_fmt=json:log_path=hw.json" -f null -[Parsed_libvmaf_0 @ 0x6000025b8000] VMAF score: 93.10The score above is a placeholder for the output's layout, and yours will differ. The comparison that matters is between curves: at a given score, how many bits does each encoder need? Use two-pass bitrate mode for the software reference so the sizes are controlled, and look at the files too, since VMAF is a model and can be fooled by banding.
Speed is how long one job takes, and -benchmark prints the CPU time and the maximum memory:
ffmpeg -benchmark -i input.mp4 -c:v h264_nvenc -preset p5 -f null -bench: utime=1.482s stime=0.311s rtime=6.104s
bench: maxrss=241664KiBThe utime and stime figures are CPU time, and rtime is wall-clock time. A job that is truly on the GPU shows low CPU time compared with real time. These values are an example of the format.
Throughput is the total frames per second across parallel jobs, and it is what a service needs. The post on parallel transcodes gives a harness. The summary is that total throughput rises with the number of jobs, flattens at the knee and that you plan below it.
A wrapper that chooses the encoder
Production scripts cannot assume a machine. This script probes the encoders in order of preference with a one-second test encode and falls back to x264. It encodes with the first one that works:
#!/usr/bin/env bash
set -u
in=${1:?usage: hwenc.sh input output}
out=${2:?usage: hwenc.sh input output}
render=${RENDER_NODE:-/dev/dri/renderD128}
src=(-f lavfi -i testsrc2=size=1280x720:rate=30 -t 1)
probe_nvenc() {
ffmpeg -v error "${src[@]}" -c:v h264_nvenc -f null - 2>/dev/null
}
probe_vaapi() {
ffmpeg -v error -vaapi_device "$render" "${src[@]}" \
-vf "format=nv12,hwupload" -c:v h264_vaapi -f null - 2>/dev/null
}
probe_qsv() {
ffmpeg -v error -init_hw_device "qsv=hw:$render" -filter_hw_device hw "${src[@]}" \
-vf "hwupload=extra_hw_frames=64,format=qsv" -c:v h264_qsv -f null - 2>/dev/null
}
probe_vtb() {
ffmpeg -v error "${src[@]}" -c:v h264_videotoolbox -f null - 2>/dev/null
}
if probe_nvenc; then
echo "using h264_nvenc"
ffmpeg -v error -y -i "$in" -c:v h264_nvenc -preset p5 -rc vbr -cq 23 -b:v 0 -c:a copy "$out"
elif probe_vaapi; then
echo "using h264_vaapi"
ffmpeg -v error -y -vaapi_device "$render" -i "$in" -vf "format=nv12,hwupload" \
-c:v h264_vaapi -qp 23 -c:a copy "$out"
elif probe_qsv; then
echo "using h264_qsv"
ffmpeg -v error -y -init_hw_device "qsv=hw:$render" -filter_hw_device hw -i "$in" \
-vf "hwupload=extra_hw_frames=64,format=qsv" -c:v h264_qsv -global_quality 23 -c:a copy "$out"
elif probe_vtb; then
echo "using h264_videotoolbox"
ffmpeg -v error -y -i "$in" -c:v h264_videotoolbox -q:v 60 -c:a copy "$out"
else
echo "using libx264"
ffmpeg -v error -y -i "$in" -c:v libx264 -preset medium -crf 21 -c:a copy "$out"
fiRun on a machine with an NVIDIA GPU:
bash hwenc.sh input.mp4 out.mp4using h264_nvencThe structure is the point: each probe is a real one-second encode, not a check of a device node, so a probe that passes means the whole stack works. The -v error option keeps FFmpeg quiet apart from failures, and a non-zero exit status from a probe moves to the next candidate. Caveats: the probes test 8-bit H.264 at 720p, so a job that needs HEVC or 10-bit needs its own probe, and the quality values differ between encoders, so the script's numbers are starting points.
Worked example: an adaptive streaming ladder on one GPU
A streaming service turns one source into several renditions at different sizes and bitrates. Done in software, the source is decoded once and every rendition costs a full encode. Done on the GPU, the decode happens once, the frames are duplicated with split, each copy is scaled by a CUDA kernel and each goes to its own NVENC session. The graph below produces three H.264 renditions as HLS playlists:
ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i input.mp4 -filter_complex "
[0:v]split=3[a][b][c];
[a]scale_cuda=w=1920:h=1080[v1080];
[b]scale_cuda=w=1280:h=720[v720];
[c]scale_cuda=w=854:h=480[v480]" \
-map "[v1080]" -map 0:a -c:v h264_nvenc -preset p5 -rc cbr -b:v 5M -maxrate 5M -bufsize 10M \
-g 96 -forced-idr 1 -c:a aac -b:a 128k -f hls -hls_time 4 -hls_playlist_type vod -hls_segment_filename "v1080_%03d.ts" v1080.m3u8 \
-map "[v720]" -map 0:a -c:v h264_nvenc -preset p5 -rc cbr -b:v 3M -maxrate 3M -bufsize 6M \
-g 96 -forced-idr 1 -c:a aac -b:a 128k -f hls -hls_time 4 -hls_playlist_type vod -hls_segment_filename "v720_%03d.ts" v720.m3u8 \
-map "[v480]" -map 0:a -c:v h264_nvenc -preset p5 -rc cbr -b:v 1500k -maxrate 1500k -bufsize 3M \
-g 96 -forced-idr 1 -c:a aac -b:a 96k -f hls -hls_time 4 -hls_playlist_type vod -hls_segment_filename "v480_%03d.ts" v480.m3u8Several details carry the design. The source is 24 frames per second, so -g 96 puts a keyframe every four seconds, which matches -hls_time 4. Segments can only start on keyframes, and a mismatch makes the segmenter produce uneven lengths. All three renditions use the same GOP length and -forced-idr 1 so that segment boundaries line up across renditions, which lets a player switch between them without a glitch. The split filter works on GPU frames, because it only duplicates references to the surface, and each scale_cuda writes into its own surface. Three encode sessions run, so the harness for parallel transcodes tells you whether your GPU's session limit allows more than one such ladder at a time.
The master playlist that lists the three variants is a small text file that you write once, and it names each rendition's bandwidth and resolution:
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=5200000,RESOLUTION=1920x1080
v1080.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3200000,RESOLUTION=1280x720
v720.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1600000,RESOLUTION=854x480
v480.m3u8The bandwidth values are the video bitrate plus the audio and some overhead, and players use them to choose a rendition. Rate the CBR encodes at the values you declare, because a rendition that exceeds its declared bandwidth makes players switch down late and stall.
Live streaming and capture
A live encode has different priorities from a file. The encoder must keep up with real time, latency should be low and the rate should not exceed the uplink. That points to constant bitrate, no B-frames, a short GOP and a small buffer:
ffmpeg -f v4l2 -i /dev/video0 -c:v h264_nvenc -preset p4 -tune ll -rc cbr -b:v 4M -maxrate 4M \
-bufsize 4M -bf 0 -g 60 -forced-idr 1 -profile:v high -f flv rtmp://example.test/live/streamkeyThe input here is a camera, and the destination and key are placeholders. -tune ll removes the look-ahead and reordering delay, -bufsize equal to the bitrate bounds the buffering to about a second and -g 60 gives a keyframe every two seconds at 30 frames per second, which is what most ingest services request. If your service asks for a keyframe interval in seconds, compute it from the frame rate.
Screen capture on Linux can stay on the GPU from the display to the encoder with the kmsgrab source, which reads the framebuffer through DRM and hands frames to VAAPI. It needs permission to open the DRM device, often through the CAP_SYS_ADMIN capability, and the grab produces DRM frames that hwmap converts to VAAPI surfaces:
ffmpeg -device /dev/dri/card0 -f kmsgrab -i - \
-vf "hwmap=derive_device=vaapi,scale_vaapi=w=1920:h=1080:format=nv12" \
-c:v h264_vaapi -qp 24 capture.mp4The hwmap step is the zero-copy handover described in the post on mixed chains: the framebuffer's memory is shared with a VAAPI surface, so no pixel is copied before the scaler. On other systems, x11grab and gdigrab produce software frames, and the commands in the pattern 1 section apply.
Reproducibility and testing recipes
Software encodes are deterministic on one machine: the same input and options give the same bytes, which makes regression tests simple. Hardware encodes are not guaranteed to be. A driver update can change the encoder's decisions, different GPU models differ, and even the same model may differ between runs when the encoder uses features such as adaptive quantisation with timing-dependent state. Treat the hardware encoder as a black box with a quality contract and not as a function with fixed output.
That changes how you test. Compare outputs by properties and by quality, not by checksums:
ffprobe -v error -select_streams v:0 \
-show_entries stream=codec_name,profile,width,height,r_frame_rate,nb_frames \
-of default=nw=1 out.mp4codec_name=h264
profile=High
width=1280
height=720
r_frame_rate=24/1
nb_frames=1440A CI check can assert that the codec, profile, geometry, frame rate and frame count match the expected values, that the duration matches the source within a frame, and that VMAF against the source stays above a threshold that you chose from your own measurements. Pin the FFmpeg and driver versions in the test environment and rerun the quality gate whenever either changes. Where a machine has no GPU, skip the hardware tests explicitly and say so in the report, so that a green run does not imply the hardware path was exercised.
Keep a small corpus of difficult clips: a dark scene with gradients, a fast pan, a scene full of fine texture such as foliage and a clip with hard cuts. Easy clips make every encoder look good, and the difficult ones are where recipes differ.
Choosing the codec: H.264, HEVC or AV1
The encoder API is half of the decision. The other half is the codec, and the hardware supports each one differently.
H.264 is the safe choice. Every GPU generation encodes it, every device decodes it and every streaming and conferencing system accepts it. Its compression is the weakest of the three, so it needs the most bitrate for a given quality. Choose it when the audience is unknown or old devices matter.
HEVC needs about half the bitrate of H.264 for similar quality in typical comparisons, and it supports 10-bit and HDR cleanly. Hardware HEVC encoders exist on all recent GPUs, and hardware decoders are common on phones, TVs and recent computers. Licensing is more complicated than for H.264, and browser support is uneven, so it suits a controlled audience such as an app, a set-top box or a fleet of Apple devices. Remember -tag:v hvc1 for Apple software.
AV1 compresses best and is royalty-free, and hardware encoders exist only on the newest GPUs: NVIDIA Ada and later, Intel Arc and Meteor Lake and later, and AMD RDNA 3 and later. Decoding support is spreading but far from universal, so a viewer with an older device decodes it in software, which costs battery and can stutter. Choose it where you control playback or where bandwidth savings repay the compatibility risk, and keep an H.264 rendition as a fallback.
A practical policy for a service is a ladder with H.264 for reach and a second ladder with HEVC or AV1 for devices that announce support, with the player choosing. The hardware encoders make the second ladder affordable to produce, because the cost of producing it in software was the reason many teams did not.
Do not compare bitrates across codecs by reading option values. A constant quality value of 23 in H.264 and a value of 28 in HEVC are scales of different meaning. Compare finished files by eye and by VMAF at equal bitrates.
Audio, subtitles and containers
Hardware accelerates video only. The audio is encoded by the usual software codecs, which are cheap, so it never limits a pipeline. Two habits keep this part simple. Copy the audio with -c:a copy when the target container accepts it, which avoids a lossy generation. Re-encode with -c:a aac -b:a 160k when it does not, as when you move PCM audio into MP4.
Containers matter for compatibility and for streaming behaviour:
| Container | Good for | Watch out for |
|---|---|---|
| MP4 | Delivery to browsers, phones and TVs | HEVC needs hvc1, and add -movflags +faststart for web |
| Matroska (MKV) | Archives, many subtitle and audio tracks | Poor support in browsers and on some TVs |
| MPEG-TS | Broadcast, HLS segments | Larger overhead per packet |
| WebM | Browsers | Restricts codecs to VP8, VP9 and AV1 with Opus or Vorbis |
| FLV | RTMP ingest | Legacy, H.264 and AAC only |
Subtitles in MP4 are limited to the mov_text format, so image-based subtitle tracks from Blu-ray sources need MKV or a burn-in. Burning in subtitles with the subtitles filter is a software step that forces a download in a GPU pipeline, as the post on mixed chains explains.
Global headers matter for some muxers. FFmpeg sets the global_header flag on encoders automatically when the container needs it, and with hardware encoders the parameter sets are emitted correctly in that case. If a player reports a missing codec configuration on an MP4 you produced, check that the file was finalised: a job that was killed leaves an MP4 without its index, and no encoder option repairs it.
Capacity and cost
A hardware encoder changes the economics of a transcoding service more than any single setting does. A CPU-only service buys cores in proportion to streams, so the cost grows linearly with load. A GPU service buys a card per many streams, and the CPU needs enough capacity for demuxing, audio and the occasional software filter. The break-even depends on prices that change, so work it out with your own numbers: measure the streams per GPU with the throughput harness, measure the streams per CPU core with the software encoder at the quality you accept, then compare cost per stream including power.
Three cautions improve the estimate. First, plan from the quality-matched comparison, not from raw speed, because a hardware encode that needs thirty percent more bitrate for the same quality raises delivery cost for every viewer. For a service that streams each file many times, bandwidth can outweigh encode cost. Second, include the session limits of the cards you can buy, since a consumer card with a cap can be the wrong tool for a many-stream service, and professional cards or data-centre parts remove or raise it. Third, include operational cost: driver management, a software fallback for failures and the engineering time to maintain two code paths. A fleet that runs one well-understood path is easier to keep alive than a clever mixed one.
Where to go next in this cluster
Once the basics here work, the follow-up posts deepen each branch. The platform recipes cover VideoToolbox, VAAPI, NVENC and Quick Sync one by one. The tuning post covers NVENC presets, look-ahead and adaptive quantisation. The AV1 post covers the three hardware AV1 encoders. The posts on keeping frames on the GPU and on mixed chains cover the pipeline design, and the post on parallel transcodes covers capacity. For the C API behind the command line, the libav guide in this topic shows how an application opens a hardware device and feeds an encoder.
Field manual: errors and what they mean
Hardware pipelines fail with messages that point at the wrong layer. This table collects the ones you will meet, with the usual cause.
| Message | Usual cause | Fix |
|---|---|---|
Unknown encoder 'h264_nvenc' | The build lacks the encoder | Use a build with NVENC, check ffmpeg -encoders |
Cannot load libcuda.so.1 or libnvidia-encode.so.1 | No NVIDIA driver, or a container without the video capability | Install the driver, set NVIDIA_DRIVER_CAPABILITIES=compute,video,utility |
OpenEncodeSessionEx failed: out of memory (10) | The session cap was reached | Run fewer parallel jobs |
Codec not supported or No capable devices found | The GPU lacks the codec | Check the vendor matrix |
Format yuv420p not supported for hardware encoding | VAAPI got a software frame | Add format=nv12,hwupload |
Invalid output format vaapi for hwframe download | hwdownload has no format after it | Add format=nv12 |
Impossible to convert between the formats ... Function not implemented | A software filter received GPU frames | Download first or use a GPU filter |
No VA display found for device | Wrong render node or no permission | Check ls -l /dev/dri and group membership |
Error creating a MFX session: -9 | libvpl or driver missing or mismatched | Install the Intel media driver and runtime |
| Black picture in QuickTime | HEVC tagged hev1 | Add -tag:v hvc1 |
| Pool exhausted, not enough surfaces | Look-ahead or B-frames need more | Raise -extra_hw_frames or extra_hw_frames |
When none of these fits, rerun with -v verbose and read the first thirty lines. Hardware negotiation prints the device, the formats at each link and which options were ignored. A recipe that silently drops its main features, for example when look-ahead is disabled because of the preset, is not doing what you think.
Operating hardware encoding in production
Several practices separate a script that works once from a service that keeps working.
Pin the versions. The behaviour of options, defaults and available encoders changes between FFmpeg releases and between driver releases. Record the FFmpeg version, the driver version and the GPU model next to every recipe, and rerun your quality check after a driver update, because a driver can change the encoder's output.
Validate output automatically. After each encode, run ffprobe to check the codec, resolution, frame rate and duration against the source. A hardware failure sometimes produces a file that plays for a few seconds, and a duration check catches it. Compare the packet count with the source if the job drops frames.
Handle fallback. Hardware may be unavailable because of a driver crash, a session cap or a node without a GPU. The wrapper pattern above gives a software fallback. Decide in advance whether a fallback is acceptable, since a software fallback may be many times slower and miss a deadline.
Isolate by GPU. On multi-GPU machines, assign jobs to devices explicitly (-gpu N for NVENC, a different render node for VAAPI) and monitor per-device sessions.
Watch temperature and clocks. Long encodes on a small or crowded case can throttle. Throughput measured cold is not throughput measured after an hour.
When not to use hardware encoding
The honest list is short. Do not use it for archives where size dominates, for content that needs precise bitrate conformance, for formats the hardware lacks such as 4:4:4 or lossless H.264 in some cases, or when the machine has no engine at all. And do not use it only because it feels modern: a slow x264 encode of a short file may cost nothing to run and give a better result. The method for deciding is to measure, and the cost of measuring is a script and an hour.


