Repository navigation
feat(linux): add VA-API and NVENC hardware video encoding - #89
Conversation
|
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, 1. Blocker: FFmpeg 6.x (libavcodec 60) never loadsOn Ubuntu 24.04 ( Cause:
Suggested fix: drop the 2. VA-API hwframe canary rejects a valid surface ID
3. Bitrate changes produce IDRs
4. Proposal: use GStreamer instead of FFmpegThe .deb already hard-depends on
Why I think it's the better base:
Caveats I hit or found in the source:
The NVENC pipeline I used: Forced keyframes: send 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 5. Smaller items
Thanks again! Happy to share the benchmark harness if it helps. |
958a7a1 to
0b28790
Compare
|
Thanks a lot @sqlpxc for the thorough review, the clear GStreamer direction, and for sharing I accepted all of your suggestions, rebased onto latest Summary of changes addressing your comments
Real-world testing & benchmarks performedTest machine: Linux Mint 22.3 (Ubuntu 24.04 base, X11
1.
|
| 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 GStreamerappsrc ! identity ! appsinkbuffer 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) across1280×720, non-4/16-aligned strides (1366×768,1590×994,1728×1080), and2560×1440(VA-API AV1), with strictffmpeg -err_detect explodeframe-count decode checks, BT.709 red/blue RGB color round-trip assertions, NVENC zero-IDR bitrate drop (verifying no raw H.264 IDR NAL5after frame 0), and VA-API hysteresis + AV1READY -> PLAYINGrate transitions.
3. Live X11 capture benchmark (encode_bench) & real-world simulated-client E2E (e2e_roundtrip)
- Ran
encode_benchcapturing the live 2560×1440 X11 desktop (NVENC H.2642560×1440 p506.35 ms,VA-API H.264p5012.10 ms,VA-API AV1p5012.85 ms). - Started a local
airhand-serverrelay (udp://0.0.0.0:4433) and rane2e_roundtripwith 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), streamedVA-API H.264 (Intel)1080p30 (OpenH264 decode verified), then switched live mid-session toVA-API AV1 (Intel)720p60 — passed.AIRHAND_HW_ENCODER=nvenc: lazily probed RTX 4090 NVENC ([H264, H265]), streamedNVENC H.2641080p30 (OpenH264 decode verified), then handled mid-session quality/codec switch cleanly — passed.AIRHAND_HW_ENCODER=software: skipped GStreamer init, advertised[H264], and streamedOpenH264(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.)
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).
Summary
Adds optional Linux hardware video encoding (VA-API and NVENC for H.264, HEVC and AV1) through the system GStreamer (
gstreamer-rs0.23 with thev1_22feature floor for Debian 12 Bookworm), replacing the earlier FFmpegdlopen/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)])appsrc(BT.709 limited-range NV12 written into an encoder-ownedGstBufferPool, 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 aKEY_FRAMEafter a sequence header.nvcudah264enc,nvcudah265enc;nvav1encon GStreamer 1.26+):bitrate/max-bitrate: a soft reconfigure on the same frame, no IDR.UpstreamForceKeyUnitEvent.vaplugin:vah264enc,vah265enc,vaav1enc, the multi-GPUvarenderD*and the*lpencvariants):b-frames=0,ref-frames=1(with the default 3, Intel iHD 24.1.0 fails atvaEndPictureafter a few frames),key-int-max=1024(the maximum), and for AV1hierarchical-level=1/gf-group-size=1for 1-in-1-out. Encoders with neither VBR nor CBR are rejected.cpb-sizeis 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.vaav1encon 1.24, whosebitratecan't change in PLAYING, goes through READY.FlushStart+FlushStop(false)onappsrc: on 1.22 a force-key-unit only promotes the frame to an I slice, and on 1.24.2 it gavevah264enca non-IDR frame without SPS/PPS and stalledvah265enc.rate-controlenum type name, or briefly going to READY) and on 1.24+ (device-path).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_devicepicks a render node. Both can be overridden withAIRHAND_HW_ENCODER/AIRHAND_VAAPI_DEVICE.OnceLockshared byavailable_codecs()andLinuxHwEncoder::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_encoderandvaapi_device, kept when the file is regenerated.encoder/mod.rs: wires up Linux and documents inVideoEncoder::set_bitratewhich backends may need a keyframe for a bitrate change..deb: depends onlibgstreamer1.0-0andlibgstreamer-plugins-base1.0-0(>= 1.22), which the binary links; the encoders come fromgstreamer1.0-plugins-bad, already a dependency.release.ymlanddocs/building*.md:libgstreamer1.0-devandlibgstreamer-plugins-base1.0-dev.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 ! appsinkround trip of padded NV12 through the buffer pool and a flush.The hardware tests are
#[ignore]d. On a machine with a GPU (andffmpegfor the strict decode checks):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.mainmainNot run on hardware yet: VA-API since the CPB change, GStreamer 1.22 (Debian 12) with a GPU, and NVENC AV1 (GStreamer 1.26).