Skip to content

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

Open
EC061 wants to merge 1 commit into
sqlpxc:mainfrom
EC061:t3/linux-hardware-acceleration
Open

EC061 wants to merge 1 commit into
sqlpxc:mainfrom
EC061:t3/linux-hardware-acceleration

Conversation

@EC061

@EC061 EC061 commented Nov 29, 2026 •

Copy link
Copy Markdown

Summary

Adds optional Linux hardware video encoding (VA-API and NVENC for H.264, HEVC, and AV1) via system GStreamer (gstreamer-rs 0.23, v1_22 feature floor for Debian 12 Bookworm compatibility), replacing the earlier FFmpeg dlopen/ABI approach and addressing all review feedback from @sqlpxc.

What's changed

  • GStreamer hardware encoder (client/src-tauri/src/host/encoder/linux.rs, #![forbid(unsafe_code)]):
    • Uses system GStreamer (gstreamer1.0-plugins-bad, already a Linux package dependency) — no C FFmpeg ABI glue, no build.rs probe, and no libavcodec* .deb recommends.
    • NVENC (nvcudah264enc, nvcudah265enc, plus nvcudaav1enc/nvav1enc on GStreamer 1.26+): feeds BT.709 limited-range NV12 through an encoder-owned GstBufferPool (honoring GStreamer's 4-byte row alignment for widths like 1366 and 1590), sets explicit downstream caps, keeps vbv-buffer-size fixed at init, and updates only bitrate/max-bitrate at runtime for same-frame, zero-IDR dynamic bitrate changes (with fallible property probing for GStreamer 1.22 / 1.24 / 1.26+).
    • VA-API (va plugin vah264enc, vah265enc, vaav1enc, multi-GPU varenderD* and *lpenc variants): resolves DRM render nodes across GStreamer 1.22 (rate-control enum type / READY fallback) and 1.24+ (device-path), sets b-frames=0, ref-frames=1 (prevents Intel iHD 24.1.0 vaEndPicture failure), key-int-max=1024, and hierarchical-level=1 / gf-group-size=1 for 1-in-1-out AV1. Uses FlushStart + FlushStop(false) on appsrc for reliable forced IDRs with full headers (avoiding GStreamer 1.24.2 GstVaBaseEnc force-key-unit bugs), rejects CQP-only drivers, detects sync keyframes + in-band headers strictly from the bitstream, and retains VA-API-only bitrate hysteresis (READY -> set -> PLAYING when bitrate is not MUTABLE_PLAYING, e.g. vaav1enc on 1.24.2).
    • Lazy cached probing & WSL2/container support: no eager startup warm_up(); caches validated candidates lazily in OnceLock<ProbeCache> shared by available_codecs() and LinuxHwEncoder::new() (so hosts without working hardware fail fast with zero retries); bypasses PCI sysfs gating when hw_encoder = "nvenc" (and checks /dev/nvidiactl / /dev/dxg in auto); uses non-blocking pool acquisition and bounded worker-thread teardown.
  • Scope & cleanup:
    • Leaves annexb_nal_types untouched (no Windows/macOS HEVC path changes).
    • Leaves host/mod.rs, host/pipeline.rs, build.rs, and tauri.linux.conf.json unchanged relative to main.
    • Updates VideoEncoder::set_bitrate documentation in encoder/mod.rs.
    • Preserves hw_encoder and vaapi_device in config.rs via put_setting (keeping the # Airhand file header banner intact).
  • CI & docs:
    • Adds libgstreamer1.0-dev and libgstreamer-plugins-base1.0-dev to .github/workflows/release.yml and docs/building*.md.
    • Adds .github/workflows/check.yml running rustfmt --edition 2024 --check on changed Rust files and cargo test --locked --lib in a Debian 12 Bookworm container (including hardware-free GStreamer appsrc ! identity ! appsink padded-NV12/pool/flush/property/cache unit tests that never silently skip).
    • Updates README*.md, docs/architecture*.md, docs/limitations*.md, and docs/usage*.md.

@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
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
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