Skip to content

feat(linux): add VA-API and NVENC hardware video encoding - #89

Merged
sqlpxc merged 3 commits into
sqlpxc:mainfrom
EC061:t3/linux-hardware-acceleration
Dec 3, 2026
Merged

sqlpxc merged 3 commits into
sqlpxc:mainfrom
EC061:t3/linux-hardware-acceleration

Conversation

@EC061

@EC061 EC061 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds optional Linux hardware video encoding (VA-API and NVENC for H.264, HEVC and AV1) through the system GStreamer (gstreamer-rs 0.23 with the v1_22 feature floor for Debian 12 Bookworm), replacing the earlier FFmpeg dlopen/ABI approach. Hosts without a working GPU, driver or GStreamer encoder plugin fall back to OpenH264 as before.

Encoder (client/src-tauri/src/host/encoder/linux.rs, #![forbid(unsafe_code)])

  • Pipeline: appsrc (BT.709 limited-range NV12 written into an encoder-owned GstBufferPool, honoring GStreamer's 4-byte row alignment for widths like 1366 and 1590) → encoder → explicit caps filter → appsink, strictly one frame in, one frame out. Keyframes are classified from the bitstream: an IDR / IRAP with in-band parameter sets, or for AV1 a KEY_FRAME after a sequence header.
  • NVENC (nvcudah264enc, nvcudah265enc; nvav1enc on GStreamer 1.26+):
    • Bitrate changes only touch bitrate / max-bitrate: a soft reconfigure on the same frame, no IDR.
    • The VBV (about 4 frames) is resized only when the size the current bitrate calls for stays 2× off (2 s down, 6 s up), or is 1.5× off on a keyframe that is coming anyway. A resize re-initializes the encoder and costs one IDR.
    • Forced keyframes via UpstreamForceKeyUnitEvent.
  • VA-API (va plugin: vah264enc, vah265enc, vaav1enc, the multi-GPU varenderD* and the *lpenc variants):
    • b-frames=0, ref-frames=1 (with the default 3, Intel iHD 24.1.0 fails at vaEndPicture after a few frames), key-int-max=1024 (the maximum), and for AV1 hierarchical-level=1 / gf-group-size=1 for 1-in-1-out. Encoders with neither VBR nor CBR are rejected.
    • VBR with the peak at about 1.5× the target. cpb-size is set with every bitrate to half the peak bitrate, the smallest GStreamer accepts: left at 0, the encoders buffer 2 s of peak bitrate (about 3 s of the target) and keep that size after a bitrate drop.
    • A bitrate change restarts the GOP, so it goes through hysteresis (a ≥1.25× drop held for 2 s, a ≥1.3× rise held for 6 s, or together with a keyframe that is coming anyway). vaav1enc on 1.24, whose bitrate can't change in PLAYING, goes through READY.
    • Forced keyframes via FlushStart + FlushStop(false) on appsrc: on 1.22 a force-key-unit only promotes the frame to an I slice, and on 1.24.2 it gave vah264enc a non-IDR frame without SPS/PPS and stalled vah265enc.
    • Render nodes are resolved on 1.22 (the rate-control enum type name, or briefly going to READY) and on 1.24+ (device-path).
  • Device selection: hw_encoder = "auto" prefers the GPU driving the connected display, and doesn't probe a secondary NVENC when the display's VA-API GPU already encodes. "vaapi", "nvenc" (no PCI check, for WSL2 and containers) and "software" force a backend; vaapi_device picks a render node. Both can be overridden with AIRHAND_HW_ENCODER / AIRHAND_VAAPI_DEVICE.
  • Probing is lazy (on the first session, no work at startup) and cached in a OnceLock shared by available_codecs() and LinuxHwEncoder::new(), so hosts without working hardware fail fast. Pipelines are torn down on a worker thread with a 3 s timeout; a factory that hangs there isn't used again in the process (nor advertised, if it happens while probing).

Other changes

  • config.rs: hw_encoder and vaapi_device, kept when the file is regenerated.
  • encoder/mod.rs: wires up Linux and documents in VideoEncoder::set_bitrate which backends may need a keyframe for a bitrate change.
  • .deb: depends on libgstreamer1.0-0 and libgstreamer-plugins-base1.0-0 (>= 1.22), which the binary links; the encoders come from gstreamer1.0-plugins-bad, already a dependency.
  • release.yml and docs/building*.md: libgstreamer1.0-dev and libgstreamer-plugins-base1.0-dev.
  • Docs: README, architecture, limitations and usage, in English and Chinese.
  • Unchanged: annexb_nal_types (no Windows / macOS HEVC changes), host/mod.rs, host/pipeline.rs, build.rs.

Testing

Unit tests need no GPU: backend and probing policy, bitstream parsing, the hysteresis clocks, CPB and VBV sizes, config round trip, and a real GStreamer appsrc ! identity ! appsink round trip of padded NV12 through the buffer pool and a flush.

The hardware tests are #[ignore]d. On a machine with a GPU (and ffmpeg for the strict decode checks):

AIRHAND_REQUIRE_HW_TEST=1 cargo test --lib host::encoder::linux -- --ignored --nocapture --test-threads=1

They cover 1-in-1-out, forced keyframes with headers, non-4/16-aligned sizes, BT.709 colors, NVENC's IDR-free bitrate drop and VBV resize, and VA-API's hysteresis, CPB size and AV1 READY cycle; every stream is decoded with ffmpeg -err_detect explode.

Where GStreamer Result
Debian 12 container, merged with main 1.22.0 Unit tests pass
WSL2, RTX 4080 Laptop GPU, merged with main 1.24.2 Unit tests and the NVENC hardware tests (H.264, HEVC) pass
Linux Mint 22.3, Intel Arrow Lake-U (iHD 24.1.0) + RTX 4090 1.24.2 VA-API H.264 / HEVC / AV1 and NVENC H.264 / HEVC hardware tests, benchmarks and an end-to-end session; run before the CPB / VBV changes (see the comments)

Not run on hardware yet: VA-API since the CPB change, GStreamer 1.22 (Debian 12) with a GPU, and NVENC AV1 (GStreamer 1.26).

@sqlpxc

sqlpxc commented Dec 1, 2026

Copy link
Copy Markdown
Owner

Thanks a lot for this. Linux hardware encoding is something we really want, and the PR clearly took a lot of care (device validation, smoke tests,
in-band headers, 1-in-1-out). I reviewed it, built it, and ran it on Ubuntu 24.04 (FFmpeg 6.1.1, NVIDIA via WSL2). Some findings, then a proposal
about the overall approach.

1. Blocker: FFmpeg 6.x (libavcodec 60) never loads

On Ubuntu 24.04 (libavcodec60 7:6.1.1-3ubuntu5, x86_64) ffmpeg::api() returns None, so every session silently falls back to OpenH264. The
unit test also prints skipping FFmpeg ABI test: no system libavcodec 60-63 found.

Cause: AhCtxFps60 puts skip_frame at offset 0, which is 8-aligned, so the compiler pads 4 bytes before subtitle_header. In the real
AVCodecContext, skip_frame sits at offset 684 (684 % 8 = 4), so that padding doesn't exist:

  • av_opt_find: skip_frame = 684, pkt_timebase = 716, so the real distance is 32
  • AhCtxFps60 expects 36
  • ah_av_ctx_framerate_offset(60, 684, 100, 716) returns -1, and init_from_handle bails

Suggested fix: drop the framerate poke entirely. You already set time_base = 1/fps, and both vaapi_encode and nvenc derive the frame rate
from time_base when framerate is unset. That removes AhCtxFps60/61, ah_av_ctx_framerate_offset, and half of the canary. With that anchor
bypassed locally, the NVENC H.264/HEVC/AV1 tests pass on FFmpeg 6.1.

2. VA-API hwframe canary rejects a valid surface ID

create_vaapi_frames fails when data[3] (the VASurfaceID) is NULL. But surface ID 0 is valid in VA-API (VA_INVALID_ID is 0xffffffff), and
intel-media-driver (iHD) hands out IDs from 0 on a fresh display (AllocPMediaSurfaceFromHeap). I couldn't test VA-API here, but I think this check
should go.

3. Bitrate changes produce IDRs

VideoEncoder::set_bitrate promises "no rebuild, no keyframe", but with FFmpeg neither backend can keep that promise: *_vaapi needs a reopen,
and nvenc.c sets resetEncoder=1, forceIDR=1 on reconfigure. The hysteresis softens this, but in practice (1080p60, 20 → 5 Mbps requested at
frame 300):

  • the new rate only took effect at frame 421, with an IDR
  • during those 2 s the encoder kept producing ~28 KiB/frame against a ~10 KiB/frame target (~2.7×), during congestion

4. Proposal: use GStreamer instead of FFmpeg

The .deb already hard-depends on gstreamer1.0-plugins-bad, which ships the nvcodec and va encoders. I built a small prototype (appsrc →
encoder → appsink, ~120 lines with gstreamer-rs) and ran the same workload through both paths on NVENC:

GStreamer nvcudah264enc FFmpeg (this PR) h264_nvenc
latency median / p95 3.9–4.3 / 6.4–7.4 ms 4.0–5.1 / 7.5–12.7 ms (noise)
CPU per frame ~1.4–1.5 ms ~1.4–1.5 ms
20 → 5 Mbps no IDR, applied on the same frame IDR (or delayed 2 s + IDR with hysteresis)
1-in-1-out, forced IDR with SPS/PPS, BT.709 colours ✓ ✓

Why I think it's the better base:

  • No ABI layer. Everything goes through stable GObject properties, so the whole ffmpeg_abi.c / ffmpeg.rs class of bugs disappears, and so
    does the need to add a new struct layout for every FFmpeg major.
  • NVENC bitrate changes without keyframes. GStreamer's GstNvEncoder reconfigures with resetEncoder=0, forceIDR=0, so the trait contract
    holds, and the hysteresis plus the pipeline.rs hook aren't needed for NVENC.
  • Better coverage. Our release .deb is built on Debian 12. Debian 12 has FFmpeg 5.1 (no hardware encoding with this PR) but GStreamer 1.22
    with nvcuda*enc and va*enc.
  • No new runtime dependency. The libavcodec recommends can go. The cost is libgstreamer1.0-dev and libgstreamer-plugins-base1.0-dev in
    CI.

Caveats I hit or found in the source:

  • In 1.24.2, nvcudah264enc only negotiates NV12/Y444 once downstream fixes a profile, so BGRA input doesn't work. Feed NV12 (the same CPU
    conversion you already do). You also need an explicit caps filter after the encoder, otherwise negotiation fails.
  • Only bitrate/max-bitrate get the soft reconfigure. Changing vbv-buffer-size at runtime triggers a full re-init (IDR plus a ~50 ms spike in
    my test), so keep the VBV fixed.
  • nvav1enc only exists from 1.26, so Ubuntu 24.04 loses NVENC AV1. VA AV1 is available from 1.24.
  • From the source only (not tested on hardware): vah26xenc still restarts the GOP (IDR) on a bitrate change, the same as FFmpeg, and
    key-int-max is capped at 1024, so it can't do an infinite GOP. The hysteresis would still be useful for VA-API.

The NVENC pipeline I used:

appsrc (video/x-raw,format=NV12,colorimetry=bt709) !
nvcudah264enc preset=p4 tune=ultra-low-latency rate-control=vbr gop-size=-1 b-frames=0
              zero-reorder-delay=true repeat-sequence-header=true aud=false vbv-buffer-size=<fixed> !
video/x-h264,stream-format=byte-stream,alignment=au,profile=high !
appsink sync=false

Forced keyframes: send UpstreamForceKeyUnitEvent with all_headers(true) on the appsink. Bitrate: set only bitrate/max-bitrate.

Would you be open to reworking the encoder part on top of GStreamer? The device selection, config keys and tests in this PR would mostly carry
over. If you'd rather keep FFmpeg, then 1 and 2 are must-fix, and 3 at least needs the trait docs updated.

5. Smaller items

  • cargo fmt: there are 73 formatting diffs in the changed files (main is clean).
  • The annexb_nal_types change also affects the Windows/macOS HEVC paths and isn't needed here. Please split it out.
  • With hw_encoder = "nvenc", the capability probe is still gated on an NVIDIA PCI device being visible in sysfs, but new() isn't. In WSL and
    some containers, H.264 then runs on NVENC while HEVC/AV1 are never advertised.
  • LinuxHwEncoder::new doesn't check the probe results, so on machines without working hardware every encoder rebuild retries all devices and
    profiles.
  • warm_up() loads libavcodec (and possibly CUDA) when the host starts, even if nobody ever connects. Could it be lazy?
  • CI doesn't run these tests, and the hardware tests skip silently, which is how item 1 slipped through.

Thanks again! Happy to share the benchmark harness if it helps.
gstbench.zip

@EC061
EC061 force-pushed the t3/linux-hardware-acceleration branch from 958a7a1 to 0b28790 Compare December 1, 2026 15:10
@EC061 EC061 changed the title Add Linux VA-API and NVENC hardware video encoding (H.264/HEVC/AV1) feat(linux): add GStreamer VA-API and NVENC hardware video encoding Dec 1, 2026
@EC061

EC061 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks a lot @sqlpxc for the thorough review, the clear GStreamer direction, and for sharing gstbench.zip! Your feedback and benchmark harness were super helpful — especially catching the FFmpeg 6.x alignment bug, the VA-API surface ID 0 check, and showing how cleanly GStreamer GstNvEncoder handles zero-IDR bitrate updates.

I accepted all of your suggestions, rebased onto latest main, and reworked the Linux hardware encoder onto system GStreamer (gstreamer / gstreamer-app / gstreamer-video 0.23 with the v1_22 floor for Debian 12 Bookworm):

Summary of changes addressing your comments

  1. Switched from FFmpeg dlopen/ABI to GStreamer (#![forbid(unsafe_code)]): dropped ffmpeg_abi.c, ffmpeg.rs, the Linux C build step, and libavcodec* .deb recommends; added libgstreamer1.0-dev and libgstreamer-plugins-base1.0-dev to .github/workflows/release.yml and docs/building*.md.
  2. NVENC soft bitrate updates (no IDR): fixed vbv-buffer-size at pipeline init and update only bitrate/max-bitrate at runtime, removing the pipeline.rs hook and limiting bitrate hysteresis to VA-API only; updated VideoEncoder::set_bitrate docs accordingly.
  3. VA-API real-hardware findings fixed via gstbench:
    • Set ref-frames=1 on VA encoders (on Intel iHD 24.1.0, vah264enc with default ref-frames=3 failed with vaEndPicture: internal encoding error after ~15 frames).
    • Set hierarchical-level=1 and gf-group-size=1 on vaav1enc for strict 1-in-1-out, and handle non-MUTABLE_PLAYING bitrate via READY -> set -> PLAYING.
    • Force VA-API keyframes via FlushStart + FlushStop(false) on appsrc (on GStreamer 1.24.2 GstVaBaseEnc, UpstreamForceKeyUnitEvent caused vah264enc to emit a headerless non-IDR slice and caused vah265enc to stall on the next frame) and classify EncodedFrame.key strictly from bitstream sync + in-band headers.
    • Respect GStreamer's 4-byte NV12 row alignment (VideoInfo strides/offsets) with an encoder-owned GstBufferPool so widths like 1366 and 1590 convert cleanly without shearing.
    • Added GStreamer 1.22 (Debian 12) compatibility for device-path discovery (rate-control enum type name / READY fallback) and fallible property setters (preset without tune on 1.22).
  4. All smaller items:
    • Clean rustfmt formatting across all changed files.
    • Reverted the annexb_nal_types change (Windows/macOS HEVC paths untouched).
    • Removed the PCI sysfs gate when hw_encoder = "nvenc" (and check /dev/nvidiactl & /dev/dxg in auto) for WSL2 / containers.
    • LinuxHwEncoder::new() now checks the cached probe results first and fails immediately when no hardware is available.
    • Removed eager startup warm_up(); probing and gst::init() are lazy on first use.
    • Added .github/workflows/check.yml (Debian 12 Bookworm) running rustfmt --edition 2024 --check on changed Rust files and cargo test --locked --lib with hardware-free GStreamer appsrc ! identity ! appsink stride/pool/flush/property/cache tests that never silently skip, plus AIRHAND_REQUIRE_HW_TEST=1 for hardware runs.

Real-world testing & benchmarks performed

Test machine: Linux Mint 22.3 (Ubuntu 24.04 base, X11 DISPLAY=:0 @ 2560×1440), GStreamer 1.24.2, dual GPU:

  • Intel Arrow Lake-U iGPU (/dev/dri/renderD128, Intel iHD 24.1.0, driving the active display)
  • NVIDIA GeForce RTX 4090 (/dev/dri/renderD129, proprietary driver + libgstnvcodec.so)

1. gstbench 1080p60 600-frame workload through LinuxHwEncoder (release build)

Using your gstbench common.rs generator/reporter verbatim (1920×1080 @ 60 fps, 600 frames, forced keyframe at frame 150, 20 → 5 Mbps bitrate drop at frame 300):

Encoder Latency median / p95 / p99 CPU/frame 1-in-1-out Forced IDR @150 (missing hdr) 20→5 Mbps @300 Avg P-frame KiB (budget 40.7 → 10.2)
NVENC H.264 (nvcudah264enc) 3.80 / 4.09 / 4.19 ms 1.49 ms ✓ (0 extra) ✓ [150] (0) 0 IDR, same frame (39.1→18.9K) 36.4 → 12.4 KiB
NVENC HEVC (nvcudah265enc) 4.57 / 5.00 / 5.16 ms 1.62 ms ✓ (0 extra) ✓ [150] (0) 0 IDR, same frame (38.9→17.3K) 38.7 → 11.3 KiB
VA-API H.264 (vah264enc) 5.97 / 8.07 / 8.38 ms 3.77 ms ✓ (0 extra) ✓ [150] (0) Hysteresis @421 (+2s, IDR+hdr) 40.8 → 10.2 KiB
VA-API HEVC (vah265enc) 6.18 / 8.36 / 10.03 ms 4.26 ms ✓ (0 extra) ✓ [150] (0) Hysteresis @420 (+2s, IDR+hdr) 43.8 → 11.9 KiB
VA-API AV1 (vaav1enc) 6.09 / 8.10 / 8.73 ms 3.82 ms ✓ (0 extra) ✓ [150] (0) Hysteresis @420 (+2s, IDR+hdr) 39.7 → 10.2 KiB

2. Unit, Debian 12 CI, & live hardware test suites

  • Debian 12 Bookworm CI (debian:bookworm, GStreamer 1.22): built cleanly and passed 121 passed, 0 failed (cargo test --locked --lib, including the hardware-free GStreamer appsrc ! identity ! appsink buffer pool / 4-byte aligned NV12 stride / flush PTS / fallible property / config header tests) + rustfmt --edition 2024 --check.
  • Live GPU suite (AIRHAND_REQUIRE_HW_TEST=1 cargo test --locked --lib): 121 passed, 0 failed (cargo clippy --locked --all-targets -- -W clippy::all: 0 warnings in changed files). Verified live VA-API (H.264, HEVC, AV1) and NVENC (H.264, HEVC) across 1280×720, non-4/16-aligned strides (1366×768, 1590×994, 1728×1080), and 2560×1440 (VA-API AV1), with strict ffmpeg -err_detect explode frame-count decode checks, BT.709 red/blue RGB color round-trip assertions, NVENC zero-IDR bitrate drop (verifying no raw H.264 IDR NAL 5 after frame 0), and VA-API hysteresis + AV1 READY -> PLAYING rate transitions.

3. Live X11 capture benchmark (encode_bench) & real-world simulated-client E2E (e2e_roundtrip)

  • Ran encode_bench capturing the live 2560×1440 X11 desktop (NVENC H.264 2560×1440 p50 6.35 ms, VA-API H.264 p50 12.10 ms, VA-API AV1 p50 12.85 ms).
  • Started a local airhand-server relay (udp://0.0.0.0:4433) and ran e2e_roundtrip with the protocol-level simulated controller over QUIC + E2E encryption in all three modes:
    • AIRHAND_HW_ENCODER=auto: lazily probed Intel VA-API ([H264, H265, AV1], skipping secondary NVENC), streamed VA-API H.264 (Intel) 1080p30 (OpenH264 decode verified), then switched live mid-session to VA-API AV1 (Intel) 720p60 — passed.
    • AIRHAND_HW_ENCODER=nvenc: lazily probed RTX 4090 NVENC ([H264, H265]), streamed NVENC H.264 1080p30 (OpenH264 decode verified), then handled mid-session quality/codec switch cleanly — passed.
    • AIRHAND_HW_ENCODER=software: skipped GStreamer init, advertised [H264], and streamed OpenH264 (took_ms=0) — passed.

(Note: Debian 12 / GStreamer 1.22 build & hardware-free tests passed in CI, and GStreamer 1.22 plugin behavior was audited against upstream source; live GPU hardware runs were executed on GStreamer 1.24.2.)

@EC061 EC061 changed the title feat(linux): add GStreamer VA-API and NVENC hardware video encoding feat(linux): add VA-API and NVENC hardware video encoding Dec 1, 2026
Review follow-ups for the GStreamer hardware encoders.

- VA-API: set cpb-size together with every bitrate (init, hysteresis, the
  READY cycle) to half the peak bitrate, the smallest GStreamer accepts. Left
  at 0, the va encoders buffer 2 s of peak bitrate (about 3 s of the target)
  and write that back to cpb-size, so after a 20 -> 5 Mbps drop the buffer
  stayed at about 12 s of the new rate and single frames (forced IDRs, scene
  changes) were barely bounded.
- NVENC: the VBV was sized once from the bitrate at creation, which in
  adaptive mode can be far from where the stream goes (created at 3 Mbps, a
  50 Mbps stream had a VBV smaller than one average frame; created at
  100 Mbps, a 2 Mbps stream had seconds of it). Resize it when the size the
  current bitrate calls for stays 2x off (2 s down, 6 s up), or is 1.5x off
  on a keyframe that is coming anyway. That costs one IDR; bitrate changes in
  between stay IDR-free. It shares one hysteresis state machine with the
  VA-API bitrate.
- Probing: a candidate whose teardown timed out (and got blacklisted) is no
  longer cached as available, which advertised codecs new() then skipped.
  The teardown timeout is 3 s instead of 1 s, since a timeout blacklists the
  factory for the whole process.
- AV1: a keyframe now needs frame_type == KEY_FRAME in the first frame
  header after the sequence header, not just both OBUs; the temporal
  delimiter is only copied in when it's missing. Drop nvcudaav1enc, which
  doesn't exist (1.26's CUDA mode AV1 encoder is nvav1enc).
- Tests: the hardware tests are #[ignore] like the other environment-bound
  tests in the repo (AIRHAND_REQUIRE_HW_TEST=1 cargo test -- --ignored); the
  NVENC one also checks the VBV resize, the VA-API one that GStreamer kept
  the cpb-size.
- The .deb depends on libgstreamer1.0-0 and libgstreamer-plugins-base1.0-0
  (>= 1.22), which the binary links directly; check.yml caches dependencies.
- docs: limitations, VideoEncoder::set_bitrate.
The repository doesn't build or test on pull requests (only the PR title is
checked), and the release workflow already builds the Linux client on
Debian 12 with the GStreamer development packages. Whether to add per-PR CI
is a separate decision; the Linux tests run locally instead (the hardware
ones with AIRHAND_REQUIRE_HW_TEST=1 cargo test -- --ignored, see linux.rs).
@sqlpxc
sqlpxc merged commit 642e7c0 into sqlpxc:main Dec 3, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants