diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c238c55e..3bb14745 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -185,7 +185,8 @@ jobs: apt-get install -y --no-install-recommends \ ca-certificates curl git file build-essential cmake pkg-config nasm \ libssl-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev \ - libxdo-dev libpulse-dev libpipewire-0.3-dev + libxdo-dev libpulse-dev libpipewire-0.3-dev \ + libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev - uses: actions/checkout@v6 diff --git a/README.md b/README.md index f82a16d5..66f65030 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ The same program is both the **host** (the device being controlled) and the **co Every stage from capture to display is built for low latency: -- **Hardware encoding and decoding**: the host encodes on the GPU (NVENC / Quick Sync / AMF, VideoToolbox, MediaCodec) in low-latency mode without B-frames; the controller decodes on the GPU (WebCodecs / MediaCodec). Measured with a 4K screen streamed at 1080p, hardware AV1 encoding takes about 7 ms per frame (RTX graphics card) +- **Hardware encoding and decoding**: the host encodes on the GPU (Windows Media Foundation NVENC / Quick Sync / AMF, macOS VideoToolbox, Linux GStreamer VA-API / NVENC, Android MediaCodec) in low-latency mode without B-frames; the controller decodes on the GPU (WebCodecs / MediaCodec). Measured with a 4K screen streamed at 1080p, hardware AV1 encoding takes about 7 ms per frame (RTX graphics card) - **The best format**: AV1 > HEVC > H.264, automatically picking the most efficient format both sides support; scaling and color conversion use SIMD, and all buffers are reused - **No lag build-up**: the host limits the bytes in flight (≈ bitrate × (RTT + 50 ms)) and skips to the latest frame on a slow network; the bitrate follows the measured queueing delay and bandwidth on every acknowledgement, backing off within a few hundred milliseconds and recovering gradually - **Direct path**: besides the relay, the two ends punch a direct path through their NATs (on the same LAN, or whenever the NAT isn't symmetric), so video and audio stop detouring through the server; the lower-latency path is picked automatically, and if the direct path breaks the session falls back to the relay without dropping @@ -55,7 +55,7 @@ See [How it works → Video](docs/architecture.md#video) for details. |---|:-:|:-:|---| | Windows 10 / 11 | ✅ | ✅ | Installed; for all users the host runs as a system service | | macOS 13+ | ✅ | ✅ | The host needs the Screen & System Audio Recording and Accessibility permissions | -| Linux | ✅ | ✅ | The host supports X11 desktops only, with software encoding for now | +| Linux | ✅ | ✅ | The host supports X11 desktops only; hardware encoding via GStreamer VA-API / NVENC with OpenH264 fallback | | Android 7+ phones / tablets | ✅ | ✅ | Can only be watched until the accessibility service is turned on; the controller connects to one device at a time | | Android TV / Google TV | — | View only | Operated entirely with the remote | | iOS / iPadOS 17+ | View only | ✅ | Sharing uses the system screen broadcast; iOS doesn't allow controlling the device | diff --git a/README.zh-CN.md b/README.zh-CN.md index eac6d062..407df45c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -19,7 +19,7 @@ Airhand 是一个**高性能、低延迟**的远程桌面:画面用 GPU 硬件 从采集到显示,每一环都为低延迟设计: -- **硬件编解码**:被控端用 GPU 硬件编码(NVENC / Quick Sync / AMF、VideoToolbox、MediaCodec),低延迟模式、无 B 帧;控制端用 GPU 解码(WebCodecs / MediaCodec)。实测 4K 屏输出 1080p 时,硬件 AV1 编码每帧约 7 ms(RTX 显卡) +- **硬件编解码**:被控端用 GPU 硬件编码(Windows Media Foundation NVENC / Quick Sync / AMF、macOS VideoToolbox、Linux GStreamer VA-API / NVENC、Android MediaCodec),低延迟模式、无 B 帧;控制端用 GPU 解码(WebCodecs / MediaCodec)。实测 4K 屏输出 1080p 时,硬件 AV1 编码每帧约 7 ms(RTX 显卡) - **最好的格式**:按 AV1 > HEVC > H.264 自动选用双方都支持的、压缩率最高的格式;缩放和颜色转换用 SIMD,缓冲区全部复用 - **延迟不堆积**:被控端限制在途字节(≈ 码率 ×(RTT + 50 ms)),网络慢时跳到最新一帧;码率每次确认都按量到的排队时延和带宽调整,几百毫秒内降下来,恢复后逐步回升 - **直连**:两端在中转之外打洞直连(同一个局域网、或者 NAT 不是对称型时),画面、声音不再绕道服务器;自动选延迟低的那条路,直连断了马上回到中转,会话不断 @@ -55,7 +55,7 @@ Airhand 是一个**高性能、低延迟**的远程桌面:画面用 GPU 硬件 |---|:-:|:-:|---| | Windows 10 / 11 | ✅ | ✅ | 需要安装,为所有用户安装时被控端作为系统服务运行 | | macOS 13+ | ✅ | ✅ | 被控端需要“屏幕与系统录音”和“辅助功能”权限 | -| Linux | ✅ | ✅ | 被控端只支持 X11 桌面,目前只有软件编码 | +| Linux | ✅ | ✅ | 被控端只支持 X11 桌面,支持基于 GStreamer 的 VA-API / NVENC 硬件编码(自动回退 OpenH264) | | Android 7+ 手机 / 平板 | ✅ | ✅ | 开启无障碍服务后才能被操作,否则只能被看;控制端同一时间连一台 | | Android TV / Google TV | — | 只看画面 | 全部用遥控器操作 | | iOS / iPadOS 17+ | 只能被看 | ✅ | 共享本机用系统的屏幕广播;iOS 不允许别的应用操作本机 | diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index 5ee7012c..22060a51 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -69,7 +69,10 @@ dependencies = [ "fast_image_resize", "fuser", "futures-util", - "glib", + "glib 0.18.5", + "gstreamer", + "gstreamer-app", + "gstreamer-video", "libc", "libpulse-binding", "objc2", @@ -240,7 +243,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" dependencies = [ "atk-sys", - "glib", + "glib 0.18.5", "libc", ] @@ -250,10 +253,10 @@ version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" dependencies = [ - "glib-sys", - "gobject-sys", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -262,6 +265,12 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "atomic_refcell" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" + [[package]] name = "autocfg" version = "1.5.1" @@ -417,7 +426,7 @@ checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" dependencies = [ "bitflags 2.13.2", "cairo-sys-rs", - "glib", + "glib 0.18.5", "libc", "once_cell", "thiserror 1.0.69", @@ -429,9 +438,9 @@ version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" dependencies = [ - "glib-sys", + "glib-sys 0.18.1", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -513,7 +522,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" dependencies = [ "smallvec", - "target-lexicon", + "target-lexicon 0.12.16", +] + +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon 0.13.5", ] [[package]] @@ -1045,6 +1064,12 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "embed-resource" version = "3.0.12" @@ -1302,7 +1327,7 @@ dependencies = [ "gdk-pixbuf", "gdk-sys", "gio", - "glib", + "glib 0.18.5", "libc", "pango", ] @@ -1315,7 +1340,7 @@ checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" dependencies = [ "gdk-pixbuf-sys", "gio", - "glib", + "glib 0.18.5", "libc", "once_cell", ] @@ -1326,11 +1351,11 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1341,13 +1366,13 @@ checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" dependencies = [ "cairo-sys-rs", "gdk-pixbuf-sys", - "gio-sys", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", "pango-sys", "pkg-config", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1357,11 +1382,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" dependencies = [ "gdk-sys", - "glib-sys", - "gobject-sys", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", "pkg-config", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1373,7 +1398,7 @@ dependencies = [ "gdk", "gdkx11-sys", "gio", - "glib", + "glib 0.18.5", "libc", "x11", ] @@ -1385,9 +1410,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" dependencies = [ "gdk-sys", - "glib-sys", + "glib-sys 0.18.1", "libc", - "system-deps", + "system-deps 6.2.2", "x11", ] @@ -1470,8 +1495,8 @@ dependencies = [ "futures-core", "futures-io", "futures-util", - "gio-sys", - "glib", + "gio-sys 0.18.1", + "glib 0.18.5", "libc", "once_cell", "pin-project-lite", @@ -1485,13 +1510,26 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" dependencies = [ - "glib-sys", - "gobject-sys", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", - "system-deps", + "system-deps 6.2.2", "winapi", ] +[[package]] +name = "gio-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521e93a7e56fc89e84aea9a52cfc9436816a4b363b030260b699950ff1336c83" +dependencies = [ + "glib-sys 0.20.10", + "gobject-sys 0.20.10", + "libc", + "system-deps 7.0.8", + "windows-sys 0.52.0", +] + [[package]] name = "glib" version = "0.18.5" @@ -1504,10 +1542,10 @@ dependencies = [ "futures-executor", "futures-task", "futures-util", - "gio-sys", - "glib-macros", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib-macros 0.18.5", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", "memchr", "once_cell", @@ -1515,6 +1553,27 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "glib" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffc4b6e352d4716d84d7dde562dd9aee2a7d48beb872dd9ece7f2d1515b2d683" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys 0.20.10", + "glib-macros 0.20.12", + "glib-sys 0.20.10", + "gobject-sys 0.20.10", + "libc", + "memchr", + "smallvec", +] + [[package]] name = "glib-macros" version = "0.18.5" @@ -1529,6 +1588,19 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "glib-macros" +version = "0.20.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8084af62f09475a3f529b1629c10c429d7600ee1398ae12dd3bf175d74e7145" +dependencies = [ + "heck 0.5.0", + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "glib-sys" version = "0.18.1" @@ -1536,7 +1608,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" dependencies = [ "libc", - "system-deps", + "system-deps 6.2.2", +] + +[[package]] +name = "glib-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ab79e1ed126803a8fb827e3de0e2ff95191912b8db65cee467edb56fc4cc215" +dependencies = [ + "libc", + "system-deps 7.0.8", ] [[package]] @@ -1551,9 +1633,143 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" dependencies = [ - "glib-sys", + "glib-sys 0.18.1", + "libc", + "system-deps 6.2.2", +] + +[[package]] +name = "gobject-sys" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec9aca94bb73989e3cfdbf8f2e0f1f6da04db4d291c431f444838925c4c63eda" +dependencies = [ + "glib-sys 0.20.10", + "libc", + "system-deps 7.0.8", +] + +[[package]] +name = "gstreamer" +version = "0.23.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8757a87f3706560037a01a9f06a59fcc7bdb0864744dcf73546606e60c4316e1" +dependencies = [ + "cfg-if", + "futures-channel", + "futures-core", + "futures-util", + "glib 0.20.12", + "gstreamer-sys", + "itertools", + "libc", + "muldiv", + "num-integer", + "num-rational", + "once_cell", + "option-operations", + "paste", + "pin-project-lite", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-app" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9a883eb21aebcf1289158225c05f7aea5da6ecf71fa7f0ff1ce4d25baf004e" +dependencies = [ + "futures-core", + "futures-sink", + "glib 0.20.12", + "gstreamer", + "gstreamer-app-sys", + "gstreamer-base", "libc", - "system-deps", +] + +[[package]] +name = "gstreamer-app-sys" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f7ef838306fe51852d503a14dc79ac42de005a59008a05098de3ecdaf05455" +dependencies = [ + "glib-sys 0.20.10", + "gstreamer-base-sys", + "gstreamer-sys", + "libc", + "system-deps 7.0.8", +] + +[[package]] +name = "gstreamer-base" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f19a74fd04ffdcb847dd322640f2cf520897129d00a7bcb92fd62a63f3e27404" +dependencies = [ + "atomic_refcell", + "cfg-if", + "glib 0.20.12", + "gstreamer", + "gstreamer-base-sys", + "libc", +] + +[[package]] +name = "gstreamer-base-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f2fb0037b6d3c5b51f60dea11e667910f33be222308ca5a101450018a09840" +dependencies = [ + "glib-sys 0.20.10", + "gobject-sys 0.20.10", + "gstreamer-sys", + "libc", + "system-deps 7.0.8", +] + +[[package]] +name = "gstreamer-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "feea73b4d92dbf9c24a203c9cd0bcc740d584f6b5960d5faf359febf288919b2" +dependencies = [ + "glib-sys 0.20.10", + "gobject-sys 0.20.10", + "libc", + "system-deps 7.0.8", +] + +[[package]] +name = "gstreamer-video" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1318b599d77ca4f7702ecbdeac1672d6304cb16b7e5752fabb3ee8260449a666" +dependencies = [ + "cfg-if", + "futures-channel", + "glib 0.20.12", + "gstreamer", + "gstreamer-base", + "gstreamer-video-sys", + "libc", + "once_cell", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-video-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a70f0947f12d253b9de9bc3fd92f981e4d025336c18389c7f08cdf388a99f5c" +dependencies = [ + "glib-sys 0.20.10", + "gobject-sys 0.20.10", + "gstreamer-base-sys", + "gstreamer-sys", + "libc", + "system-deps 7.0.8", ] [[package]] @@ -1569,7 +1785,7 @@ dependencies = [ "gdk", "gdk-pixbuf", "gio", - "glib", + "glib 0.18.5", "gtk-sys", "gtk3-macros", "libc", @@ -1587,12 +1803,12 @@ dependencies = [ "cairo-sys-rs", "gdk-pixbuf-sys", "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", "pango-sys", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1962,6 +2178,15 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1975,7 +2200,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" dependencies = [ "bitflags 1.3.2", - "glib", + "glib 0.18.5", "javascriptcore-rs-sys", ] @@ -1985,10 +2210,10 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" dependencies = [ - "glib-sys", - "gobject-sys", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -2184,7 +2409,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" dependencies = [ - "glib", + "glib 0.18.5", "gtk", "gtk-sys", "libappindicator-sys", @@ -2431,6 +2656,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "muldiv" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" + [[package]] name = "nasm-rs" version = "0.3.2" @@ -2555,6 +2786,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2938,6 +3179,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "option-operations" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c26d27bb1aeab65138e4bf7666045169d1717febcc9ff870166be8348b223d0" +dependencies = [ + "paste", +] + [[package]] name = "opus" version = "0.4.0" @@ -2973,7 +3223,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" dependencies = [ "gio", - "glib", + "glib 0.18.5", "libc", "once_cell", "pango-sys", @@ -2985,10 +3235,10 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" dependencies = [ - "glib-sys", - "gobject-sys", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -3014,6 +3264,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4079,7 +4335,7 @@ checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" dependencies = [ "futures-channel", "gio", - "glib", + "glib 0.18.5", "libc", "soup3-sys", ] @@ -4090,11 +4346,11 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -4237,13 +4493,26 @@ version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" dependencies = [ - "cfg-expr", + "cfg-expr 0.15.8", "heck 0.5.0", "pkg-config", "toml 0.8.2", "version-compare", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr 0.20.11", + "heck 0.5.0", + "pkg-config", + "toml 1.1.8+spec-1.1.0", + "version-compare", +] + [[package]] name = "tao" version = "0.37.2" @@ -4301,6 +4570,12 @@ version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tauri" version = "2.12.5" @@ -5248,10 +5523,10 @@ dependencies = [ "gdk", "gdk-sys", "gio", - "gio-sys", - "glib", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib 0.18.5", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "gtk", "gtk-sys", "javascriptcore-rs", @@ -5270,15 +5545,15 @@ dependencies = [ "bitflags 1.3.2", "cairo-sys-rs", "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", + "gio-sys 0.18.1", + "glib-sys 0.18.1", + "gobject-sys 0.18.0", "gtk-sys", "javascriptcore-rs-sys", "libc", "pkg-config", "soup3-sys", - "system-deps", + "system-deps 6.2.2", ] [[package]] diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 2ac732f2..e9645550 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -125,6 +125,10 @@ x11rb = { version = "0.13", features = ["shm", "damage", "xfixes", "randr", "xte # 不链接 libfuse:经 fusermount3 挂载 fuser = { version = "0.15", default-features = false } libpulse-binding = "2" +# 硬件视频编码(VA-API / NVENC):使用系统 GStreamer(Debian 12 为 1.22),与 WebKitGTK 共用同一套运行时库 +gstreamer = { version = "0.23", features = ["v1_22"] } +gstreamer-app = { version = "0.23", features = ["v1_22"] } +gstreamer-video = { version = "0.23", features = ["v1_22"] } # macOS 被控端:ScreenCaptureKit 采集画面和系统声音,VideoToolbox 硬件编码,CGEvent 注入键鼠, # NSPasteboard 检测剪贴板变化。与 Tauri 用同一套 objc2 绑定(版本一致,不会重复编译两份); diff --git a/client/src-tauri/src/config.rs b/client/src-tauri/src/config.rs index 0b4e6962..12903cf3 100644 --- a/client/src-tauri/src/config.rs +++ b/client/src-tauri/src/config.rs @@ -99,6 +99,43 @@ const KEEP_CHECK: Duration = if cfg!(test) { Duration::from_secs(3) }; +/// Linux 硬件编码器选择(`hw_encoder`,`config.toml` 可选,也可用环境变量 `AIRHAND_HW_ENCODER` 覆盖)。 +#[cfg(target_os = "linux")] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum HwEncoderPref { + /// 自动:优先选正在驱动已连接显示器的那一侧显卡(VA-API / NVENC),缺失时按策略回退 + #[default] + Auto, + /// 只使用 VA-API(Intel / AMD) + Vaapi, + /// 只使用 NVIDIA NVENC + Nvenc, + /// 禁用硬件编码,只使用 OpenH264 软件编码 + Software, +} + +#[cfg(target_os = "linux")] +impl HwEncoderPref { + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "auto" => Some(Self::Auto), + "vaapi" => Some(Self::Vaapi), + "nvenc" => Some(Self::Nvenc), + "software" | "cpu" | "off" => Some(Self::Software), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Auto => "auto", + Self::Vaapi => "vaapi", + Self::Nvenc => "nvenc", + Self::Software => "software", + } + } +} + /// 进程启动时读到的配置。 #[derive(Debug, Clone, PartialEq, Eq)] pub struct Settings { @@ -129,6 +166,12 @@ pub struct Settings { pub update_channel: crate::update::Channel, /// 自动检查更新(`check_updates`)。同上 pub check_updates: bool, + /// Linux 硬件编码后端偏好(`hw_encoder`,模板里没有它:默认 `"auto"`) + #[cfg(target_os = "linux")] + pub hw_encoder: HwEncoderPref, + /// Linux VA-API 指定渲染节点路径(`vaapi_device`,例如 `"/dev/dri/renderD128"`,模板里没有它) + #[cfg(target_os = "linux")] + pub vaapi_device: Option, /// 服务器分配的控制码和加密过的密钥(`[code]`),用 [`Settings::code`] 解开 saved_code: Option<(i64, String)>, } @@ -146,6 +189,10 @@ impl Default for Settings { pause_awdl: false, update_channel: crate::update::Channel::Stable, check_updates: true, + #[cfg(target_os = "linux")] + hw_encoder: HwEncoderPref::Auto, + #[cfg(target_os = "linux")] + vaapi_device: None, saved_code: None, } } @@ -280,6 +327,20 @@ fn parse(text: &str) -> Result { warn!("config.toml: unknown language {v:?}, following the system language"); } } + #[cfg(target_os = "linux")] + { + if let Some(v) = doc.get("hw_encoder").and_then(|v| v.as_str()) { + match HwEncoderPref::parse(v) { + Some(p) => s.hw_encoder = p, + None => warn!("config.toml: unknown hw_encoder {v:?}, using auto"), + } + } + if let Some(v) = doc.get("vaapi_device").and_then(|v| v.as_str()) + && !v.trim().is_empty() + { + s.vaapi_device = Some(v.trim().to_string()); + } + } if let Some(t) = doc.get("code").and_then(|v| v.as_table_like()) { let code = t.get("code").and_then(|v| v.as_integer()); let secret = t.get("secret").and_then(|v| v.as_str()); @@ -754,6 +815,31 @@ fn regenerate(before: Option<&str>) -> Result { if let Some(on) = old.get("check_updates").and_then(Item::as_bool) { put_check_updates(&mut doc, on); } + #[cfg(target_os = "linux")] + { + if let Some(v) = old + .get("hw_encoder") + .and_then(Item::as_str) + .and_then(HwEncoderPref::parse) + { + put_setting( + &mut doc, + "hw_encoder", + toml_edit::value(v.as_str()), + hw_encoder_note, + ); + } + if let Some(v) = old.get("vaapi_device").and_then(Item::as_str) + && !v.trim().is_empty() + { + put_setting( + &mut doc, + "vaapi_device", + toml_edit::value(v.trim()), + vaapi_device_note, + ); + } + } if let (Some(from), Some(to)) = ( old.get("code").and_then(Item::as_table_like), doc.get_mut("code").and_then(Item::as_table_like_mut), @@ -1119,6 +1205,22 @@ fn language_note() -> String { ) } +#[cfg(target_os = "linux")] +fn hw_encoder_note() -> String { + tr!( + "# Linux 硬件编码后端:\"auto\"(默认)、\"vaapi\"、\"nvenc\" 或 \"software\",修改后需重启 Airhand\n", + "# Linux hardware encoder backend: \"auto\" (default), \"vaapi\", \"nvenc\" or \"software\" (restart Airhand after changing)\n" + ) +} + +#[cfg(target_os = "linux")] +fn vaapi_device_note() -> String { + tr!( + "# Linux VA-API 指定渲染节点(如 \"/dev/dri/renderD128\"),修改后需重启 Airhand\n", + "# Linux VA-API render node override (e.g. \"/dev/dri/renderD128\"; restart Airhand after changing)\n" + ) +} + /// 写入文件开头的一项设置(`key = value`)。已经有了就只改值;没有(模板里没有)时加上 `note()` 这段说明, /// 排在已有的设置后面;一项设置都没有时放在文件开头的说明后面 /// (直接插入的话 toml_edit 会把它排在整个文件的第一行,开头的说明前面) @@ -2318,4 +2420,34 @@ mod tests { let conf = include_str!("../tauri.conf.json"); assert!(conf.contains(&format!("\"identifier\": \"{BUNDLE_ID}\""))); } + + #[cfg(target_os = "linux")] + #[test] + fn linux_hw_encoder_config_roundtrip() { + let s = parse("hw_encoder = \"nvenc\"\nvaapi_device = \"/dev/dri/renderD128\"\n").unwrap(); + assert_eq!(s.hw_encoder, HwEncoderPref::Nvenc); + assert_eq!(s.vaapi_device.as_deref(), Some("/dev/dri/renderD128")); + + let s = parse("hw_encoder = \"VAAPI\"\n").unwrap(); + assert_eq!(s.hw_encoder, HwEncoderPref::Vaapi); + + let s = parse("hw_encoder = \"software\"\n").unwrap(); + assert_eq!(s.hw_encoder, HwEncoderPref::Software); + + let s = parse("hw_encoder = \"invalid\"\n").unwrap(); + assert_eq!(s.hw_encoder, HwEncoderPref::Auto); + + let regen = regenerate(Some( + "hw_encoder = \"vaapi\"\nvaapi_device = \"/dev/dri/renderD128\"\n", + )) + .unwrap() + .to_string(); + assert!( + regen.starts_with("# Airhand"), + "regenerated config must keep the file header banner first:\n{regen}" + ); + let parsed = parse(®en).unwrap(); + assert_eq!(parsed.hw_encoder, HwEncoderPref::Vaapi); + assert_eq!(parsed.vaapi_device.as_deref(), Some("/dev/dri/renderD128")); + } } diff --git a/client/src-tauri/src/host/encoder/linux.rs b/client/src-tauri/src/host/encoder/linux.rs new file mode 100644 index 00000000..026040ec --- /dev/null +++ b/client/src-tauri/src/host/encoder/linux.rs @@ -0,0 +1,2794 @@ +#![forbid(unsafe_code)] +//! Linux 硬件视频编码(基于系统 GStreamer:Intel / AMD VA-API 与 NVIDIA NVENC),支持 H.264 / HEVC / AV1。 +//! +//! * 使用系统已安装的 GStreamer(`gstreamer1.0-plugins-bad` 里的 `va` 和 `nvcodec` 插件,本包已依赖它), +//! 不维护 FFmpeg ABI 偏移表,运行时缺少硬件编码插件或驱动时安静回退到 OpenH264; +//! * **NVENC**(`nvcudah264enc` / `nvcudah265enc` / GStreamer 1.26+ `nvav1enc`): +//! 运行时只改 `bitrate` / `max-bitrate`,不触发 IDR 即可在当帧生效;`vbv-buffer-size` 改动会让编码器整个重新初始化 +//! (出 IDR),所以只在码率持续偏离到 VBV 差出一倍以上时才按新码率重设(滞回,见 [`NVENC_VBV_RULE`]); +//! * **VA-API**(`va` 插件的 `vah264enc` / `vah265enc` / `vaav1enc` 及多卡/低功耗变体): +//! `b-frames=0`、`ref-frames=1`、AV1 关闭未来参考(`hierarchical-level=1`、`gf-group-size=1`); +//! 改码率会重启 GOP(产生关键帧),因此仅对 VA-API 保留码率滞回,防止拥塞时 IDR 震荡; +//! HRD 缓冲(`cpb-size`)跟着码率一起设成 GStreamer 允许的最小值(见 [`vaapi_cpb_kbits`]); +//! * **双显卡自动选择**(`hw_encoder = "auto"`):优先选正在驱动已连接显示器的那一侧显卡; +//! 驱动显示器的 VA-API 显卡已提供硬编能力时不再探测次选 NVENC。所有探测均按需延迟执行并缓存结果。 + +use std::collections::{BTreeSet, HashSet}; +use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _}; +use std::path::{Path, PathBuf}; +use std::str::FromStr as _; +use std::sync::{Mutex, OnceLock, mpsc}; +use std::time::{Duration, Instant}; + +use airhand_proto::session::{Codec, EncoderInfo}; +use anyhow::{Context, Result, anyhow, bail}; +use gst::glib; +use gst::prelude::*; +use gstreamer as gst; +use gstreamer_app as gst_app; +use gstreamer_video as gst_video; +use tracing::{debug, info, warn}; +use yuvutils_rs::{YuvBiPlanarImageMut, YuvConversionMode, YuvRange, YuvStandardMatrix}; + +use super::{EncodedFrame, VideoEncoder, annexb_nal_types}; +use crate::config::{self, HwEncoderPref}; + +/// PCI vendor IDs +const PCI_VENDOR_NVIDIA: &str = "0x10de"; +const PCI_VENDOR_INTEL: &str = "0x8086"; +const PCI_VENDOR_AMD: &str = "0x1002"; + +/// Linux DRM 字符设备主设备号(`Documentation/admin-guide/devices.txt`) +const DRM_MAJOR: u64 = 226; + +/// 滞回的保持时间:目标持续偏离(下降 2 秒、上升 6 秒)才下发,避免拥塞时 IDR 震荡 +const BITRATE_DROP_HOLD: Duration = Duration::from_secs(2); +const BITRATE_RAISE_HOLD: Duration = Duration::from_secs(6); +/// 下发失败后的退避窗口 +const BITRATE_RETRY_BACKOFF: Duration = Duration::from_secs(5); + +/// VA-API 码率:下降 ≥ 1.25×、上升 ≥ 1.3× 才计时;反正要出关键帧时有变化就顺带下发 +const VA_BITRATE_RULE: HysteresisRule = HysteresisRule { + drop_permille: 1_250, + raise_permille: 1_300, + piggyback_permille: 1_000, +}; + +/// NVENC VBV:按当前码率算出的大小和正在用的差出一倍才计时(VBV 偏大,拥塞时单帧能冲得很大; +/// 偏小,码率升上去之后每帧都被压在 VBV 以内);反正要出关键帧时差出 1.5 倍就顺带重设 +const NVENC_VBV_RULE: HysteresisRule = HysteresisRule { + drop_permille: 2_000, + raise_permille: 2_000, + piggyback_permille: 1_500, +}; + +/// 硬件编码分辨率边界(必须为偶数;探测使用 256×256 以高于各硬件编码器最小宽/高) +const MIN_DIM: u32 = 64; +const MAX_DIM: u32 = 8192; +const PROBE_DIM: u32 = 256; + +/// 拉取编码结果的超时:首帧允许硬件会话初始化,稳态帧快速失败以触发回退 +const FIRST_FRAME_TIMEOUT: Duration = Duration::from_millis(2_500); +const STEADY_FRAME_TIMEOUT: Duration = Duration::from_millis(500); +/// Drop 时关闭管线的超时,防止驱动卡死拖住采集/编码线程。超时的 factory 在本进程里不再使用, +/// 所以不能太紧:机器忙的时候销毁 CUDA 上下文 / VA 上下文也可能要几百毫秒 +const TEARDOWN_TIMEOUT: Duration = Duration::from_secs(3); + +/// AV1 2 字节 Temporal Delimiter OBU(`obu_type=2`, `has_size=1`, `size=0`) +const AV1_TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Backend { + Vaapi, + Nvenc, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DisplayOwner { + Vaapi, + Nvidia, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BitrateDir { + Drop, + Raise, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct RenderNode { + path: String, + vendor_label: String, + has_display: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Candidate { + backend: Backend, + codec: Codec, + factory: String, + device_path: Option, + label: String, + low_power: bool, +} + +#[derive(Debug, Default)] +struct ProbeCache { + h264: Vec, + h265: Vec, + av1: Vec, +} + +impl ProbeCache { + fn candidates(&self, codec: Codec) -> &[Candidate] { + match codec { + Codec::H264 => &self.h264, + Codec::H265 => &self.h265, + Codec::AV1 => &self.av1, + Codec::Unknown(_) => &[], + } + } + + fn candidates_mut(&mut self, codec: Codec) -> Option<&mut Vec> { + match codec { + Codec::H264 => Some(&mut self.h264), + Codec::H265 => Some(&mut self.h265), + Codec::AV1 => Some(&mut self.av1), + Codec::Unknown(_) => None, + } + } + + fn has(&self, codec: Codec) -> bool { + !self.candidates(codec).is_empty() + } + + fn any_hw(&self) -> bool { + !self.h264.is_empty() || !self.h265.is_empty() || !self.av1.is_empty() + } +} + +/// 关闭时卡死的 factory,不再在同一进程里反复打开。 +fn broken_factories() -> &'static Mutex> { + static BROKEN: OnceLock>> = OnceLock::new(); + BROKEN.get_or_init(|| Mutex::new(HashSet::new())) +} + +fn mark_factory_broken(factory: &str) { + if let Ok(mut set) = broken_factories().lock() { + set.insert(factory.to_string()); + } +} + +fn is_factory_broken(factory: &str) -> bool { + broken_factories() + .lock() + .is_ok_and(|set| set.contains(factory)) +} + +/// 检查编码器 factory 的静态 sink pad 模板 caps 是否支持 `(w, h)`,避免对明确超限的分辨率做无效打开。 +fn factory_supports_size(factory_name: &str, w: u32, h: u32) -> bool { + let Some(factory) = gst::ElementFactory::find(factory_name) else { + return false; + }; + let probe_caps = gst::Caps::builder("video/x-raw") + .field("width", w as i32) + .field("height", h as i32) + .build(); + let mut saw_sink_caps = false; + for tpl in factory.static_pad_templates() { + if tpl.direction() != gst::PadDirection::Sink { + continue; + } + saw_sink_caps = true; + if tpl.caps().can_intersect(&probe_caps) { + return true; + } + } + !saw_sink_caps +} + +// ───────────────────────────── GStreamer 初始化与安全属性工具 ───────────────────────────── + +/// 按需初始化 GStreamer(进程内一次,线程安全;永不调用 `gst_deinit` 以与 WebKitGTK 共存)。 +fn ensure_gst() -> Result<()> { + static INIT: OnceLock> = OnceLock::new(); + match INIT.get_or_init(|| gst::init().map_err(|e| e.to_string())) { + Ok(()) => Ok(()), + Err(msg) => bail!("GStreamer initialization failed: {msg}"), + } +} + +fn is_writable_at_runtime(pspec: &glib::ParamSpec) -> bool { + let flags = pspec.flags(); + flags.contains(glib::ParamFlags::WRITABLE) && !flags.contains(glib::ParamFlags::CONSTRUCT_ONLY) +} + +/// 安全地通过字符串反序列化设置属性,永不 panic(适配 GStreamer 1.22 / 1.24 / 1.26 及不同驱动枚举差异)。 +/// +/// 返回 `Ok(true)` 表示已设置,`Ok(false)` 表示该元素没有此属性或不可写,`Err` 表示属性值/枚举不被接受。 +fn try_set_str(el: &gst::Element, name: &str, raw: &str) -> Result { + let Some(pspec) = el.find_property(name) else { + return Ok(false); + }; + if !is_writable_at_runtime(&pspec) { + return Ok(false); + } + let value = glib::Value::deserialize_with_pspec(raw, &pspec) + .map_err(|e| anyhow!("invalid value {raw:?} for property {name}: {e}"))?; + el.set_property_from_value(name, &value); + Ok(true) +} + +/// 安全地设置无符号整数属性(自动按属性 `[min, max]` 裁剪,永不 panic)。 +fn try_set_u32(el: &gst::Element, name: &str, val: u32) -> Option { + let pspec = el.find_property(name)?; + if !is_writable_at_runtime(&pspec) { + return None; + } + if let Some(spec) = pspec.downcast_ref::() { + let clamped = val.clamp(spec.minimum(), spec.maximum()); + el.set_property_from_value(name, &clamped.to_value()); + return Some(clamped); + } + if let Some(spec) = pspec.downcast_ref::() { + let lo = spec.minimum().max(0) as u32; + let hi = spec.maximum().max(0) as u32; + let clamped = val.clamp(lo, hi); + el.set_property_from_value(name, &(clamped as i32).to_value()); + return Some(clamped); + } + if let Some(spec) = pspec.downcast_ref::() { + let clamped = u64::from(val).clamp(spec.minimum(), spec.maximum()); + el.set_property_from_value(name, &clamped.to_value()); + return Some(clamped.min(u64::from(u32::MAX)) as u32); + } + None +} + +/// 安全地设置有符号整数属性(如 `gop-size = -1`,自动按属性 `[min, max]` 裁剪,永不 panic)。 +fn try_set_i32(el: &gst::Element, name: &str, val: i32) -> Option { + let pspec = el.find_property(name)?; + if !is_writable_at_runtime(&pspec) { + return None; + } + if let Some(spec) = pspec.downcast_ref::() { + let clamped = val.clamp(spec.minimum(), spec.maximum()); + el.set_property_from_value(name, &clamped.to_value()); + return Some(clamped); + } + if let Some(spec) = pspec.downcast_ref::() { + let target = val.max(0) as u32; + let clamped = target.clamp(spec.minimum(), spec.maximum()); + el.set_property_from_value(name, &clamped.to_value()); + return i32::try_from(clamped).ok(); + } + None +} + +/// 安全地设置布尔属性(永不 panic)。 +fn try_set_bool(el: &gst::Element, name: &str, val: bool) -> bool { + let Some(pspec) = el.find_property(name) else { + return false; + }; + if !is_writable_at_runtime(&pspec) || pspec.value_type() != glib::Type::BOOL { + return false; + } + el.set_property_from_value(name, &val.to_value()); + true +} + +/// 判断属性是否允许在 `PLAYING` 状态下修改(例如 `vah264enc` 允许,GStreamer 1.24.2 `vaav1enc` 不允许)。 +fn is_mutable_playing(el: &gst::Element, name: &str) -> bool { + el.find_property(name) + .is_some_and(|p| p.flags().contains(gst::PARAM_FLAG_MUTABLE_PLAYING)) +} + +/// 读取只读字符串属性(用于 NULL 状态下查询 VA 元素的 `device-path`)。 +fn read_str_prop(el: &gst::Element, name: &str) -> Option { + let pspec = el.find_property(name)?; + if pspec.value_type() != glib::Type::STRING { + return None; + } + el.property_value(name).get::>().ok()? +} + +// ───────────────────────────── 设备选择与显示归属 ───────────────────────────── + +/// 纯函数:根据用户偏好与当前显示归属决定硬件后端尝试顺序。 +pub(crate) fn backend_order(pref: HwEncoderPref, owner: DisplayOwner) -> Vec { + match pref { + HwEncoderPref::Software => Vec::new(), + HwEncoderPref::Vaapi => vec![Backend::Vaapi], + HwEncoderPref::Nvenc => vec![Backend::Nvenc], + HwEncoderPref::Auto => match owner { + DisplayOwner::Nvidia => vec![Backend::Nvenc, Backend::Vaapi], + DisplayOwner::Vaapi | DisplayOwner::Unknown => vec![Backend::Vaapi, Backend::Nvenc], + }, + } +} + +fn effective_pref() -> HwEncoderPref { + if let Ok(raw) = std::env::var("AIRHAND_HW_ENCODER") { + let trimmed = raw.trim(); + if !trimmed.is_empty() { + if let Some(p) = HwEncoderPref::parse(trimmed) { + return p; + } + warn!( + value = trimmed, + "ignoring unknown AIRHAND_HW_ENCODER value (expected auto/vaapi/nvenc/software)" + ); + } + } + config::settings().hw_encoder +} + +fn effective_vaapi_device() -> Option { + if let Ok(raw) = std::env::var("AIRHAND_VAAPI_DEVICE") { + let trimmed = raw.trim(); + if !trimmed.is_empty() { + return Some(trimmed.to_string()); + } + } + config::settings().vaapi_device.clone() +} + +fn read_trimmed(path: &Path) -> Option { + std::fs::read_to_string(path) + .ok() + .map(|s| s.trim().to_ascii_lowercase()) +} + +fn vendor_label(vendor_hex: Option<&str>, sysfs_dir: &Path) -> String { + match vendor_hex { + Some(PCI_VENDOR_INTEL) => "Intel".into(), + Some(PCI_VENDOR_AMD) => "AMD".into(), + Some(PCI_VENDOR_NVIDIA) => "NVIDIA".into(), + _ => std::fs::read_link(sysfs_dir.join("device/driver")) + .ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())) + .unwrap_or_else(|| "VA-API".into()), + } +} + +/// 找出当前所有状态为 `connected` 的 DRM 显卡的 PCI 设备真实路径及其 vendor。 +fn connected_drm_cards() -> Vec<(PathBuf, Option)> { + let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { + return Vec::new(); + }; + let mut connected_cards = BTreeSet::::new(); + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if let Some((card, _)) = name.split_once('-') + && card.starts_with("card") + && read_trimmed(&entry.path().join("status")).as_deref() == Some("connected") + { + connected_cards.insert(card.to_string()); + } + } + let mut out = Vec::new(); + for card in connected_cards { + let dev_link = Path::new("/sys/class/drm").join(&card).join("device"); + let Ok(canon) = std::fs::canonicalize(&dev_link) else { + continue; + }; + let vendor = read_trimmed(&dev_link.join("vendor")); + out.push((canon, vendor)); + } + out +} + +/// 通过 DRM sysfs 与 X11 RandR 判断当前已连接显示器归属哪一侧显卡(进程内缓存一次)。 +fn display_owner() -> DisplayOwner { + static OWNER: OnceLock = OnceLock::new(); + *OWNER.get_or_init(detect_display_owner) +} + +fn detect_display_owner() -> DisplayOwner { + let cards = connected_drm_cards(); + if !cards.is_empty() { + let any_non_nv = cards + .iter() + .any(|(_, v)| v.as_deref() != Some(PCI_VENDOR_NVIDIA)); + if any_non_nv { + return DisplayOwner::Vaapi; + } + return DisplayOwner::Nvidia; + } + if let Some(owner) = detect_display_owner_x11() { + return owner; + } + DisplayOwner::Unknown +} + +fn detect_display_owner_x11() -> Option { + use x11rb::protocol::randr::{Connection, ConnectionExt as _}; + let x = crate::host::x11::X11::connect().ok()?; + if !x.has_extension(x11rb::protocol::randr::X11_EXTENSION_NAME) { + return None; + } + let ver = x.conn.randr_query_version(1, 4).ok()?.reply().ok()?; + if (ver.major_version, ver.minor_version) < (1, 4) { + return None; + } + let providers = x.conn.randr_get_providers(x.root()).ok()?.reply().ok()?; + let mut has_nvidia = false; + let mut has_other = false; + for provider in providers.providers { + if let Ok(cookie) = x + .conn + .randr_get_provider_info(provider, providers.timestamp) + && let Ok(info) = cookie.reply() + { + let has_active_output = info.outputs.iter().any(|&out| { + x.conn + .randr_get_output_info(out, providers.timestamp) + .ok() + .and_then(|c| c.reply().ok()) + .is_some_and(|oi| oi.crtc != 0 || oi.connection == Connection::CONNECTED) + }); + if !has_active_output { + continue; + } + let name = String::from_utf8_lossy(&info.name).to_ascii_lowercase(); + if name.contains("nvidia") { + has_nvidia = true; + } else if !name.is_empty() { + has_other = true; + } + } + } + if has_nvidia && !has_other { + Some(DisplayOwner::Nvidia) + } else if has_other { + Some(DisplayOwner::Vaapi) + } else { + None + } +} + +/// 在 `auto` 模式下检查本机是否存在 NVIDIA GPU(兼容 PCI sysfs、容器 `/dev/nvidiactl` 与 WSL2 `/dev/dxg`)。 +/// +/// 当用户显式配置 `hw_encoder = "nvenc"` 时**不**调用此检查,确保容器与 WSL2 始终探测全部 NVENC 格式。 +fn has_nvidia_hint() -> bool { + if Path::new("/dev/nvidiactl").exists() || Path::new("/dev/dxg").exists() { + return true; + } + let Ok(entries) = std::fs::read_dir("/sys/bus/pci/devices") else { + return true; + }; + entries + .flatten() + .any(|e| read_trimmed(&e.path().join("vendor")).as_deref() == Some(PCI_VENDOR_NVIDIA)) +} + +/// 校验用户指定的 VA-API 设备路径:必须解析到 `/dev/dri/renderD<数字>` DRM 字符设备(主设备号 226)且非 NVIDIA 节点。 +fn validate_vaapi_device(raw: &str) -> Result<(String, String)> { + let canon = + std::fs::canonicalize(raw).with_context(|| format!("invalid vaapi_device path {raw:?}"))?; + let parent = canon.parent().and_then(Path::to_str); + let name = canon.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let suffix = name.strip_prefix("renderD").unwrap_or(""); + if parent != Some("/dev/dri") + || suffix.is_empty() + || !suffix.bytes().all(|b| b.is_ascii_digit()) + { + bail!("vaapi_device must point to a /dev/dri/renderD node, got {canon:?}"); + } + let meta = + std::fs::metadata(&canon).with_context(|| format!("cannot stat vaapi_device {canon:?}"))?; + if !meta.file_type().is_char_device() { + bail!("vaapi_device is not a character device: {canon:?}"); + } + let major = libc::major(meta.rdev()) as u64; + if major != DRM_MAJOR { + bail!("vaapi_device {canon:?} has unexpected major number {major} (expected {DRM_MAJOR})"); + } + let sysfs = Path::new("/sys/class/drm").join(name); + let vendor = read_trimmed(&sysfs.join("device/vendor")); + if vendor.as_deref() == Some(PCI_VENDOR_NVIDIA) { + bail!( + "refusing NVIDIA render node {canon:?} for VA-API; use hw_encoder = \"nvenc\" instead" + ); + } + Ok(( + canon.to_string_lossy().into_owned(), + vendor_label(vendor.as_deref(), &sysfs), + )) +} + +/// 枚举适合 VA-API 编码的 DRM render 节点(跳过 NVIDIA,按显示归属和设备路径排序)。 +fn discover_vaapi_nodes(device_override: Option<&str>) -> Vec { + if let Some(path) = device_override { + match validate_vaapi_device(path) { + Ok((canon, vendor_label)) => { + return vec![RenderNode { + path: canon, + vendor_label, + has_display: true, + }]; + } + Err(e) => { + warn!(path, "ignoring invalid vaapi_device override: {e:#}"); + return Vec::new(); + } + } + } + + let connected = connected_drm_cards(); + let mut nodes = Vec::new(); + if let Ok(entries) = std::fs::read_dir("/sys/class/drm") { + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + let Some(suffix) = name.strip_prefix("renderD") else { + continue; + }; + if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_digit()) { + continue; + } + let sysfs = entry.path(); + let vendor = read_trimmed(&sysfs.join("device/vendor")); + if vendor.as_deref() == Some(PCI_VENDOR_NVIDIA) { + debug!(node = %name, "skipping NVIDIA DRM render node for VA-API"); + continue; + } + let dev_path = format!("/dev/dri/{name}"); + if !Path::new(&dev_path).exists() { + continue; + } + let canon = std::fs::canonicalize(sysfs.join("device")).ok(); + let has_display = canon + .as_ref() + .is_some_and(|c| connected.iter().any(|(cc, _)| cc == c)); + nodes.push(RenderNode { + path: dev_path, + vendor_label: vendor_label(vendor.as_deref(), &sysfs), + has_display, + }); + } + } else if let Ok(entries) = std::fs::read_dir("/dev/dri") { + // 容器场景下 `/sys/class/drm` 可能未挂载:直接扫描 `/dev/dri/renderD*` + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name.starts_with("renderD") + && let Ok((canon, vendor_label)) = + validate_vaapi_device(&format!("/dev/dri/{name}")) + { + nodes.push(RenderNode { + path: canon, + vendor_label, + has_display: false, + }); + } + } + } + nodes.sort_by(|a, b| b.has_display.cmp(&a.has_display).then(a.path.cmp(&b.path))); + nodes +} + +fn codec_label(codec: Codec) -> &'static str { + match codec { + Codec::H264 | Codec::Unknown(_) => "H.264", + Codec::H265 => "HEVC", + Codec::AV1 => "AV1", + } +} + +fn codec_media_type(codec: Codec) -> Option<&'static str> { + match codec { + Codec::H264 => Some("video/x-h264"), + Codec::H265 => Some("video/x-h265"), + Codec::AV1 => Some("video/x-av1"), + Codec::Unknown(_) => None, + } +} + +fn canonicalize_or_keep(path: String) -> String { + std::fs::canonicalize(&path) + .map(|c| c.to_string_lossy().into_owned()) + .unwrap_or(path) +} + +/// 从 GStreamer `va` 元素的动态枚举类型名中提取渲染节点路径(如 `GstVaEncoderRateControl_H264_renderD128`), +/// 在 GStreamer 1.22(Debian 12)下 `device-path` 于 `NULL` 状态返回 `NULL` 时可零开销解析。 +pub(crate) fn parse_va_rate_control_type_node(type_name: &str) -> Option { + let (_, suffix) = type_name.rsplit_once("_renderD")?; + if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(format!("/dev/dri/renderD{suffix}")) +} + +/// 解析 GStreamer `va` 编码器元素对应的 `/dev/dri/renderD` 路径(兼容 1.22 与 1.24+)。 +fn resolve_va_device_path(el: &gst::Element, factory_name: &str) -> Option { + // 1. GStreamer 1.24+:NULL 状态下即可直接读到 `device-path` + if let Some(p) = read_str_prop(el, "device-path").filter(|s| !s.is_empty()) { + return Some(canonicalize_or_keep(p)); + } + // 2. GStreamer 1.22(Debian 12):无需打开设备,先从动态 `rate-control` 枚举名提取 `_renderD` + if let Some(p) = el + .find_property("rate-control") + .and_then(|pspec| parse_va_rate_control_type_node(pspec.value_type().name())) + { + return Some(canonicalize_or_keep(p)); + } + // 3. 多卡后缀工厂名(如 `varenderD129h264enc`) + if let Some(p) = parse_va_factory_node(factory_name) { + return Some(canonicalize_or_keep(p)); + } + // 4. 兜底:短暂切到 READY 打开 display 读取 `device-path`,随后立刻退回 NULL + if el.set_state(gst::State::Ready).is_ok() { + let path = read_str_prop(el, "device-path") + .filter(|s| !s.is_empty()) + .map(canonicalize_or_keep); + let _ = el.set_state(gst::State::Null); + return path; + } + None +} + +/// 从 GStreamer `va` 插件中枚举匹配目标 `codec` 与已发现 DRM 节点的候选工厂(包含低功耗 `*lpenc` 变体)。 +fn discover_va_candidates(codec: Codec, nodes: &[RenderNode]) -> Vec { + let Some(media_type) = codec_media_type(codec) else { + return Vec::new(); + }; + if nodes.is_empty() { + return Vec::new(); + } + let factories = gst::ElementFactory::factories_with_type( + gst::ElementFactoryType::ENCODER | gst::ElementFactoryType::MEDIA_VIDEO, + gst::Rank::NONE, + ); + + // 收集所有属于 `va` 插件(排除旧版 `vaapi` 插件)且输出格式匹配的 factory 及对应设备路径 + let mut discovered: Vec<(String, Option, bool)> = Vec::new(); + for factory in factories { + if factory.plugin_name().as_deref() != Some("va") { + continue; + } + let matches_codec = factory.static_pad_templates().iter().any(|tpl| { + tpl.direction() == gst::PadDirection::Src + && tpl.caps().iter().any(|s| s.name().as_str() == media_type) + }); + if !matches_codec { + continue; + } + let name = factory.name().to_string(); + let low_power = name.ends_with("lpenc"); + let dev_path = factory + .create() + .build() + .ok() + .and_then(|el| resolve_va_device_path(&el, &name)); + discovered.push((name, dev_path, low_power)); + } + + let mut out = Vec::new(); + for node in nodes { + let mut matched: Vec<(String, bool)> = discovered + .iter() + .filter(|(fname, dpath, _)| match dpath { + Some(p) => p == &node.path, + None => parse_va_factory_node(fname).is_some_and(|n| n == node.path), + }) + .map(|(fname, _, lp)| (fname.clone(), *lp)) + .collect(); + // 普通入口优先于低功耗入口,同级按名称排序 + matched.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0))); + for (factory, low_power) in matched { + out.push(Candidate { + backend: Backend::Vaapi, + codec, + factory, + device_path: Some(node.path.clone()), + label: format!("VA-API {} ({})", codec_label(codec), node.vendor_label), + low_power, + }); + } + } + out +} + +/// 兜底解析形如 `varenderD129h264enc` / `varenderD129h265lpenc` 的 factory 名称对应的设备路径。 +pub(crate) fn parse_va_factory_node(factory_name: &str) -> Option { + let rest = factory_name.strip_prefix("varenderD")?; + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + if digits.is_empty() { + return None; + } + Some(format!("/dev/dri/renderD{digits}")) +} + +/// 为 NVENC 枚举目标 `codec` 的现代 `GstNvEncoder` 候选工厂(跳过 1.22/1.24 的旧版 `GstNvBaseEnc`)。 +fn discover_nvenc_candidates(codec: Codec) -> Vec { + let names: &[&str] = match codec { + Codec::H264 => &["nvcudah264enc", "nvh264enc"], + Codec::H265 => &["nvcudah265enc", "nvh265enc"], + // GStreamer 1.26 的 CUDA 模式 AV1 编码器就叫 `nvav1enc`(没有 `nvcudaav1enc`) + Codec::AV1 => &["nvav1enc"], + Codec::Unknown(_) => return Vec::new(), + }; + let mut out = Vec::new(); + for &name in names { + let Some(factory) = gst::ElementFactory::find(name) else { + continue; + }; + // 旧版 `nvh264enc`/`nvh265enc`(GstNvBaseEnc)没有 `zero-reorder-delay` 也不支持无 IDR 软重配; + // 1.26+ 统一后的 `nv*enc` 与 1.22+ `nvcuda*enc` 均基于 `GstNvEncoder`。 + if (name == "nvh264enc" || name == "nvh265enc") + && factory.create().build().ok().is_none_or(|el| { + el.find_property("zero-reorder-delay").is_none() + && el.find_property("tune").is_none() + }) + { + continue; + } + out.push(Candidate { + backend: Backend::Nvenc, + codec, + factory: name.to_string(), + device_path: None, + label: format!("NVENC {}", codec_label(codec)), + low_power: false, + }); + } + out +} + +/// 纯探测逻辑(可注入自定义枚举与打开函数以便无硬件单元测试)。 +fn probe_with( + pref: HwEncoderPref, + owner: DisplayOwner, + allow_nvenc_in_auto: bool, + mut discover: impl FnMut(Backend, Codec) -> Vec, + mut try_candidate: impl FnMut(&Candidate) -> bool, +) -> ProbeCache { + let mut cache = ProbeCache::default(); + let order = backend_order(pref, owner); + if order.is_empty() { + return cache; + } + + for (idx, backend) in order.iter().copied().enumerate() { + if backend == Backend::Nvenc && pref == HwEncoderPref::Auto { + // 双显卡自动模式:驱动显示器的 VA-API 核显已有硬编能力时,不再探测次选 NVENC + if idx > 0 && cache.any_hw() { + debug!( + "primary VA-API backend already provides hardware encoding; skipping secondary NVENC probe" + ); + break; + } + if !allow_nvenc_in_auto { + debug!("no NVIDIA device hint detected in auto mode; skipping NVENC probe"); + continue; + } + } + + for &codec in Codec::KNOWN { + let candidates = discover(backend, codec); + for cand in candidates { + if try_candidate(&cand) { + info!( + factory = %cand.factory, + label = %cand.label, + device = ?cand.device_path, + ?codec, + "Linux hardware encoder available" + ); + if let Some(slot) = cache.candidates_mut(codec) { + slot.push(cand); + } + // 保留所有通过冒烟测试的候选(例如普通入口与低功耗入口、多张 VA 节点), + // 便于实际分辨率协商或并发受限时按顺序回退 + } + } + } + } + cache +} + +fn probe_cache() -> &'static ProbeCache { + static CACHE: OnceLock = OnceLock::new(); + CACHE.get_or_init(|| { + let pref = effective_pref(); + if pref == HwEncoderPref::Software { + info!("Linux hardware encoding disabled by configuration"); + return ProbeCache::default(); + } + if let Err(e) = ensure_gst() { + warn!("GStreamer unavailable, using software encoding: {e:#}"); + return ProbeCache::default(); + } + let owner = display_owner(); + let device_override = effective_vaapi_device(); + let va_nodes = discover_vaapi_nodes(device_override.as_deref()); + let allow_nvenc_in_auto = has_nvidia_hint(); + info!( + ?pref, + ?owner, + va_nodes = va_nodes.len(), + allow_nvenc_in_auto, + "probing Linux GStreamer hardware encoders" + ); + probe_with( + pref, + owner, + allow_nvenc_in_auto, + |backend, codec| match backend { + Backend::Vaapi => discover_va_candidates(codec, &va_nodes), + Backend::Nvenc => discover_nvenc_candidates(codec), + }, + |cand| { + if is_factory_broken(&cand.factory) { + return false; + } + // 先关掉(这条语句结束时释放)再看:关闭时卡住的 factory 已经被拉黑, + // `new()` 不会再用它,就不能报告成可用的格式 + let opened = + LinuxHwEncoder::open_candidate(cand, PROBE_DIM, PROBE_DIM, 30, 2_000).is_ok(); + opened && !is_factory_broken(&cand.factory) + }, + ) + }) +} + +pub fn has_hardware(codec: Codec) -> bool { + probe_cache().has(codec) +} + +// ───────────────────────────── 码流检查与打包 ───────────────────────────── + +/// 读取单个 AV1 OBU 头与长度,返回 `(obu_type, payload_len, next_offset)`。 +fn parse_av1_obu(data: &[u8], offset: usize) -> Option<(u8, usize, usize)> { + let mut i = offset; + let hdr = *data.get(i)?; + i += 1; + // AV1 spec §5.3.2: obu_forbidden_bit (MSB) 必须为 0 + if hdr & 0x80 != 0 { + return None; + } + let obu_type = (hdr >> 3) & 0x0f; + let has_ext = (hdr >> 2) & 1 != 0; + let has_size = (hdr >> 1) & 1 != 0; + if has_ext { + if i >= data.len() { + return None; + } + i += 1; + } + if !has_size { + return Some((obu_type, data.len() - i, data.len())); + } + // AV1 spec §4.10.5: leb128() 最多 8 字节,使用 u64 累加并限制在 u32::MAX 内 + let mut size = 0u64; + let mut shift = 0u32; + let mut done = false; + while i < data.len() && shift < 56 { + let b = data[i]; + i += 1; + size |= u64::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + done = true; + break; + } + shift += 7; + } + if !done || size > u64::from(u32::MAX) { + return None; + } + let size = usize::try_from(size).ok()?; + if size > data.len().saturating_sub(i) { + return None; + } + Some((obu_type, size, i + size)) +} + +/// AV1 OBU 码流中是否包含完整且合法的 Sequence Header OBU(`obu_type == 1`)。 +#[cfg(test)] +pub(crate) fn av1_has_sequence_header(data: &[u8]) -> bool { + let mut i = 0usize; + while i < data.len() { + let Some((obu_type, size, next)) = parse_av1_obu(data, i) else { + return false; + }; + if obu_type == 1 && size > 0 { + return true; + } + i = next; + } + false +} + +/// AV1 访问单元是否是带序列头的关键帧:先有非空 Sequence Header OBU(`obu_type == 1`), +/// 之后第一个帧 / 帧头 OBU(`obu_type == 6 | 3`)是 `KEY_FRAME`(不是 `show_existing_frame`)。 +/// 只看有没有序列头和帧不够:编码器可以在每一帧前都重复序列头,帧本身却是帧间帧。 +fn av1_is_key_frame_with_sequence_header(data: &[u8]) -> bool { + let mut i = 0usize; + // Sequence Header 的 `reduced_still_picture_header`:为 1 时帧头里没有 frame_type,所有帧都是关键帧 + let mut reduced_still = None; + while i < data.len() { + let Some((obu_type, size, next)) = parse_av1_obu(data, i) else { + return false; + }; + let payload = &data[next - size..next]; + match obu_type { + // seq_profile f(3)、still_picture f(1)、reduced_still_picture_header f(1) + 1 if size > 0 => reduced_still = Some(payload[0] & 0x08 != 0), + 3 | 6 if size > 0 => { + // 帧在序列头之前:这个访问单元解码不了 + let Some(reduced) = reduced_still else { + return false; + }; + // uncompressed_header():show_existing_frame f(1)、frame_type f(2)(KEY_FRAME = 0) + return reduced || (payload[0] & 0x80 == 0 && (payload[0] >> 5) & 0x03 == 0); + } + _ => {} + } + i = next; + } + false +} + +/// 确保 AV1 帧以合法的 Temporal Delimiter OBU(`obu_type == 2`, `size == 0`)开头, +/// 兼容带多字节 LEB128 零长度编码的硬件编码器,不重复插入 TD OBU(已经有的话原样返回,不复制)。 +pub(crate) fn ensure_av1_temporal_delimiter(data: Vec) -> Vec { + if let Some((2, 0, _)) = parse_av1_obu(&data, 0) { + return data; + } + let mut out = Vec::with_capacity(AV1_TEMPORAL_DELIMITER.len() + data.len()); + out.extend_from_slice(&AV1_TEMPORAL_DELIMITER); + out.extend_from_slice(&data); + out +} + +/// 纯码流关键帧判断(不信任 `GstBufferFlags::DELTA_UNIT`,因 `vah265enc` / `vaav1enc` 在关键帧上也会保留该标志)。 +/// +/// 只有同时包含随机访问点(IDR / IRAP / Sequence Header + 编码帧)与完整带内参数集时才返回 `true`, +/// 确保 `pipeline.rs` 标记为关键帧的访问单元可以作为独立解码恢复点。 +pub(crate) fn is_sync_keyframe_with_headers(codec: Codec, data: &[u8]) -> bool { + match codec { + Codec::H264 => { + let (mut idr, mut sps, mut pps) = (false, false, false); + for t in annexb_nal_types(data, false) { + idr |= t == 5; + sps |= t == 7; + pps |= t == 8; + } + idr && sps && pps + } + Codec::H265 => { + let (mut irap, mut vps, mut sps, mut pps) = (false, false, false, false); + for t in annexb_nal_types(data, true) { + irap |= (16..=21).contains(&t); + vps |= t == 32; + sps |= t == 33; + pps |= t == 34; + } + irap && vps && sps && pps + } + Codec::AV1 => av1_is_key_frame_with_sequence_header(data), + Codec::Unknown(_) => false, + } +} + +// ───────────────────────────── 码率计算与滞回状态机 ───────────────────────────── + +/// NVENC 的 VBV 缓冲区大小(kbit):约 4 帧的数据量。改动它会让 NVENC 整个重新初始化(出 IDR), +/// 所以只在初始化时设,之后码率持续偏离一倍以上才重设(见 [`NVENC_VBV_RULE`])。 +pub(crate) fn nvenc_vbv_kbits(kbps: u32, fps: u8) -> u32 { + let base = kbps.max(8_000); + (base.saturating_mul(4) / u32::from(fps.max(1))).clamp(512, 8_192) +} + +/// VA-API 的 GStreamer `bitrate` 属性就是目标平均码率(kbps):VBR 模式下 `GstVaBaseEnc` 内部会按 +/// `target-percentage` 自动推算峰值码率(67% 对应约 1.5× 峰值),因此直接传入 `kbps` 即可。 +pub(crate) fn vaapi_bitrate_prop(kbps: u32) -> u32 { + kbps.max(100) +} + +/// VA-API VBR 的 `target-percentage`:峰值码率是目标的 100/67 ≈ 1.5 倍,和 Media Foundation、VideoToolbox、NVENC 一样 +const VA_TARGET_PERCENTAGE: u32 = 67; +/// GStreamer `va` 编码器 `target-percentage` 的默认值(没法设置时按它算峰值码率) +const VA_DEFAULT_TARGET_PERCENTAGE: u32 = 66; + +/// VA-API 的 HRD 缓冲(`cpb-size`,kbit)。 +/// +/// GStreamer 不设时取 2 秒的峰值码率(`_calculate_bitrate_hrd`),约是目标码率 3 秒的数据,单帧(强制 IDR、 +/// 场景切换、每 1024 帧的周期 IDR)几乎不受约束;它还会把算出来的值写回 `cpb-size`,之后降码率重新配置时 +/// 沿用旧值(20 → 5 Mbps 后约是新码率 12 秒的数据)。所以每次设码率都一起设它,取 GStreamer 允许的最小值: +/// 峰值码率的一半(再小会被丢掉、换回 2 秒)。峰值码率按 GStreamer 的算法(向下取整): +/// VBR 是 `bitrate * 100 / target-percentage`,CBR(`target_percentage = 100`)就是 `bitrate`。 +pub(crate) fn vaapi_cpb_kbits(bitrate: u32, target_percentage: u32) -> u32 { + let peak = u64::from(bitrate) * 100 / u64::from(target_percentage.clamp(1, 100)); + u32::try_from(peak.div_ceil(2)).unwrap_or(u32::MAX) +} + +/// 滞回规则:目标和当前值之比(千分比)到多少才开始计时;反正要出关键帧时,到多少就顺带下发 +/// (1000:有变化就下发)。 +#[derive(Debug, Clone, Copy)] +struct HysteresisRule { + drop_permille: u64, + raise_permille: u64, + piggyback_permille: u64, +} + +/// `hi / lo` 至少是 `permille / 1000` +fn ratio_at_least(hi: u32, lo: u32, permille: u64) -> bool { + u64::from(hi) * 1000 >= u64::from(lo) * permille +} + +/// 下发一次就要出关键帧的参数(VA-API 的码率、NVENC 的 VBV)用的滞回状态机:目标持续偏离当前值一段时间 +/// (下降 [`BITRATE_DROP_HOLD`]、上升 [`BITRATE_RAISE_HOLD`])才下发,避免拥塞时 IDR 震荡。 +/// 时钟由调用方传入,方便无硬件单元测试。 +#[derive(Debug)] +struct Hysteresis { + rule: HysteresisRule, + active: u32, + target: u32, + pending: Option<(Instant, BitrateDir)>, + fail_until: Option, +} + +impl Hysteresis { + fn new(rule: HysteresisRule, value: u32) -> Self { + Self { + rule, + active: value, + target: value, + pending: None, + fail_until: None, + } + } + + fn set_target(&mut self, value: u32, now: Instant) { + self.target = value; + let dir = + if value < self.active && ratio_at_least(self.active, value, self.rule.drop_permille) { + Some(BitrateDir::Drop) + } else if value > self.active + && ratio_at_least(value, self.active, self.rule.raise_permille) + { + Some(BitrateDir::Raise) + } else { + None + }; + match dir { + Some(d) => match self.pending { + Some((_, cur)) if cur == d => {} + _ => self.pending = Some((now, d)), + }, + None => self.pending = None, + } + } + + fn should_apply(&self, force_key: bool, now: Instant) -> Option { + if self.target == self.active { + return None; + } + if self.fail_until.is_some_and(|until| now < until) { + return None; + } + let (hi, lo) = (self.target.max(self.active), self.target.min(self.active)); + let piggyback = force_key && ratio_at_least(hi, lo, self.rule.piggyback_permille); + let sustained = self.pending.is_some_and(|(since, dir)| { + let hold = match dir { + BitrateDir::Drop => BITRATE_DROP_HOLD, + BitrateDir::Raise => BITRATE_RAISE_HOLD, + }; + now.saturating_duration_since(since) >= hold + }); + (piggyback || sustained).then_some(self.target) + } + + fn mark_applied(&mut self, value: u32) { + self.active = value; + self.pending = None; + self.fail_until = None; + } + + fn mark_failed(&mut self, now: Instant) { + self.pending = None; + self.fail_until = Some(now + BITRATE_RETRY_BACKOFF); + } +} + +// ───────────────────────────── NV12 转换(遵守 GStreamer 4 字节行对齐) ───────────────────────────── + +fn validate_dimensions(w: u32, h: u32) -> Result<()> { + if !(MIN_DIM..=MAX_DIM).contains(&w) + || !(MIN_DIM..=MAX_DIM).contains(&h) + || !w.is_multiple_of(2) + || !h.is_multiple_of(2) + { + bail!( + "unsupported hardware encode dimensions {w}x{h} (must be even {MIN_DIM}..={MAX_DIM})" + ); + } + Ok(()) +} + +/// 构造标准 BT.709 有限范围 NV12 的 `GstVideoInfo`(行步长自动按 GStreamer 规则 4 字节对齐)。 +fn build_nv12_video_info(w: u32, h: u32, fps: u8) -> Result { + let colorimetry = gst_video::VideoColorimetry::from_str("bt709") + .map_err(|_| anyhow!("invalid bt709 colorimetry"))?; + gst_video::VideoInfo::builder(gst_video::VideoFormat::Nv12, w, h) + .fps(gst::Fraction::new(i32::from(fps.max(1)), 1)) + .colorimetry(&colorimetry) + .build() + .map_err(|e| anyhow!("failed to build NV12 VideoInfo for {w}x{h}: {e}")) +} + +/// 将紧密排列的 BGRA 写入遵循 `video_info` 偏移与步长的 NV12 缓冲。 +/// +/// GStreamer 对 `video/x-raw,format=NV12` 默认采用 4 字节行对齐(例如 `1366` → 步长 `1368`、`1590` → `1592`), +/// 而 `yuvutils_rs` 0.8 要求 UV 平面紧密排列;因此在 `uv_stride != uv_row` 时借用 `uv_scratch` 按行写入, +/// 在 `w % 4 == 0` 的常见分辨率上零额外拷贝直接写入目标缓冲。 +fn write_bgra_to_nv12_slice( + video_info: &gst_video::VideoInfo, + dst: &mut [u8], + bgra: &[u8], + uv_scratch: &mut Vec, +) -> Result<()> { + let w = video_info.width(); + let h = video_info.height(); + let expected = (w as usize) + .checked_mul(h as usize) + .and_then(|n| n.checked_mul(4)) + .ok_or_else(|| anyhow!("BGRA buffer size overflow"))?; + if bgra.len() < expected { + bail!("BGRA buffer too small: {} < {expected}", bgra.len()); + } + let min_size = video_info.size(); + if dst.len() < min_size { + bail!( + "NV12 destination buffer too small: {} < {min_size}", + dst.len() + ); + } + let y_stride = usize::try_from(video_info.stride()[0]) + .map_err(|_| anyhow!("invalid negative Y stride"))?; + let uv_stride = usize::try_from(video_info.stride()[1]) + .map_err(|_| anyhow!("invalid negative UV stride"))?; + let uv_offset = video_info.offset()[1]; + let y_stride_u32 = u32::try_from(y_stride).map_err(|_| anyhow!("Y stride overflow"))?; + let uv_row = (w as usize).div_ceil(2) * 2; + let uv_row_u32 = u32::try_from(uv_row).map_err(|_| anyhow!("UV row overflow"))?; + let uv_h = (h as usize).div_ceil(2); + let y_len = y_stride * (h as usize); + let uv_need = uv_stride * uv_h; + if uv_offset < y_len || uv_offset.saturating_add(uv_need) > dst.len() { + bail!("NV12 VideoInfo plane layout out of bounds"); + } + + let (y_part, uv_part) = dst.split_at_mut(uv_offset); + let y_plane = &mut y_part[..y_len]; + if uv_stride == uv_row { + let mut img = YuvBiPlanarImageMut { + y_plane: yuvutils_rs::BufferStoreMut::Borrowed(y_plane), + y_stride: y_stride_u32, + uv_plane: yuvutils_rs::BufferStoreMut::Borrowed(&mut uv_part[..uv_row * uv_h]), + uv_stride: uv_row_u32, + width: w, + height: h, + }; + yuvutils_rs::bgra_to_yuv_nv12( + &mut img, + &bgra[..expected], + w * 4, + YuvRange::Limited, + YuvStandardMatrix::Bt709, + YuvConversionMode::Balanced, + ) + .map_err(|e| anyhow!("color conversion failed: {e:?}"))?; + } else { + uv_scratch.resize(uv_row * uv_h, 128); + let mut img = YuvBiPlanarImageMut { + y_plane: yuvutils_rs::BufferStoreMut::Borrowed(y_plane), + y_stride: y_stride_u32, + uv_plane: yuvutils_rs::BufferStoreMut::Borrowed(uv_scratch.as_mut_slice()), + uv_stride: uv_row_u32, + width: w, + height: h, + }; + yuvutils_rs::bgra_to_yuv_nv12( + &mut img, + &bgra[..expected], + w * 4, + YuvRange::Limited, + YuvStandardMatrix::Bt709, + YuvConversionMode::Balanced, + ) + .map_err(|e| anyhow!("color conversion failed: {e:?}"))?; + for (dst_row, src_row) in uv_part[..uv_need] + .chunks_mut(uv_stride) + .zip(uv_scratch.chunks(uv_row)) + .take(uv_h) + { + dst_row[..uv_row].copy_from_slice(src_row); + } + } + Ok(()) +} + +// ───────────────────────────── 管线构建与安全回收 ───────────────────────────── + +/// 封装 GStreamer 管线与缓冲池,确保任意错误路径与 Drop 均将管线切回 `State::Null`(带超时防驱动卡死)。 +struct PipelineGuard { + pipeline: Option, + src: gst_app::AppSrc, + pool: gst::BufferPool, + factory: String, +} + +impl PipelineGuard { + fn pipeline(&self) -> &gst::Pipeline { + self.pipeline.as_ref().expect("pipeline still alive") + } +} + +impl Drop for PipelineGuard { + fn drop(&mut self) { + let Some(pipeline) = self.pipeline.take() else { + return; + }; + let src = self.src.clone(); + let pool = self.pool.clone(); + let factory = self.factory.clone(); + let (tx, rx) = mpsc::channel(); + // 将可能阻塞的 pool 停用、FlushStart 与 set_state(Null) 全部放进带超时的清理线程,避免卡住编码线程 + let spawn = std::thread::Builder::new() + .name("airhand-gst-teardown".into()) + .spawn(move || { + let _ = pool.set_active(false); + let _ = src.send_event(gst::event::FlushStart::new()); + let _ = pipeline.set_state(gst::State::Null); + let _ = tx.send(()); + }); + match spawn { + Ok(_) => { + if rx.recv_timeout(TEARDOWN_TIMEOUT).is_err() { + warn!( + factory = %factory, + "GStreamer pipeline teardown timed out; blacklisting factory for this process" + ); + mark_factory_broken(&factory); + } + } + Err(e) => { + warn!( + factory = %factory, + "failed to spawn GStreamer teardown thread ({e}); blacklisting factory" + ); + mark_factory_broken(&factory); + } + } + } +} + +/// 构造编码器输出 caps 候选列表(显式固定 `byte-stream`/`obu-stream` 与主流 profile,必要时降级)。 +fn output_caps_candidates(codec: Codec) -> Vec { + match codec { + Codec::H264 => vec![ + gst::Caps::builder("video/x-h264") + .field("stream-format", "byte-stream") + .field("alignment", "au") + .field("profile", "high") + .build(), + gst::Caps::builder("video/x-h264") + .field("stream-format", "byte-stream") + .field("alignment", "au") + .field("profile", "main") + .build(), + gst::Caps::builder("video/x-h264") + .field("stream-format", "byte-stream") + .field("alignment", "au") + .build(), + ], + Codec::H265 => vec![ + gst::Caps::builder("video/x-h265") + .field("stream-format", "byte-stream") + .field("alignment", "au") + .field("profile", "main") + .build(), + gst::Caps::builder("video/x-h265") + .field("stream-format", "byte-stream") + .field("alignment", "au") + .build(), + ], + Codec::AV1 => vec![ + // 注意:不强制 `alignment=au`/`tu`:`vaav1enc` 仅声明 `alignment=frame`,而 `nvav1enc` 可能用 `tu`/`frame` + gst::Caps::builder("video/x-av1") + .field("stream-format", "obu-stream") + .field("profile", "main") + .build(), + gst::Caps::builder("video/x-av1") + .field("stream-format", "obu-stream") + .build(), + ], + Codec::Unknown(_) => Vec::new(), + } +} + +/// 配置 NVENC 编码器,返回设置的 `vbv-buffer-size`(kbit;`None`:驱动不支持自定义 VBV,没有这个属性)。 +fn configure_nvenc(enc: &gst::Element, codec: Codec, fps: u8, kbps: u32) -> Option { + let kbps = kbps.max(100); + // GStreamer 1.24+ 支持 `preset=p4` + `tune=ultra-low-latency`;Debian 12 (1.22) 无 `tune`,使用旧式低延迟 preset + if enc.find_property("tune").is_some() { + let _ = try_set_str(enc, "preset", "p4"); + let _ = try_set_str(enc, "tune", "ultra-low-latency"); + } else if try_set_str(enc, "preset", "low-latency-hq").unwrap_or(false) { + // ok + } else { + let _ = try_set_str(enc, "preset", "low-latency"); + } + if !try_set_str(enc, "rate-control", "vbr").unwrap_or(false) { + let _ = try_set_str(enc, "rc-mode", "vbr"); + } + let _ = try_set_i32(enc, "gop-size", -1); + if try_set_u32(enc, "b-frames", 0).is_none() { + let _ = try_set_u32(enc, "bframes", 0); + } + if !try_set_bool(enc, "zero-reorder-delay", true) { + let _ = try_set_bool(enc, "zerolatency", true); + } + if codec != Codec::AV1 { + let _ = try_set_bool(enc, "repeat-sequence-header", true); + let _ = try_set_bool(enc, "aud", false); + } + // VBV 大小(kbit)平时不改,`bitrate`/`max-bitrate` 走软重配、不产生 IDR(见 [`NVENC_VBV_RULE`]) + let vbv = try_set_u32(enc, "vbv-buffer-size", nvenc_vbv_kbits(kbps, fps)); + let max_kbps = kbps.saturating_mul(3) / 2; + let _ = try_set_u32(enc, "max-bitrate", max_kbps); + let _ = try_set_u32(enc, "bitrate", kbps); + vbv +} + +/// 配置 VA-API 编码器,返回峰值码率用的 `target-percentage`(CBR 为 100,见 [`vaapi_cpb_kbits`])。 +fn configure_vaapi(enc: &gst::Element, codec: Codec, kbps: u32) -> Result { + let kbps = kbps.max(100); + if enc.find_property("b-frames").is_some() && try_set_u32(enc, "b-frames", 0).is_none() { + bail!("failed to set b-frames=0 on VA-API encoder"); + } + // Intel iHD 24.1.0 上 `vah264enc` 默认 `ref-frames=3` 会触发 `vaEndPicture` 内部错误;`ref-frames=1` 稳定且低延迟 + let _ = try_set_u32(enc, "ref-frames", 1); + if codec != Codec::AV1 { + let _ = try_set_bool(enc, "aud", false); + } else { + // `vaav1enc` 默认 `hierarchical-level=6, gf-group-size=32` 会缓存多帧破坏一进一出 + if try_set_u32(enc, "hierarchical-level", 1) != Some(1) { + bail!("vaav1enc failed to set hierarchical-level=1 for 1-in-1-out"); + } + if try_set_u32(enc, "gf-group-size", 1) != Some(1) { + bail!("vaav1enc failed to set gf-group-size=1 for 1-in-1-out"); + } + } + let _ = try_set_u32(enc, "key-int-max", 1024); + let _ = try_set_u32(enc, "target-usage", 4); + + // 不知道用的是哪种码率控制时,峰值码率按 GStreamer 默认的 target-percentage 算(偏大,缓冲不会低于下限) + let mut target_percentage = VA_DEFAULT_TARGET_PERCENTAGE; + if enc.find_property("rate-control").is_some() { + if try_set_str(enc, "rate-control", "vbr").unwrap_or(false) { + target_percentage = try_set_u32(enc, "target-percentage", VA_TARGET_PERCENTAGE) + .unwrap_or(VA_DEFAULT_TARGET_PERCENTAGE); + } else if try_set_str(enc, "rate-control", "cbr").unwrap_or(false) { + target_percentage = 100; + } else { + bail!("VA-API encoder exposes neither VBR nor CBR rate control"); + } + } + let bitrate = vaapi_bitrate_prop(kbps); + let _ = try_set_u32(enc, "bitrate", bitrate); + let _ = try_set_u32(enc, "cpb-size", vaapi_cpb_kbits(bitrate, target_percentage)); + Ok(target_percentage) +} + +fn create_buffer_pool(video_info: &gst_video::VideoInfo) -> Result { + let pool = gst::BufferPool::new(); + let mut cfg = pool.config(); + let caps = video_info + .to_caps() + .map_err(|e| anyhow!("failed to create caps for buffer pool: {e}"))?; + let size = u32::try_from(video_info.size()).map_err(|_| anyhow!("NV12 frame size overflow"))?; + // 预分配 2 帧实现零缺页复用;max_buffers = 0 配合 DONTWAIT 确保永不在编码线程上死等缓冲池 + cfg.set_params(Some(&caps), size, 2, 0); + pool.set_config(cfg) + .map_err(|e| anyhow!("failed to configure GStreamer buffer pool: {e}"))?; + pool.set_active(true) + .map_err(|e| anyhow!("failed to activate GStreamer buffer pool: {e}"))?; + Ok(pool) +} + +fn pop_bus_error(pipeline: &gst::Pipeline) -> Option { + let bus = pipeline.bus()?; + let mut err_msg = None; + while let Some(msg) = bus.pop() { + if let gst::MessageView::Error(e) = msg.view() { + err_msg = Some(format!("{} ({:?})", e.error(), e.debug())); + } + } + err_msg +} + +enum Mode { + Nvenc { + active_kbps: u32, + fps: u8, + /// `vbv-buffer-size`(kbit)的滞回;`None`:驱动不支持自定义 VBV,不重设 + vbv: Option, + }, + Vaapi { + bitrate_mutable_playing: bool, + /// 峰值码率用的 `target-percentage`(见 [`vaapi_cpb_kbits`]) + target_percentage: u32, + /// `bitrate`(kbps)的滞回 + rate: Hysteresis, + }, +} + +pub struct LinuxHwEncoder { + guard: PipelineGuard, + src: gst_app::AppSrc, + sink: gst_app::AppSink, + enc: gst::Element, + video_info: gst_video::VideoInfo, + mode: Mode, + info: EncoderInfo, + frame_ns: u64, + pts_idx: u64, + /// `smoke_test()` 消耗了首帧后,保证调用方第一帧始终输出带完整参数集的关键帧 + need_initial_key: bool, + uv_scratch: Vec, +} + +impl LinuxHwEncoder { + /// 按已缓存的探测结果创建硬件编码器;无硬件支持或分辨率超出静态模板范围时立刻失败,不重复探测。 + pub fn new(codec: Codec, w: u32, h: u32, fps: u8, kbps: u32) -> Result { + validate_dimensions(w, h)?; + let candidates = probe_cache().candidates(codec); + if candidates.is_empty() { + bail!("no Linux hardware encoder available for {codec:?}"); + } + let mut last_err = anyhow!("no Linux hardware encoder accepted {codec:?} at {w}x{h}"); + let mut tried_any = false; + for cand in candidates { + if is_factory_broken(&cand.factory) || !factory_supports_size(&cand.factory, w, h) { + continue; + } + tried_any = true; + match Self::open_candidate(cand, w, h, fps, kbps) { + Ok(enc) => return Ok(enc), + Err(e) => { + debug!( + factory = %cand.factory, + ?codec, + w, + h, + "Linux hardware encoder open failed: {e:#}" + ); + last_err = e; + } + } + } + if !tried_any { + bail!("no Linux hardware encoder factory supports {codec:?} at {w}x{h}"); + } + Err(last_err) + } + + #[cfg(test)] + pub(crate) fn new_vaapi( + codec: Codec, + w: u32, + h: u32, + fps: u8, + kbps: u32, + device_override: Option<&str>, + ) -> Result { + validate_dimensions(w, h)?; + ensure_gst()?; + let nodes = discover_vaapi_nodes(device_override); + let candidates = discover_va_candidates(codec, &nodes); + if candidates.is_empty() { + bail!("no VA-API GStreamer encoder factory found for {codec:?}"); + } + let mut last_err = anyhow!("no VA-API candidate succeeded for {codec:?}"); + for cand in &candidates { + match Self::open_candidate(cand, w, h, fps, kbps) { + Ok(enc) => return Ok(enc), + Err(e) => last_err = e, + } + } + Err(last_err) + } + + #[cfg(test)] + pub(crate) fn new_nvenc(codec: Codec, w: u32, h: u32, fps: u8, kbps: u32) -> Result { + validate_dimensions(w, h)?; + ensure_gst()?; + let candidates = discover_nvenc_candidates(codec); + if candidates.is_empty() { + bail!("no NVENC GStreamer encoder factory found for {codec:?}"); + } + let mut last_err = anyhow!("no NVENC candidate succeeded for {codec:?}"); + for cand in &candidates { + match Self::open_candidate(cand, w, h, fps, kbps) { + Ok(enc) => return Ok(enc), + Err(e) => last_err = e, + } + } + Err(last_err) + } + + fn open_candidate(cand: &Candidate, w: u32, h: u32, fps: u8, kbps: u32) -> Result { + let caps_list = output_caps_candidates(cand.codec); + if caps_list.is_empty() { + bail!("unsupported codec {:?}", cand.codec); + } + let mut last_err = anyhow!("failed to open {}", cand.factory); + for out_caps in caps_list { + match Self::open_with_caps(cand, w, h, fps, kbps, &out_caps) { + Ok(enc) => return Ok(enc), + Err(e) => { + debug!( + factory = %cand.factory, + caps = %out_caps, + "GStreamer encoder attempt failed: {e:#}" + ); + last_err = e; + } + } + } + Err(last_err) + } + + fn open_with_caps( + cand: &Candidate, + w: u32, + h: u32, + fps: u8, + kbps: u32, + out_caps: &gst::Caps, + ) -> Result { + let fps = fps.max(1); + let kbps = kbps.max(100); + let video_info = build_nv12_video_info(w, h, fps)?; + let in_caps = video_info + .to_caps() + .map_err(|e| anyhow!("failed to build input caps: {e}"))?; + + let src = gst_app::AppSrc::builder() + .caps(&in_caps) + .format(gst::Format::Time) + .is_live(true) + .block(false) + .max_buffers(2) + .build(); + src.set_property("emit-signals", false); + + let enc = gst::ElementFactory::make(&cand.factory) + .build() + .with_context(|| format!("failed to instantiate GStreamer element {}", cand.factory))?; + + let mode = match cand.backend { + Backend::Nvenc => { + let vbv = configure_nvenc(&enc, cand.codec, fps, kbps); + Mode::Nvenc { + active_kbps: kbps, + fps, + vbv: vbv.map(|kbits| Hysteresis::new(NVENC_VBV_RULE, kbits)), + } + } + Backend::Vaapi => { + let target_percentage = configure_vaapi(&enc, cand.codec, kbps)?; + let bitrate_mutable_playing = is_mutable_playing(&enc, "bitrate"); + Mode::Vaapi { + bitrate_mutable_playing, + target_percentage, + rate: Hysteresis::new(VA_BITRATE_RULE, vaapi_bitrate_prop(kbps)), + } + } + }; + + let capsfilter = gst::ElementFactory::make("capsfilter") + .property("caps", out_caps) + .build() + .context("failed to instantiate capsfilter")?; + + let sink = gst_app::AppSink::builder() + .sync(false) + .async_(false) + .enable_last_sample(false) + .qos(false) + .drop(false) + .max_buffers(4) + .build(); + sink.set_property("emit-signals", false); + + let pipeline = gst::Pipeline::new(); + pipeline + .add_many([src.upcast_ref(), &enc, &capsfilter, sink.upcast_ref()]) + .context("failed to add elements to GStreamer pipeline")?; + gst::Element::link_many([src.upcast_ref(), &enc, &capsfilter, sink.upcast_ref()]) + .with_context(|| format!("failed to link pipeline for {}", cand.factory))?; + + let pool = create_buffer_pool(&video_info)?; + let guard = PipelineGuard { + pipeline: Some(pipeline), + src: src.clone(), + pool, + factory: cand.factory.clone(), + }; + + guard + .pipeline() + .set_state(gst::State::Playing) + .map_err(|e| { + let detail = pop_bus_error(guard.pipeline()).unwrap_or_default(); + anyhow!( + "failed to start GStreamer pipeline {}: {e:?} {detail}", + cand.factory + ) + })?; + + let mut encoder = Self { + guard, + src, + sink, + enc, + video_info, + mode, + info: EncoderInfo { + codec: cand.codec, + name: cand.label.clone(), + hardware: true, + width: w, + height: h, + stream: 0, + }, + frame_ns: 1_000_000_000 / u64::from(fps), + pts_idx: 0, + need_initial_key: true, + uv_scratch: Vec::new(), + }; + encoder + .smoke_test() + .with_context(|| format!("{} smoke test", cand.factory))?; + Ok(encoder) + } + + /// 冒烟测试:编码一帧全黑关键帧并校验输出带完整参数集 / Sequence Header。 + fn smoke_test(&mut self) -> Result<()> { + let len = (self.info.width as usize) + .checked_mul(self.info.height as usize) + .and_then(|n| n.checked_mul(4)) + .ok_or_else(|| anyhow!("frame size overflow"))?; + let black = vec![0u8; len]; + let frame = self + .encode_frame(&black, false, true, FIRST_FRAME_TIMEOUT)? + .ok_or_else(|| anyhow!("encoder produced no output for smoke test frame"))?; + if frame.data.is_empty() || !frame.key { + bail!( + "encoder smoke test frame was not a valid keyframe with headers for {:?}", + self.info.codec + ); + } + self.need_initial_key = true; + Ok(()) + } + + /// 在 NVENC 上直接更新 `bitrate` / `max-bitrate`(保持 `vbv-buffer-size` 不变,无 IDR); + /// VBV 按新码率该有的大小只记进滞回,持续偏离时才在 [`VideoEncoder::encode`] 里重设。 + fn apply_nvenc_bitrate(&mut self, kbps: u32, now: Instant) { + let Mode::Nvenc { + active_kbps, + fps, + vbv, + } = &mut self.mode + else { + return; + }; + let kbps = kbps.max(100); + if kbps == *active_kbps { + return; + } + let max_kbps = kbps.saturating_mul(3) / 2; + if kbps > *active_kbps { + // 升码率时先升上限再升目标,避免短暂出现 bitrate > max-bitrate + let _ = try_set_u32(&self.enc, "max-bitrate", max_kbps); + let _ = try_set_u32(&self.enc, "bitrate", kbps); + } else { + let _ = try_set_u32(&self.enc, "bitrate", kbps); + let _ = try_set_u32(&self.enc, "max-bitrate", max_kbps); + } + *active_kbps = kbps; + if let Some(vbv) = vbv { + vbv.set_target(nvenc_vbv_kbits(kbps, *fps), now); + } + } + + /// NVENC 的码率持续偏离 VBV 一倍以上(或者反正要出关键帧、偏离 1.5 倍以上)时按现在的码率重设 VBV。 + /// 编码器会在这一帧整个重新初始化,输出带参数集的 IDR(由码流判断,见 [`is_sync_keyframe_with_headers`])。 + fn resize_nvenc_vbv(&mut self, force_key: bool, now: Instant) { + let Mode::Nvenc { vbv: Some(vbv), .. } = &mut self.mode else { + return; + }; + let Some(kbits) = vbv.should_apply(force_key, now) else { + return; + }; + if try_set_u32(&self.enc, "vbv-buffer-size", kbits).is_some() { + vbv.mark_applied(kbits); + debug!(encoder = %self.info.name, kbits, "resized the NVENC VBV"); + } else { + vbv.mark_failed(now); + } + } + + /// 在 VA-API 上应用新的码率,返回是否已因此重启 GOP(重启后下一帧必然是 IDR,无需再发 flush)。 + fn apply_vaapi_bitrate(&mut self, kbps: u32) -> Result { + let Mode::Vaapi { + bitrate_mutable_playing, + target_percentage, + .. + } = self.mode + else { + return Ok(false); + }; + let rate = vaapi_bitrate_prop(kbps); + let cpb = vaapi_cpb_kbits(rate, target_percentage); + if bitrate_mutable_playing { + if try_set_u32(&self.enc, "bitrate", rate).is_none() { + bail!("failed to set VA-API bitrate property"); + } + // `cpb-size` 本身不触发重新配置,只记下来:上面改 `bitrate` 触发的那次重新配置一起生效 + let _ = try_set_u32(&self.enc, "cpb-size", cpb); + // `vah264enc`/`vah265enc` 更改 bitrate 后会自动重启 GOP 并输出带参数集的 IDR + Ok(true) + } else { + // GStreamer 1.24.2 `vaav1enc` 的 `bitrate` 不可在 PLAYING 状态修改:切到 READY 修改再恢复 + let pipeline = self.guard.pipeline(); + pipeline + .set_state(gst::State::Ready) + .map_err(|e| anyhow!("VA-API Ready transition failed: {e:?}"))?; + let set_ok = try_set_u32(&self.enc, "bitrate", rate).is_some(); + let _ = try_set_u32(&self.enc, "cpb-size", cpb); + pipeline.set_state(gst::State::Playing).map_err(|e| { + let detail = pop_bus_error(pipeline).unwrap_or_default(); + anyhow!("VA-API Playing restore failed: {e:?} {detail}") + })?; + if !set_ok { + bail!("failed to set VA-API bitrate in Ready state"); + } + Ok(true) + } + } + + /// 请求强制关键帧:NVENC 走 `UpstreamForceKeyUnitEvent`;VA-API 走 `FlushStart` + `FlushStop(false)` + /// 以规避 GStreamer 1.24.2 `vah264enc` 无 SPS 非 IDR 及 `vah265enc` 后续帧挂起问题。 + fn trigger_force_key(&self) -> Result<()> { + match self.mode { + Mode::Nvenc { .. } => { + let ev = gst_video::UpstreamForceKeyUnitEvent::builder() + .all_headers(true) + .build(); + if !self.sink.send_event(ev) { + bail!("NVENC rejected UpstreamForceKeyUnitEvent"); + } + } + Mode::Vaapi { .. } => { + if !self.src.send_event(gst::event::FlushStart::new()) { + bail!("VA-API appsrc rejected FlushStart"); + } + if !self.src.send_event(gst::event::FlushStop::new(false)) { + bail!("VA-API appsrc rejected FlushStop"); + } + } + } + Ok(()) + } + + fn acquire_nv12_buffer(&mut self, bgra: &[u8]) -> Result { + let params = + gst::BufferPoolAcquireParams::with_flags(gst::BufferPoolAcquireFlags::DONTWAIT); + let mut buf = self + .guard + .pool + .acquire_buffer(Some(¶ms)) + .map_err(|e| anyhow!("failed to acquire NV12 buffer from pool: {e:?}"))?; + { + let buf_mut = buf + .get_mut() + .ok_or_else(|| anyhow!("acquired pool buffer is unexpectedly shared"))?; + let mut map = buf_mut + .map_writable() + .map_err(|e| anyhow!("failed to map NV12 buffer writable: {e}"))?; + write_bgra_to_nv12_slice( + &self.video_info, + map.as_mut_slice(), + bgra, + &mut self.uv_scratch, + )?; + } + let pts = gst::ClockTime::from_nseconds(self.pts_idx.saturating_mul(self.frame_ns)); + let dur = gst::ClockTime::from_nseconds(self.frame_ns); + self.pts_idx = self.pts_idx.saturating_add(1); + { + let buf_mut = buf.get_mut().unwrap(); + buf_mut.set_pts(pts); + buf_mut.set_duration(dur); + } + Ok(buf) + } + + fn encode_frame( + &mut self, + bgra: &[u8], + send_force_key: bool, + require_key: bool, + timeout: Duration, + ) -> Result> { + if send_force_key { + self.trigger_force_key()?; + } + let buf = self.acquire_nv12_buffer(bgra)?; + let pushed_pts = buf.pts(); + self.src.push_buffer(buf).map_err(|e| { + let detail = pop_bus_error(self.guard.pipeline()).unwrap_or_default(); + anyhow!("appsrc push_buffer failed: {e:?} {detail}") + })?; + + let sample = self + .sink + .try_pull_sample(gst::ClockTime::from_nseconds(timeout.as_nanos() as u64)) + .ok_or_else(|| { + let detail = pop_bus_error(self.guard.pipeline()) + .unwrap_or_else(|| "timed out waiting for encoded sample".into()); + anyhow!("hardware encoder produced no output: {detail}") + })?; + + let out_buf = sample + .buffer() + .ok_or_else(|| anyhow!("appsink sample missing buffer"))?; + if let (Some(expected), Some(got)) = (pushed_pts, out_buf.pts()) + && expected != got + { + debug!( + factory = %self.guard.factory, + expected_ns = expected.nseconds(), + got_ns = got.nseconds(), + "encoded sample PTS differed from pushed PTS" + ); + } + let map = out_buf + .map_readable() + .map_err(|e| anyhow!("failed to map encoded output buffer: {e}"))?; + let mut combined = map.as_slice().to_vec(); + drop(map); + + // 排空同帧可能产生的多余片段,保持严格一进一出 + while let Some(extra) = self.sink.try_pull_sample(gst::ClockTime::ZERO) { + if let Some(eb) = extra.buffer() + && let Ok(emap) = eb.map_readable() + { + combined.extend_from_slice(emap.as_slice()); + } + } + if let Some(bus_err) = pop_bus_error(self.guard.pipeline()) { + bail!("GStreamer bus error: {bus_err}"); + } + if combined.is_empty() { + bail!("hardware encoder produced an empty frame"); + } + let data = if self.info.codec == Codec::AV1 { + ensure_av1_temporal_delimiter(combined) + } else { + combined + }; + let key = is_sync_keyframe_with_headers(self.info.codec, &data); + if require_key && !key { + self.need_initial_key = true; + bail!( + "forced keyframe on {} did not contain sync frame and in-band headers", + self.guard.factory + ); + } + Ok(Some(EncodedFrame { + data, + key, + ltr: None, + })) + } +} + +impl VideoEncoder for LinuxHwEncoder { + fn info(&self) -> &EncoderInfo { + &self.info + } + + fn set_bitrate(&mut self, kbps: u32) { + let now = Instant::now(); + match &mut self.mode { + Mode::Nvenc { .. } => self.apply_nvenc_bitrate(kbps, now), + Mode::Vaapi { rate, .. } => rate.set_target(vaapi_bitrate_prop(kbps), now), + } + } + + fn encode(&mut self, bgra: &[u8], mut force_key: bool) -> Result> { + if self.need_initial_key { + force_key = true; + self.need_initial_key = false; + } + + let now = Instant::now(); + self.resize_nvenc_vbv(force_key, now); + let mut gop_restarted_by_bitrate = false; + let va_apply = match &self.mode { + Mode::Vaapi { rate, .. } => rate.should_apply(force_key, now), + Mode::Nvenc { .. } => None, + }; + if let Some(target_kbps) = va_apply { + match self.apply_vaapi_bitrate(target_kbps) { + Ok(restarted) => { + gop_restarted_by_bitrate = restarted; + if let Mode::Vaapi { rate, .. } = &mut self.mode { + rate.mark_applied(target_kbps); + } + debug!( + encoder = %self.info.name, + kbps = target_kbps, + "applied VA-API bitrate update" + ); + } + Err(e) => { + warn!( + encoder = %self.info.name, + kbps = target_kbps, + "VA-API bitrate update failed, backing off retry: {e:#}" + ); + if let Mode::Vaapi { rate, .. } = &mut self.mode { + rate.mark_failed(now); + } + } + } + } + + // 若 VA-API 刚刚因调码率重启了 GOP,则跳过重复 flush,但仍保留 `require_key = force_key` 的输出校验 + let send_force_key = force_key && !gop_restarted_by_bitrate; + self.encode_frame(bgra, send_force_key, force_key, STEADY_FRAME_TIMEOUT) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ───────────────────────────── 无硬件单元测试(CI 中必跑,不跳过) ───────────────────────────── + + #[test] + fn backend_order_rules() { + assert_eq!( + backend_order(HwEncoderPref::Auto, DisplayOwner::Vaapi), + vec![Backend::Vaapi, Backend::Nvenc] + ); + assert_eq!( + backend_order(HwEncoderPref::Auto, DisplayOwner::Unknown), + vec![Backend::Vaapi, Backend::Nvenc] + ); + assert_eq!( + backend_order(HwEncoderPref::Auto, DisplayOwner::Nvidia), + vec![Backend::Nvenc, Backend::Vaapi] + ); + assert_eq!( + backend_order(HwEncoderPref::Vaapi, DisplayOwner::Nvidia), + vec![Backend::Vaapi] + ); + assert_eq!( + backend_order(HwEncoderPref::Nvenc, DisplayOwner::Vaapi), + vec![Backend::Nvenc] + ); + assert!(backend_order(HwEncoderPref::Software, DisplayOwner::Vaapi).is_empty()); + } + + #[test] + fn parse_va_factory_node_names() { + assert_eq!( + parse_va_factory_node("varenderD129h264enc").as_deref(), + Some("/dev/dri/renderD129") + ); + assert_eq!( + parse_va_factory_node("varenderD130h265lpenc").as_deref(), + Some("/dev/dri/renderD130") + ); + assert_eq!(parse_va_factory_node("vah264enc"), None); + assert_eq!(parse_va_factory_node("varenderDh264enc"), None); + + // Debian 12 (GStreamer 1.22) 动态枚举名解析(无需打开设备即可识别主节点) + assert_eq!( + parse_va_rate_control_type_node("GstVaEncoderRateControl_H264_renderD128").as_deref(), + Some("/dev/dri/renderD128") + ); + assert_eq!( + parse_va_rate_control_type_node("GstVaEncoderRateControl_H265_renderD129").as_deref(), + Some("/dev/dri/renderD129") + ); + assert_eq!( + parse_va_rate_control_type_node("GstVaEncoderRateControl"), + None + ); + } + + #[test] + fn av1_obu_and_sync_keyframe_detection() { + // H.264: IDR + SPS + PPS -> true; non-IDR I-slice + PPS only -> false + let h264_idr = [ + 0, 0, 0, 1, 0x67, 0x42, 0, 0, 0, 1, 0x68, 0xce, 0, 0, 0, 1, 0x65, 0x88, + ]; + assert!(is_sync_keyframe_with_headers(Codec::H264, &h264_idr)); + let h264_pps_slice = [0, 0, 0, 1, 0x68, 0xce, 0, 0, 0, 1, 0x41, 0x9a]; + assert!(!is_sync_keyframe_with_headers(Codec::H264, &h264_pps_slice)); + let h264_idr_no_sps = [0, 0, 0, 1, 0x68, 0xce, 0, 0, 0, 1, 0x65, 0x88]; + assert!(!is_sync_keyframe_with_headers( + Codec::H264, + &h264_idr_no_sps + )); + + // H.265: VPS(32) + SPS(33) + PPS(34) + IDR(19) -> true; PPS+non-IDR -> false + let h265_idr = [ + 0, 0, 0, 1, 0x40, 0x01, 0, 0, 0, 1, 0x42, 0x01, 0, 0, 0, 1, 0x44, 0x01, 0, 0, 0, 1, + 0x26, 0x01, + ]; + assert!(is_sync_keyframe_with_headers(Codec::H265, &h265_idr)); + let h265_no_vps = [ + 0, 0, 0, 1, 0x42, 0x01, 0, 0, 0, 1, 0x44, 0x01, 0, 0, 0, 1, 0x26, 0x01, + ]; + assert!(!is_sync_keyframe_with_headers(Codec::H265, &h265_no_vps)); + + // AV1: TD(2, len=0) + SeqHdr(1, len=2) + Frame(6, len=2) -> 合法关键帧 + // (序列头 0xaa:reduced_still_picture_header = 1,所有帧都是关键帧) + let key_with_frame = [0x12, 0x00, 0x0a, 0x02, 0xaa, 0xbb, 0x32, 0x02, 0x11, 0x22]; + assert!(av1_has_sequence_header(&key_with_frame)); + assert!(is_sync_keyframe_with_headers(Codec::AV1, &key_with_frame)); + assert_eq!( + ensure_av1_temporal_delimiter(key_with_frame.to_vec()), + key_with_frame + ); + + // 普通序列头(0x00):看帧头的 show_existing_frame 和 frame_type + // Frame OBU:0x10 = KEY_FRAME;0x20 = INTER_FRAME;0x80 = show_existing_frame + let key = [0x12, 0x00, 0x0a, 0x02, 0x00, 0x00, 0x32, 0x02, 0x10, 0x00]; + assert!(is_sync_keyframe_with_headers(Codec::AV1, &key)); + // Frame Header OBU(3)同样认 + let key_hdr = [0x12, 0x00, 0x0a, 0x02, 0x00, 0x00, 0x1a, 0x01, 0x10]; + assert!(is_sync_keyframe_with_headers(Codec::AV1, &key_hdr)); + // 每帧都重复序列头的帧间帧、显示已有帧不是关键帧 + let inter = [0x12, 0x00, 0x0a, 0x02, 0x00, 0x00, 0x32, 0x02, 0x20, 0x00]; + assert!(!is_sync_keyframe_with_headers(Codec::AV1, &inter)); + let shown = [0x12, 0x00, 0x0a, 0x02, 0x00, 0x00, 0x1a, 0x01, 0x80]; + assert!(!is_sync_keyframe_with_headers(Codec::AV1, &shown)); + // 帧在序列头之前 + let late_seq = [0x12, 0x00, 0x32, 0x02, 0x10, 0x00, 0x0a, 0x02, 0x00, 0x00]; + assert!(!is_sync_keyframe_with_headers(Codec::AV1, &late_seq)); + + // 只有 TD + SeqHdr、没有编码帧的访问单元不应视为可独立解码的关键帧 + let hdr_only = [0x12, 0x00, 0x0a, 0x02, 0xaa, 0xbb]; + assert!(av1_has_sequence_header(&hdr_only)); + assert!(!is_sync_keyframe_with_headers(Codec::AV1, &hdr_only)); + + // 缺少 TD 时补齐 0x12 0x00;已带多字节 LEB128 零长 TD 时不重复插入 + let no_td = [0x0a, 0x02, 0xaa, 0xbb, 0x32, 0x02, 0x11, 0x22]; + assert_eq!( + ensure_av1_temporal_delimiter(no_td.to_vec()), + key_with_frame + ); + let padded_td = [0x12, 0x80, 0x00, 0x0a, 0x02, 0xaa, 0xbb]; + assert_eq!(ensure_av1_temporal_delimiter(padded_td.to_vec()), padded_td); + + let delta = [0x1a, 0x02, 0x01, 0x02]; + assert!(!av1_has_sequence_header(&delta)); + assert!(!is_sync_keyframe_with_headers(Codec::AV1, &delta)); + assert_eq!( + ensure_av1_temporal_delimiter(delta.to_vec()), + [0x12, 0x00, 0x1a, 0x02, 0x01, 0x02] + ); + + // 畸形 OBU 拒绝:forbidden bit、截断、空 Sequence Header + assert!(!av1_has_sequence_header(&[0x8a, 0x02, 0xaa, 0xbb])); + assert!(!av1_has_sequence_header(&[0x0a, 0x04, 0xaa])); + assert!(!av1_has_sequence_header(&[0x0a, 0x00])); + } + + #[test] + fn vaapi_device_and_dimension_validation() { + assert!(validate_vaapi_device("/etc/passwd").is_err()); + assert!(validate_vaapi_device("127.0.0.1:0").is_err()); + assert!(validate_vaapi_device(":0").is_err()); + assert!(validate_vaapi_device("/dev/null").is_err()); + assert!(validate_dimensions(1280, 720).is_ok()); + assert!(validate_dimensions(0, 720).is_err()); + assert!(validate_dimensions(32, 32).is_err()); + assert!(validate_dimensions(1281, 720).is_err()); + assert!(validate_dimensions(10000, 720).is_err()); + } + + #[test] + fn bitrate_math_and_va_hysteresis_clock() { + assert_eq!(nvenc_vbv_kbits(20_000, 60), 1_333); + assert_eq!(nvenc_vbv_kbits(1_000, 60), 533); // 地板 8000 kbps 避免低码率起步时 VBV 过小 + assert_eq!(vaapi_bitrate_prop(6_000), 6_000); + assert_eq!(vaapi_bitrate_prop(10), 100); + + // HRD 缓冲取 GStreamer 允许的最小值:峰值码率(向下取整)的一半,不能比 `max_bitrate / 2` 小 + for (kbps, pct) in [ + (20_000, 67), + (5_000, 67), + (6_001, 67), + (101, 66), + (5_000, 100), + ] { + let peak = kbps * 100 / pct; + let cpb = vaapi_cpb_kbits(kbps, pct); + assert!( + cpb >= peak / 2 && cpb <= peak / 2 + 1, + "{kbps} kbps / {pct}%: {cpb}" + ); + } + // 20 Mbps 时约 0.75 秒的目标码率,而不是默认的约 3 秒 + assert_eq!(vaapi_cpb_kbits(20_000, 67), 14_925); + assert_eq!(vaapi_cpb_kbits(5_000, 100), 2_500); + + let t0 = Instant::now(); + let mut st = Hysteresis::new(VA_BITRATE_RULE, 8_000); + // 小幅波动不计时、不触发 + st.set_target(7_000, t0); + assert!(st.pending.is_none()); + assert_eq!(st.should_apply(false, t0 + Duration::from_secs(10)), None); + // 强制关键帧时顺带下发最新码率 + assert_eq!(st.should_apply(true, t0), Some(7_000)); + + // ≥1.25× 下降:未满 2s 不触发,满 2s 触发 + st.set_target(5_000, t0); + assert_eq!(st.should_apply(false, t0 + Duration::from_secs(1)), None); + assert_eq!(st.should_apply(false, t0 + BITRATE_DROP_HOLD), Some(5_000)); + st.mark_applied(5_000); + + // ≥1.3× 上升:未满 6s 不触发,满 6s 触发 + let t1 = t0 + Duration::from_secs(3); + st.set_target(8_000, t1); + assert_eq!(st.should_apply(false, t1 + Duration::from_secs(5)), None); + assert_eq!(st.should_apply(false, t1 + BITRATE_RAISE_HOLD), Some(8_000)); + + // 失败退避窗口内不重试 + st.mark_failed(t1); + assert_eq!(st.should_apply(true, t1 + Duration::from_secs(1)), None); + assert_eq!( + st.should_apply(true, t1 + BITRATE_RETRY_BACKOFF), + Some(8_000) + ); + } + + #[test] + fn nvenc_vbv_follows_sustained_bitrate_changes() { + let vbv = |kbps| nvenc_vbv_kbits(kbps, 60); + let t0 = Instant::now(); + let mut st = Hysteresis::new(NVENC_VBV_RULE, vbv(20_000)); + + // 20 → 14 Mbps:VBV 差不到一倍,不重设;反正要出关键帧时也差不到 1.5 倍 + st.set_target(vbv(14_000), t0); + assert!(st.pending.is_none()); + assert_eq!(st.should_apply(false, t0 + Duration::from_secs(60)), None); + assert_eq!(st.should_apply(true, t0), None); + + // 20 → 5 Mbps(VBV 1333 → 533 kbit):持续 2 秒才重设;中途要出关键帧就顺带重设 + st.set_target(vbv(5_000), t0); + assert_eq!(st.should_apply(false, t0 + Duration::from_secs(1)), None); + assert_eq!(st.should_apply(true, t0), Some(533)); + assert_eq!(st.should_apply(false, t0 + BITRATE_DROP_HOLD), Some(533)); + st.mark_applied(533); + + // 回到 50 Mbps(VBV 3333 kbit,5 Mbps 时的 VBV 只有平均一帧的 64%):持续 6 秒才重设 + let t1 = t0 + Duration::from_secs(3); + st.set_target(vbv(50_000), t1); + assert_eq!(st.should_apply(false, t1 + Duration::from_secs(5)), None); + assert_eq!(st.should_apply(false, t1 + BITRATE_RAISE_HOLD), Some(3_333)); + + // 低码率区间 VBV 有下限:1 → 8 Mbps 不动 VBV + let mut low = Hysteresis::new(NVENC_VBV_RULE, vbv(1_000)); + low.set_target(vbv(8_000), t0); + assert_eq!(low.should_apply(true, t0 + Duration::from_secs(60)), None); + } + + #[test] + fn probe_policy_skips_secondary_nvenc_and_respects_explicit_nvenc() { + let mk = |backend, codec, factory: &str| Candidate { + backend, + codec, + factory: factory.into(), + device_path: None, + label: factory.into(), + low_power: false, + }; + + // Auto + DisplayOwner::Vaapi 且 VA-API 可用(H.264/HEVC):不探测 NVENC + let mut nvenc_probed = false; + let cache = probe_with( + HwEncoderPref::Auto, + DisplayOwner::Vaapi, + true, + |b, c| match (b, c) { + (Backend::Vaapi, Codec::H264) => vec![mk(b, c, "vah264enc")], + (Backend::Vaapi, Codec::H265) => vec![mk(b, c, "vah265enc")], + (Backend::Nvenc, Codec::AV1) => vec![mk(b, c, "nvav1enc")], + _ => Vec::new(), + }, + |cand| { + if cand.backend == Backend::Nvenc { + nvenc_probed = true; + } + true + }, + ); + assert!( + !nvenc_probed, + "secondary NVENC must not be probed when VA-API works" + ); + assert!(cache.has(Codec::H264)); + assert!(cache.has(Codec::H265)); + assert!(!cache.has(Codec::AV1)); + + // 显式 HwEncoderPref::Nvenc:即使 allow_nvenc_in_auto == false(如 WSL2/容器无 PCI sysfs),仍照常探测 + let cache_nv = probe_with( + HwEncoderPref::Nvenc, + DisplayOwner::Unknown, + false, + |b, c| match (b, c) { + (Backend::Nvenc, Codec::H264) => vec![mk(b, c, "nvcudah264enc")], + (Backend::Nvenc, Codec::H265) => vec![mk(b, c, "nvcudah265enc")], + _ => Vec::new(), + }, + |_| true, + ); + assert!(cache_nv.has(Codec::H264)); + assert!(cache_nv.has(Codec::H265)); + assert!(!cache_nv.has(Codec::AV1)); + + // Software 模式返回空缓存 + let cache_sw = probe_with( + HwEncoderPref::Software, + DisplayOwner::Nvidia, + true, + |b, c| vec![mk(b, c, "nvcudah264enc")], + |_| true, + ); + assert!(!cache_sw.any_hw()); + } + + /// 真实 GStreamer 无硬件管线测试:验证 `gst::init`、安全属性工具、缓冲池、4 字节对齐步长(1366 / 1590)及 flush 恢复。 + #[test] + fn gst_nv12_stride_pool_and_identity_pipeline() { + ensure_gst().expect("GStreamer must initialize in CI/dev environment"); + + // 校验安全属性工具不会因缺失属性/非法枚举而 panic + let id = gst::ElementFactory::make("identity") + .build() + .expect("GStreamer coreelements identity element must exist"); + assert!(!try_set_str(&id, "nonexistent-prop", "foo").unwrap()); + assert_eq!(try_set_u32(&id, "nonexistent-prop", 42), None); + assert!(!try_set_bool(&id, "nonexistent-prop", true)); + assert!(try_set_bool(&id, "silent", true)); + + // 校验非 4 字节对齐宽度(1366x768, 1590x994)与常规宽度(1280x720)经 BufferPool + identity 往返 + for (w, h, expected_stride) in [ + (1280u32, 720u32, 1280usize), + (1366, 768, 1368), + (1590, 994, 1592), + ] { + let vi = build_nv12_video_info(w, h, 30).unwrap(); + assert_eq!(vi.stride()[0] as usize, expected_stride); + assert_eq!(vi.stride()[1] as usize, expected_stride); + let caps = vi.to_caps().unwrap(); + + let src = gst_app::AppSrc::builder() + .caps(&caps) + .format(gst::Format::Time) + .is_live(true) + .build(); + let ident = gst::ElementFactory::make("identity").build().unwrap(); + let sink = gst_app::AppSink::builder() + .sync(false) + .async_(false) + .enable_last_sample(false) + .build(); + let pipeline = gst::Pipeline::new(); + pipeline + .add_many([src.upcast_ref(), &ident, sink.upcast_ref()]) + .unwrap(); + gst::Element::link_many([src.upcast_ref(), &ident, sink.upcast_ref()]).unwrap(); + let pool = create_buffer_pool(&vi).unwrap(); + let _guard = PipelineGuard { + pipeline: Some(pipeline.clone()), + src: src.clone(), + pool: pool.clone(), + factory: "identity".into(), + }; + pipeline.set_state(gst::State::Playing).unwrap(); + + let bgra = red_blue_frame(w, h); + let mut uv_scratch = Vec::new(); + for i in 0..4u64 { + if i == 2 { + assert!(src.send_event(gst::event::FlushStart::new())); + assert!(src.send_event(gst::event::FlushStop::new(false))); + } + let mut buf = pool.acquire_buffer(None).unwrap(); + let expected_pts = gst::ClockTime::from_mseconds(i * 33); + { + let bm = buf.get_mut().unwrap(); + let mut map = bm.map_writable().unwrap(); + write_bgra_to_nv12_slice(&vi, map.as_mut_slice(), &bgra, &mut uv_scratch) + .unwrap(); + drop(map); + bm.set_pts(expected_pts); + bm.set_duration(gst::ClockTime::from_mseconds(33)); + } + src.push_buffer(buf).unwrap(); + let sample = sink + .try_pull_sample(gst::ClockTime::from_seconds(2)) + .expect("identity sample"); + let out_buf = sample.buffer().unwrap(); + assert_eq!(out_buf.pts(), Some(expected_pts)); + let out = out_buf.map_readable().unwrap(); + assert_eq!(out.len(), vi.size()); + // 检查底部行的红色与蓝色色度在对齐步长下没有发生行错位 + let y_last = (h as usize - 1) * expected_stride; + let red_y = out[y_last + (w as usize) / 4]; + let blue_y = out[y_last + (w as usize) * 3 / 4]; + assert!( + red_y > 40 && red_y < 90, + "{w}x{h} unexpected BT.709 red Y={red_y}" + ); + assert!( + blue_y > 16 && blue_y < 50, + "{w}x{h} unexpected BT.709 blue Y={blue_y}" + ); + } + } + } + + // ───────────────────────────── 实机硬件测试辅助与用例 ───────────────────────────── + // + // 实机测试默认不跑(`#[ignore]`,和仓库里其他依赖环境的测试一样),在有显卡的机器上这样跑: + // AIRHAND_REQUIRE_HW_TEST=1 cargo test --lib host::encoder::linux -- --ignored --nocapture + // 设了 AIRHAND_REQUIRE_HW_TEST=1 时找不到硬件算失败,不跳过;解码校验要装 ffmpeg。 + + fn require_hw() -> bool { + std::env::var("AIRHAND_REQUIRE_HW_TEST") + .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")) + } + + fn pattern_frame(w: u32, h: u32, idx: u32) -> Vec { + let mut px = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + let i = ((y * w + x) * 4) as usize; + px[i] = ((x + idx * 17) % 256) as u8; + px[i + 1] = ((y + idx * 9) % 256) as u8; + px[i + 2] = (((x / 16 + y / 16 + idx) % 2) * 255) as u8; + px[i + 3] = 255; + } + } + px + } + + fn noisy_motion_frames(w: usize, h: usize, count: usize) -> Vec> { + let mut seed: u64 = 0x9E37_79B9_7F4A_7C15; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let mut v = vec![0u8; w * h * 4]; + for y in 0..h { + for x in 0..w { + let gx = x + i * 8; + let o = (y * w + x) * 4; + v[o] = (gx & 0xff) as u8; + v[o + 1] = ((y + i * 4) & 0xff) as u8; + v[o + 2] = (((gx >> 2) + (y >> 2)) & 0xff) as u8; + v[o + 3] = 255; + } + } + let (bw, bh) = (w / 6, h / 6); + let bx = (i * 37) % (w - bw); + let by = (i * 23) % (h - bh); + for y in by..by + bh { + for x in bx..bx + bw { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let o = (y * w + x) * 4; + v[o..o + 3].copy_from_slice(&seed.to_le_bytes()[..3]); + } + } + out.push(v); + } + out + } + + fn red_blue_frame(w: u32, h: u32) -> Vec { + let mut px = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + let i = ((y * w + x) * 4) as usize; + if x < w / 2 { + px[i..i + 4].copy_from_slice(&[0, 0, 255, 255]); + } else { + px[i..i + 4].copy_from_slice(&[255, 0, 0, 255]); + } + } + } + px + } + + fn ffmpeg_format(codec: Codec) -> &'static str { + match codec { + Codec::H265 => "hevc", + Codec::AV1 => "obu", + Codec::H264 | Codec::Unknown(_) => "h264", + } + } + + fn ffmpeg_strict_decode_count(codec: Codec, stream: &[u8], tag: &str) -> Option { + let path = std::env::temp_dir().join(format!( + "airhand-linux-hw-{}-{tag}-{}.bin", + std::process::id(), + rand::random::() + )); + std::fs::write(&path, stream).unwrap(); + let out = std::process::Command::new("ffmpeg") + .args([ + "-hide_banner", + "-loglevel", + "error", + "-err_detect", + "explode", + "-f", + ffmpeg_format(codec), + "-i", + ]) + .arg(&path) + .args(["-f", "framemd5", "-"]) + .output(); + let _ = std::fs::remove_file(&path); + let out = out.ok()?; + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "ffmpeg ({tag}): {stderr}"); + assert!(stderr.is_empty(), "ffmpeg stderr ({tag}): {stderr}"); + let stdout = String::from_utf8(out.stdout).unwrap(); + Some(stdout.lines().filter(|l| !l.starts_with('#')).count()) + } + + fn verify_red_blue_roundtrip(enc: &mut LinuxHwEncoder, tag: &str) { + let (w, h) = (enc.info.width, enc.info.height); + let src = red_blue_frame(w, h); + let ef = enc + .encode(&src, true) + .unwrap() + .expect("red/blue keyframe output"); + assert!(ef.key, "{tag}: expected keyframe with headers"); + + let path = std::env::temp_dir().join(format!( + "airhand-linux-color-{}-{tag}-{}.bin", + std::process::id(), + rand::random::() + )); + std::fs::write(&path, &ef.data).unwrap(); + let out = std::process::Command::new("ffmpeg") + .args([ + "-hide_banner", + "-loglevel", + "error", + "-f", + ffmpeg_format(enc.info.codec), + "-i", + ]) + .arg(&path) + .args(["-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "-"]) + .output(); + let _ = std::fs::remove_file(&path); + let Ok(out) = out else { + return; + }; + assert!( + out.status.success(), + "ffmpeg color decode ({tag}): {}", + String::from_utf8_lossy(&out.stderr) + ); + let rgb = out.stdout; + assert_eq!(rgb.len(), (w * h * 3) as usize); + let px = |x: u32, y: u32| { + let i = ((y * w + x) * 3) as usize; + [rgb[i], rgb[i + 1], rgb[i + 2]] + }; + let left = px(w / 4, h / 2); + let right = px(w * 3 / 4, h / 2); + assert!( + left[0] > 220 && left[1] < 35 && left[2] < 35, + "{tag}: left pixel should be red, got {left:?}" + ); + assert!( + right[0] < 35 && right[1] < 35 && right[2] > 220, + "{tag}: right pixel should be blue, got {right:?}" + ); + } + + fn exercise_encoder(mut enc: LinuxHwEncoder, tag: &str, frames: u32) { + let (w, h) = (enc.info.width, enc.info.height); + let codec = enc.info.codec; + let mut stream = Vec::new(); + for i in 0..frames { + let force_key = i == 0 || i == 10 || i == 25; + if i == 10 { + enc.set_bitrate(2_000); + } + let f = enc + .encode(&pattern_frame(w, h, i), force_key) + .unwrap() + .expect("expected 1-in-1-out frame"); + assert!(!f.data.is_empty(), "{tag} frame {i} empty"); + if force_key { + assert!(f.key, "{tag} frame {i} must be sync keyframe with headers"); + } + stream.extend_from_slice(&f.data); + } + if let Some(n) = ffmpeg_strict_decode_count(codec, &stream, tag) { + assert_eq!(n, frames as usize, "{tag}: decoded frame count mismatch"); + } + verify_red_blue_roundtrip(&mut enc, tag); + } + + /// 实机 VA-API 测试(H.264 / HEVC / AV1、≥30 帧防 iHD `ref-frames` 回归、非 4/16 对齐步长与色彩校验)。 + #[test] + #[ignore = "needs a VA-API GPU (AIRHAND_REQUIRE_HW_TEST=1 cargo test -- --ignored)"] + fn vaapi_codecs_and_strides() { + ensure_gst().unwrap(); + let nodes = discover_vaapi_nodes(None); + if nodes.is_empty() { + assert!( + !require_hw(), + "AIRHAND_REQUIRE_HW_TEST=1 but no VA-API render nodes found" + ); + println!("No VA-API render nodes, skipping"); + return; + } + let mut ok_codecs = Vec::new(); + for codec in [Codec::H264, Codec::H265, Codec::AV1] { + match LinuxHwEncoder::new_vaapi(codec, 1280, 720, 30, 6_000, None) { + Ok(enc) => { + println!("VA-API {codec:?}: {}", enc.info.name); + exercise_encoder(enc, &format!("vaapi-{codec:?}-720p"), 35); + ok_codecs.push(codec); + } + Err(e) => println!("VA-API {codec:?} unavailable: {e:#}"), + } + } + if require_hw() { + assert!( + ok_codecs.contains(&Codec::H264), + "AIRHAND_REQUIRE_HW_TEST=1 but VA-API H.264 failed" + ); + } + // 已可用的格式在非 4/16 对齐分辨率与 1440p 下必须全部通过(不再静默吞掉错误) + for &codec in &ok_codecs { + for (w, h) in [(1366u32, 768u32), (1590, 994), (1728, 1080)] { + let enc = LinuxHwEncoder::new_vaapi(codec, w, h, 30, 8_000, None) + .unwrap_or_else(|e| panic!("VA-API {codec:?} {w}x{h} failed: {e:#}")); + exercise_encoder(enc, &format!("vaapi-{codec:?}-{w}x{h}"), 12); + } + if codec == Codec::AV1 { + let enc = LinuxHwEncoder::new_vaapi(codec, 2560, 1440, 30, 8_000, None) + .unwrap_or_else(|e| panic!("VA-API AV1 2560x1440 failed: {e:#}")); + exercise_encoder(enc, "vaapi-AV1-2560x1440", 12); + } + } + } + + /// 实机 NVENC 测试(H.264 / HEVC / 可选 AV1、非 4/16 对齐步长、无 IDR 软调码率、VBV 重设与色彩校验)。 + #[test] + #[ignore = "needs an NVIDIA GPU (AIRHAND_REQUIRE_HW_TEST=1 cargo test -- --ignored)"] + fn nvenc_codecs_strides_and_zero_idr_bitrate_drop() { + ensure_gst().unwrap(); + let mut ok_codecs = Vec::new(); + for codec in [Codec::H264, Codec::H265, Codec::AV1] { + match LinuxHwEncoder::new_nvenc(codec, 1280, 720, 30, 6_000) { + Ok(enc) => { + println!("NVENC {codec:?}: {}", enc.info.name); + exercise_encoder(enc, &format!("nvenc-{codec:?}-720p"), 35); + ok_codecs.push(codec); + } + Err(e) => println!("NVENC {codec:?} unavailable: {e:#}"), + } + } + if ok_codecs.is_empty() { + assert!( + !require_hw(), + "AIRHAND_REQUIRE_HW_TEST=1 but no NVENC codec succeeded" + ); + println!("No NVENC hardware encoder available, skipping"); + return; + } + for &codec in &ok_codecs { + for (w, h) in [(1366u32, 768u32), (1590, 994), (1728, 1080)] { + let enc = LinuxHwEncoder::new_nvenc(codec, w, h, 30, 8_000) + .unwrap_or_else(|e| panic!("NVENC {codec:?} {w}x{h} failed: {e:#}")); + exercise_encoder(enc, &format!("nvenc-{codec:?}-{w}x{h}"), 12); + } + } + + // 专门验证 NVENC 20 -> 5 Mbps 动态降码率:不产生任何额外 IDR,且码率立即下降 + let mut enc = LinuxHwEncoder::new_nvenc(Codec::H264, 1280, 720, 60, 20_000).unwrap(); + let frames = noisy_motion_frames(1280, 720, 16); + let mut before_sizes = Vec::new(); + let mut after_sizes = Vec::new(); + let mut stream = Vec::new(); + for i in 0..120usize { + if i == 60 { + enc.set_bitrate(5_000); + } + // 这一段只看软调码率本身:VBV 的计时一直留在刚开始,不让它在循环里到期重设(重设见下面) + if let Mode::Nvenc { vbv: Some(vbv), .. } = &mut enc.mode + && let Some((_, dir)) = vbv.pending + { + vbv.pending = Some((Instant::now(), dir)); + } + let ef = enc + .encode(&frames[i % frames.len()], i == 0) + .unwrap() + .expect("1-in-1-out frame"); + if i == 0 { + assert!(ef.key, "frame 0 must be keyframe"); + } else { + assert!( + !ef.key && !annexb_nal_types(&ef.data, false).any(|t| t == 5), + "NVENC bitrate drop must not emit an IDR (unexpected IDR at frame {i})" + ); + } + if (20..60).contains(&i) { + before_sizes.push(ef.data.len()); + } else if (65..120).contains(&i) { + after_sizes.push(ef.data.len()); + } + stream.extend_from_slice(&ef.data); + } + let avg_before = before_sizes.iter().sum::() as f64 / before_sizes.len() as f64; + let avg_after = after_sizes.iter().sum::() as f64 / after_sizes.len() as f64; + assert!( + avg_after * 1.5 < avg_before, + "expected NVENC bitrate drop to shrink P-frames immediately: before={avg_before:.0}B after={avg_after:.0}B" + ); + + // 降码率持续超过 2 秒:VBV 按 5 Mbps 重设(1333 → 533 kbit),编码器整个重新初始化, + // 这一帧是带 SPS/PPS 的 IDR。驱动不支持自定义 VBV(没有这个属性)时不重设 + let resized = match &mut enc.mode { + Mode::Nvenc { vbv: Some(vbv), .. } => { + let (_, dir) = vbv.pending.expect("20 -> 5 Mbps should start the VBV hold"); + vbv.pending = Some(( + Instant::now() - BITRATE_DROP_HOLD - Duration::from_millis(50), + dir, + )); + true + } + _ => false, + }; + if resized { + let ef = enc + .encode(&frames[0], false) + .unwrap() + .expect("1-in-1-out frame"); + assert!( + ef.key, + "resizing the VBV should restart with an IDR and SPS/PPS" + ); + assert_eq!( + enc.enc.property::("vbv-buffer-size"), + nvenc_vbv_kbits(5_000, 60) + ); + stream.extend_from_slice(&ef.data); + } + if let Some(n) = ffmpeg_strict_decode_count(Codec::H264, &stream, "nvenc-bitrate-drop") { + assert_eq!(n, 120 + usize::from(resized)); + } + } + + /// 实机 VA-API 滞回、HRD 缓冲与 AV1 READY→PLAYING 码率切换验证。 + #[test] + #[ignore = "needs a VA-API GPU (AIRHAND_REQUIRE_HW_TEST=1 cargo test -- --ignored)"] + fn vaapi_bitrate_hysteresis_and_av1_ready_cycle() { + ensure_gst().unwrap(); + let Ok(mut enc) = LinuxHwEncoder::new_vaapi(Codec::H264, 640, 360, 30, 8_000, None) else { + assert!( + !require_hw(), + "AIRHAND_REQUIRE_HW_TEST=1 but VA-API H.264 unavailable" + ); + return; + }; + let f0 = enc + .encode(&pattern_frame(640, 360, 0), true) + .unwrap() + .unwrap(); + assert!(f0.key); + // GStreamer 接受了设的 HRD 缓冲(太小的话会换回 2 秒的默认值,并写回 `cpb-size`) + let Mode::Vaapi { + target_percentage, .. + } = enc.mode + else { + unreachable!() + }; + if enc.enc.find_property("cpb-size").is_some() { + assert_eq!( + enc.enc.property::("cpb-size"), + vaapi_cpb_kbits(8_000, target_percentage) + ); + } + + // 小幅波动不发关键帧 + enc.set_bitrate(7_000); + let f1 = enc + .encode(&pattern_frame(640, 360, 1), false) + .unwrap() + .unwrap(); + assert!(!f1.key, "small dip must not emit an unsolicited keyframe"); + + // 瞬时降码率未到 2s 不发关键帧 + enc.set_bitrate(5_000); + let f2 = enc + .encode(&pattern_frame(640, 360, 2), false) + .unwrap() + .unwrap(); + assert!(!f2.key, "transient drop must wait for hold window"); + + // 模拟持续超过 2s:下发新码率并产生带参数集的 IDR + if let Mode::Vaapi { rate, .. } = &mut enc.mode { + rate.pending = Some(( + Instant::now() - BITRATE_DROP_HOLD - Duration::from_millis(50), + BitrateDir::Drop, + )); + } + let f3 = enc + .encode(&pattern_frame(640, 360, 3), false) + .unwrap() + .unwrap(); + assert!(f3.key, "sustained >=1.25x drop should reconfigure with IDR"); + if let Mode::Vaapi { rate, .. } = &enc.mode { + assert_eq!(rate.active, 5_000); + } + // 降码率之后 HRD 缓冲跟着变小,不沿用 8 Mbps 时的大小 + if enc.enc.find_property("cpb-size").is_some() { + assert_eq!( + enc.enc.property::("cpb-size"), + vaapi_cpb_kbits(5_000, target_percentage) + ); + } + + // 若支持 VA-API AV1,额外验证 READY→PLAYING 码率切换后仍能严格解码 + if let Ok(mut av1) = LinuxHwEncoder::new_vaapi(Codec::AV1, 640, 360, 30, 6_000, None) { + let mut stream = Vec::new(); + for i in 0..8u32 { + if i == 4 { + av1.set_bitrate(2_000); + } + let ef = av1 + .encode(&pattern_frame(640, 360, i), i == 0 || i == 4) + .unwrap() + .unwrap(); + if i == 0 || i == 4 { + assert!(ef.key, "AV1 frame {i} must be keyframe"); + } + stream.extend_from_slice(&ef.data); + } + if let Some(n) = ffmpeg_strict_decode_count(Codec::AV1, &stream, "vaapi-av1-rate") { + assert_eq!(n, 8); + } + } + } +} diff --git a/client/src-tauri/src/host/encoder/mod.rs b/client/src-tauri/src/host/encoder/mod.rs index 3ceefd00..1396c4e8 100644 --- a/client/src-tauri/src/host/encoder/mod.rs +++ b/client/src-tauri/src/host/encoder/mod.rs @@ -1,7 +1,8 @@ //! 视频编码。 //! //! * **硬件编码**(优先):Windows Media Foundation 硬件 MFT(NVENC / Quick Sync / AMF), -//! 支持 H.264 / H.265 / AV1;macOS VideoToolbox,支持 H.264 / H.265。几乎不占用 CPU; +//! 支持 H.264 / H.265 / AV1;macOS VideoToolbox,支持 H.264 / H.265; +//! Linux GStreamer VA-API(Intel / AMD)与 NVENC(NVIDIA),支持 H.264 / H.265 / AV1。几乎不占用 CPU; //! * **软件编码**(兜底):OpenH264 屏幕内容模式。 //! //! 被控端只在画面变化时才编码,静止画面完全不占带宽。 @@ -12,8 +13,11 @@ //! `MFCreateDXGISurfaceBuffer` 直接交给硬件 MFT(见 mf.rs);macOS 的 ScreenCaptureKit 采集时就按编码尺寸输出 NV12, //! `CVPixelBuffer` 原样交给 VideoToolbox(见 vt.rs、`capture/sck.rs`)。省掉了读回、大块拷贝、CPU 缩放和色彩转换 //! (4K、Retina 屏上这些加起来每帧十几毫秒); -//! * **CPU 回退**:软件编码、Linux 或显卡不支持零拷贝时,读出 BGRA,按需缩放并转换成 YUV 4:2:0。 +//! * **CPU 回退**:软件编码、Linux(X11 采集在内存里,转换 NV12 后交给 GStreamer 硬件编码器)或显卡不支持零拷贝时, +//! 读出 BGRA,按需缩放并转换成 YUV 4:2:0。 +#[cfg(target_os = "linux")] +mod linux; #[cfg(windows)] mod mf; mod software; @@ -26,7 +30,7 @@ use airhand_proto::session::{Codec, EncoderInfo, Notice, QualitySettings}; use anyhow::{Context, Result, anyhow, bail}; use fast_image_resize as fir; use tracing::info; -#[cfg(any(windows, target_os = "macos"))] +#[cfg(any(windows, target_os = "macos", target_os = "linux"))] use tracing::warn; use super::capture::{Frame, GpuFrame}; @@ -126,7 +130,10 @@ pub use airhand_link::refs::LtrReport; pub trait VideoEncoder { fn info(&self) -> &EncoderInfo; - /// 运行时调整码率(不重建编码器、不产生关键帧)。 + /// 更新目标码率。支持动态码率的后端(OpenH264、Media Foundation、VideoToolbox、Linux NVENC) + /// 会不重建编码器、不产生关键帧地直接生效;无法无关键帧调码率的后端(如 Linux VA-API) + /// 可能延迟到持续变化或下次关键帧时再下发,并开启新 GOP(由 [`EncodedFrame::key`] 反映实际输出)。 + /// Linux NVENC 的码率持续变化一倍以上时还会按新码率重设 VBV,同样出一个关键帧。 fn set_bitrate(&mut self, kbps: u32); /// 能控制几个长期参考帧的槽位(0:不能,丢了帧只能编关键帧,见 `airhand_link::refs`) fn ltr_slots(&self) -> u8 { @@ -178,7 +185,7 @@ pub fn available_codecs() -> Vec { .get_or_init(|| { #[allow(unused_mut)] let mut list = vec![Codec::H264]; - #[cfg(any(windows, target_os = "macos"))] + #[cfg(any(windows, target_os = "macos", target_os = "linux"))] for c in [Codec::H265, Codec::AV1] { if has_hardware(c) { list.push(c); @@ -231,6 +238,11 @@ fn has_hardware(codec: Codec) -> bool { vt::has_hardware(codec) } +#[cfg(target_os = "linux")] +fn has_hardware(codec: Codec) -> bool { + linux::has_hardware(codec) +} + #[cfg(windows)] fn hardware_encoder( codec: Codec, @@ -253,6 +265,19 @@ fn hardware_encoder( Ok(Box::new(vt::VtEncoder::new(codec, w, h, fps, kbps, gpu)?)) } +#[cfg(target_os = "linux")] +fn hardware_encoder( + codec: Codec, + (w, h): (u32, u32), + fps: u8, + kbps: u32, + _gpu: Option<&GpuFrame>, +) -> Result> { + Ok(Box::new(linux::LinuxHwEncoder::new( + codec, w, h, fps, kbps, + )?)) +} + /// 缩放 + 编码。持有可复用的缩放缓冲区。 pub struct Encoder { inner: Box, @@ -291,7 +316,7 @@ impl Encoder { #[allow(unused_mut)] let mut inner: Option> = None; - #[cfg(any(windows, target_os = "macos"))] + #[cfg(any(windows, target_os = "macos", target_os = "linux"))] if allow_hw { let mut order = vec![s.codec]; if s.codec != Codec::H264 { @@ -310,7 +335,7 @@ impl Encoder { } } } - #[cfg(not(any(windows, target_os = "macos")))] + #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] let _ = (allow_hw, gpu); let inner = match inner { @@ -410,7 +435,10 @@ impl Encoder { } /// 在 Annex-B 码流中查找 NAL 类型(用于判断是否包含参数集 / 关键帧)。 -#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))] +#[cfg_attr( + not(any(windows, target_os = "macos", target_os = "linux")), + allow(dead_code) +)] pub(crate) fn annexb_nal_types(data: &[u8], hevc: bool) -> impl Iterator + '_ { let mut i = 0usize; std::iter::from_fn(move || { @@ -522,7 +550,7 @@ mod tests { assert_eq!(check(Codec::H264, false).as_deref(), Some("OpenH264")); } - #[cfg(any(windows, target_os = "macos"))] + #[cfg(any(windows, target_os = "macos", target_os = "linux"))] #[test] fn hardware_all() { for c in available_codecs() { diff --git a/client/src-tauri/tauri.linux.conf.json b/client/src-tauri/tauri.linux.conf.json index 4954d2e0..271325d9 100644 --- a/client/src-tauri/tauri.linux.conf.json +++ b/client/src-tauri/tauri.linux.conf.json @@ -8,6 +8,8 @@ "depends": [ "libpulse0", "libpipewire-0.3-0 (>= 0.3.49)", + "libgstreamer1.0-0 (>= 1.22)", + "libgstreamer-plugins-base1.0-0 (>= 1.22)", "gstreamer1.0-plugins-base", "gstreamer1.0-plugins-good", "gstreamer1.0-plugins-bad" diff --git a/docs/architecture.md b/docs/architecture.md index 2086f1f1..cc929bed 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -159,7 +159,7 @@ On Windows all of this runs in the system service (see [Windows service](#window | Screen capture | DXGI Desktop Duplication | ScreenCaptureKit | MIT-SHM shared memory + DAMAGE change notifications; RandR for multiple monitors | MediaProjection (a virtual display rendering straight into the encoder) | | Cursor shape | DXGI | NSCursor | XFIXES | — | | Cursor drawn into the picture (Game mode) | Desktop Duplication's hardware cursor, reading back just its patch (frames on the GPU) | ScreenCaptureKit `showsCursor` | XFIXES cursor image + polling the pointer position | — | -| Video encoding | Media Foundation hardware encoders, OpenH264 fallback | VideoToolbox hardware encoders (H.264 / HEVC), OpenH264 fallback | OpenH264 | MediaCodec (hardware encoders preferred) | +| Video encoding | Media Foundation hardware encoders, OpenH264 fallback | VideoToolbox hardware encoders (H.264 / HEVC), OpenH264 fallback | GStreamer VA-API / NVENC hardware encoders (H.264 / HEVC / AV1), OpenH264 fallback | MediaCodec (hardware encoders preferred) | | Input injection | SendInput (scan codes; relative movement like a real mouse) | CGEvent (virtual key codes; relative movement with deltas) | XTEST (evdev physical key codes; relative motion) | Accessibility service (gestures, system actions, text input) | | Hidden cursor (Auto mode switches to relative movement) | DXGI + `GetCursorInfo` (a software cursor drawn into the image, e.g. while dragging or resizing a window, still counts as shown) | Not detected (use Game mode) | XFIXES (fully transparent cursor) | — | | Audio capture | WASAPI loopback | ScreenCaptureKit (system mix) | PulseAudio / PipeWire output monitor | AudioPlaybackCapture (Android 10+) | @@ -207,7 +207,7 @@ Installed just for the current user there is no system service (`client/src-taur | Capture | Frames are only produced when the screen changes (DXGI on Windows, ScreenCaptureKit on macOS, DAMAGE on X11), so an idle desktop uses almost no bandwidth. The frame rate is limited by the frames' own timestamps (`client/src-tauri/src/host/pace.rs`, the same on Android), not by when the previous frame was done, so processing time never adds up to lag or periodically skipped frames | | Refinement when still | A frame with a large change (switching windows, scrolling) only gets about one frame's worth of bitrate, so text comes out blurry. 200 ms after the screen stops changing, the last frame is encoded a few more times; the encoder only has to code the residual, so within a few frames it is close to the original (until the encoder has nothing meaningful left to add, at most 8 frames), then nothing more is sent | | Preprocessing | **GPU zero-copy**: frames never leave the GPU. On Windows the duplicated desktop is copied into our own texture, and the hardware encoder scales, rotates and converts it to NV12 (BT.709 limited range) with `ID3D11VideoProcessor` on the same D3D11 device, then hands it to the hardware MFT through `MFCreateDXGISurfaceBuffer` + `IMFDXGIDeviceManager` (only encoders on the capturing GPU are used); on macOS ScreenCaptureKit outputs NV12 at the encoding size directly and the `CVPixelBuffer` goes to VideoToolbox as is. This skips the readback, a copy of tens of MB, CPU scaling and color conversion (`client/src-tauri/src/host/encoder/mod.rs`)
**CPU fallback** (software encoding, unsupported GPUs, or Linux): frames in memory are scaled when necessary with `fast_image_resize` (SIMD, parallel horizontal stripes) and converted from BGRA to NV12/I420 with `yuvutils-rs`; buffers are reused. | -| Encoding | **Hardware first**: Media Foundation hardware encoders (NVENC / Quick Sync / AMF) for **AV1 / HEVC / H.264**, low-latency mode, no B-frames, very long GOP; on macOS VideoToolbox (H.264 / HEVC, low-latency rate control for H.264). Without one it falls back to **OpenH264 in screen-content mode**. Formats are ranked **AV1 > HEVC > H.264**; the most efficient one both sides support (the host can encode, the controller can decode) is picked automatically | +| Encoding | **Hardware first**: Media Foundation hardware encoders (NVENC / Quick Sync / AMF) for **AV1 / HEVC / H.264**, low-latency mode, no B-frames, very long GOP; on macOS VideoToolbox (H.264 / HEVC, low-latency rate control for H.264); on Linux GStreamer **VA-API / NVENC** (H.264 / HEVC / AV1). Without one it falls back to **OpenH264 in screen-content mode**. Formats are ranked **AV1 > HEVC > H.264**; the most efficient one both sides support (the host can encode, the controller can decode) is picked automatically | | Rate control | The controller ACKs every frame. The host caps **in-flight bytes** (≈ bitrate × (base RTT + 50 ms)); on a slow network it waits and **skips to the newest frame** instead of building up lag. The bitrate follows the measured queueing delay and bandwidth on every ACK (waiting for an earlier frame's retransmission counts as queueing, so loss and policing cut it at once: latency first). Estimated loss above 10% also cuts the bitrate, and above 2% stops it rising | | Transport | QUIC with **BBR**. Control and video use separate bounded queues and QUIC streams, audio uses QUIC datagrams, avoiding video stream head-of-line blocking. Video uses one stream per frame ([frame streams](#frame-streams-and-reference-invalidation)), so a lost packet doesn't hold up later frames. Connection bandwidth is still shared; the console's final hop (loopback on the desktop) remains a single WebSocket. When a [direct path](#direct-path) can be punched and isn't slower than the relay, video and audio take it and bypass the server | | Loss recovery | QUIC retransmits lost packets. On `Lost`, the host abandons stale frames for that display and recovers from a delivered long-term reference or a keyframe. | diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index 07c52b12..cc7ff8a9 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -159,7 +159,7 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 | 屏幕采集 | DXGI Desktop Duplication | ScreenCaptureKit | MIT-SHM 共享内存 + DAMAGE 变化通知,RandR 多显示器 | MediaProjection(虚拟显示器直接输出到编码器) | | 光标形状 | DXGI | NSCursor | XFIXES | — | | 光标画进画面(游戏模式) | 桌面复制的硬件光标,只读回光标那一块叠上去(显卡上的画面) | ScreenCaptureKit 的 `showsCursor` | XFIXES 光标图像 + 定时查询指针位置 | — | -| 视频编码 | Media Foundation 硬件编码,OpenH264 兜底 | VideoToolbox 硬件编码(H.264 / HEVC),OpenH264 兜底 | OpenH264 | MediaCodec(优先硬件编码器) | +| 视频编码 | Media Foundation 硬件编码,OpenH264 兜底 | VideoToolbox 硬件编码(H.264 / HEVC),OpenH264 兜底 | GStreamer VA-API / NVENC 硬件编码(H.264 / HEVC / AV1),OpenH264 兜底 | MediaCodec(优先硬件编码器) | | 输入注入 | SendInput(扫描码;相对移动同真实鼠标) | CGEvent(虚拟键码;相对移动带移动量) | XTEST(evdev 物理键码;相对移动) | 无障碍服务(手势、系统操作、文字输入) | | 光标隐藏(自动模式改用相对移动) | DXGI + `GetCursorInfo`(拖动、缩放窗口时画进画面里的软件光标不算隐藏) | 检测不到(用游戏模式) | XFIXES(全透明光标) | — | | 声音采集 | WASAPI 环回 | ScreenCaptureKit(系统混音) | PulseAudio / PipeWire 的输出监视器 | AudioPlaybackCapture(Android 10+) | @@ -207,7 +207,7 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 | 采集 | 只在画面变化时产生帧(Windows 靠 DXGI,macOS 靠 ScreenCaptureKit,X11 靠 DAMAGE),静止的桌面几乎不占带宽。帧率按画面自己的时间戳节流(`client/src-tauri/src/host/pace.rs`,Android 同样),不按上一帧处理完的时刻,处理花的时间不会累积成延迟,也不会每隔一阵跳掉一帧 | | 静止后补画质 | 画面大面积变化(切换窗口、滚动)的那一帧只能分到大约一帧的码率,文字是糊的。画面停下来 200 ms 后把最后一帧再编几次,编码器只补残差,几帧之内就接近原画(补到编码器不再输出有意义的数据为止,最多 8 帧),之后就不再发帧 | | 预处理 | **GPU 零拷贝**:画面不离开显卡。Windows 把桌面复制的画面复制进自己的纹理,硬件编码器在同一个 D3D11 设备上用 `ID3D11VideoProcessor` 缩放、旋转、转成 NV12(BT.709 有限范围),`MFCreateDXGISurfaceBuffer` + `IMFDXGIDeviceManager` 直接交给硬件 MFT(只用和采集同一块显卡上的编码器);macOS 让 ScreenCaptureKit 直接按编码尺寸输出 NV12,`CVPixelBuffer` 原样交给 VideoToolbox。省掉了读回、几十 MB 的拷贝、CPU 缩放和色彩转换(`client/src-tauri/src/host/encoder/mod.rs`)
**CPU 回退**(软件编码、显卡不支持或 Linux):内存里的画面按需用 `fast_image_resize` 缩放(SIMD,按行分条并行处理),再用 `yuvutils-rs` 把 BGRA 转成 NV12/I420,缓冲区复用。 | -| 编码 | **硬件优先**:Media Foundation 硬件编码器(NVENC / Quick Sync / AMF),支持 **AV1 / HEVC / H.264**,低延迟模式、无 B 帧、超长 GOP;macOS 上是 VideoToolbox(H.264 / HEVC,H.264 用低延迟码率控制);没有硬件编码器时回退到 **OpenH264 屏幕内容模式**。格式按 **AV1 > HEVC > H.264** 的优先级,自动选用双方都支持(对方能编码、本机能解码)的里压缩率最高的 | +| 编码 | **硬件优先**:Media Foundation 硬件编码器(NVENC / Quick Sync / AMF),支持 **AV1 / HEVC / H.264**,低延迟模式、无 B 帧、超长 GOP;macOS 上是 VideoToolbox(H.264 / HEVC,H.264 用低延迟码率控制);Linux 上是基于 GStreamer 的 **VA-API / NVENC**(H.264 / HEVC / AV1);没有硬件编码器时回退到 **OpenH264 屏幕内容模式**。格式按 **AV1 > HEVC > H.264** 的优先级,自动选用双方都支持(对方能编码、本机能解码)的里压缩率最高的 | | 码率控制 | 控制端每帧都回 ACK,被控端限制**在途字节**(≈ 码率 ×(基础 RTT + 50 ms)),网络慢时等待并**跳到最新一帧**,不会越积越卡;码率每次确认都按量到的排队时延和带宽调整(等前面的帧重传也算排队:丢包、被限速时马上降,延迟优先)。估计丢包率超过 10% 也降、超过 2% 时不再加 | | 传输 | QUIC + **BBR**;控制、画面使用独立的有界队列和 QUIC 流,声音走 QUIC 数据报,避免视频流内的丢包 / 背压阻塞其它流。画面每帧一条流([帧流](#帧流与参考帧失效)),一帧丢了包不挡后面的帧。仍共享连接带宽;控制台最后一段(桌面版在本机)仍是单条 WebSocket。打得通[直连](#直连)、并且它不比中转慢时,画面和声音走直连,不经过服务器 | | 丢包恢复 | QUIC 重传。持续缺帧时被控端按每路的 `Lost` 反馈放弃过时帧,从已交付的长期参考帧恢复,或发送关键帧。 | diff --git a/docs/building.md b/docs/building.md index d513ba4a..8bbacd27 100644 --- a/docs/building.md +++ b/docs/building.md @@ -13,13 +13,14 @@ The clients have the **relay server's address and certificate fingerprint** comp | All | A recent stable Rust (edition 2024), Node.js 20+, CMake (to build libopus) | | Windows | Windows 10/11. WebView2 usually ships with the OS; if it's missing the installer downloads and installs it | | macOS | macOS 13 or later and the Xcode Command Line Tools with a macOS 14.2+ SDK for microphone forwarding (`xcode-select --install`); CMake can come from `brew install cmake` | -| Linux | Tauri's dependencies, the PulseAudio and PipeWire development files and the GStreamer plugins the console uses to decode video (see below) | +| Linux | Tauri's dependencies, the PulseAudio, PipeWire, and GStreamer development files, and the GStreamer plugins used for hardware encoding and console decoding (see below) | Debian / Ubuntu: ```bash sudo apt install build-essential cmake pkg-config libssl-dev libwebkit2gtk-4.1-dev \ libayatana-appindicator3-dev librsvg2-dev libxdo-dev libpulse-dev libpipewire-0.3-dev \ + libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \ gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav ``` diff --git a/docs/building.zh-CN.md b/docs/building.zh-CN.md index 71348ed1..649d62c5 100644 --- a/docs/building.zh-CN.md +++ b/docs/building.zh-CN.md @@ -13,13 +13,14 @@ | 所有系统 | 较新的 stable Rust(edition 2024)、Node.js 20+、CMake(编译 libopus) | | Windows | Windows 10/11。WebView2 一般是系统自带的,没有时安装程序会自动下载安装 | | macOS | macOS 13 及以上,Xcode 命令行工具(需 macOS 14.2 或更新的 SDK 来编译麦克风转发,`xcode-select --install`);CMake 可以用 `brew install cmake` 安装 | -| Linux | Tauri 的依赖、PulseAudio 和 PipeWire 开发库,以及控制台解码视频用的 GStreamer 插件(见下) | +| Linux | Tauri 的依赖、PulseAudio / PipeWire / GStreamer 开发库,以及硬编与控制台解码视频用的 GStreamer 插件(见下) | Debian / Ubuntu: ```bash sudo apt install build-essential cmake pkg-config libssl-dev libwebkit2gtk-4.1-dev \ libayatana-appindicator3-dev librsvg2-dev libxdo-dev libpulse-dev libpipewire-0.3-dev \ + libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \ gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav ``` diff --git a/docs/limitations.md b/docs/limitations.md index 154f255c..59d24462 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -46,7 +46,7 @@ ## Linux - The host only supports **X11** desktops. Under Wayland only X11 (XWayland) applications can be seen and controlled; native Wayland windows are black and the controller suggests logging in with an X11 (Xorg) session. Full Wayland support needs xdg-desktop-portal screen sharing (the local user has to confirm each time) and isn't implemented -- The host only has OpenH264 software encoding (no VA-API / NVENC yet), so the controller uses H.264 +- Hardware encoding on the host uses GStreamer (`gstreamer1.0-plugins-bad`, already a package dependency) for **VA-API** (`va` plugin: Intel / AMD) and **NVENC** (`nvcodec` plugin: NVIDIA), supporting H.264, HEVC, and AV1 (AV1 VA-API needs GStreamer 1.24+ and a GPU/driver with AV1 encode; NVENC AV1 needs GStreamer 1.26+). Frames are converted to NV12 on the CPU before upload (no GPU zero-copy yet). Systems without a compatible GPU driver or GStreamer hardware encoder plugin automatically fall back to OpenH264 software encoding. On dual-GPU machines, Airhand defaults to the GPU driving the active display and skips probing secondary NVENC when the display-owning VA-API GPU already provides hardware encoding; you can override this in `config.toml` with `hw_encoder = "auto" | "vaapi" | "nvenc" | "software"` (and `vaapi_device = "/dev/dri/renderD128"`, restart required) or via `AIRHAND_HW_ENCODER` / `AIRHAND_VAAPI_DEVICE` (NVENC requires the proprietary NVIDIA driver). On GPUs/drivers that support dynamic bitrate updates, NVENC adjusts bitrate without emitting a keyframe (only when the bitrate stays at more than twice or less than half of what its VBV buffer was sized for is the buffer resized, at the cost of one keyframe); VA-API restarts its GOP on sustained bitrate changes and caps its GOP at 1024 frames, and GStreamer's VA encoders keep at least half a second of peak bitrate in their rate control buffer, so single frames (keyframes, scene changes) can get bigger than with NVENC - The lock screen can't be controlled (the screensaver grabs the keyboard and mouse) - Receiving files copied on the other side needs FUSE (`fusermount3` and `/dev/fuse`): without it (in a container, for example) only text is synced. The clipboard used is X11's CLIPBOARD, so native Wayland apps only see it through XWayland - Decoding on the controller relies on WebKitGTK + GStreamer: H.264 needs `gstreamer1.0-plugins-bad` (parsing) and `gstreamer1.0-libav` or openh264 (decoding); AV1 / HEVC depend on the installed GStreamer decoders. If a format turns out not to produce a picture, the controller switches to the next available format by priority diff --git a/docs/limitations.zh-CN.md b/docs/limitations.zh-CN.md index a5e17914..377b9f85 100644 --- a/docs/limitations.zh-CN.md +++ b/docs/limitations.zh-CN.md @@ -46,7 +46,7 @@ ## Linux - 被控端只支持 **X11** 桌面。Wayland 下只能看到 / 操作 X11(XWayland)程序,原生 Wayland 窗口是黑的,控制端会提示改用 X11(Xorg)会话登录。完整的 Wayland 支持需要 xdg-desktop-portal 屏幕共享(每次都要本机用户确认),尚未实现 -- 被控端只有 OpenH264 软件编码(还没接 VA-API / NVENC),控制端会使用 H.264 +- 被控端硬件编码基于系统 GStreamer(`gstreamer1.0-plugins-bad`,已是安装包的既有依赖),支持 **VA-API**(`va` 插件:Intel / AMD)和 **NVENC**(`nvcodec` 插件:NVIDIA)的 H.264 / HEVC / AV1 编码(VA-API 的 AV1 需要 GStreamer 1.24+ 与支持 AV1 硬件编码的显卡驱动;NVENC 的 AV1 需要 GStreamer 1.26+)。画面先在 CPU 转为 NV12 再上传编码(尚无 GPU 零拷贝);缺少兼容驱动或硬件编码插件时自动回退到 OpenH264 软件编码。双显卡机器默认优先使用正在驱动显示器的那一侧显卡,且当驱动显示器的 VA-API 核显已提供硬件编码能力时不再探测次选 NVENC;可在 `config.toml` 中设置 `hw_encoder = "auto" | "vaapi" | "nvenc" | "software"`(以及 `vaapi_device = "/dev/dri/renderD128"`,修改后需重启 Airhand),或用环境变量 `AIRHAND_HW_ENCODER` / `AIRHAND_VAAPI_DEVICE` 覆盖(NVENC 需要 NVIDIA 闭源驱动)。在支持动态码率重配的显卡与驱动上,NVENC 运行时调整码率不产生关键帧(只有码率持续变成 VBV 缓冲所按码率的两倍以上或一半以下时,才按新码率重设 VBV,出一个关键帧);VA-API 在码率持续变化时会重启 GOP(产生关键帧),且最大 GOP 长度为 1024 帧,GStreamer 的 VA 编码器码率控制缓冲最少是半秒的峰值码率,单帧(关键帧、场景切换)可能比 NVENC 的大 - 锁屏无法操作(屏保程序会独占键鼠) - 接收对方复制的文件要 FUSE(`fusermount3` 和 `/dev/fuse`):没有的话(例如在容器里)只同步文本。剪贴板用的是 X11 的 CLIPBOARD,原生 Wayland 程序要经 XWayland 才看得到 - 控制端的解码依赖 WebKitGTK + GStreamer:H.264 需要 `gstreamer1.0-plugins-bad`(解析)和 `gstreamer1.0-libav` 或 openh264(解码);AV1 / HEVC 取决于装了哪些 GStreamer 解码器。某种格式实际解不出画面时,控制端会按优先级改用下一个可用的格式 diff --git a/docs/usage.md b/docs/usage.md index c1e2b79a..f5347bb7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -126,6 +126,8 @@ Everything Airhand saves is in one `config.toml` (with comments). The menu in th | `pause_awdl` | macOS: pause AirDrop during remote control (see "Periodic stutter over Wi-Fi" under [Host](#host-default)): written when you switch **Pause AirDrop during remote control** in the menu bar icon's menu. Without it nothing is paused (`false`). Setting it to `true` by hand doesn't install the helper; turn it on in the menu | | `update_channel` | The [update](#updates) channel: `"stable"` or `"prerelease"`, written when you switch it in the tray menu or the console. Without it, stable | | `check_updates` | Check for updates automatically, written when you switch it in the tray menu or the console. Without it, `true` | +| `hw_encoder` | Linux: hardware encoder backend (`"auto"`, `"vaapi"`, `"nvenc"`, or `"software"`). Without it, `"auto"` (prefers the GPU driving the active display). Can also be overridden with `AIRHAND_HW_ENCODER`; restart Airhand after editing | +| `vaapi_device` | Linux: specific VA-API DRM render node (e.g. `"/dev/dri/renderD128"`). Without it, Airhand selects the display-owning non-NVIDIA render node. Can also be overridden with `AIRHAND_VAAPI_DEVICE`; restart Airhand after editing | | `[code]` | This computer's control code, and the secret that gets it back. Delete `code` and `secret` to get a new code | | `[host]` | Maintained by Airhand: this computer's end-to-end identity as a host (`key`), the pairing code and whether pairing is paused, all stored encrypted. Deleting `key` creates a new identity: controllers that connected before will warn that this computer's identity changed | | `[[paired]]` | Maintained by Airhand: paired controllers (public key, name, when they paired); they connect without the pairing code. Delete an entry to forget that controller | diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index eb407e3e..e3cb883b 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -126,6 +126,8 @@ Airhand 要保存的东西都在一个 `config.toml` 里(里面有注释)。 | `pause_awdl` | macOS:远程控制时暂停隔空投送(见[被控端](#被控端默认)的“走 Wi-Fi 时画面周期性地卡顿”):在菜单栏图标的菜单里切换**远程控制时暂停隔空投送**时写入。没有这一项就是 `false`(不暂停)。手动改成 `true` 不会安装组件,要在菜单里打开 | | `update_channel` | [自动更新](#自动更新)的通道:`"stable"`(正式版)或 `"prerelease"`(预发布版),在托盘菜单、控制台里切换时写入。没有这一项就是正式版 | | `check_updates` | 自动检查更新,在托盘菜单、控制台里切换时写入。没有这一项就是 `true` | +| `hw_encoder` | Linux:硬件编码后端偏好(`"auto"`、`"vaapi"`、`"nvenc"` 或 `"software"`)。没有这一项时默认 `"auto"`(优先使用正在驱动显示器的显卡)。也可用环境变量 `AIRHAND_HW_ENCODER` 覆盖,修改配置文件后需重启 Airhand | +| `vaapi_device` | Linux:指定 VA-API 的 DRM 渲染节点路径(如 `"/dev/dri/renderD128"`)。没有这一项时自动选择正在驱动显示器的非 NVIDIA 渲染节点。也可用环境变量 `AIRHAND_VAAPI_DEVICE` 覆盖,修改配置文件后需重启 Airhand | | `[code]` | 本机的控制码,以及取回它用的密钥。删掉 `code` 和 `secret` 就会重新分配 | | `[host]` | 由 Airhand 维护:本机作为被控端的端到端加密身份(`key`)、配对码和它有没有暂停,都是加密保存的。删掉 `key` 会生成新的身份:连过本机的控制端会提示本机的身份变了 | | `[[paired]]` | 由 Airhand 维护:配对过的控制端(公钥、名称、配对的时间),不用配对码就能连。删掉一项就是忘掉那个控制端 |