From 37a1fbb592db1b104f3b3bb345bfb093fb2bad6c Mon Sep 17 00:00:00 2001 From: sqlpxc Date: Fri, 4 Dec 2026 16:19:18 +0800 Subject: [PATCH] feat(windows,audio,proto): plug the controller's microphone into Windows hosts through usbip-win2 Windows hosts no longer use Steam Streaming Microphone (Steam had to be installed, its driver was installed from Steam's files with administrator rights, and its two sides usually needed exclusive mode). The controller's microphone is now Airhand Microphone, a USB Audio Class 1.0 microphone served by airhand-dock 0.3.0 and plugged through usbip-win2, like the gamepads: Windows drives it with its own usbaudio.sys, so nothing else is installed, no administrator rights, no exclusive mode, no sound settings changed, and it has the same name on every platform. - host/mic/usb.rs: plugged on the first "microphone on" of a session and ready once Windows has published its recording device (found by its interface name). The first time a computer sees it, Windows sets it up and briefly disables the recording device; the host waits for it to come back (about 6 s instead of 1 s). Turning the microphone off or switching connections doesn't unplug it, so programs that chose it don't fall back to the computer's own microphone; it is unplugged when every session that turned it on has ended (at once for a normal end, after 30 s without a reconnect otherwise). A fixed USB serial keeps programs' choice and the default device setting. - host/dock.rs: one airhand-dock Dock per process for gamepads and the microphone. - proto: MicState::NoDriver (usbip-win2 missing). NoDevice, SteamMissing and SetupFailed are only sent by older Windows hosts; the console keeps their texts. - The render loop's opener now says why it can't open yet (no driver, preparing) and polls faster while preparing; device format parsing for WASAPI is gone, as are the zip and tempfile dependencies. - Installer, usbip-win2 README and docs describe usbip-win2 as the gamepad and microphone driver. - Tests: mic_reaches_airhand_microphone records a 1 kHz tone back through the real device (AIRHAND_TEST_MIC_SERIAL simulates a first plug); e2e_mic uses it on Windows. --- README.md | 2 +- README.zh-CN.md | 2 +- client/scripts/fetch-usbip-win2.mjs | 2 +- client/src-tauri/Cargo.lock | 53 +-- client/src-tauri/Cargo.toml | 11 +- client/src-tauri/src/e2e.rs | 19 +- client/src-tauri/src/host/dock.rs | 24 ++ client/src-tauri/src/host/gamepad.rs | 14 +- client/src-tauri/src/host/mic/mod.rs | 314 +++++++------- client/src-tauri/src/host/mic/native.rs | 6 +- client/src-tauri/src/host/mic/steam.rs | 415 ------------------- client/src-tauri/src/host/mic/usb.rs | 495 +++++++++++++++++++++++ client/src-tauri/src/host/mic/wasapi.rs | 384 +++--------------- client/src-tauri/src/host/mod.rs | 2 + client/src-tauri/src/host/session.rs | 27 +- client/src-tauri/windows/hooks.nsh | 18 +- client/src-tauri/windows/usbip/README.md | 4 +- client/src/components/SessionView.tsx | 9 +- client/src/lib/api.ts | 15 +- client/src/lib/mic.ts | 2 +- client/src/locales/en.ts | 5 +- client/src/locales/zh.ts | 5 +- client/tests/session.test.ts | 7 +- crates/airhand-proto/src/session.rs | 15 +- crates/airhand-proto/tests/v10.rs | 1 + docs/architecture.md | 8 +- docs/architecture.zh-CN.md | 8 +- docs/development.md | 8 +- docs/development.zh-CN.md | 7 +- docs/limitations.md | 4 +- docs/limitations.zh-CN.md | 4 +- docs/usage.md | 10 +- docs/usage.zh-CN.md | 10 +- 33 files changed, 868 insertions(+), 1042 deletions(-) create mode 100644 client/src-tauri/src/host/dock.rs delete mode 100644 client/src-tauri/src/host/mic/steam.rs create mode 100644 client/src-tauri/src/host/mic/usb.rs diff --git a/README.md b/README.md index 3b757c28..0960d47a 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ See [How it works → Video](docs/architecture.md#video) for details. - **Remote terminal**: when you only want to run command-line programs such as `claude`, `codex` or `pi` on the other computer, open just a terminal there instead of the screen (Windows / macOS / Linux hosts, running as the signed-in user), from the desktop app or from a phone (Android / iOS): next to no bandwidth, and after a dropped connection you get the same terminal back with its programs still running. [Details](docs/usage.md#remote-terminal) - **Android**: control computers and phones from a phone as a trackpad or touchscreen, or share your own screen to get help (a device needs the pairing code shown on the phone the first time, and you're notified whenever one connects); watch on a TV with the remote - **iPhone / iPad**: the same remote control as on Android (trackpad / touch gestures, keyboard, mouse with pointer lock on iPad, game controls), or share the screen through the system screen broadcast (view only: iOS doesn't let apps be controlled) -- **Audio**: the host's system audio plays on the controller (Opus + adaptive jitter buffer), with optional A/V sync for watching videos. The other way, the controller can send its microphone to meeting apps and voice typing on Windows, macOS 14.2+ and Linux (PipeWire) hosts. Mac and Linux hosts publish **Airhand Microphone** while forwarding is on +- **Audio**: the host's system audio plays on the controller (Opus + adaptive jitter buffer), with optional A/V sync for watching videos. The other way, the controller can send its microphone to meeting apps and voice typing on Windows, macOS 14.2+ and Linux (PipeWire) hosts, where it's the recording device **Airhand Microphone**: on Windows a virtual USB microphone plugged through [airhand-dock](https://github.com/sqlpxc/airhand-dock) and usbip-win2, like gamepads. [Details](docs/usage.md#microphone) - **Gamepads**: gamepads on the controller (desktop and web consoles, Android phones and TVs, iPhone / iPad) are plugged into Windows and Linux hosts as wired Xbox 360 controllers through [airhand-dock](https://github.com/sqlpxc/airhand-dock), so every game sees a real gamepad, and games make your gamepad vibrate. Game keys on phones can be an on-screen gamepad too. Windows hosts need the [usbip-win2](https://github.com/vadimgrn/usbip-win2) driver, which the Airhand installer includes and offers to install. [Details](docs/usage.md#gamepads) - **Handy tools**: two-way clipboard sync (text, plus files and folders, sent when you paste), typing the clipboard as keystrokes, system shortcuts (Win, Alt+Tab, Ctrl+Shift+Esc…), multiple monitors (switch between them, show and control several at once, or give each its own window to put on your own screens in full screen), keyboard lock in fullscreen, quality presets - **Secure by default**: sessions are end-to-end encrypted, so the relay server can't see the screen or keystrokes; the first connection needs the pairing code from the other computer's tray (it never goes through the server), and its identity is recognized afterwards; TLS 1.3 with certificate pinning, brute-force protection for control codes; the host always sees who is connected and can disconnect them with one click diff --git a/README.zh-CN.md b/README.zh-CN.md index 4b5eb7c5..b932efad 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -43,7 +43,7 @@ Airhand 是一个**高性能、低延迟**的远程桌面:画面用 GPU 硬件 - **远程终端**:只想在对方电脑上跑 `claude`、`codex`、`pi` 这类命令行程序时,不传画面、只开一个终端(Windows / macOS / Linux 被控端,以登录的用户的身份运行),电脑和手机(Android / iOS)上都能开:几乎不占带宽,断线重连后接回原来的终端,里面的程序一直在跑。[详细说明](docs/usage.zh-CN.md#远程终端) - **Android**:在手机上用触控板或触屏的方式控制电脑、手机,也能共享自己的屏幕让别人协助(对方第一次连接时要输入手机上显示的配对码,有设备连上来时会提醒你);在电视上用遥控器看画面 - **iPhone / iPad**:和 Android 一样控制电脑、手机(触控板 / 触屏手势、键盘、外接鼠标,iPad 上可以锁定指针、游戏按键),也能用系统的屏幕广播共享自己的屏幕(只能被看:iOS 不允许别的应用操作本机) -- **声音**:被控端的系统声音同步到控制端(Opus + 自适应抖动缓冲),看视频时可以打开音画同步。反过来,控制端的麦克风可以转发给 Windows、macOS 14.2+ 和 Linux(PipeWire)被控端,供那里的会议软件和语音输入使用。Mac 和 Linux 会在转发期间提供一个 **Airhand Microphone** 录音设备 +- **声音**:被控端的系统声音同步到控制端(Opus + 自适应抖动缓冲),看视频时可以打开音画同步。反过来,控制端的麦克风可以转发给 Windows、macOS 14.2+ 和 Linux(PipeWire)被控端,在那里是录音设备 **Airhand Microphone**,供会议软件和语音输入使用:Windows 上是和手柄一样经 [airhand-dock](https://github.com/sqlpxc/airhand-dock) 和 usbip-win2 插上的虚拟 USB 麦克风。[详情](docs/usage.zh-CN.md#麦克风) - **手柄**:控制端接着的手柄(桌面和网页控制台、Android 手机和电视、iPhone / iPad)经 [airhand-dock](https://github.com/sqlpxc/airhand-dock) 作为有线 Xbox 360 手柄插到 Windows、Linux 被控端上,所有游戏看到的都是真手柄,游戏的震动也传回你的手柄。手机上的游戏按键也可以是屏幕上的手柄。Windows 被控端要用 [usbip-win2](https://github.com/vadimgrn/usbip-win2) 驱动,Airhand 的安装包里带着,安装时会问要不要装。[详情](docs/usage.zh-CN.md#手柄) - **实用工具**:剪贴板双向同步(文字,以及文件、文件夹:粘贴时才传)、以键盘输入方式发送剪贴板、系统快捷键(Win、Alt+Tab、Ctrl+Shift+Esc……)、多显示器(可以同时显示、同时操作对方的几个显示器,也可以每个显示器单独一个窗口,放到本机的各个显示器上全屏)、全屏时锁定键盘、画质预设 - **默认安全**:会话端到端加密,中转服务器看不到画面和键盘输入;第一次连接要输入对方托盘里的配对码(不经过服务器),之后认得出对方的身份;TLS 1.3 + 证书指纹固定,控制码防暴力猜测;被控端随时能看到谁连着,一键断开 diff --git a/client/scripts/fetch-usbip-win2.mjs b/client/scripts/fetch-usbip-win2.mjs index 0bb59eeb..945fcc1c 100644 --- a/client/scripts/fetch-usbip-win2.mjs +++ b/client/scripts/fetch-usbip-win2.mjs @@ -75,6 +75,6 @@ main().catch((e) => { } console.warn( `warning: usbip-win2 couldn't be downloaded (${e.message ?? e}).\n` + - "The Windows installer is built without it and won't offer to install the gamepad driver.", + "The Windows installer is built without it and won't offer to install the gamepad and microphone driver.", ); }); diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index 4240d04a..a6c6bb8a 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -111,13 +111,12 @@ dependencies = [ "winreg", "x11rb", "yuvutils-rs", - "zip", ] [[package]] name = "airhand-dock" -version = "0.2.0" -source = "git+https://github.com/sqlpxc/airhand-dock?tag=v0.2.0#3b3cc9291a819fdbe9d808f12d5985da6b1754f4" +version = "0.3.0" +source = "git+https://github.com/sqlpxc/airhand-dock?tag=v0.3.0#a6bb19e598f4f2552cf90b6800549c5b8b6b81d5" dependencies = [ "libc", "log", @@ -204,7 +203,7 @@ dependencies = [ "objc2-foundation", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "x11rb", ] @@ -1125,7 +1124,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1251,7 +1250,7 @@ dependencies = [ "libc", "log", "memchr", - "nix 0.29.0", + "nix", "page_size", "smallvec", "zerocopy", @@ -2730,18 +2729,6 @@ dependencies = [ "libc", ] -[[package]] -name = "nix" -version = "0.31.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases", - "libc", -] - [[package]] name = "nom" version = "7.1.3" @@ -3576,7 +3563,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3833,7 +3820,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3891,7 +3878,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4812,7 +4799,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5217,12 +5204,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "typed-path" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" - [[package]] name = "typeid" version = "1.0.3" @@ -5651,7 +5632,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6204,20 +6185,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "zip" -version = "9.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" -dependencies = [ - "crc32fast", - "flate2", - "indexmap 2.14.2", - "memchr", - "nix 0.31.4", - "typed-path", -] - [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index efc50000..18d68ece 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -53,12 +53,10 @@ semver = "1" sha2 = "0.10" [target.'cfg(windows)'.dependencies] -# 从本机 Steam 的安装目录或自解压 ZIP 读取虚拟麦克风驱动 +# 注册表:虚拟显示器驱动的设置(src/host/virtual_display/device.rs)、登录的用户的设置(src/winsvc/user.rs) winreg = "0.56" # 自动更新:Windows 上按系统的代理设置(Internet 选项)连 GitHub ureq = { version = "3", default-features = false, features = ["win-system-proxy"] } -zip = { version = "9", default-features = false, features = ["deflate-flate2-zlib-rs"] } -tempfile = "3" # #[implement] 展开的代码直接引用 windows_core(剪贴板里的文件:自己实现的 IDataObject、IStream) windows-core = "0.62" windows = { version = "0.62", features = [ @@ -104,7 +102,7 @@ windows = { version = "0.62", features = [ "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging", "Win32_UI_HiDpi", - # 声音设备的属性(控制端的麦克风:按接口名找 Steam Streaming Microphone、读它的设备格式) + # 声音设备的属性(控制端的麦克风:按接口名找 Airhand Microphone 的录音设备) "Win32_UI_Shell_PropertiesSystem", # 剪贴板里的文件:对方复制的文件以"虚拟文件"放进本机剪贴板(FILEDESCRIPTORW / FILECONTENTS,见 src/clipfiles/windows.rs) "Win32_UI_Shell", @@ -116,9 +114,10 @@ windows = { version = "0.62", features = [ [target.'cfg(not(windows))'.dependencies] dirs = "7" -# 控制端的手柄插成本机的虚拟 Xbox 360 手柄(见 src/host/gamepad.rs):Windows 经 usbip-win2,Linux 经 vhci-hcd 或 uinput +# 控制端的手柄插成本机的虚拟 Xbox 360 手柄(见 src/host/gamepad.rs):Windows 经 usbip-win2,Linux 经 vhci-hcd 或 uinput。 +# Windows 上控制端的麦克风也是经 usbip-win2 插上的 USB 麦克风(见 src/host/mic/usb.rs) [target.'cfg(any(windows, target_os = "linux"))'.dependencies] -airhand-dock = { git = "https://github.com/sqlpxc/airhand-dock", tag = "v0.2.0" } +airhand-dock = { git = "https://github.com/sqlpxc/airhand-dock", tag = "v0.3.0" } # Linux 被控端:X11(MIT-SHM 采集 + DAMAGE 变化检测 + XFIXES 光标/剪贴板 + XTEST 注入), # 声音用 PulseAudio(PipeWire 的 pipewire-pulse 同样适用)监听默认输出设备。 diff --git a/client/src-tauri/src/e2e.rs b/client/src-tauri/src/e2e.rs index 9b52bb46..12a87c98 100644 --- a/client/src-tauri/src/e2e.rs +++ b/client/src-tauri/src/e2e.rs @@ -530,7 +530,7 @@ async fn e2e_roundtrip() { } assert!(rep.hello, "没有收到 Hello"); assert!(rep.pongs >= 3, "Ping/Pong 不工作"); - // 同一个版本的两端都懂麦克风:被控端会说它能不能接(Windows 看有没有 Steam Streaming Microphone) + // 同一个版本的两端都懂麦克风:被控端会说它能不能接(Windows 看有没有 usbip-win2) let mic = rep.mic.expect("被控端没有说麦克风的状态"); assert_eq!(mic, crate::host::mic::probe(0).await.0); // 手柄也是:被控端会说它能不能接(Windows 看有没有 usbip-win2,Linux 看 vhci-hcd / uinput) @@ -738,7 +738,7 @@ async fn e2e_multi_display() { /// 控制端的麦克风,从协议级的控制端一直到系统录音设备。每 20 ms 发一包 1 kHz 的声音, /// 故意丢一部分数据报,再通过独立的录音客户端检查频率和连续性。先启动中转服务器。 #[tokio::test(flavor = "multi_thread")] -#[ignore = "requires a relay and the system audio server; on Windows may install the Steam driver"] +#[ignore = "requires a relay and the system audio server; on Windows plugs a USB microphone through usbip-win2"] async fn e2e_mic() { use crate::host::mic::tests::goertzel; #[cfg(not(windows))] @@ -787,24 +787,19 @@ async fn e2e_mic() { continue; }; println!("麦克风: {state:?} {detail:?}"); - if state == MicState::SteamMissing && !enabled { - println!("这台电脑上没有 Steam,跳过声音的检查"); + if state == MicState::NoDriver && !enabled { + println!("这台电脑上没有 usbip-win2,跳过声音的检查"); return; } assert!( - matches!( - state, - MicState::Ready | MicState::NoDevice | MicState::Preparing - ), + matches!(state, MicState::Ready | MicState::Preparing), "{state:?}: {detail:?}" ); if !enabled { ctl.send(&ControllerMsg::Mic { enabled: true }).await; enabled = true; - // Unix publishes its device on demand. Wait for the live lease's Ready. - if !cfg!(windows) { - continue; - } + // 打开之后才插上 / 发布设备:等它说 ready + continue; } if state == MicState::Ready { break; diff --git a/client/src-tauri/src/host/dock.rs b/client/src-tauri/src/host/dock.rs new file mode 100644 index 00000000..c3d35319 --- /dev/null +++ b/client/src-tauri/src/host/dock.rs @@ -0,0 +1,24 @@ +//! [airhand-dock](https://github.com/sqlpxc/airhand-dock) 的 [`Dock`]:整个进程一个,控制端的手柄(见 [`super::gamepad`]) +//! 和 Windows 上控制端的麦克风(见 `super::mic`)都插在它上面:一个本机回环的 USB/IP 服务器,一套线程。 +//! +//! 第一次插设备时打开(Windows 上会顺便拔掉之前崩溃的进程留下的设备),之后一直留着;打不开(例如还没装 usbip-win2) +//! 就不留,下次再试。打开会阻塞:只在插拔设备的线程上调用。 + +use std::sync::Mutex; + +use airhand_dock::Dock; +use tracing::info; + +static DOCK: Mutex> = Mutex::new(None); + +/// 这个进程的 [`Dock`],还没有就打开它 +pub(crate) fn get() -> airhand_dock::Result { + let mut dock = DOCK.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(d) = &*dock { + return Ok(d.clone()); + } + let d = Dock::new()?; + info!(backend = %d.backend(), "opened the virtual device dock"); + *dock = Some(d.clone()); + Ok(d) +} diff --git a/client/src-tauri/src/host/gamepad.rs b/client/src-tauri/src/host/gamepad.rs index f1848df7..70b12b10 100644 --- a/client/src-tauri/src/host/gamepad.rs +++ b/client/src-tauri/src/host/gamepad.rs @@ -244,10 +244,9 @@ mod imp { } } - /// 插拔线程:整个进程一个,插拔都在这里一个一个做。airhand-dock 的 [`Dock`] 也在这里,第一次插手柄时打开 - /// (Windows 上会顺便拔掉之前崩溃的进程留下的),之后一直留着 + /// 插拔线程:整个进程一个,插拔都在这里一个一个做。手柄插在整个进程共用的 airhand-dock 的 [`Dock`] 上 + /// (见 [`crate::host::dock`]:第一次插手柄时打开,之后一直留着) fn worker(rx: mpsc::Receiver) { - let mut dock: Option = None; for job in rx { match job { Job::Plug { @@ -256,14 +255,7 @@ mod imp { generation, device, } => { - let result = match &dock { - Some(d) => Ok(d.clone()), - None => Dock::new().inspect(|d| { - info!(backend = %d.backend(), "opened the gamepad dock"); - dock = Some(d.clone()); - }), - } - .and_then(|d| d.plug(&device)); + let result = crate::host::dock::get().and_then(|d| d.plug(&device)); let mut owners = owners(); let pad = owners .get_mut(&controller) diff --git a/client/src-tauri/src/host/mic/mod.rs b/client/src-tauri/src/host/mic/mod.rs index 2fc4b57b..8686623d 100644 --- a/client/src-tauri/src/host/mic/mod.rs +++ b/client/src-tauri/src/host/mic/mod.rs @@ -1,12 +1,14 @@ //! 控制端的麦克风(协议见 `airhand_proto::session` 的"麦克风"):把控制端发来的声音放进本机的虚拟麦克风, //! 本机的程序(会议、语音输入)选它做录音设备,就像用着一个本地麦克风。 //! -//! Windows 用 Steam 的虚拟声卡 Steam Streaming Microphone(见 [`wasapi`])。打开转发时如果缺少设备, -//! 从本机 Steam 安装签名驱动(见 [`steam`])。 -//! macOS 14.2+ 和 Linux/PipeWire 在打开转发期间发布 Airhand Microphone(见 `native`)。 +//! 本机的程序看到的都是录音设备 Airhand Microphone: +//! +//! * Windows:经 airhand-dock 和 usbip-win2 插上的一个 USB 麦克风,系统用自带的驱动(见 [`usb`])。控制端第一次打开麦克风时 +//! 插上,关掉时不拔(选了它的程序不会换成别的麦克风),打开过它的会话都结束了才拔掉([`ended`]); +//! * macOS 14.2+ 和 Linux/PipeWire:在打开转发期间发布(见 `native`)。 //! //! * 同一时刻只给一个会话([`open`]):别的会话这时看到的是 `Busy`,空出来之后告诉它们([`owner_changed`]); -//! * 控制端打开麦克风时才打开设备、开始播放线程,关掉或者会话结束时(丢掉 [`MicLease`])停止:不一直占着设备; +//! * 控制端打开麦克风时才打开设备、开始播放线程,关掉或者会话结束时(丢掉 [`MicLease`])停止; //! * 声音包在会话的读任务里交给 [`MicInput`](不能等),经有界队列交给播放线程:解码 Opus(丢了的包用 Opus 的 //! 丢包补偿盖过去),抖动缓冲([`Playout`])攒够 [`TARGET_MS`] 再开始放,换成设备的格式([`Format`])写进去。 //! 没有声音的时候写静音;网络卡住、积压太多时丢掉旧的,延迟不会越积越多。 @@ -19,7 +21,7 @@ pub(crate) mod unix_recorder; pub(crate) use native::cleanup as cleanup_stale; #[cfg(windows)] -mod steam; +mod usb; #[cfg(windows)] pub(crate) mod wasapi; @@ -33,7 +35,7 @@ use std::time::{Duration, Instant}; use airhand_link::host::MicSink; use airhand_proto::media::{self, AUDIO_FRAME_MS, AUDIO_SAMPLE_RATE, AudioHeader}; use airhand_proto::session::MicState; -use anyhow::{Result, bail}; +use anyhow::Result; use tokio::sync::watch; use tracing::{debug, info, warn}; @@ -50,8 +52,10 @@ const MAX_CONCEAL: u32 = 3; const QUEUE: usize = 32; /// 打不开设备时隔这么久再试 const REOPEN: Duration = Duration::from_secs(1); +/// 设备在准备(在等系统发布录音设备)时隔这么久再看,准备好了马上开始 +const PREPARING_POLL: Duration = Duration::from_millis(200); /// 设备里最多先写这么多:够播放线程两次醒来之间用(Windows 的计时器可能要 15.6 ms 才叫醒它)。 -/// 不能把设备的缓冲填满:那会把抖动缓冲里的一下子取光,包稍晚一点就断粮(这台电脑上设备的缓冲是 80 ms) +/// 不能把设备的缓冲填满:那会把抖动缓冲里的一下子取光,包稍晚一点就断粮,延迟也更大 const AHEAD_MS: usize = 40; /// 告诉控制端的状态:状态和给排查问题用的技术信息(英文) @@ -76,7 +80,7 @@ impl MicSink for MicInput { /// 现在是哪个会话在用麦克风 static OWNER: LazyLock>> = LazyLock::new(|| watch::Sender::new(None)); -/// 上一个播放线程:新的播放线程等它放开设备再开始(独占模式下设备同时只能打开一次) +/// 上一个播放线程:新的播放线程等它放开设备再开始(设备同时只给一个播放线程写) struct Worker { stop: Arc, thread: Option>, @@ -133,7 +137,7 @@ pub(crate) fn shutdown() -> Result<()> { #[cfg(target_os = "macos")] cleanup_stale()?; if matches!(joined, Some(Err(_))) { - bail!("microphone thread panicked"); + anyhow::bail!("microphone thread panicked"); } Ok(()) } @@ -151,7 +155,7 @@ pub async fn probe(session_id: u64) -> Status { } #[cfg(windows)] { - tokio::task::spawn_blocking(wasapi::probe) + tokio::task::spawn_blocking(usb::probe) .await .unwrap_or_else(|e| (MicState::Failed, Some(e.to_string()))) } @@ -166,28 +170,56 @@ pub async fn probe(session_id: u64) -> Status { } /// 控制端打开了麦克风:占用麦克风,开始播放线程。别的会话占着时为 `Err(Busy)`,这个平台不支持时为 -/// `Err(Unsupported)`。打开设备在播放线程里做,结果从 [`MicLease::changed`] 来 -pub fn open(session_id: u64, input: &Arc, initial: Status) -> Result { - let initial = if cfg!(windows) { - initial - } else { - (MicState::Preparing, None) - }; - open_with(session_id, input, initial, |rx, stop, status| { +/// `Err(Unsupported)`。打开设备在播放线程里做(先是 `Preparing`),结果从 [`MicLease::changed`] 来 +pub fn open(session_id: u64, input: &Arc) -> Result { + let lease = open_with( + session_id, + input, + (MicState::Preparing, None), + |rx, stop, status| { + #[cfg(windows)] + render(rx, stop, status, usb::open); + #[cfg(any(target_os = "macos", target_os = "linux"))] + render(rx, stop, status, || native::open().map(Ok)); + #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] + let _ = (rx, stop, status); + }, + )?; + // Windows 的虚拟麦克风插上之后留到这个会话结束(见 [`ended`]) + #[cfg(windows)] + usb::hold(session_id); + Ok(lease) +} + +/// 一个会话对虚拟麦克风的占用,和会话一样长。Windows 的虚拟麦克风插上之后留到打开过它的会话都结束: +/// 丢掉这个(会话结束,任务被中止了也算)时开始等它重连,正常结束的接着由 [`ended`] 马上拔掉(见 [`usb`])。 +/// 别的平台丢掉 [`MicLease`] 时就已经收起来了 +pub struct MicSession { + #[cfg_attr(not(windows), allow(dead_code))] + session_id: u64, +} + +impl MicSession { + pub fn new(session_id: u64) -> Self { + Self { session_id } + } +} + +impl Drop for MicSession { + fn drop(&mut self) { #[cfg(windows)] - { - let mut setup = steam::DriverSetup::default(); - render(rx, stop, status, wasapi::open, |notify| { - setup.missing(notify) - }); - } - #[cfg(any(target_os = "macos", target_os = "linux"))] - render(rx, stop, status, native::open, |_| { - (MicState::NoDevice, None) - }); - #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] - let _ = (rx, stop, status); - }) + usb::release(self.session_id); + } +} + +/// 会话结束了(它的 [`MicSession`] 已经丢掉),`normal`:正常结束的(控制端断开、本机断开了它)。 +/// Windows:它是最后一个打开过麦克风的会话的话,不等它重连,马上拔掉虚拟麦克风。不阻塞 +#[allow(unused_variables)] +pub fn ended(session_id: u64, normal: bool) { + #[cfg(windows)] + if normal { + usb::ended(session_id); + } } fn open_with( @@ -292,23 +324,18 @@ impl Drop for MicLease { // ───────────────────────────── 播放 ───────────────────────────── /// 采样的格式 -#[cfg_attr(not(any(windows, test)), allow(dead_code))] // WASAPI also accepts integer sample formats. +#[cfg_attr(not(test), allow(dead_code))] // Windows writes 16-bit PCM, macOS and Linux float. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Sample { F32, I16, - /// 3 字节紧挨着 - I24, - /// 32 位整数(包括 32 位容器里的 24 位:有效位在高位,按 32 位写就对了) - I32, } impl Sample { fn size(self) -> usize { match self { Sample::I16 => 2, - Sample::I24 => 3, - Sample::F32 | Sample::I32 => 4, + Sample::F32 => 4, } } } @@ -319,57 +346,11 @@ pub(crate) struct Format { pub sample: Sample, pub channels: usize, pub rate: u32, - /// 一帧多少字节(可能比 声道数 × 采样大小 多出几个填充字节) + /// 一帧多少字节(不少于 声道数 × 采样大小,多出来的是填充字节) pub block_align: usize, } -#[cfg(any(windows, test))] -const WAVE_FORMAT_PCM: u16 = 1; -#[cfg(any(windows, test))] -const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; - impl Format { - /// 解析 `WAVEFORMATEX` / `WAVEFORMATEXTENSIBLE` 的字节(Windows 设备属性里的设备格式就是这个) - #[cfg(any(windows, test))] - pub fn parse(b: &[u8]) -> Result { - const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; - let u16_at = |i: usize| b.get(i..i + 2).map(|s| u16::from_le_bytes([s[0], s[1]])); - let u32_at = |i: usize| { - b.get(i..i + 4) - .map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) - }; - let (Some(tag), Some(channels), Some(rate), Some(block_align), Some(bits)) = - (u16_at(0), u16_at(2), u32_at(4), u16_at(12), u16_at(14)) - else { - bail!("the wave format is too short ({} bytes)", b.len()); - }; - let tag = match tag { - // 扩展格式:真正的格式是 SubFormat(一个 GUID,前 4 个字节就是 WAVE_FORMAT_*) - WAVE_FORMAT_EXTENSIBLE => match u32_at(24) { - Some(sub) => sub as u16, - None => bail!("the extensible wave format is too short"), - }, - t => t, - }; - let sample = match (tag, bits) { - (WAVE_FORMAT_IEEE_FLOAT, 32) => Sample::F32, - (WAVE_FORMAT_PCM, 16) => Sample::I16, - (WAVE_FORMAT_PCM, 24) => Sample::I24, - (WAVE_FORMAT_PCM, 32) => Sample::I32, - _ => bail!("unsupported wave format (tag {tag:#x}, {bits} bits)"), - }; - let (channels, block_align) = (channels as usize, block_align as usize); - if channels == 0 || rate == 0 || block_align < channels * sample.size() { - bail!("invalid wave format ({channels} channels, {rate} Hz, block {block_align})"); - } - Ok(Self { - sample, - channels, - rate, - block_align, - }) - } - /// 把一帧(`frame.len() == block_align`)写成 `v`(每个声道一样,填充字节为 0) fn write(&self, frame: &mut [u8], v: f32) { let v = v.clamp(-1.0, 1.0); @@ -380,10 +361,6 @@ impl Format { match self.sample { Sample::F32 => s.copy_from_slice(&v.to_le_bytes()), Sample::I16 => s.copy_from_slice(&((v * 32767.0) as i16).to_le_bytes()), - Sample::I24 => s.copy_from_slice(&((v * 8_388_607.0) as i32).to_le_bytes()[..3]), - Sample::I32 => { - s.copy_from_slice(&((v as f64 * 2_147_483_647.0) as i32).to_le_bytes()) - } } } } @@ -520,8 +497,9 @@ pub(crate) trait Output { fn write(&mut self, frames: usize, fill: &mut dyn FnMut(&mut [u8])) -> Result<()>; } -/// 打开播放端:`Ok(None)` 是没有虚拟麦克风 -pub(crate) type Opener = fn() -> Result>>; +/// 打开播放端:`Ok(Err(status))` 是现在还打不开(缺驱动、设备还在准备……),`status` 告诉控制端为什么; +/// `Err` 是出错了(`Failed`)。过一会儿都再试 +pub(crate) type Opener = fn() -> Result, Status>>; /// 播放线程:收包、打开设备(打不开隔一会儿再试)、往设备里写,直到 `stop` 或者会话放开了麦克风 pub(crate) fn render( @@ -529,7 +507,6 @@ pub(crate) fn render( stop: &AtomicBool, status: &watch::Sender, open: Opener, - mut missing: impl FnMut(&dyn Fn(Status)) -> Status, ) { let set = |s: Status| { status.send_if_modified(|now| { @@ -567,16 +544,21 @@ pub(crate) fn render( } if out.is_none() && Instant::now() >= retry { match open() { - Ok(Some(o)) => { + Ok(Ok(o)) => { let fmt = o.format(); info!(?fmt, "the virtual microphone is open"); failures = 0; set((MicState::Ready, None)); out = Some((o, Resampler::new(fmt.rate))); } - Ok(None) => { - set(missing(&set)); - retry = Instant::now() + REOPEN; + Ok(Err(s)) => { + let wait = if s.0 == MicState::Preparing { + PREPARING_POLL + } else { + REOPEN + }; + set(s); + retry = Instant::now() + wait; } Err(e) => { failures += 1; @@ -667,46 +649,6 @@ pub(crate) mod tests { / x.len().max(1) as f64 } - #[test] - fn wave_formats() { - // Steam Streaming Microphone 录音端在这台电脑上的设备格式:扩展格式,单声道 44.1 kHz 32 位整数 - let mut ext = vec![0u8; 40]; - ext[..2].copy_from_slice(&WAVE_FORMAT_EXTENSIBLE.to_le_bytes()); - ext[2..4].copy_from_slice(&1u16.to_le_bytes()); - ext[4..8].copy_from_slice(&44_100u32.to_le_bytes()); - ext[12..14].copy_from_slice(&4u16.to_le_bytes()); - ext[14..16].copy_from_slice(&32u16.to_le_bytes()); - ext[16..18].copy_from_slice(&22u16.to_le_bytes()); - ext[24..28].copy_from_slice(&1u32.to_le_bytes()); - let f = Format::parse(&ext).unwrap(); - assert_eq!( - f, - Format { - sample: Sample::I32, - channels: 1, - rate: 44_100, - block_align: 4 - } - ); - ext[24..28].copy_from_slice(&3u32.to_le_bytes()); - assert_eq!(Format::parse(&ext).unwrap().sample, Sample::F32); - // 普通的 WAVEFORMATEX:立体声 48 kHz 16 位 - let mut plain = vec![0u8; 18]; - plain[..2].copy_from_slice(&WAVE_FORMAT_PCM.to_le_bytes()); - plain[2..4].copy_from_slice(&2u16.to_le_bytes()); - plain[4..8].copy_from_slice(&48_000u32.to_le_bytes()); - plain[12..14].copy_from_slice(&4u16.to_le_bytes()); - plain[14..16].copy_from_slice(&16u16.to_le_bytes()); - assert_eq!(Format::parse(&plain).unwrap().sample, Sample::I16); - assert!(Format::parse(&plain[..10]).is_err()); - assert!(Format::parse(&ext[..20]).is_err()); - plain[12..14].copy_from_slice(&2u16.to_le_bytes()); - assert!( - Format::parse(&plain).is_err(), - "block too small for 2 × 16 bits" - ); - } - #[test] fn samples_are_written_in_the_device_format() { let f = |sample, channels, block_align| Format { @@ -716,15 +658,15 @@ pub(crate) mod tests { block_align, }; let mut b = [0xaau8; 8]; - f(Sample::I32, 1, 4).write(&mut b[..4], 1.0); - assert_eq!(b[..4], i32::MAX.to_le_bytes()); + f(Sample::I16, 1, 2).write(&mut b[..2], 1.0); + assert_eq!(b[..2], i16::MAX.to_le_bytes()); f(Sample::I16, 2, 4).write(&mut b[..4], -1.0); assert_eq!(b[..4], [0x01, 0x80, 0x01, 0x80]); - f(Sample::I24, 2, 8).write(&mut b, 0.5); + f(Sample::I16, 2, 8).write(&mut b, 0.5); assert_eq!( b, - [0xff, 0xff, 0x3f, 0xff, 0xff, 0x3f, 0, 0], - "two 24-bit samples and padding" + [0xff, 0x3f, 0xff, 0x3f, 0, 0, 0, 0], + "two 16-bit samples and padding" ); f(Sample::F32, 2, 8).write(&mut b, 2.0); assert_eq!(b[..4], 1.0f32.to_le_bytes(), "clamped"); @@ -796,8 +738,8 @@ pub(crate) mod tests { p.push(&[1, 2, 3]); } - /// 假的设备:和真的一样按时间取走数据,记下写进去的(单声道 44.1 kHz 32 位整数,和这台电脑上的 - /// Steam Streaming Microphone 一样) + /// 假的设备:和真的一样按时间取走数据,记下写进去的左声道(立体声 44.1 kHz 16 位:采样率、声道都和 + /// 收到的声音不一样) struct Fake { fmt: Format, written: Arc>>, @@ -824,7 +766,7 @@ pub(crate) mod tests { buf.as_chunks::<4>() .0 .iter() - .map(|s| i32::from_le_bytes(*s) as f32 / 2_147_483_648.0), + .map(|s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32_768.0), ); Ok(()) } @@ -832,18 +774,22 @@ pub(crate) mod tests { static FAKE_WRITTEN: LazyLock>>> = LazyLock::new(Arc::default); - fn open_fake() -> Result>> { - Ok(Some(Box::new(Fake { + fn fake(written: &Arc>>) -> Box { + Box::new(Fake { fmt: Format { - sample: Sample::I32, - channels: 1, + sample: Sample::I16, + channels: 2, rate: 44_100, block_align: 4, }, - written: FAKE_WRITTEN.clone(), + written: written.clone(), start: Instant::now(), done: 0, - }))) + }) + } + + fn open_fake() -> Result, Status>> { + Ok(Ok(fake(&FAKE_WRITTEN))) } /// 播放线程:包从队列来,解码、换成设备的采样率和格式写进去;写进去的还是 1 kHz(采样率换对了) @@ -853,7 +799,7 @@ pub(crate) mod tests { let stop = AtomicBool::new(false); let (status_tx, status) = watch::channel((MicState::Failed, None)); std::thread::scope(|s| { - let t = s.spawn(|| render(rx, &stop, &status_tx, open_fake, |_| unreachable!())); + let t = s.spawn(|| render(rx, &stop, &status_tx, open_fake)); // 和网络上一样每 20 ms 来一包 let start = Instant::now(); for (i, p) in tone_packets(40, 1000.0).into_iter().enumerate() { @@ -884,6 +830,65 @@ pub(crate) mod tests { ); } + static PREPARING_OPENS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + static PREPARED_WRITTEN: LazyLock>>> = LazyLock::new(Arc::default); + + /// 前两次还在准备(等系统发布录音设备),第三次打开 + fn open_when_prepared() -> Result, Status>> { + Ok(match PREPARING_OPENS.fetch_add(1, Ordering::Relaxed) { + 0 => Err(( + MicState::NoDriver, + Some("usbip-win2 is not installed".into()), + )), + 1 => Err((MicState::Preparing, None)), + _ => Ok(fake(&PREPARED_WRITTEN)), + }) + } + + /// 还打不开的时候告诉控制端为什么,过一会儿再试;在准备的很快再看,准备好了就开始写 + #[test] + fn the_render_loop_waits_until_the_device_is_ready() { + let (_tx, rx) = sync_channel(QUEUE); + let stop = AtomicBool::new(false); + let (status_tx, mut status) = watch::channel((MicState::Preparing, None)); + status.mark_unchanged(); + let start = Instant::now(); + let mut seen = Vec::new(); + std::thread::scope(|s| { + let t = s.spawn(|| render(rx, &stop, &status_tx, open_when_prepared)); + while seen.last().is_none_or(|x: &Status| x.0 != MicState::Ready) { + assert!(start.elapsed() < Duration::from_secs(5), "{seen:?}"); + if status.has_changed().unwrap() { + seen.push(status.borrow_and_update().clone()); + } + std::thread::sleep(Duration::from_millis(5)); + } + stop.store(true, Ordering::Release); + t.join().unwrap(); + }); + assert_eq!( + seen, + [ + ( + MicState::NoDriver, + Some("usbip-win2 is not installed".into()) + ), + (MicState::Preparing, None), + (MicState::Ready, None), + ] + ); + // 缺驱动的隔 REOPEN 再试,在准备的隔 PREPARING_POLL + let took = start.elapsed(); + assert!(took >= REOPEN + PREPARING_POLL, "{took:?}"); + assert!( + took < REOPEN + PREPARING_POLL + Duration::from_millis(500), + "{took:?}" + ); + // 没有声音的时候写静音 + let w = PREPARED_WRITTEN.lock().unwrap(); + assert!(!w.is_empty() && w.iter().all(|v| *v == 0.0)); + } + /// Real OS objects: force a publisher to exit without Drop, then run startup cleanup, /// release a normal lease, and exercise the uninstall hook while a second lease is live. #[cfg(any(target_os = "macos", target_os = "linux"))] @@ -921,7 +926,7 @@ pub(crate) mod tests { }; let input = Arc::new(MicInput::default()); let ready = || async { - let mut lease = super::open(7001, &input, (MicState::Ready, None)).unwrap(); + let mut lease = super::open(7001, &input).unwrap(); while lease.status().0 == MicState::Preparing { tokio::time::timeout(Duration::from_secs(5), lease.changed()) .await @@ -949,10 +954,7 @@ pub(crate) mod tests { let _live = ready().await; super::shutdown().unwrap(); objects(0); - assert_eq!( - super::open(7002, &input, (MicState::Ready, None)).err(), - Some(MicState::Unsupported) - ); + assert_eq!(super::open(7002, &input).err(), Some(MicState::Unsupported)); super::shutdown().unwrap(); } // Shutdown applies to the entire process. Keep the parent test runner usable. diff --git a/client/src-tauri/src/host/mic/native.rs b/client/src-tauri/src/host/mic/native.rs index 64d13e92..9299bfae 100644 --- a/client/src-tauri/src/host/mic/native.rs +++ b/client/src-tauri/src/host/mic/native.rs @@ -105,7 +105,7 @@ struct Device { scratch: Vec, } -pub(super) fn open() -> Result>> { +pub(super) fn open() -> Result> { let (uid, tap) = identifiers(); let mut error = [0; 256]; let name = if cfg!(test) { @@ -123,10 +123,10 @@ pub(super) fn open() -> Result>> { ) }; let handle = NonNull::new(ptr).ok_or_else(|| anyhow!(message(&error)))?; - Ok(Some(Box::new(Device { + Ok(Box::new(Device { handle, scratch: Vec::new(), - }))) + })) } impl Output for Device { diff --git a/client/src-tauri/src/host/mic/steam.rs b/client/src-tauri/src/host/mic/steam.rs deleted file mode 100644 index d8328d47..00000000 --- a/client/src-tauri/src/host/mic/steam.rs +++ /dev/null @@ -1,415 +0,0 @@ -//! 从本机 Steam 安装虚拟麦克风。Steam Client Service 通常已把驱动解包到 Common Files, -//! 刚装好的 Steam 也可能只有 bin/drivers.exe(带签名的自解压 ZIP)。这里只读取其中的麦克风驱动包。 - -use std::ffi::OsString; -use std::fs::File; -use std::io::{self, Read}; -use std::path::{Component, Path, PathBuf, Prefix}; -use std::time::{Duration, Instant}; - -use airhand_proto::session::MicState; -use anyhow::{Context, Result, bail, ensure}; -use windows::Win32::Devices::DeviceAndDriverInstallation::*; -use windows::Win32::Foundation::{ERROR_DEVINST_ALREADY_EXISTS, ERROR_NO_MORE_ITEMS}; -use windows::Win32::System::SystemInformation::{ - IMAGE_FILE_MACHINE_AMD64, IMAGE_FILE_MACHINE_ARM64, IMAGE_FILE_MACHINE_I386, -}; -use windows::Win32::System::Threading::{GetCurrentProcess, IsWow64Process2}; -use windows::core::{BOOL, HSTRING, Owned, PCWSTR, w}; -use winreg::{RegKey, enums::*}; -use zip::ZipArchive; - -use super::Status; -use crate::host::capture::wire_detail; - -const INF: &str = "SteamStreamingMicrophone.inf"; -const FILES: [&str; 3] = [ - INF, - "steamstreamingmicrophone.cat", - "SteamStreamingMicrophone.sys", -]; -const HARDWARE_ID: PCWSTR = w!(r"ROOT\SteamStreamingMicrophone"); -const INSTANCE: PCWSTR = w!(r"ROOT\SteamStreamingMicrophone\0000"); -const ENDPOINT_WAIT: Duration = Duration::from_secs(15); - -#[derive(Debug)] -enum Package { - Directory(PathBuf), - Archive(PathBuf, &'static str), -} - -fn native_arch() -> Result<&'static str> { - let mut native = Default::default(); - unsafe { - IsWow64Process2( - GetCurrentProcess(), - &mut Default::default(), - Some(&mut native), - )? - }; - match native { - IMAGE_FILE_MACHINE_AMD64 => Ok("x64"), - IMAGE_FILE_MACHINE_I386 => Ok("x86"), - IMAGE_FILE_MACHINE_ARM64 => Ok("arm64"), - _ => bail!("unsupported Windows driver architecture {:#x}", native.0), - } -} - -fn steam_roots() -> Vec { - const STEAM_KEY: &str = r"Software\Valve\Steam"; - let mut roots = Vec::new(); - let mut add = |hive, key: &str, view, name: &str| { - if let Ok(path) = RegKey::predef(hive) - .open_subkey_with_flags(key, KEY_READ | view) - .and_then(|key| key.get_value::(name)) - { - roots.push(PathBuf::from(path)); - } - }; - for view in [KEY_WOW64_32KEY, KEY_WOW64_64KEY] { - add(HKEY_LOCAL_MACHINE, STEAM_KEY, view, "InstallPath"); - } - if crate::winsvc::is_agent() { - // 服务的 HKCU 是 SYSTEM。登录用户的自定义 SteamPath 在其已加载的用户配置单元里。 - for sid in RegKey::predef(HKEY_USERS).enum_keys().flatten() { - if sid.starts_with("S-1-") && !sid.ends_with("_Classes") { - add(HKEY_USERS, &format!(r"{sid}\{STEAM_KEY}"), 0, "SteamPath"); - } - } - } else { - add(HKEY_CURRENT_USER, STEAM_KEY, 0, "SteamPath"); - } - roots.extend(steam_folders(["ProgramFiles(x86)", "ProgramFiles"])); - roots -} - -fn steam_folders(vars: [&str; 2]) -> impl Iterator { - vars.into_iter() - .filter_map(std::env::var_os) - .map(|p| PathBuf::from(p).join("Steam")) -} - -fn discover( - services: impl IntoIterator, - roots: Vec, -) -> Result> { - let mut bases = Vec::new(); - for service in services { - if service.join("SteamService.exe").try_exists()? { - bases.push(service); - } - } - for root in roots { - // 注册表里的路径可以由用户写入。只查本机磁盘上的 Steam,避免服务访问网络路径。 - if root.is_absolute() - && matches!(root.components().next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::Disk(_))) - && root.join("steam.exe").try_exists()? - { - bases.push(root.join("bin")); - bases.push(root); - } - } - if bases.is_empty() { - return Ok(None); - } - find_package(&bases, native_arch()?).map(Some) -} - -fn find_package(bases: &[PathBuf], arch: &'static str) -> Result { - for base in bases { - let dir = base.join("drivers").join("Windows10").join(arch); - if FILES.iter().all(|name| dir.join(name).is_file()) { - return Ok(Package::Directory(dir)); - } - } - for base in bases { - let archive = base.join("drivers.exe"); - if archive.is_file() { - return Ok(Package::Archive(archive, arch)); - } - } - bail!( - "Steam's microphone driver package is missing for {arch}. Open or update Steam on the host" - ) -} - -impl Package { - /// 固定输入和输出文件名,解压时限制实际写入的大小。安装使用这份临时副本,避免验证后源文件被替换。 - fn stage(&self, dest: &Path) -> Result { - let copy = |name: &str, reader: &mut dyn Read| -> Result<()> { - const MAX_FILE: u64 = 16 * 1024 * 1024; - let written = io::copy( - &mut reader.take(MAX_FILE + 1), - &mut File::create(dest.join(name))?, - )?; - ensure!( - written <= MAX_FILE, - "Steam microphone driver file {name} is too large" - ); - Ok(()) - }; - match self { - Self::Directory(dir) => { - for name in FILES { - copy(name, &mut File::open(dir.join(name))?)?; - } - } - Self::Archive(file, arch) => { - let mut archive = ZipArchive::new(File::open(file)?)?; - for name in FILES { - let path = format!("drivers/Windows10/{arch}/{name}"); - let mut entry = archive - .by_name(&path) - .with_context(|| format!("{path} is missing from Steam's drivers.exe"))?; - copy(name, &mut entry)?; - } - } - } - Ok(dest.join(INF)) - } - - fn install(self) -> Result<()> { - let dir = tempfile::Builder::new().prefix("airhand-mic-").tempdir()?; - let inf = self - .stage(dir.path()) - .context("reading Steam's microphone driver package")?; - let path = HSTRING::from(inf.as_path()); - verify_inf(&path)?; - install_device(&path) - } -} - -fn verify_inf(path: &HSTRING) -> Result<()> { - let mut signer = SP_INF_SIGNER_INFO_V2_W { - cbSize: size_of::() as u32, - ..Default::default() - }; - unsafe { SetupVerifyInfFileW(path, None, &mut signer).ok() } - .context("verifying Steam's microphone driver catalog") -} - -/// 新机器上还没有 ROOT 设备。使用 Steam INF 声明的固定实例名,重试时复用它。Windows 根据硬件 ID 绑定签名驱动。 -fn install_device(path: &HSTRING) -> Result<()> { - unsafe { - let devices = Owned::new(SetupDiCreateDeviceInfoList( - Some(&GUID_DEVCLASS_MEDIA), - None, - )?); - let mut data = SP_DEVINFO_DATA { - cbSize: size_of::() as u32, - ..Default::default() - }; - let created = match SetupDiCreateDeviceInfoW( - *devices, - INSTANCE, - &GUID_DEVCLASS_MEDIA, - PCWSTR::null(), - None, - Default::default(), - Some(&mut data), - ) { - Ok(()) => { - // SPDRP_HARDWAREID 是两个 NUL 结尾的 REG_MULTI_SZ。 - let ids: Vec = HARDWARE_ID - .as_wide() - .iter() - .copied() - .chain([0, 0]) - .flat_map(u16::to_le_bytes) - .collect(); - SetupDiSetDeviceRegistryPropertyW( - *devices, - &mut data, - SPDRP_HARDWAREID, - Some(&ids), - )?; - SetupDiCallClassInstaller(DIF_REGISTERDEVICE, *devices, Some(&data)) - .context("registering the Steam microphone (administrator rights required)")?; - true - } - Err(e) if e.code() == ERROR_DEVINST_ALREADY_EXISTS.to_hresult() => false, - Err(e) => return Err(e).context("creating the Steam microphone device"), - }; - let mut reboot = BOOL::default(); - if let Err(e) = UpdateDriverForPlugAndPlayDevicesW( - None, - HARDWARE_ID, - path, - INSTALLFLAG_NONINTERACTIVE, - Some(&mut reboot), - ) { - // 注册根设备时 PnP 可能已经从驱动存储绑定了同版或更新的驱动。保留它,等 WASAPI 端点出现。 - if e.code() == ERROR_NO_MORE_ITEMS.to_hresult() { - return Ok(()); - } - if created { - let _ = SetupDiCallClassInstaller(DIF_REMOVE, *devices, Some(&data)); - } - return Err(e) - .context("installing the Steam microphone driver (administrator rights required)"); - } - ensure!( - !reboot.as_bool(), - "Windows needs a restart to finish installing the Steam microphone" - ); - Ok(()) - } -} - -fn package() -> Result { - let services = steam_folders(["CommonProgramFiles(x86)", "CommonProgramFiles"]); - match discover(services, steam_roots()) { - Ok(Some(p)) => Ok(p), - Ok(None) => Err((MicState::SteamMissing, None)), - Err(e) => Err((MicState::SetupFailed, Some(wire_detail(&e)))), - } -} - -/// 被动探测只查位置。只有播放线程(用户打开了转发)才进入安装流程。 -pub(super) fn probe_missing() -> Status { - package().map_or_else(|status| status, |_| (MicState::NoDevice, None)) -} - -#[derive(Default)] -pub(super) struct DriverSetup { - /// 每次打开转发最多实际安装一次。设备出现后播放线程会直接打开它。 - attempt: Option>, -} - -impl DriverSetup { - pub(super) fn missing(&mut self, notify: &dyn Fn(Status)) -> Status { - self.try_install(package, Package::install, notify) - } - - fn try_install

( - &mut self, - find: impl FnOnce() -> Result, - install: impl FnOnce(P) -> Result<()>, - notify: &dyn Fn(Status), - ) -> Status { - if self.attempt.is_none() { - let package = match find() { - Ok(p) => p, - Err(status) => return status, - }; - notify((MicState::Preparing, None)); - tracing::info!("installing Steam Streaming Microphone"); - self.attempt = Some( - install(package) - .map(|()| Instant::now() + ENDPOINT_WAIT) - .map_err(|e| { - tracing::warn!("Steam microphone setup failed: {e:#}"); - wire_detail(&e) - }), - ); - } - match self.attempt.as_ref().unwrap() { - Ok(deadline) if Instant::now() < *deadline => (MicState::Preparing, None), - Ok(_) => ( - MicState::SetupFailed, - Some("Check that both Steam Streaming Microphone devices are enabled in Windows sound settings".into()), - ), - Err(detail) => (MicState::SetupFailed, Some(detail.clone())), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - use std::io::Write; - use zip::{ZipWriter, write::SimpleFileOptions}; - - #[test] - fn discovers_custom_steam_and_stages_only_the_native_microphone() -> Result<()> { - let temp = tempfile::tempdir()?; - let root = temp.path().join("Steam 客户端"); - let locate = || discover([], vec![root.clone()]); - assert!(locate()?.is_none()); // 注册表残留,但没有 Steam - fs::create_dir_all(root.join("bin"))?; - fs::write(root.join("steam.exe"), [])?; - assert!(locate().is_err()); // Steam 在,只是包还没到 - - let arch = native_arch()?; - let mut archive = ZipWriter::new(File::create(root.join("bin/drivers.exe"))?); - for name in FILES.into_iter().chain(["SteamStreamingSpeakers.inf"]) { - archive.start_file( - format!("drivers/Windows10/{arch}/{name}"), - SimpleFileOptions::default(), - )?; - archive.write_all(name.as_bytes())?; - } - drop(archive.finish()?); - let stage = tempfile::tempdir()?; - let inf = locate()?.unwrap().stage(stage.path())?; - assert_eq!(fs::read(&inf)?, INF.as_bytes()); - assert_eq!(fs::read_dir(stage.path())?.count(), FILES.len()); - assert!(verify_inf(&HSTRING::from(inf.as_path())).is_err()); - - let service = temp.path().join("Common Files/Steam"); - let unpacked = service.join("drivers/Windows10").join(arch); - fs::create_dir_all(&unpacked)?; - fs::write(service.join("SteamService.exe"), [])?; - for name in FILES { - fs::write(unpacked.join(name), [])?; - } - assert!( - matches!(discover([service], vec![root])?, Some(Package::Directory(dir)) if dir == unpacked) - ); - Ok(()) - } - - #[test] - fn opening_waits_for_steam_and_installs_once_per_activation() { - let mut setup = DriverSetup::default(); - let missing = (MicState::SteamMissing, None); - assert_eq!( - setup.try_install( - || Err::<(), _>(missing.clone()), - |_| unreachable!(), - &|_| unreachable!() - ), - missing - ); - let pending = (MicState::Preparing, None); - assert_eq!( - setup.try_install(|| Ok(()), |_| Ok(()), &|s| assert_eq!(s, pending)), - pending - ); - let poll = |setup: &mut DriverSetup| { - setup.try_install( - || -> Result<(), Status> { unreachable!() }, - |_| unreachable!(), - &|_| unreachable!(), - ) - }; - assert_eq!(poll(&mut setup), pending); - setup.attempt = Some(Ok(Instant::now())); - assert_eq!(poll(&mut setup).0, MicState::SetupFailed); - - let mut retry = DriverSetup::default(); - let failed = retry.try_install(|| Ok(()), |_| bail!("access denied"), &|s| { - assert_eq!(s, pending) - }); - assert_eq!( - failed, - (MicState::SetupFailed, Some("access denied".into())) - ); - assert_eq!(poll(&mut retry), failed); - } - - /// 在装了 Steam 的 Windows 上读取实际的自解压包并验证微软签名。 - #[test] - #[ignore] - fn verifies_local_steam_microphone_archive() -> Result<()> { - let archive = steam_roots() - .into_iter() - .map(|root| root.join("bin/drivers.exe")) - .find(|path| path.is_file()) - .context("Steam's drivers.exe")?; - let temp = tempfile::tempdir()?; - let inf = Package::Archive(archive, native_arch()?).stage(temp.path())?; - verify_inf(&HSTRING::from(inf.as_path())) - } -} diff --git a/client/src-tauri/src/host/mic/usb.rs b/client/src-tauri/src/host/mic/usb.rs new file mode 100644 index 00000000..e83b7714 --- /dev/null +++ b/client/src-tauri/src/host/mic/usb.rs @@ -0,0 +1,495 @@ +//! Windows 的虚拟麦克风:经 [airhand-dock](https://github.com/sqlpxc/airhand-dock) 和 usbip-win2 插上的一个 USB 麦克风 +//! (USB Audio Class 1.0,见 `airhand_dock::Microphone`),和控制端的手柄插在同一个 [`Dock`] 上(见 `crate::host::dock`)。 +//! Windows 用自带的 usbaudio.sys 驱动它,程序里看到的是录音设备"麦克风 (Airhand Microphone)":除了 usbip-win2 +//! (Airhand 的安装程序带着)不用装别的驱动,不要管理员权限,不用独占模式,也不改声音设置。 +//! +//! * 插上要几十毫秒,Windows 发布录音设备还要一秒左右。控制端打开麦克风时,播放线程插上它、等到录音设备 +//! 能用了才说能接([`open`],之前是 `Preparing`)。这台电脑第一次插上它时要等得久一些(见 [`FIRST_SETTLE`]); +//! * 拔掉的话,选了它的程序(会议软件)会换成别的麦克风:可能是这台电脑上真的麦克风!所以控制端关掉麦克风、切到别的 +//! 连接时都不拔,只是不往里写,它就是一个静音的麦克风。打开过麦克风的会话([`hold`])都结束了才拔: +//! 会话一结束([`release`],任务被中止了也算)开始等 [`KEEP`],这期间连回来接着用;正常结束的(控制端断开、 +//! 本机断开了它)不等,马上拔([`ended`]); +//! * 序列号固定:Windows 每次都认得是同一个设备,程序里的选择、默认录音设备的设置都还在; +//! * 插拔都会阻塞(拔掉要等系统放开设备,最多几秒),不在异步任务里做:插在播放线程里,拔在单独的线程里。 +//! 插、拔都拿着 [`DEVICE`] 的锁做,一个接一个。 + +use std::collections::BTreeSet; +use std::sync::{Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use airhand_dock::{BackendKind, Dock, ErrorKind, Microphone, MicrophoneConfig, Plugged}; +use airhand_proto::media::AUDIO_SAMPLE_RATE; +use airhand_proto::session::MicState; +use anyhow::{Result, bail}; +use tracing::{info, warn}; +use windows::Win32::Devices::DeviceAndDriverInstallation::{ + CM_LOCATE_DEVNODE_PHANTOM, CM_Locate_DevNodeW, CR_SUCCESS, +}; +use windows::core::HSTRING; + +use super::wasapi::{self, Endpoint}; +use super::{Format, Output, Sample, Status}; + +/// 录音设备的名字(USB 的产品名),程序里看到的是"麦克风 (Airhand Microphone)"。测试用另一个,不碰这台电脑上 +/// 正在用的那个 +pub(super) const NAME: &str = if cfg!(test) { + "Airhand Test Microphone" +} else { + "Airhand Microphone" +}; +/// USB 的厂商、产品 ID(airhand-dock 默认的那一对,Linux 的 USB 声卡 gadget 也用它)。和序列号一起就是 +/// Windows 认设备的依据:设备实例 `USB\VID_1D6B&PID_0101\<序列号>` +const VENDOR_ID: u16 = 0x1D6B; +const PRODUCT_ID: u16 = 0x0101; + +/// USB 序列号(见模块说明)。测试可以用 `AIRHAND_TEST_MIC_SERIAL` 换一个,当作这台电脑第一次插上它 +fn serial() -> String { + #[cfg(test)] + if let Ok(s) = std::env::var("AIRHAND_TEST_MIC_SERIAL") { + return s; + } + if cfg!(test) { + "AIRHANDTEST1" + } else { + "AIRHANDMIC1" + } + .into() +} + +/// 这台电脑第一次插上它时,录音设备要一直能用这么久才算好了:Windows 还在装这个设备,录音设备出现 +/// 一秒多之后会停用两秒左右再回来,这期间打开它的程序会断掉(这之后再插上就不会了) +const FIRST_SETTLE: Duration = Duration::from_secs(4); +/// 第一次插上时录音设备停用过又回来了(Windows 装好了):再能用这么久就算好了 +const SETTLED: Duration = Duration::from_millis(500); +/// 插不上(不是缺驱动)时过这么久再试:插一次最多要等十秒 +const RETRY: Duration = Duration::from_secs(5); +/// 插上之后录音设备这么久还没出现,就告诉控制端打不开(接着等) +const ENDPOINT_WAIT: Duration = Duration::from_secs(20); +/// 最后一个打开过麦克风的会话断掉(不是正常结束)之后,麦克风留这么久等它重连(和手柄一样) +const KEEP: Duration = crate::host::gamepad::KEEP; + +/// 写进去的格式:和收到的声音一样是 48 kHz 单声道,16 位是麦克风自己的格式 +const FORMAT: Format = Format { + sample: Sample::I16, + channels: 1, + rate: AUDIO_SAMPLE_RATE, + block_align: 2, +}; + +/// 插着的麦克风 +struct Device { + mic: Microphone, + /// 丢掉就是拔掉(会阻塞) + plugged: Plugged, + /// 什么时候插上的 + at: Instant, + /// 录音设备要一直能用多久才算好了:这台电脑认得的设备不用等,第一次插上的见 [`FIRST_SETTLE`] + settle: Duration, + /// 录音设备从什么时候起一直能用 + active_since: Option, +} + +struct Slot { + device: Option, + /// 上次插不上:告诉控制端的状态,这之前不再试 + failed: Option<(Status, Instant)>, +} + +/// 插拔的锁(见模块说明) +static DEVICE: Mutex = Mutex::new(Slot { + device: None, + failed: None, +}); + +fn slot() -> MutexGuard<'static, Slot> { + DEVICE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// 打开过麦克风、还没结束的会话 +struct Holders { + sessions: BTreeSet, + /// 每有一个会话打开麦克风加一:等着拔的线程据此知道这期间有没有会话用过它 + epoch: u64, + /// 最后结束的会话和那时的 `epoch`([`ended`] 据此认出它) + last: Option<(u64, u64)>, +} + +impl Holders { + const fn new() -> Self { + Self { + sessions: BTreeSet::new(), + epoch: 0, + last: None, + } + } + + fn hold(&mut self, session_id: u64) { + self.epoch += 1; + self.sessions.insert(session_id); + } + + /// 会话结束了:它是最后一个的话,返回现在的 `epoch`(该拔了) + fn release(&mut self, session_id: u64) -> Option { + if !(self.sessions.remove(&session_id) && self.sessions.is_empty()) { + return None; + } + self.last = Some((session_id, self.epoch)); + Some(self.epoch) + } + + /// 会话正常结束了:它是最后一个、之后也没有会话再打开过麦克风的话,返回它结束时的 `epoch` + fn ended(&self, session_id: u64) -> Option { + self.last + .filter(|&(s, epoch)| s == session_id && self.unused_since(epoch)) + .map(|(_, epoch)| epoch) + } + + /// 从 `epoch` 那时起没有会话再打开过麦克风 + fn unused_since(&self, epoch: u64) -> bool { + self.sessions.is_empty() && self.epoch == epoch + } +} + +static HOLDERS: Mutex = Mutex::new(Holders::new()); + +fn holders() -> MutexGuard<'static, Holders> { + HOLDERS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// airhand-dock 说的原因 → 告诉控制端的(和手柄一样:缺驱动的装好就能用,别的是出错了) +fn state(reason: Option) -> MicState { + match reason { + Some(ErrorKind::BackendUnavailable) => MicState::NoDriver, + _ => MicState::Failed, + } +} + +/// 能不能接(不插、没有副作用):装好了能用的 usbip-win2 就能接。会阻塞(要打开 usbip-win2 的设备) +pub(super) fn probe() -> Status { + let s = Dock::status(BackendKind::Auto); + if s.available { + (MicState::Ready, None) + } else { + (state(s.reason), s.problem) + } +} + +/// 会话 `session_id` 打开了麦克风:插上之后留到它结束(见模块说明) +pub(super) fn hold(session_id: u64) { + holders().hold(session_id); +} + +/// 会话结束了(丢掉它的 [`super::MicSession`] 时)。打开过麦克风的会话都结束了的话,过 [`KEEP`] 拔掉它 +/// (正常结束的会话接着由 [`ended`] 马上拔)。不阻塞 +pub(super) fn release(session_id: u64) { + if let Some(epoch) = holders().release(session_id) { + unplug_later(epoch, KEEP); + } +} + +/// 会话正常结束了(控制端断开、本机断开了它,在 [`release`] 之后):它是最后一个打开过麦克风的话,不等它重连, +/// 马上拔掉。不阻塞 +pub(super) fn ended(session_id: u64) { + if let Some(epoch) = holders().ended(session_id) { + unplug_later(epoch, Duration::ZERO); + } +} + +/// 在另一个线程上:等 `wait`,这期间没有会话再打开过麦克风的话拔掉它 +fn unplug_later(epoch: u64, wait: Duration) { + let spawned = std::thread::Builder::new() + .name("airhand-mic-unplug".into()) + .spawn(move || { + std::thread::sleep(wait); + unplug_unused(epoch); + }); + if let Err(e) = spawned { + warn!("can't start the thread that unplugs the virtual microphone: {e}"); + } +} + +/// 从 `epoch` 那时起没有会话再打开过麦克风的话,拔掉它 +fn unplug_unused(epoch: u64) { + let mut slot = slot(); + // 拿到插拔的锁之后再看:等着的时候可能又有会话打开了麦克风(它的播放线程可能正插着) + if !holders().unused_since(epoch) { + return; + } + slot.failed = None; + if let Some(d) = slot.device.take() { + info!("no session uses the virtual microphone any more, unplugging it"); + drop(d.plugged); + } +} + +/// 播放线程打开麦克风([`super::Opener`]):没插上就插上,等到 Windows 发布了它的录音设备 +pub(super) fn open() -> Result, Status>> { + let mut slot = slot(); + // 插着的断开了(usbip-win2 拔掉了它、被卸载了……):重新插 + if slot + .device + .as_ref() + .is_some_and(|d| !d.plugged.is_connected()) + { + warn!("the virtual microphone was unplugged, plugging it in again"); + slot.device = None; + } + if slot.device.is_none() { + if let Some((status, until)) = &slot.failed + && Instant::now() < *until + { + return Ok(Err(status.clone())); + } + // 会话在插上之前就都结束了(播放线程马上也会停下):不插,不然没人拔 + if holders().sessions.is_empty() { + return Ok(Err((MicState::Preparing, None))); + } + match plug() { + Ok(d) => { + info!(plugged = ?d.plugged, "plugged the virtual microphone"); + slot.failed = None; + slot.device = Some(d); + } + Err(e) => { + warn!("can't plug the virtual microphone: {e}"); + let status = (state(Some(e.kind())), Some(e.to_string())); + slot.failed = Some((status.clone(), Instant::now() + RETRY)); + return Ok(Err(status)); + } + } + } + let Some(d) = &mut slot.device else { + unreachable!("plugged above") + }; + let endpoint = wasapi::capture_endpoint(NAME)?; + if endpoint != Endpoint::Active { + d.active_since = None; + } + let waiting = d.at.elapsed() < ENDPOINT_WAIT; + match endpoint { + Endpoint::Active => { + let since = *d.active_since.get_or_insert_with(Instant::now); + if since.elapsed() < d.settle { + return Ok(Err((MicState::Preparing, None))); + } + Ok(Ok(Box::new(UsbOutput { + mic: d.mic.clone(), + bytes: Vec::new(), + samples: Vec::new(), + }))) + } + // 第一次插上,Windows 还在装它(见 FIRST_SETTLE) + Endpoint::Disabled if !d.settle.is_zero() && waiting => { + d.settle = SETTLED; + Ok(Err((MicState::Preparing, None))) + } + Endpoint::Disabled => bail!("{NAME} is disabled in the Windows sound settings"), + Endpoint::Missing if waiting => Ok(Err((MicState::Preparing, None))), + Endpoint::Missing => Ok(Err(( + MicState::Failed, + Some(format!("Windows hasn't set up {NAME} yet")), + ))), + } +} + +fn plug() -> airhand_dock::Result { + let serial = serial(); + let known = known(&serial); + let mic = Microphone::with_config( + MicrophoneConfig::default() + .ids(VENDOR_ID, PRODUCT_ID) + .manufacturer("Airhand") + .product(NAME) + .serial(serial), + )?; + let plugged = crate::host::dock::get()?.plug(&mic)?; + if !known { + info!("this computer hasn't seen the virtual microphone before, Windows is setting it up"); + } + Ok(Device { + mic, + plugged, + at: Instant::now(), + settle: if known { Duration::ZERO } else { FIRST_SETTLE }, + active_since: None, + }) +} + +/// 这台电脑以前插过序列号是 `serial` 的麦克风没有(PnP 里有它的设备实例,现在不在也算) +fn known(serial: &str) -> bool { + let id = HSTRING::from(format!( + r"USB\VID_{VENDOR_ID:04X}&PID_{PRODUCT_ID:04X}\{serial}" + )); + let mut node = 0u32; + unsafe { CM_Locate_DevNodeW(&mut node, &id, CM_LOCATE_DEVNODE_PHANTOM) == CR_SUCCESS } +} + +/// 往麦克风里写:它的队列按时间清空,不管有没有程序在录(见 `airhand_dock::Microphone`),排着的就是延迟 +struct UsbOutput { + mic: Microphone, + bytes: Vec, + samples: Vec, +} + +impl Output for UsbOutput { + fn format(&self) -> Format { + FORMAT + } + + fn buffered(&mut self) -> Result<(usize, usize)> { + if !self.mic.is_connected() { + bail!("{NAME} was unplugged"); + } + Ok((self.mic.queued(), self.mic.capacity())) + } + + fn write(&mut self, frames: usize, fill: &mut dyn FnMut(&mut [u8])) -> Result<()> { + self.bytes.resize(frames * FORMAT.block_align, 0); + fill(&mut self.bytes); + self.samples.clear(); + self.samples.extend( + self.bytes + .as_chunks::<2>() + .0 + .iter() + .map(|b| i16::from_le_bytes(*b)), + ); + self.mic.write(&self.samples); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 打开过麦克风的会话都结束了才拔;等着拔的期间有会话打开过的,不拔;正常结束的只有最后一个算数 + #[test] + fn unplugged_when_the_last_holder_ends() { + let mut h = Holders::new(); + h.hold(1); + h.hold(2); + h.hold(1); + assert_eq!(h.release(1), None, "session 2 still holds it"); + assert_eq!(h.ended(1), None, "not the last one"); + assert_eq!(h.release(3), None, "never held it"); + let epoch = h.release(2).unwrap(); + assert!(h.unused_since(epoch)); + assert_eq!(h.ended(2), Some(epoch)); + assert_eq!(h.release(2), None, "already released"); + // 断掉的会话在等它重连:连回来又打开了(还开着,或者又结束了) + h.hold(4); + assert!(!h.unused_since(epoch)); + assert_eq!(h.ended(2), None, "used again since"); + let later = h.release(4).unwrap(); + assert!(!h.unused_since(epoch), "a newer wait decides"); + assert!(h.unused_since(later)); + assert_eq!(h.ended(4), Some(later)); + } + + /// 真的插上虚拟麦克风(要装好 usbip-win2),像控制端那样每 20 ms 发一包 1 kHz 的声音,从它的录音设备录到的应该 + /// 还是 1 kHz。关掉麦克风之后它还插着,会话结束了才拔掉。 + /// `cargo test --lib mic_reaches_airhand_microphone -- --ignored --nocapture` + #[test] + #[ignore = "plugs a USB microphone through usbip-win2"] + fn mic_reaches_airhand_microphone() { + use crate::host::mic::wasapi::tests::Recorder; + use crate::host::mic::{MicInput, MicSession, open as open_mic, tests::goertzel}; + use airhand_link::host::MicSink; + use airhand_proto::media::{self, AudioHeader}; + use std::sync::Arc; + + let _ = tracing_subscriber::fmt() + .with_env_filter("debug") + .try_init(); + assert_eq!(probe().0, MicState::Ready, "{:?}", probe()); + let session = 7; + let held = MicSession::new(session); + let input = Arc::new(MicInput::default()); + let lease = open_mic(session, &input).expect("the microphone is free"); + // 插上,等 Windows 发布录音设备(第一次插上时还要装好设备) + let deadline = Instant::now() + Duration::from_secs(60); + while lease.status().0 != MicState::Ready { + assert!(Instant::now() < deadline, "{:?}", lease.status()); + std::thread::sleep(Duration::from_millis(50)); + } + let took = slot().device.as_ref().map(|d| d.at.elapsed()); + println!("ready {took:?} after plugging"); + assert!(known(&serial()), "Windows knows it from now on"); + let mut rec = Recorder::open().expect("record from the virtual microphone"); + let mut enc = opus::Encoder::new( + AUDIO_SAMPLE_RATE, + opus::Channels::Mono, + opus::Application::Voip, + ) + .unwrap(); + let mut phase = 0f64; + let mut opus_buf = vec![0u8; 1000]; + let mut recorded = Vec::new(); + let start = Instant::now(); + for seq in 1..=100u32 { + let at = start + Duration::from_millis(20 * (seq as u64 - 1)); + std::thread::sleep(at.saturating_duration_since(Instant::now())); + let pcm: Vec = (0..960) + .map(|_| { + let v = phase.sin() as f32 * 0.5; + phase += 2.0 * std::f64::consts::PI * 1000.0 / AUDIO_SAMPLE_RATE as f64; + v + }) + .collect(); + let len = enc.encode_float(&pcm, &mut opus_buf).unwrap(); + let h = AudioHeader { + seq, + start: seq == 1, + capture_us: seq as u64 * 20_000, + }; + input.packet(media::frame(&h.encode(), &[&opus_buf[..len]])[4..].to_vec()); + rec.read(&mut recorded).unwrap(); + } + std::thread::sleep(Duration::from_millis(200)); + rec.read(&mut recorded).unwrap(); + assert_eq!(lease.status().0, MicState::Ready, "{:?}", lease.status()); + let voice: Vec = recorded + .iter() + .copied() + .skip_while(|v| v.abs() < 0.05) + .collect(); + let secs = voice.len() as f64 / AUDIO_SAMPLE_RATE as f64; + let windows: Vec = voice + .chunks(480) + .take(150) + .map(|w| (w.iter().map(|v| v * v).sum::() / w.len() as f32).sqrt()) + .collect(); + let quiet = windows.iter().filter(|r| **r < 0.1).count(); + let at = |f| goertzel(&voice, AUDIO_SAMPLE_RATE as f64, f); + let (tone, others) = (at(1000.0), [at(500.0), at(918.0), at(1088.0)]); + println!( + "recorded {secs:.2} s of voice, {quiet} quiet 10 ms windows: 1 kHz {tone:.3}, \ + 500/918/1088 Hz {others:.4?}" + ); + assert!(secs > 1.0, "too little voice came out of the microphone"); + assert!(quiet <= 3, "the voice broke up"); + assert!(tone > 0.15, "too quiet: {tone}"); + assert!( + others.iter().all(|o| tone > o * 20.0), + "the voice came out at the wrong pitch" + ); + drop(rec); + + // 关掉:还插着(一个静音的麦克风),选了它的程序不会换成别的麦克风 + drop(lease); + std::thread::sleep(Duration::from_millis(500)); + assert_eq!(wasapi::capture_endpoint(NAME).unwrap(), Endpoint::Active); + // 会话结束了:断掉的会等它重连,正常结束的马上拔掉 + drop(held); + std::thread::sleep(Duration::from_millis(500)); + assert_eq!(wasapi::capture_endpoint(NAME).unwrap(), Endpoint::Active); + super::super::ended(session, true); + let deadline = Instant::now() + Duration::from_secs(10); + while wasapi::capture_endpoint(NAME).unwrap() != Endpoint::Missing { + assert!(Instant::now() < deadline, "still plugged"); + std::thread::sleep(Duration::from_millis(50)); + } + assert!(slot().device.is_none()); + } +} diff --git a/client/src-tauri/src/host/mic/wasapi.rs b/client/src-tauri/src/host/mic/wasapi.rs index 48c70ee0..8c72b88f 100644 --- a/client/src-tauri/src/host/mic/wasapi.rs +++ b/client/src-tauri/src/host/mic/wasapi.rs @@ -1,148 +1,94 @@ -//! Windows 的虚拟麦克风:Steam Streaming Microphone(Steam 远程同乐的虚拟声卡驱动,Valve 的、微软签过名的)。 +//! Windows 的录音设备(WASAPI 的端点)。虚拟麦克风(见 [`super::usb`])插上之后,Windows 过一会儿才发布它的录音设备; +//! 用户也可能在声音设置里停用了它。 //! -//! 它有一对设备:播放设备"扬声器 (Steam Streaming Microphone)"和录音设备"麦克风 (Steam Streaming Microphone)", -//! 写进播放设备的字节**原样**从录音设备出来。驱动不换格式,所以两边的格式必须一样,否则录到的声音会变调 -//! (实测播放端 48 kHz 立体声、录音端 44.1 kHz 单声道时,1 kHz 的声音录出来是 459 Hz = 1000 × 44100 / 96000): -//! -//! * 两个设备的设备格式(声音设置里的"默认格式")一样:共享模式,系统把声音换成那个格式; -//! * 不一样(这台电脑上就是):独占模式,直接按录音端的格式写进播放端。不改系统的声音设置, -//! 独占的只是这个虚拟设备,而且只在控制端打开麦克风期间(Steam 远程同乐这时用不了它)。 -//! -//! 设备按接口名("Steam Streaming Microphone")找,不按显示名:显示名前面的"扬声器""麦克风"随系统语言变。 -//! 两个端点都可用才算就绪,缺少端点时由 [`super::steam`] 检查驱动来源。 +//! 按接口名找(`PKEY_DeviceInterface_FriendlyName`,USB 麦克风的就是它的产品名),不按显示名:显示名前面的"麦克风" +//! 随系统语言变。 -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result}; use windows::Win32::Foundation::PROPERTYKEY; use windows::Win32::Media::Audio::*; use windows::Win32::System::Com::StructuredStorage::PropVariantClear; use windows::Win32::System::Com::{ CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, STGM_READ, }; -use windows::Win32::System::Variant::{VT_BLOB, VT_LPWSTR}; +use windows::Win32::System::Variant::VT_LPWSTR; use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore; use windows::core::GUID; -use airhand_proto::media::AUDIO_SAMPLE_RATE; -use airhand_proto::session::MicState; - -use super::{Format, Output, Sample, Status, steam}; - /// 设备的接口名(`PKEY_DeviceInterface_FriendlyName`,不随系统语言变) -const STEAM_MIC: &str = "Steam Streaming Microphone"; const PKEY_DEVICE_INTERFACE_FRIENDLY_NAME: PROPERTYKEY = PROPERTYKEY { fmtid: GUID::from_u128(0x026e516e_b814_414b_83cd_856d6fef4822), pid: 2, }; -/// 共享模式的缓冲:100 ms -const SHARED_BUFFER_HNS: i64 = 1_000_000; -/// 独占模式的缓冲:40 ms(写得越多延迟越大,播放线程每 5 ms 补一次) -const EXCLUSIVE_BUFFER_HNS: i64 = 400_000; -/// 找到的一对设备 -struct Pair { - render: IMMDevice, - /// 两边的设备格式(`WAVEFORMATEX` 的字节) - render_format: Vec, - capture_format: Vec, -} - -/// 有没有 Steam Streaming Microphone(不打开) -pub fn probe() -> Status { - match find() { - Ok(Some(_)) => (MicState::Ready, None), - Ok(None) => steam::probe_missing(), - Err(e) => { - tracing::warn!("can't look for the virtual microphone: {e:#}"); - ( - MicState::Failed, - Some(crate::host::capture::wire_detail(&e)), - ) - } - } +/// 一个录音设备现在怎么样 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Endpoint { + /// 程序可以选它录音 + Active, + /// 在声音设置里停用了 + Disabled, + /// 没有(还没发布、拔掉了) + Missing, } -/// 打开播放端(见模块说明:两边格式一样用共享模式,不一样用独占模式按录音端的格式写) -pub fn open() -> Result>> { - let Some(pair) = find()? else { - return Ok(None); - }; - let capture = Format::parse(&pair.capture_format).context("the microphone's format")?; - let render = Format::parse(&pair.render_format).context("the speaker side's format")?; - let same = render.sample == capture.sample - && render.channels == capture.channels - && render.rate == capture.rate; +/// 接口名是 `name` 的录音设备现在怎么样 +pub(crate) fn capture_endpoint(name: &str) -> Result { unsafe { - let out = if same { - shared(&pair.render)? - } else { - exclusive(&pair.render, &pair.capture_format, capture)? - }; - out.client.Start()?; - tracing::info!( - shared = same, - ?render, - ?capture, - "writing into Steam Streaming Microphone" - ); - Ok(Some(Box::new(out))) + let en = enumerator()?; + Ok(match find_capture(&en, name)? { + None => Endpoint::Missing, + Some(d) if d.GetState()? == DEVICE_STATE_ACTIVE => Endpoint::Active, + Some(_) => Endpoint::Disabled, + }) } } -fn find() -> Result> { +unsafe fn enumerator() -> Result { unsafe { // 每个线程都要初始化 COM(重复调用没关系) let _ = CoInitializeEx(None, COINIT_MULTITHREADED); - let en: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) - .context("can't create MMDeviceEnumerator")?; - let (Some((render, render_format)), Some((_, capture_format))) = - (find_flow(&en, eRender)?, find_flow(&en, eCapture)?) - else { - return Ok(None); - }; - Ok(Some(Pair { - render, - render_format, - capture_format, - })) + CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) + .context("can't create MMDeviceEnumerator") } } -/// 一个方向上的 Steam Streaming Microphone 和它的设备格式 -unsafe fn find_flow( - en: &IMMDeviceEnumerator, - flow: EDataFlow, -) -> Result)>> { +/// 接口名是 `name` 的录音设备:用着的优先,其次是停用了的 +unsafe fn find_capture(en: &IMMDeviceEnumerator, name: &str) -> Result> { unsafe { let all = en.EnumAudioEndpoints( - flow, + eCapture, DEVICE_STATE(DEVICE_STATE_ACTIVE.0 | DEVICE_STATE_DISABLED.0), )?; - let mut disabled = false; + let mut disabled = None; for i in 0..all.GetCount()? { let Ok(device) = all.Item(i) else { continue }; let Ok(store) = device.OpenPropertyStore(STGM_READ) else { continue; }; - if string_prop(&store, &PKEY_DEVICE_INTERFACE_FRIENDLY_NAME).as_deref() - != Some(STEAM_MIC) + if !string_prop(&store, &PKEY_DEVICE_INTERFACE_FRIENDLY_NAME) + .is_some_and(|n| same_name(&n, name)) { continue; } - if device.GetState()? == DEVICE_STATE_DISABLED { - disabled = true; - continue; + if device.GetState()? == DEVICE_STATE_ACTIVE { + return Ok(Some(device)); } - let format = blob_prop(&store, &PKEY_AudioEngine_DeviceFormat) - .context("Steam Streaming Microphone has no device format")?; - return Ok(Some((device, format))); - } - if disabled { - bail!("Enable both Steam Streaming Microphone devices in Windows sound settings"); + disabled = Some(device); } - Ok(None) + Ok(disabled) } } +/// `found` 是不是 `name`:Windows 给重名的设备加上"2- "这样的前缀 +fn same_name(found: &str, name: &str) -> bool { + found == name + || found + .strip_suffix(name) + .and_then(|p| p.strip_suffix("- ")) + .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + unsafe fn string_prop(store: &IPropertyStore, key: &PROPERTYKEY) -> Option { unsafe { let mut v = store.GetValue(key).ok()?; @@ -154,154 +100,24 @@ unsafe fn string_prop(store: &IPropertyStore, key: &PROPERTYKEY) -> Option Option> { - unsafe { - let mut v = store.GetValue(key).ok()?; - let b = (v.Anonymous.Anonymous.vt == VT_BLOB).then(|| { - let blob = &v.Anonymous.Anonymous.Anonymous.blob; - if blob.pBlobData.is_null() { - Vec::new() - } else { - std::slice::from_raw_parts(blob.pBlobData, blob.cbSize as usize).to_vec() - } - }); - let _ = PropVariantClear(&mut v); - b.filter(|b| !b.is_empty()) - } -} - -/// 写进播放端 -struct Wasapi { - client: IAudioClient, - render: IAudioRenderClient, - /// 缓冲多少帧 - size: u32, - fmt: Format, -} - -/// 共享模式:交给系统的是 48 kHz 单声道 float,系统换成设备格式 -unsafe fn shared(device: &IMMDevice) -> Result { - unsafe { - let fmt = Format { - sample: Sample::F32, - channels: 1, - rate: AUDIO_SAMPLE_RATE, - block_align: 4, - }; - let wave = WAVEFORMATEX { - wFormatTag: 3, // WAVE_FORMAT_IEEE_FLOAT - nChannels: 1, - nSamplesPerSec: AUDIO_SAMPLE_RATE, - nAvgBytesPerSec: AUDIO_SAMPLE_RATE * 4, - nBlockAlign: 4, - wBitsPerSample: 32, - cbSize: 0, - }; - let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?; - client - .Initialize( - AUDCLNT_SHAREMODE_SHARED, - AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, - SHARED_BUFFER_HNS, - 0, - &wave, - None, - ) - .context("can't open Steam Streaming Microphone (shared)")?; - finish(client, fmt) - } -} - -/// 独占模式:按录音端的设备格式(`wave`,解析出来是 `fmt`)直接写进播放端 -unsafe fn exclusive(device: &IMMDevice, wave: &[u8], fmt: Format) -> Result { - unsafe { - let ptr = wave.as_ptr().cast::(); - let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?; - let client = match client.Initialize( - AUDCLNT_SHAREMODE_EXCLUSIVE, - 0, - EXCLUSIVE_BUFFER_HNS, - 0, - ptr, - None, - ) { - Ok(()) => client, - // 缓冲的大小要对齐到设备的要求:按它给的大小重新来一次(初始化失败的 IAudioClient 不能再用) - Err(e) if e.code() == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED => { - let frames = client.GetBufferSize()?; - let hns = (10_000_000.0 * frames as f64 / fmt.rate as f64).round() as i64; - let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?; - client.Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0, hns, 0, ptr, None)?; - client - } - Err(e) if e.code() == AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED => bail!( - "exclusive mode is turned off for Steam Streaming Microphone: allow it in the sound settings, \ - or give its speaker and microphone sides the same default format ({e})" - ), - Err(e) if e.code() == AUDCLNT_E_DEVICE_IN_USE => { - bail!( - "Steam Streaming Microphone is in use by another program (Steam Remote Play?): {e}" - ) - } - Err(e) => return Err(e).context("can't open Steam Streaming Microphone (exclusive)"), - }; - finish(client, fmt) - } -} - -unsafe fn finish(client: IAudioClient, fmt: Format) -> Result { - unsafe { - let size = client.GetBufferSize()?; - tracing::debug!(frames = size, rate = fmt.rate, "virtual microphone buffer"); - let render: IAudioRenderClient = client.GetService()?; - Ok(Wasapi { - client, - render, - size, - fmt, - }) - } -} - -impl Output for Wasapi { - fn format(&self) -> Format { - self.fmt - } - - fn buffered(&mut self) -> Result<(usize, usize)> { - let padding = unsafe { self.client.GetCurrentPadding()? }; - Ok((padding as usize, self.size as usize)) - } - - fn write(&mut self, frames: usize, fill: &mut dyn FnMut(&mut [u8])) -> Result<()> { - unsafe { - let p = self.render.GetBuffer(frames as u32)?; - let buf = std::slice::from_raw_parts_mut(p, frames * self.fmt.block_align); - fill(buf); - self.render.ReleaseBuffer(frames as u32, 0)?; - } - Ok(()) - } -} - -impl Drop for Wasapi { - fn drop(&mut self) { - unsafe { - let _ = self.client.Stop(); - } - } -} - #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::host::mic::{MicInput, open as open_mic, tests::goertzel}; - use airhand_link::host::MicSink; - use airhand_proto::media::{self, AudioHeader}; - use std::sync::Arc; - use std::time::{Duration, Instant}; + use airhand_proto::media::AUDIO_SAMPLE_RATE; - /// 从"麦克风 (Steam Streaming Microphone)"录音(共享模式,系统换成 48 kHz 单声道 float),像本机的程序那样 + #[test] + fn names_with_a_number_from_windows_match() { + let name = "Airhand Microphone"; + assert!(same_name("Airhand Microphone", name)); + assert!(same_name("2- Airhand Microphone", name)); + assert!(same_name("12- Airhand Microphone", name)); + assert!(!same_name("- Airhand Microphone", name)); + assert!(!same_name("My Airhand Microphone", name)); + assert!(!same_name("x- Airhand Microphone", name)); + assert!(!same_name("Airhand Microphone 2", name)); + } + + /// 从虚拟麦克风的录音设备录音(共享模式,系统换成 48 kHz 单声道 float),像本机的程序那样 pub(crate) struct Recorder { client: IAudioClient, capture: IAudioCaptureClient, @@ -310,14 +126,13 @@ pub(crate) mod tests { impl Recorder { pub(crate) fn open() -> Result { unsafe { - let _ = CoInitializeEx(None, COINIT_MULTITHREADED); - let en: IMMDeviceEnumerator = - CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?; - let (device, _) = - find_flow(&en, eCapture)?.context("no Steam Streaming Microphone")?; + let name = crate::host::mic::usb::NAME; + let device = find_capture(&enumerator()?, name)? + .filter(|d| d.GetState().ok() == Some(DEVICE_STATE_ACTIVE)) + .with_context(|| format!("no recording device named {name}"))?; let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?; let wave = WAVEFORMATEX { - wFormatTag: 3, + wFormatTag: 3, // WAVE_FORMAT_IEEE_FLOAT nChannels: 1, nSamplesPerSec: AUDIO_SAMPLE_RATE, nAvgBytesPerSec: AUDIO_SAMPLE_RATE * 4, @@ -365,75 +180,4 @@ pub(crate) mod tests { } } } - - /// 需要这台电脑上有可用的 Steam Streaming Microphone。 - /// 像控制端那样每 20 ms 发一包 1 kHz 的声音,从"麦克风 (Steam Streaming Microphone)"录到的应该还是 1 kHz: - /// 设备的格式对不上的话会变调(见模块说明)。 - /// `cargo test --lib mic_reaches_steam_streaming_microphone -- --ignored --nocapture` - #[test] - #[ignore] - fn mic_reaches_steam_streaming_microphone() { - let _ = tracing_subscriber::fmt() - .with_env_filter("debug") - .try_init(); - assert_eq!( - probe().0, - MicState::Ready, - "no Steam Streaming Microphone on this computer" - ); - let input = Arc::new(MicInput::default()); - let lease = open_mic(7, &input, (MicState::Ready, None)).expect("the microphone is free"); - let mut rec = Recorder::open().expect("record from Steam Streaming Microphone"); - let mut enc = opus::Encoder::new( - AUDIO_SAMPLE_RATE, - opus::Channels::Mono, - opus::Application::Voip, - ) - .unwrap(); - let mut phase = 0f64; - let mut opus_buf = vec![0u8; 1000]; - let mut recorded = Vec::new(); - let start = Instant::now(); - for seq in 1..=100u32 { - let at = start + Duration::from_millis(20 * (seq as u64 - 1)); - std::thread::sleep(at.saturating_duration_since(Instant::now())); - let pcm: Vec = (0..960) - .map(|_| { - let v = phase.sin() as f32 * 0.5; - phase += 2.0 * std::f64::consts::PI * 1000.0 / AUDIO_SAMPLE_RATE as f64; - v - }) - .collect(); - let len = enc.encode_float(&pcm, &mut opus_buf).unwrap(); - let h = AudioHeader { - seq, - start: seq == 1, - capture_us: seq as u64 * 20_000, - }; - input.packet(media::frame(&h.encode(), &[&opus_buf[..len]])[4..].to_vec()); - rec.read(&mut recorded).unwrap(); - } - std::thread::sleep(Duration::from_millis(200)); - rec.read(&mut recorded).unwrap(); - println!("status: {:?}", lease.status()); - assert_eq!(lease.status().0, MicState::Ready, "{:?}", lease.status()); - let voice: Vec = recorded - .iter() - .copied() - .skip_while(|v| v.abs() < 0.05) - .collect(); - let secs = voice.len() as f64 / AUDIO_SAMPLE_RATE as f64; - let at = |f| goertzel(&voice, AUDIO_SAMPLE_RATE as f64, f); - let (tone, others) = (at(1000.0), [at(459.0), at(500.0), at(918.0), at(1088.0)]); - println!( - "recorded {secs:.2} s of voice: 1 kHz {tone:.3}, 459/500/918/1088 Hz {others:.4?}" - ); - assert!(secs > 1.0, "too little voice came out of the microphone"); - assert!( - others.iter().all(|o| tone > o * 20.0), - "the voice came out at the wrong pitch" - ); - drop(rec); - drop(lease); - } } diff --git a/client/src-tauri/src/host/mod.rs b/client/src-tauri/src/host/mod.rs index e73352b3..70358bda 100644 --- a/client/src-tauri/src/host/mod.rs +++ b/client/src-tauri/src/host/mod.rs @@ -6,6 +6,8 @@ pub(crate) mod clock; mod cursor; #[cfg(windows)] pub(crate) mod desktop; +#[cfg(any(windows, target_os = "linux"))] +pub(crate) mod dock; pub mod encoder; pub(crate) mod ending; pub(crate) mod gamepad; diff --git a/client/src-tauri/src/host/session.rs b/client/src-tauri/src/host/session.rs index 35d8de7f..77278312 100644 --- a/client/src-tauri/src/host/session.rs +++ b/client/src-tauri/src/host/session.rs @@ -41,7 +41,7 @@ use super::ending; use super::gamepad::{self, Gamepads}; use super::gate::DesktopGate; use super::input::InjectorThread; -use super::mic::{self, MicInput, MicLease}; +use super::mic::{self, MicInput, MicLease, MicSession}; use super::pipeline::{self, Pipeline}; use super::power::{self, Awake}; use super::virtual_display::{self, Lease, Privacy}; @@ -65,7 +65,7 @@ pub(super) const PLATFORM: airhand_proto::session::Platform = const PERMISSION_CHECK: Duration = Duration::from_secs(2); /// 检查显示器有没有变化(插拔、旋转、改分辨率 / 缩放 / 排列)的间隔 const DISPLAY_CHECK: Duration = Duration::from_secs(2); -/// 没有虚拟麦克风(或者打不开)时隔多久再找一次,例如对方刚装好 Steam +/// 没有虚拟麦克风(或者打不开)时隔多久再找一次,例如对方刚装好 usbip-win2 const MIC_CHECK: Duration = Duration::from_secs(5); /// macOS:会话开始时列不出显示器(睡着了)的话,叫醒它之后最多等这么久 const WAKE_WAIT: Duration = Duration::from_secs(3); @@ -208,8 +208,9 @@ pub async fn run(inc: Incoming, gate: Arc) -> Result<()> { // 控制端断开了、本机断开了它(`Ok`):远程控制马上算结束;失联、连接出错:等它重连(见 ending)。 // 任务在这之前被中止了的(与服务器的连接断了)也算出错 presence.end(result.is_ok()); - // 手柄也一样:正常结束的马上拔掉,断掉的等它重连(见 gamepad) + // 手柄也一样:正常结束的马上拔掉,断掉的等它重连(见 gamepad);Windows 的虚拟麦克风也是(见 mic) gamepad::ended(session_id, result.is_ok()); + mic::ended(session_id, result.is_ok()); result } @@ -293,6 +294,8 @@ struct Mic { owner: watch::Receiver>, /// 没有设备、打不开时定时再看看 tick: Interval, + /// 丢掉时(会话结束)这个会话不再占着虚拟麦克风:都不占着了就收起来(见 [`MicSession`]) + _session: MicSession, } impl Mic { @@ -301,19 +304,9 @@ impl Mic { mic::supported() && self.lease.is_none() } - /// 现在用不了是因为设备(没有、打不开):定时再找 + /// 现在用不了是因为设备(缺驱动、打不开):定时再找 fn missing(&self) -> bool { - self.waiting() - && matches!( - self.sent, - Some(( - MicState::NoDevice - | MicState::Failed - | MicState::SteamMissing - | MicState::SetupFailed, - _ - )) - ) + self.waiting() && matches!(self.sent, Some((MicState::NoDriver | MicState::Failed, _))) } } @@ -377,6 +370,7 @@ impl Desktop { sent: None, owner: mic::owner_changed(), tick: ticker(MIC_CHECK), + _session: MicSession::new(session_id), }, privacy_changes: screens.privacy_changes(), display_changes: screens.display_changes(), @@ -438,8 +432,7 @@ impl Desktop { /// 控制端要开着麦克风:轮到这个会话了就打开,不然告诉它为什么开不了 fn open_mic(&mut self) -> Result<()> { - let initial = self.mic.sent.clone().unwrap_or((MicState::Preparing, None)); - let status = match mic::open(self.session_id, &self.mic.input, initial) { + let status = match mic::open(self.session_id, &self.mic.input) { Ok(lease) => { let s = lease.status(); self.mic.lease = Some(lease); diff --git a/client/src-tauri/windows/hooks.nsh b/client/src-tauri/windows/hooks.nsh index 1b0bfd8d..8960036a 100644 --- a/client/src-tauri/windows/hooks.nsh +++ b/client/src-tauri/windows/hooks.nsh @@ -46,8 +46,8 @@ ; 防窥撤下的显示器放回去。模板自己的确认页上加不了勾选框(它的 un.ConfirmShow 画了"删除应用程序数据"), ; 这个文件又在模板声明页面之前引入,所以这一页排在确认页前面。 ; -; 手柄驱动 usbip-win2(它自己的安装程序,打包前由 scripts/fetch-usbip-win2.mjs 下载到 windows/usbip/,见那里的 README.md): -; 控制端的手柄插到这台电脑上要用它(src/host/gamepad.rs)。两种安装方式都能用(装好之后不要管理员权限): +; 手柄和麦克风的驱动 usbip-win2(它自己的安装程序,打包前由 scripts/fetch-usbip-win2.mjs 下载到 windows/usbip/,见那里的 README.md): +; 控制端的手柄、麦克风插到这台电脑上要用它(src/host/gamepad.rs、src/host/mic/usb.rs)。两种安装方式都能用(装好之后不要管理员权限): ; * 这台电脑没装、是 x64 的 Windows 10 1903 以上:交互安装时问一次(不记住答案:当时没装的话,重新运行安装程序还会问, ; 这就是以后再装的办法)。静默、被动安装(自动更新)不问不装,命令行里有 /USBIP 就不问直接装; ; * 装的时候解压到临时目录,很安静地运行它(只装驱动和命令行工具,不重启)。它要管理员权限:安装程序没有提升权限时 @@ -133,13 +133,13 @@ LangString AirhandVddPageText 1033 "The virtual display driver (Virtual Display LangString AirhandVddRemove 2052 "同时删除虚拟显示器驱动" LangString AirhandVddRemove 1033 "Also remove the virtual display driver" -; 手柄驱动 usbip-win2(见文件开头) -LangString AirhandAskUsbip 2052 "要安装手柄驱动 usbip-win2 吗?$\r$\n$\r$\n装上之后,控制端接着的手柄(电脑、手机、平板上的)和手机屏幕上的虚拟手柄可以作为 Xbox 360 手柄插到这台电脑上玩游戏,游戏也能让手柄震动。$\r$\n$\r$\nusbip-win2 是免费的开源 USB/IP 驱动(BSD 许可,有微软的签名),随安装包带着,作为单独的程序装上,以后可以在$\"设置 → 应用$\"里卸载。安装时这台电脑的 USB 设备(键盘、鼠标等)会断开一两秒再恢复;usbip-win2 建议装好后重新启动一次电脑。$\r$\n$\r$\n现在不装的话,以后重新运行 Airhand 的安装程序会再问。" -LangString AirhandAskUsbip 1033 "Install the gamepad driver usbip-win2?$\r$\n$\r$\nWith it, gamepads on the controller's side (on a computer, phone or tablet) and the on-screen gamepad of the phone app are plugged into this computer as Xbox 360 controllers for games, and games can make them vibrate.$\r$\n$\r$\nusbip-win2 is a free, open-source USB/IP driver (BSD license, signed by Microsoft). It's shipped with this installer and installed as a separate program, which you can remove under Settings → Apps. While it installs, this computer's USB devices (keyboard, mouse…) disconnect for a second or two; usbip-win2 recommends restarting the computer afterwards.$\r$\n$\r$\nIf you skip it now, running the Airhand installer again asks again." +; 手柄和麦克风的驱动 usbip-win2(见文件开头) +LangString AirhandAskUsbip 2052 "要安装手柄和麦克风的驱动 usbip-win2 吗?$\r$\n$\r$\n装上之后,控制端接着的手柄(电脑、手机、平板上的)和手机屏幕上的虚拟手柄可以作为 Xbox 360 手柄插到这台电脑上玩游戏,游戏也能让手柄震动;控制端的麦克风也能作为录音设备 Airhand Microphone 插到这台电脑上,供会议软件和语音输入使用。$\r$\n$\r$\nusbip-win2 是免费的开源 USB/IP 驱动(BSD 许可,有微软的签名),随安装包带着,作为单独的程序装上,以后可以在$\"设置 → 应用$\"里卸载。安装时这台电脑的 USB 设备(键盘、鼠标等)会断开一两秒再恢复;usbip-win2 建议装好后重新启动一次电脑。$\r$\n$\r$\n现在不装的话,以后重新运行 Airhand 的安装程序会再问。" +LangString AirhandAskUsbip 1033 "Install the gamepad and microphone driver usbip-win2?$\r$\n$\r$\nWith it, gamepads on the controller's side (on a computer, phone or tablet) and the on-screen gamepad of the phone app are plugged into this computer as Xbox 360 controllers for games, and games can make them vibrate; the controller's microphone is plugged in as the recording device Airhand Microphone, for meeting apps and voice typing.$\r$\n$\r$\nusbip-win2 is a free, open-source USB/IP driver (BSD license, signed by Microsoft). It's shipped with this installer and installed as a separate program, which you can remove under Settings → Apps. While it installs, this computer's USB devices (keyboard, mouse…) disconnect for a second or two; usbip-win2 recommends restarting the computer afterwards.$\r$\n$\r$\nIf you skip it now, running the Airhand installer again asks again." LangString AirhandUsbipNeedsAdmin 2052 "安装它需要管理员权限:Windows 会请你确认(普通账户要输入管理员密码)。" LangString AirhandUsbipNeedsAdmin 1033 "Installing it needs administrator rights: Windows will ask you to confirm (other accounts need an administrator password)." -LangString AirhandUsbipFailed 2052 "没能安装 usbip-win2($0),这台电脑暂时不能接控制端的手柄。$\r$\n$\r$\n以后可以重新运行 Airhand 的安装程序再装,或者从 github.com/vadimgrn/usbip-win2/releases 下载安装。" -LangString AirhandUsbipFailed 1033 "Couldn't install usbip-win2 ($0), so this computer can't take the controller's gamepads for now.$\r$\n$\r$\nYou can run the Airhand installer again later, or install it from github.com/vadimgrn/usbip-win2/releases." +LangString AirhandUsbipFailed 2052 "没能安装 usbip-win2($0),这台电脑暂时不能接控制端的手柄和麦克风。$\r$\n$\r$\n以后可以重新运行 Airhand 的安装程序再装,或者从 github.com/vadimgrn/usbip-win2/releases 下载安装。" +LangString AirhandUsbipFailed 1033 "Couldn't install usbip-win2 ($0), so this computer can't take the controller's gamepads and microphone for now.$\r$\n$\r$\nYou can run the Airhand installer again later, or install it from github.com/vadimgrn/usbip-win2/releases." ; 选择安装目录的页面:说明两种方式各能装在哪里(不符合时"下一步"不能点,见 .onVerifyInstDir) LangString AirhandDirTop 2052 "为所有用户安装时只能装在 Program Files 里:Airhand 作为系统服务运行,别的位置普通用户可能改得了它的程序。仅为我安装时不能装在 Program Files 或 Windows 文件夹里:设置要保存在程序旁边。" @@ -452,7 +452,7 @@ FunctionEnd ${EndIf} ${EndIf} ${EndIf} - ; 手柄驱动 usbip-win2(见文件开头):在启动服务、托盘之前装好 + ; 手柄和麦克风的驱动 usbip-win2(见文件开头):在启动服务、托盘之前装好 !ifdef AIRHAND_USBIP_VERSION Call AirhandUsbipMissing ${If} $0 == 1 @@ -472,7 +472,7 @@ FunctionEnd airhand_usbip_asked: ${EndIf} ${If} $1 == 1 - DetailPrint "Installing usbip-win2 ${AIRHAND_USBIP_VERSION} (the gamepad driver)…" + DetailPrint "Installing usbip-win2 ${AIRHAND_USBIP_VERSION} (the gamepad and microphone driver)…" InitPluginsDir File "/oname=$PLUGINSDIR\usbip-win2-setup.exe" "${AIRHAND_USBIP_SETUP}" ; 只装驱动和命令行工具(main、client),不装图形界面、SDK、调试符号;不重启。要重启时它也返回 0 diff --git a/client/src-tauri/windows/usbip/README.md b/client/src-tauri/windows/usbip/README.md index d75cfb79..62a90f0f 100644 --- a/client/src-tauri/windows/usbip/README.md +++ b/client/src-tauri/windows/usbip/README.md @@ -1,6 +1,6 @@ -# 手柄驱动(usbip-win2) +# 手柄和麦克风的驱动(usbip-win2) -控制端的手柄插到 Windows 被控端上要用到 usbip-win2 的驱动(见 `src/host/gamepad.rs` 和 +控制端的手柄、麦克风插到 Windows 被控端上要用到 usbip-win2 的驱动(见 `src/host/gamepad.rs`、`src/host/mic/usb.rs` 和 [airhand-dock](https://github.com/sqlpxc/airhand-dock))。Windows 安装包带着它的安装程序,安装时问用户要不要装 (见 `windows/hooks.nsh`),用户不用自己去下载。 diff --git a/client/src/components/SessionView.tsx b/client/src/components/SessionView.tsx index 5ba0199e..e2a58fc2 100644 --- a/client/src/components/SessionView.tsx +++ b/client/src/components/SessionView.tsx @@ -953,14 +953,17 @@ function micProblem(s: RemoteSession): boolean { function micHint(s: RemoteSession): string { if (s.micError !== null) return t(`mic.local.${s.micError}` as const); - const device = s.hostPlatform === "windows" ? "Steam Streaming Microphone" : "Airhand Microphone"; + const device = "Airhand Microphone"; switch (s.micState) { + case "noDriver": + return t("mic.noDriver"); + case "preparing": + return t("mic.preparing"); + // 旧版本的 Windows 被控端(用 Steam Streaming Microphone)才会说的 case "noDevice": return t("mic.noDevice"); case "steamMissing": return t("mic.steamMissing"); - case "preparing": - return s.hostPlatform === "windows" ? t("mic.preparingSteam") : t("mic.preparing"); case "setupFailed": return t("mic.setupFailed", { detail: s.micDetail ?? "—" }); case "busy": diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts index e1f81e7d..f0da64ab 100644 --- a/client/src/lib/api.ts +++ b/client/src/lib/api.ts @@ -327,9 +327,20 @@ export type Platform = "windows" | "mac" | "linux" | "android" | "ios"; /** * 被控端能不能接本机的麦克风(airhand_proto::session::MicState):unsupported = 那个平台还不支持; - * noDevice = 打开转发时可安装驱动,steamMissing = 需要先安装 Steam,preparing = 正在准备设备,setupFailed = 驱动未就绪。 + * noDriver = Windows 缺驱动 usbip-win2,preparing = 正在准备设备。 + * 用 Steam Streaming Microphone 的旧版本 Windows 被控端还会发:noDevice = 打开转发时可安装驱动, + * steamMissing = 需要先安装 Steam,setupFailed = 驱动未就绪。 */ -export type MicState = "unsupported" | "noDevice" | "ready" | "busy" | "failed" | "steamMissing" | "preparing" | "setupFailed"; +export type MicState = + | "unsupported" + | "noDevice" + | "ready" + | "busy" + | "failed" + | "steamMissing" + | "preparing" + | "setupFailed" + | "noDriver"; /** * 被控端的防窥模式(airhand_proto::session::PrivacyState):unavailable = 对方没装虚拟显示器驱动(或不是为所有用户安装的), diff --git a/client/src/lib/mic.ts b/client/src/lib/mic.ts index 94d2f920..df91f9ff 100644 --- a/client/src/lib/mic.ts +++ b/client/src/lib/mic.ts @@ -1,7 +1,7 @@ // 本机麦克风的采集(主线程只负责打开和关掉):getUserMedia → AudioWorklet(mic-worklet.ts:混成单声道、换成 48 kHz、 // 每 20 ms 一块)→ 经 MessageChannel 直接交给控制台的 Worker(mic-encoder.ts:编成 Opus、打包、发给控制端服务)。 // -// 被控端把这些声音放进它的虚拟麦克风(Windows:Steam Streaming Microphone),那台电脑上的程序就听得到 +// 被控端把这些声音放进它的虚拟麦克风 Airhand Microphone,那台电脑上的程序就听得到 // (协议见 crates/airhand-proto/src/session.rs 的"麦克风")。打开浏览器的回声消除:远程的声音从这台电脑的扬声器放出来, // 不会再被麦克风录回去。 import workletUrl from "./mic-worklet?worker&url"; diff --git a/client/src/locales/en.ts b/client/src/locales/en.ts index 5e40feb5..ce5ae3bf 100644 --- a/client/src/locales/en.ts +++ b/client/src/locales/en.ts @@ -317,10 +317,11 @@ const en: Record = { "mic.ready": "Turn on forwarding, then choose {device} as the input in the remote app. Audio is sent while you’re viewing this connection.", "mic.live": "Sending. Choose {device} as the input in the remote app.", "mic.macPermission": "macOS may ask you to allow the app using this device to record system audio.", + "mic.noDriver": "The remote computer needs the driver usbip-win2 (the one gamepads use too): run the Airhand installer there again and choose to install it (or get it from github.com/vadimgrn/usbip-win2/releases). No need to restart Airhand", + "mic.preparing": "Creating Airhand Microphone on the remote computer. Forwarding will start when it’s ready", + // Older Windows hosts, which use Steam Streaming Microphone "mic.noDevice": "Turn on forwarding to install the virtual microphone driver included with Steam on the remote computer", "mic.steamMissing": "Install Steam on the remote computer so Airhand can use its microphone driver", - "mic.preparing": "Creating Airhand Microphone on the remote computer", - "mic.preparingSteam": "Preparing the Steam virtual microphone on the remote computer. Forwarding will start when it’s ready", "mic.setupFailed": "The Steam virtual microphone on the remote computer isn’t ready ({detail}). Turn forwarding off and on to retry after addressing the issue", "mic.busy": "Another controller is using the remote microphone. You'll take over when it stops", "mic.failed": "The remote computer can’t open {device} and is retrying ({detail})", diff --git a/client/src/locales/zh.ts b/client/src/locales/zh.ts index fcd76bfb..55e0ecb1 100644 --- a/client/src/locales/zh.ts +++ b/client/src/locales/zh.ts @@ -329,10 +329,11 @@ export default { "mic.ready": "打开后,在对方电脑的程序里选 {device} 作为录音设备。只在查看这个连接时发送", "mic.live": "正在发送,请在对方的程序里选择 {device} 录音", "mic.macPermission": "Mac 可能会要求允许使用这个设备的程序录制系统音频。", + "mic.noDriver": "对方电脑要先装驱动 usbip-win2(和手柄用的是同一个):在那台电脑上重新运行 Airhand 的安装程序,选择安装它(也可以从 github.com/vadimgrn/usbip-win2/releases 下载),不用重启 Airhand", + "mic.preparing": "正在对方电脑上创建 Airhand Microphone,就绪后会自动开始转发", + // 旧版本的 Windows 被控端(用 Steam Streaming Microphone) "mic.noDevice": "打开转发后,Airhand 会在对方电脑上安装 Steam 自带的虚拟麦克风驱动", "mic.steamMissing": "请先在对方电脑上安装 Steam,Airhand 会用它自带的驱动转发麦克风", - "mic.preparing": "正在对方电脑上创建 Airhand Microphone", - "mic.preparingSteam": "正在对方电脑上准备 Steam 虚拟麦克风,就绪后会自动开始转发", "mic.setupFailed": "对方电脑上的 Steam 虚拟麦克风未就绪({detail})。处理后可重新打开转发来重试", "mic.busy": "另一个控制端正在用对方的麦克风,它关掉之后自动换成你", "mic.failed": "对方电脑打不开 {device},正在重试({detail})", diff --git a/client/tests/session.test.ts b/client/tests/session.test.ts index 5bfe9c16..bf287897 100644 --- a/client/tests/session.test.ts +++ b/client/tests/session.test.ts @@ -704,10 +704,13 @@ test("麦克风:对方说了能接、开关打开、正在查看时才告诉 // 对方还没说(版本旧的对方不会说):开关打开也不发 s.setMicEnabled(true); assert.deepEqual(mics(), []); - // 对方最初没有 Steam,后来装上了:准备驱动期间不采集,也不重复发送打开请求 + // 对方最初没有驱动,后来装上了:准备设备期间不采集,也不重复发送打开请求 + s.onEvent({ type: "mic", state: "noDriver", detail: "usbip-win2 is not installed" }); + assert.equal(s.micDetail, "usbip-win2 is not installed"); + s.onEvent({ type: "mic", state: "preparing", detail: null }); + // 旧版本的 Windows 被控端(Steam Streaming Microphone)也一样 s.onEvent({ type: "mic", state: "steamMissing", detail: null }); s.onEvent({ type: "mic", state: "noDevice", detail: null }); - s.onEvent({ type: "mic", state: "preparing", detail: null }); s.onEvent({ type: "mic", state: "setupFailed", detail: "restart required" }); assert.equal(s.micDetail, "restart required"); assert.deepEqual(mics(), [true]); diff --git a/crates/airhand-proto/src/session.rs b/crates/airhand-proto/src/session.rs index 1718d58d..99c51a51 100644 --- a/crates/airhand-proto/src/session.rs +++ b/crates/airhand-proto/src/session.rs @@ -95,7 +95,7 @@ //! 就像用着一个本地麦克风。能不能用由被控端的平台和设备决定: //! //! * 被控端在 [`HostMsg::Hello`] 之后发 [`HostMsg::Mic`],说明它现在能不能接([`MicState`]:平台不支持、 -//! 没有虚拟麦克风、需要安装 Steam、准备设备、能接、被别的控制端占着、出错了),之后有变化再发; +//! 缺驱动、准备设备、能接、被别的控制端占着、出错了……),之后有变化再发; //! * 控制端在能接时发 [`ControllerMsg::Mic`] 打开,之后的声音和被控端的声音一样走声音数据报(方向相反, //! 同样带着之前几包的副本,见 [`crate::media`] 的"声音数据报");关掉时也发 [`ControllerMsg::Mic`]。 //! 被控端只在打开着的时候接(同一时刻只给一个控制端,后来的是 [`MicState::Busy`]); @@ -345,7 +345,8 @@ open_enum! { pub enum MicState { /// 这台被控端的平台还不支持 Unsupported = 0 => "unsupported", - /// 支持,但没有可用的虚拟麦克风。Windows 被控端可以在打开转发时从 Steam 安装驱动 + /// 支持,但没有可用的虚拟麦克风。只有用 Steam Streaming Microphone 的旧版本 Windows 被控端发: + /// 它们可以在打开转发时从 Steam 安装驱动 NoDevice = 1 => "noDevice", /// 能接:控制端打开麦克风之后,声音放进虚拟麦克风 Ready = 2 => "ready", @@ -353,12 +354,16 @@ open_enum! { Busy = 3 => "busy", /// 打不开(例如被别的程序独占了),被控端在重试 Failed = 4 => "failed", - /// Windows 上既没有可用的设备,也没找到 Steam + /// Windows 上既没有可用的设备,也没找到 Steam(只有旧版本的 Windows 被控端发,见 [`MicState::NoDevice`]) SteamMissing = 5 => "steamMissing", - /// 正在打开设备、安装驱动或等 Windows 发布声音端点 + /// 正在创建、打开虚拟麦克风,或者等系统发布它的录音设备 Preparing = 6 => "preparing", - /// Steam 在,但驱动包不可用、安装失败或设备没有出现。detail 给出原因 + /// Steam 在,但驱动包不可用、安装失败或设备没有出现(只有旧版本的 Windows 被控端发, + /// 见 [`MicState::NoDevice`])。detail 给出原因 SetupFailed = 7 => "setupFailed", + /// 缺驱动:Windows 被控端没有装 usbip-win2(虚拟麦克风是经它插上的 USB 麦克风,和手柄共用)。 + /// 装好之后不用重启 Airhand,被控端定时再看。detail 给出原因 + NoDriver = 8 => "noDriver", } } diff --git a/crates/airhand-proto/tests/v10.rs b/crates/airhand-proto/tests/v10.rs index aefaee28..783c6c0a 100644 --- a/crates/airhand-proto/tests/v10.rs +++ b/crates/airhand-proto/tests/v10.rs @@ -219,6 +219,7 @@ fn session_messages_layout() { (MicState::SteamMissing, "820c8105"), (MicState::Preparing, "820c8106"), (MicState::SetupFailed, "820c8107"), + (MicState::NoDriver, "820c8108"), ] { golden( HostMsg::Mic { diff --git a/docs/architecture.md b/docs/architecture.md index 262a56bd..8c756916 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -175,7 +175,7 @@ On Windows all of this runs in the system service (see [Windows service](#window | 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+) | -| Controller's microphone | Steam Streaming Microphone (WASAPI, see [Microphone](#microphone)) | Public Core Audio tap and aggregate device (14.2+) | Session-owned PipeWire source | Not yet | +| Controller's microphone | A USB microphone plugged through usbip-win2 (see [Microphone](#microphone)) | Public Core Audio tap and aggregate device (14.2+) | Session-owned PipeWire source | Not yet | | Clipboard | Change detection via the clipboard sequence number | NSPasteboard change count | XFIXES selection-owner change notifications | Write only (controller → phone) | | Files on the clipboard (see [Files on the clipboard](#files-on-the-clipboard)) | OLE virtual files (placed and read by the tray) | Receive from menu bar, send by copying | FUSE + X11 clipboard | Content URIs; the phone's files go out through the share menu | | Console UI | WebView2 | WKWebView | WebKitGTK (WebCodecs decoding via GStreamer) | Jetpack Compose (MediaCodec decoding) | @@ -252,12 +252,12 @@ The controller's microphone can go the other way, into a virtual microphone on t | Stage | How | |---|---| -| State | After `Hello` the host says whether it can take a microphone (`HostMsg::Mic`: unsupported / no virtual microphone / ready / another controller has it / failed, with a technical detail) and again when that changes. The console only shows the microphone button when it can | +| State | After `Hello` the host says whether it can take a microphone (`HostMsg::Mic`: unsupported / no driver / preparing / ready / another controller has it / failed, with a technical detail) and again when that changes. The console only shows the microphone button when it can. Older Windows hosts, which used Steam Streaming Microphone, may also say no device / Steam missing / setup failed | | Capture | Only the session you're looking at, and only when the user turned it on: `getUserMedia` with the browser's echo cancellation, noise suppression and gain control (the remote sound coming out of this computer's speakers isn't recorded back) → AudioWorklet mixes to mono, resamples to 48 kHz and posts 20 ms blocks straight to the console's Worker (`client/src/lib/mic.ts`, `mic-worklet.ts`) | | Encoding | WebCodecs Opus, 48 kHz mono, 32 kbps, 20 ms per packet, in the Worker; the same packet format as the host's sound (`media.ts` `audioPacket`), sent to the controller service as a binary WebSocket message `2 \| sid \| packet` (`mic-encoder.ts`) | | Transport | The controller service adds copies of the previous packets and seals them into audio datagrams like the host does (controller → host has its own key), on the path the video comes on (direct or relay). Controller and relay drop packets when they can't keep up | | Playback | The host's read task decrypts, drops copies and hands packets straight to the platform (`airhand_link::host::MicSink`). The shared desktop playout thread decodes them (Opus packet loss concealment covers up to 3 missing packets), buffers 60 ms (drops the excess after a stall so latency doesn't build up) and keeps 40 ms queued in the device (`client/src-tauri/src/host/mic/`) | -| Virtual microphone | Windows: **Steam Streaming Microphone**, Steam Remote Play's virtual sound card, found by its interface name (not the localized display name). Bytes written to its "Speakers" side come out of its "Microphone" side unchanged, without format conversion, so both sides must use the same format: if their default formats match, shared mode (the system converts); otherwise exclusive mode in the microphone side's format (on this test machine the speaker side is 48 kHz stereo and the microphone side 44.1 kHz mono: writing in the speaker format turns a 1 kHz tone into 459 Hz). Only opened while a controller's microphone is on, one controller at a time. When the device is missing, the host installs the microphone driver from its local copy of Steam and starts forwarding once the endpoints are ready | +| Windows virtual microphone | **Airhand Microphone**, a USB Audio Class 1.0 microphone (48 kHz mono 16-bit) served by [airhand-dock](https://github.com/sqlpxc/airhand-dock) and plugged through usbip-win2, on the same dock as the gamepads (`client/src-tauri/src/host/mic/usb.rs`). Windows binds its own `usbaudio.sys`: no driver besides usbip-win2, no administrator rights, no exclusive mode, no sound settings changed. Its queue empties in real time whether or not a program records, so what's queued is the latency. Plugged when a controller first turns its microphone on; ready once Windows has published the recording device, found by its interface name (not the localized display name): about a second, about 6 s the first time on a computer, when Windows sets the device up and briefly disables its recording device. Turning the microphone off (or switching to another connection) doesn't unplug it, so programs that chose it don't fall back to another microphone: it's a silent microphone then. It's unplugged when every session that turned it on has ended: at once for a normal end, after 30 s without a reconnect for a dropped one. A fixed USB serial number makes Windows recognize it on every plug, so programs' choice and the default device setting stick | | Mac / Linux virtual microphone | On Mac a public Core Audio tap takes only the host process’s mono output. `CATapMuted` keeps it off the speakers. On Linux the host publishes a client-owned PipeWire `Audio/Source` node. Both use a bounded PCM ring and zero-fill underruns. | `e2e_mic` sends a 1 kHz tone from a protocol-level controller through a real relay, deliberately drops datagrams and checks the frequency and continuity recorded from the host’s audio device on each platform. `native_mic_cleanup` checks crash recovery, disconnect and uninstall on Mac and Linux. @@ -271,7 +271,7 @@ Gamepads on the controller are plugged into the host as wired Xbox 360 controlle | State | After `Hello` a desktop host says whether it can take gamepads (`HostMsg::Gamepad`: unsupported / no driver / no permission / ready / failed, with a technical detail) and again when that changes. Hosts that don't say (phones) take no gamepad input; the controllers don't send any | | Capture | Console: the Gamepad API, polled every 4 ms by one hub for the whole page and handed to the session you're viewing (`client/src/lib/gamepad.ts`); Android: key and joystick events of gamepad input devices (`controller/Gamepads.kt`, TVs included); iOS: GameController (`Controller/Gamepads.swift`). All map to XInput's layout (buttons by position, triggers 0–255, sticks with Y up). The on-screen gamepad of game keys on phones (gamepad buttons and sticks, `GameControls.kt` / `GameLayer.swift`) is one more pad in the same `Gamepads`: its state is put together from the held gamepad buttons and pushed sticks, it takes a number when first pressed and is unplugged when the layout has none left | | Transport | Input events on the control lane like keys and the mouse (`InputEvent::Gamepad` carries the whole state of one pad, `GamepadRemoved` unplugs it). Only changes are sent (stick noise below 1/1024 of the range isn't); consecutive states of one pad with the same buttons are coalesced at every queue, never across a button change. Stale input becomes "release all", which puts every remote pad back to rest. Since a pad held still sends nothing new, the controller service resends every pad that isn't at rest every 500 ms, and when it drops queued input itself the "release all" carries the current state of every pad (and the removals it dropped); a stale `GamepadRemoved` is still carried out by the host. A UI puts a session's pads back to rest before it stops handing it the gamepads | -| Virtual pad | [airhand-dock](https://github.com/sqlpxc/airhand-dock) (`client/src-tauri/src/host/gamepad.rs`): one dock per process, opened on first use; plugging and unplugging on one worker thread (plugging takes tens of milliseconds). Windows: usbip-win2 attaches the device served on a loopback USB/IP server, Windows binds its own `xusb22`; the installer carries usbip-win2's own installer and offers it (`client/src-tauri/windows/usbip/`). Linux: `vhci-hcd` as root, otherwise `uinput`, where airhand-dock plays the USB host and the `xpad` driver itself. macOS can't | +| Virtual pad | [airhand-dock](https://github.com/sqlpxc/airhand-dock) (`client/src-tauri/src/host/gamepad.rs`): one dock per process, shared with the Windows microphone and opened on first use (`host/dock.rs`); plugging and unplugging on one worker thread (plugging takes tens of milliseconds). Windows: usbip-win2 attaches the device served on a loopback USB/IP server, Windows binds its own `xusb22`; the installer carries usbip-win2's own installer and offers it (`client/src-tauri/windows/usbip/`). Linux: `vhci-hcd` as root, otherwise `uinput`, where airhand-dock plays the USB host and the `xpad` driver itself. macOS can't | | Ownership | Pads belong to the controller (its identity from the end-to-end handshake), not to a session: a reconnect keeps them. When its last session ends normally they're unplugged at once; when it drops, after 30 s without a reconnect | | Rumble | airhand-dock reports the motors the game set; the host sends `HostMsg::Rumble` to the controller's latest session (latest value per pad, ahead of queued messages). The console uses `vibrationActuator` (refreshed every 4 s while on), Android the input device's vibrators, iOS CoreHaptics on the pad's handles; for the on-screen gamepad, the phone's own motor | ## A/V sync (optional, off by default) diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index 160dbd3c..1ab6bd58 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -175,7 +175,7 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 | 输入注入 | SendInput(扫描码;相对移动同真实鼠标) | CGEvent(虚拟键码;相对移动带移动量) | XTEST(evdev 物理键码;相对移动) | 无障碍服务(手势、系统操作、文字输入) | | 光标隐藏(自动模式改用相对移动) | DXGI + `GetCursorInfo`(拖动、缩放窗口时画进画面里的软件光标不算隐藏) | 检测不到(用游戏模式) | XFIXES(全透明光标) | — | | 声音采集 | WASAPI 环回 | ScreenCaptureKit(系统混音) | PulseAudio / PipeWire 的输出监视器 | AudioPlaybackCapture(Android 10+) | -| 控制端的麦克风 | Steam Streaming Microphone(WASAPI,见[麦克风](#麦克风)) | 公开的 Core Audio tap 和聚合设备(14.2+) | 会话期间的 PipeWire 录音源 | 还不支持 | +| 控制端的麦克风 | 经 usbip-win2 插上的 USB 麦克风(见[麦克风](#麦克风)) | 公开的 Core Audio tap 和聚合设备(14.2+) | 会话期间的 PipeWire 录音源 | 还不支持 | | 剪贴板 | 剪贴板序号检测变化 | NSPasteboard 变化计数 | XFIXES 选择所有者变化通知 | 只能写入(控制端 → 手机) | | 剪贴板里的文件(见[剪贴板里的文件](#剪贴板里的文件)) | OLE 虚拟文件(托盘放、托盘读) | 菜单栏接收,本地复制发出 | FUSE + X11 剪贴板 | content URI;手机的文件用分享菜单发 | | 控制台界面 | WebView2 | WKWebView | WebKitGTK(WebCodecs 由 GStreamer 解码) | Jetpack Compose(MediaCodec 解码) | @@ -252,12 +252,12 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 | 环节 | 做法 | |---|---| -| 状态 | 被控端在 `Hello` 之后说它能不能接(`HostMsg::Mic`:不支持 / 没有虚拟麦克风 / 能接 / 别的控制端在用 / 出错了,带技术信息),之后有变化再说。控制台只在能接时显示麦克风按钮 | +| 状态 | 被控端在 `Hello` 之后说它能不能接(`HostMsg::Mic`:不支持 / 缺驱动 / 在准备 / 能接 / 别的控制端在用 / 出错了,带技术信息),之后有变化再说。控制台只在能接时显示麦克风按钮。用 Steam Streaming Microphone 的旧版本 Windows 被控端还可能说没有设备 / 没有 Steam / 驱动没装好 | | 采集 | 只在用户打开、而且正在查看这个会话时:`getUserMedia`,打开浏览器的回声消除、降噪和自动增益(远程的声音从这台电脑的扬声器放出来,不会再被录回去)→ AudioWorklet 混成单声道、换成 48 kHz,每 20 ms 一块直接交给控制台的 Worker(`client/src/lib/mic.ts`、`mic-worklet.ts`) | | 编码 | Worker 里 WebCodecs 编 Opus,48 kHz 单声道 32 kbps,每包 20 ms;和被控端的声音包同一个格式(`media.ts` 的 `audioPacket`),以二进制 WebSocket 消息 `2 \| sid \| 声音包` 交给控制端服务(`mic-encoder.ts`) | | 传输 | 控制端服务和被控端一样给每个数据报带上之前几包的副本、加密成声音数据报(控制端 → 被控端用自己的密钥),走画面来的那条路(直连或中转)。控制端服务、中转跟不上时丢包 | | 播放 | 被控端的读任务解密、去掉副本,直接交给平台(`airhand_link::host::MicSink`)。各桌面平台共用的播放线程解码(连着丢了不超过 3 包时用 Opus 的丢包补偿补上),抖动缓冲 60 ms(卡了一阵之后积压的丢掉,延迟不会越积越多),设备里一直排着 40 ms(`client/src-tauri/src/host/mic/`) | -| 虚拟麦克风 | Windows:Steam 远程同乐的虚拟声卡 **Steam Streaming Microphone**,按接口名找(不按随系统语言变的显示名)。写进它“扬声器”一边的字节原样从“麦克风”一边出来,不换格式,所以两边的格式必须一样:两边的默认格式一样时用共享模式(系统换格式);不一样时用独占模式按“麦克风”一边的格式写(测试的这台电脑上扬声器一边是 48 kHz 立体声、麦克风一边是 44.1 kHz 单声道:按扬声器的格式写,1 kHz 的声音会变成 459 Hz)。只在有控制端打开麦克风期间打开,同一时刻只给一个控制端。缺少设备时从本机 Steam 安装麦克风驱动,设备就绪后开始转发 | +| Windows 虚拟麦克风 | **Airhand Microphone**:[airhand-dock](https://github.com/sqlpxc/airhand-dock) 提供、经 usbip-win2 插上的 USB Audio Class 1.0 麦克风(48 kHz 单声道 16 位),和手柄插在同一个 dock 上(`client/src-tauri/src/host/mic/usb.rs`)。系统用自带的 `usbaudio.sys`:除了 usbip-win2 不用装驱动,不要管理员权限,不用独占模式,不改声音设置。它的队列按时间清空,不管有没有程序在录,排着的就是延迟。控制端第一次打开麦克风时插上;Windows 发布了录音设备(按接口名找,不按随系统语言变的显示名)才算能接:一秒左右,一台电脑第一次插上时约 6 秒(Windows 要装好设备,录音设备会停用一下再回来)。关掉麦克风(或者切到别的连接)时不拔,选了它的程序不会换成别的麦克风:它就是一个静音的麦克风。打开过它的会话都结束了才拔:正常结束的马上拔,断掉的等 30 秒没连回来再拔。USB 序列号固定,Windows 每次都认得它,程序里的选择、默认设备的设置都还在 | | Mac / Linux 虚拟麦克风 | Mac 只截取本进程的单声道输出,用 `CATapMuted` 静音扬声器,并将 tap 作为 Airhand Microphone 的输入。Linux 通过 PipeWire 发布客户端持有的 `Audio/Source` 节点。录音回调从有界缓冲区取样,欠载时填静音。 | `e2e_mic` 让协议级控制端通过真实中转发送 1 kHz 测试音,并故意丢弃一些数据报。测试从各平台的系统录音设备录回声音,检查频率和连续性。`native_mic_cleanup` 检查 Mac 和 Linux 的强退恢复、断开和卸载。 @@ -271,7 +271,7 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 | 状态 | 桌面被控端在 `Hello` 之后说它能不能接手柄(`HostMsg::Gamepad`:不支持 / 缺驱动 / 没有权限 / 能接 / 出错了,带技术信息),之后有变化再说。不说的被控端(手机)不接手柄,控制端也就不发 | | 采集 | 控制台:Gamepad API,整个网页一个轮询(每 4 ms),交给正在查看的会话(`client/src/lib/gamepad.ts`);Android:手柄设备的按键和摇杆事件(`controller/Gamepads.kt`,电视也是);iOS:GameController(`Controller/Gamepads.swift`)。都换成 XInput 的格式(按钮按位置、扳机 0–255、摇杆 Y 向上为正)。手机上游戏按键里画面上的手柄(手柄的按钮、摇杆,`GameControls.kt` / `GameLayer.swift`)是同一个 `Gamepads` 里的又一个手柄:按着的手柄按钮、推着的摇杆拼成它的状态,第一次按下时分编号,方案里没有了就拔掉 | | 传输 | 和键盘鼠标一样是控制通道上的输入(`InputEvent::Gamepad` 是一个手柄完整的状态,`GamepadRemoved` 拔掉它)。只在变了的时候发(摇杆不到量程 1/1024 的抖动不算);每个队列里同一个手柄、按钮一样的相邻状态只留最后一个,不会越过按钮的变化。过时的输入换成“释放所有按键”,对方把手柄都放回原位。按着不动的手柄不会再发什么,所以控制端服务把不在原位的手柄每 500 ms 再发一次,自己丢掉排着的输入时补的“释放所有按键”里带着每个手柄现在的样子(以及丢掉的“拔掉了”);过时的 `GamepadRemoved` 被控端照样执行。界面不再把手柄交给一个会话之前,先让它把手柄放回原位 | -| 虚拟手柄 | [airhand-dock](https://github.com/sqlpxc/airhand-dock)(`client/src-tauri/src/host/gamepad.rs`):整个进程一个,第一次用时打开;插拔都在一个线程上(插一个要几十毫秒)。Windows:usbip-win2 把本机回环 USB/IP 服务器上的设备插上,系统用自带的 `xusb22` 驱动,安装包带着 usbip-win2 自己的安装程序、安装时问要不要装(`client/src-tauri/windows/usbip/`);Linux:root 时用 `vhci-hcd`,否则用 `uinput`,airhand-dock 自己当 USB 主机、做 `xpad` 驱动做的事。macOS 不行 | +| 虚拟手柄 | [airhand-dock](https://github.com/sqlpxc/airhand-dock)(`client/src-tauri/src/host/gamepad.rs`):整个进程一个,和 Windows 的麦克风共用,第一次用时打开(`host/dock.rs`);插拔都在一个线程上(插一个要几十毫秒)。Windows:usbip-win2 把本机回环 USB/IP 服务器上的设备插上,系统用自带的 `xusb22` 驱动,安装包带着 usbip-win2 自己的安装程序、安装时问要不要装(`client/src-tauri/windows/usbip/`);Linux:root 时用 `vhci-hcd`,否则用 `uinput`,airhand-dock 自己当 USB 主机、做 `xpad` 驱动做的事。macOS 不行 | | 归属 | 手柄属于控制端(端到端握手里的身份),不属于会话:断线重连接着用。它的最后一个会话正常结束时马上拔掉,断掉的等 30 秒没连回来再拔 | | 震动 | airhand-dock 报告游戏设置的马达,被控端发 `HostMsg::Rumble` 给这个控制端最新的会话(每个手柄只留最新值,排在前面)。控制台用 `vibrationActuator`(震着时每 4 秒重放),Android 用手柄设备的振动器,iOS 用手柄两侧的 CoreHaptics;画面上的手柄用手机自己的马达 | ## 音画同步(可选,默认关闭) diff --git a/docs/development.md b/docs/development.md index 6e7a5147..26806879 100644 --- a/docs/development.md +++ b/docs/development.md @@ -27,8 +27,10 @@ cargo test --lib cargo test --lib ltr_probe -- --ignored --nocapture # audio loopback capture (needs an audio output device; plays a 1.5 s test tone at -60 dBFS, barely audible) cargo test --lib loopback_captures_tone -- --ignored --nocapture -# Windows: the controller's microphone into Steam Streaming Microphone (needs it on this computer), recorded back as a 1 kHz tone -cargo test --lib mic_reaches_steam_streaming_microphone -- --ignored --nocapture +# Windows: the controller's microphone into a USB microphone plugged through airhand-dock (needs usbip-win2), recorded back +# as a 1 kHz tone; still plugged after it's turned off, unplugged when the session ends. AIRHAND_TEST_MIC_SERIAL= +# makes it a microphone this computer has never seen (Windows sets it up the first time) +cargo test --lib mic_reaches_airhand_microphone -- --ignored --nocapture # a virtual Xbox 360 gamepad plugged and unplugged through airhand-dock (Windows: needs usbip-win2; Linux: root or access to /dev/uinput) cargo test --lib plugs_a_virtual_gamepad -- --ignored --nocapture # macOS 14.2+ / Linux with PipeWire and pactl: crash recovery, disconnect and uninstall during forwarding @@ -69,7 +71,7 @@ AIRHAND_CERT=target/e2e/cert.pem AIRHAND_KEY=target/e2e/key.pem ./target/debug/a cargo test --lib e2e_roundtrip -- --ignored --nocapture # video frame streams / codec switching / clipboard / audio / ping / disconnect cargo test --lib e2e_reconnect -- --ignored --nocapture # getting the code back after a server restart, changing the code cargo test --lib e2e_multi_display -- --ignored --nocapture # showing two displays at once, then one (skipped with a single display) -cargo test --lib e2e_mic -- --ignored --nocapture # record a 1 kHz tone from the OS device (Swift on Mac, pipewire-pulse and parec on Linux, Steam driver on Windows) +cargo test --lib e2e_mic -- --ignored --nocapture # record a 1 kHz tone from the OS device (Swift on Mac, pipewire-pulse and parec on Linux, usbip-win2 on Windows) cargo test --lib e2e_terminal -- --ignored --nocapture # remote terminal: refused when turned off, then run a command and exit ``` diff --git a/docs/development.zh-CN.md b/docs/development.zh-CN.md index 1ecefc33..4bbe87a6 100644 --- a/docs/development.zh-CN.md +++ b/docs/development.zh-CN.md @@ -27,8 +27,9 @@ cargo test --lib cargo test --lib ltr_probe -- --ignored --nocapture # 声音环回采集(需要声音输出设备,会以 -60 dBFS 播放 1.5 秒测试音,几乎听不见) cargo test --lib loopback_captures_tone -- --ignored --nocapture -# Windows:控制端的麦克风写进 Steam Streaming Microphone(这台电脑上要有它),从它的录音端录回 1 kHz 的声音 -cargo test --lib mic_reaches_steam_streaming_microphone -- --ignored --nocapture +# Windows:控制端的麦克风写进经 airhand-dock 插上的 USB 麦克风(要装好 usbip-win2),从它的录音设备录回 1 kHz 的声音; +# 关掉之后还插着,会话结束了才拔掉。AIRHAND_TEST_MIC_SERIAL=<新的序列号> 当作这台电脑没见过的麦克风(Windows 要先装好它) +cargo test --lib mic_reaches_airhand_microphone -- --ignored --nocapture # 经 airhand-dock 插上、拔掉一个虚拟的 Xbox 360 手柄(Windows 要装好 usbip-win2;Linux 要 root 或者能用 /dev/uinput) cargo test --lib plugs_a_virtual_gamepad -- --ignored --nocapture # macOS 14.2+ / Linux(PipeWire、pactl):检查强退后的清理、断开和转发期间卸载 @@ -68,7 +69,7 @@ AIRHAND_CERT=target/e2e/cert.pem AIRHAND_KEY=target/e2e/key.pem ./target/debug/a cargo test --lib e2e_roundtrip -- --ignored --nocapture # 视频帧流/ 编码切换 / 剪贴板 / 声音 / Ping / 断开 cargo test --lib e2e_reconnect -- --ignored --nocapture # 服务器重启后取回控制码、更换控制码 cargo test --lib e2e_multi_display -- --ignored --nocapture # 同时看两个显示器、再改回只看一个(只有一个显示器时跳过) -cargo test --lib e2e_mic -- --ignored --nocapture # 从录音设备录回 1 kHz。Mac 用系统 Swift 工具,Linux 用 pipewire-pulse 和 parec,Windows 需要 Steam 驱动 +cargo test --lib e2e_mic -- --ignored --nocapture # 从录音设备录回 1 kHz。Mac 用系统 Swift 工具,Linux 用 pipewire-pulse 和 parec,Windows 要装好 usbip-win2 cargo test --lib e2e_terminal -- --ignored --nocapture # 远程终端:关掉时被拒绝,打开后跑一条命令、退出 ``` diff --git a/docs/limitations.md b/docs/limitations.md index 2064dbd2..2b51650c 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -6,7 +6,7 @@ - Clipboard file transfer (see [How it works → Files on the clipboard](architecture.md#files-on-the-clipboard)): when only the relay is available, one paste can carry at most what the server allows (`AIRHAND_MAX_FILE_SIZE`, 50 MiB by default); there's no limit while the direct path is up. Files changed after they were copied can't be fetched (size or modification time no longer match): copy them again. Links inside a folder are only recreated when they are relative and stay inside the folder, and only Linux recreates them when receiving; other platforms skip them. There's no overall progress: the progress bar is the receiving file manager's own - Audio is captured after the host's volume control, so a muted host sends silence -- Microphone forwarding requires Steam Streaming Microphone on Windows (already installed or available from the host’s copy of Steam), macOS 14.2+, or a running user PipeWire server (0.3.49+) on Linux. Android hosts and the native Android controller do not yet support it. +- Microphone forwarding requires usbip-win2 on Windows (the same driver as gamepads; the installer offers it on x64 Windows 10 1903 or later), macOS 14.2+, or a running user PipeWire server (0.3.49+) on Linux. Android hosts and the native Android controller do not yet support it. - Sessions are end-to-end encrypted, so the relay can't see their content, but it still knows who connected to whom, when, and how much traffic flowed, and with one stream per video frame also how large each frame is (see [Security](security.md#end-to-end-encryption)) - The web console is where end-to-end encryption ends: the machine running it can see the picture - On the first connection to a computer its identity is whatever was seen then (like SSH): only the pairing code (or comparing the safety code) proves nobody is impersonating it @@ -29,7 +29,7 @@ - Switching to the virtual display and back means enabling / disabling the device and changing display settings, so the picture pauses for a few seconds; windows move to the virtual display, and when switching back Windows puts the monitors back as it has them saved, so windows may not end up exactly where they were. The virtual display doesn't support HDR - Privacy mode can't block Ctrl+Alt+Del at the remote computer (it only switches to the secure desktop, which doesn't show on its monitors either), nor sleep from closing the lid or pressing the power button; the remote computer's sound still plays from its own speakers (that's what the host captures). While the controller is still connected, people at the remote computer can only end it by disconnecting it from the network (and pressing a key once the session has dropped) or restarting it - Keeping the screen on and the computer awake during sessions relies on power requests: sleep the user asks for (closing the lid, the power button) isn't held off, and on Modern Standby computers running on battery, Windows ends these requests 5 minutes after the sleep timeout -- The controller's microphone is written into Steam Streaming Microphone in exclusive mode when its two devices ("Speakers" and "Microphone" in the sound settings) have different default formats (the usual case): while a controller's microphone is on, Steam Remote Play can't use it and vice versa, and it can't be opened if "Allow applications to take exclusive control of this device" is turned off (giving both devices the same default format avoids exclusive mode). It isn't made the default recording device automatically: choose it in the program, or set it in the sound settings yourself +- Airhand Microphone on Windows is a USB microphone that stays plugged in from the first time a connection turns on forwarding until that connection ends, also while forwarding is off (then it records silence). It isn't made the default recording device automatically: choose it in the program, or set it in the sound settings yourself. The first time it's plugged into a computer, Windows takes about 6 s to set it up ## macOS diff --git a/docs/limitations.zh-CN.md b/docs/limitations.zh-CN.md index e381d680..5af74abb 100644 --- a/docs/limitations.zh-CN.md +++ b/docs/limitations.zh-CN.md @@ -6,7 +6,7 @@ - 剪贴板传文件(见[工作原理 → 剪贴板里的文件](architecture.zh-CN.md#剪贴板里的文件)):只能走中转时,一次粘贴最多传服务器允许的大小(`AIRHAND_MAX_FILE_SIZE`,默认 50 MiB),直连通着时不限。复制之后又改过的文件取不了(大小、修改时间对不上),要重新复制。文件夹里的链接只重建相对路径、不出这个文件夹的,而且只有 Linux 接收时重建,别的平台跳过。没有总进度:进度条是接收方的文件管理器自己的 - 采集的是被控端音量调节之后的声音,被控端静音时传过来的也是静音 -- 麦克风转发需要 Windows 的 Steam Streaming Microphone(已有设备或从本机 Steam 安装)、macOS 14.2+ 或 Linux 用户会话里的 PipeWire 0.3.49+。Android 被控端和 Android 原生控制端还不支持。 +- 麦克风转发需要 Windows 装好 usbip-win2(和手柄同一个驱动,x64 的 Windows 10 1903 以上安装时会问)、macOS 14.2+ 或 Linux 用户会话里的 PipeWire 0.3.49+。Android 被控端和 Android 原生控制端还不支持。 - 会话是端到端加密的,中转服务器看不到内容,但仍然知道谁在什么时候连了谁、流量有多大,画面每帧一条流时还看得出每一帧有多大(见[安全](security.zh-CN.md#端到端加密)) - 网页控制台是端到端加密的终点:它所在的机器看得到画面 - 第一次连接一台电脑时,对方的身份是“第一次连上时记下的”(和 SSH 一样):输入配对码(或者核对安全码)才能确定中间没有人冒充对方 @@ -29,7 +29,7 @@ - 换到虚拟显示器、换回来都要启用 / 停用设备、改显示设置,画面会停几秒;窗口跟着挪到虚拟显示器上,换回来时 Windows 按它记着的设置把显示器放回去,窗口的位置不一定和原来一样。虚拟显示器不支持 HDR - 防窥模式挡不住本机按 Ctrl+Alt+Del(只是切到安全桌面,本机的显示器上也看不到),也挡不住合盖、按电源键让电脑睡眠;本机的声音照样从本机的扬声器放出来(被控端采集的就是它)。控制端还连着的时候,本机的人要结束它只能断开网络(会话断开之后按一下键盘)或者重启电脑 - 有会话时保持亮屏、不睡眠靠的是电源请求:合盖、按电源键这些用户自己让电脑睡眠的挡不住;支持现代待机的电脑用电池时,系统会在睡眠超时 5 分钟后终止这些请求 -- 控制端的麦克风写进 Steam Streaming Microphone 时:它的两个设备(声音设置里的“扬声器”和“麦克风”)默认格式不一样的话(常见),用独占模式写:控制端打开麦克风期间 Steam 远程同乐用不了它,反过来也一样;声音设置里关掉了“允许应用程序独占控制该设备”时打不开(把两个设备的默认格式调成一样就不用独占了)。不会自动把它设为默认录音设备:在程序里选,或者自己在声音设置里设 +- Windows 上的 Airhand Microphone 是一个 USB 麦克风:一个连接第一次打开转发时插上,一直插到这个连接结束,关掉转发期间也插着(录到的是静音)。不会自动把它设为默认录音设备:在程序里选,或者自己在声音设置里设。第一次插到一台电脑上时,Windows 要花约 6 秒装好它 ## macOS diff --git a/docs/usage.md b/docs/usage.md index 41400e3c..cba25420 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -53,7 +53,7 @@ On Windows Airhand is installed with its installer, either for all users or just - **First install**: administrator accounts choose in the installer (for all users by default). For other accounts the installer asks first: Yes runs it again as administrator (you'll need an administrator password) to install for all users; No installs just for you - **Upgrading, reinstalling**: the installer keeps the way Airhand was installed and doesn't ask again. The copy installed for all users needs administrator rights; other accounts get an explanation and then a prompt for an administrator password. If the tray was open before the upgrade, it opens again afterwards (when you upgrade someone's computer remotely, the connection comes back) - **Switching between the two**: uninstall first, then install again -- **Gamepad driver**: the installer includes [usbip-win2](https://github.com/vadimgrn/usbip-win2) and asks whether to install it when the computer doesn't have it yet (both ways of installing), see [Gamepads](#gamepads) +- **Gamepad and microphone driver**: the installer includes [usbip-win2](https://github.com/vadimgrn/usbip-win2) and asks whether to install it when the computer doesn't have it yet (both ways of installing), see [Gamepads](#gamepads) and [Microphone](#microphone) ### For all users @@ -152,7 +152,7 @@ Settings → Apps → Airhand → Uninstall. The uninstaller stops and removes t If the [virtual display](#virtual-display) driver was installed, a page before the confirmation offers "Also remove the virtual display driver", unticked by default: unticked keeps the disabled driver (with the record that recognizes it, `HKLM\SOFTWARE\Airhand\VirtualDisplay`, and its settings in `%ProgramData%\Airhand\VirtualDisplay`) for a later reinstall; ticked removes it too. -The [gamepad driver usbip-win2](#gamepads), if it was installed with Airhand, is a separate program and stays when Airhand is uninstalled; uninstall USBip under Settings → Apps if you no longer need it (all USB devices disconnect for a moment, and it recommends restarting afterwards). +The [gamepad and microphone driver usbip-win2](#gamepads), if it was installed with Airhand, is a separate program and stays when Airhand is uninstalled; uninstall USBip under Settings → Apps if you no longer need it (all USB devices disconnect for a moment, and it recommends restarting afterwards). (Choosing "uninstall the old version first" during an upgrade isn't an uninstall: `config.toml` is kept, see [Windows installation](#windows-installation).) @@ -332,8 +332,8 @@ See [Known limitations](limitations.md) for the details. Send this computer's microphone to the remote computer: programs there (meetings, voice typing, voice messages) hear you when they record from its virtual microphone. Off by default and turned on per connection (the microphone button in the toolbar → **Send this computer's microphone**); it's only sent while you're viewing that connection. The browser asks for microphone access the first time (the desktop console doesn't). -- **Windows hosts** use Steam’s **Steam Streaming Microphone** (Valve’s virtual microphone driver, signed by Microsoft). When you turn on forwarding, Airhand looks for an existing device and installs the driver from Steam on the remote computer if needed. Forwarding starts as soon as the device is ready. The microphone menu prompts you to install Steam if it’s missing from the remote computer -- In programs on the remote computer, choose "Microphone (Steam Streaming Microphone)" as the recording device, or make it the default under Sound settings → Input there, so programs that use the default microphone (such as Windows voice typing, Win+H) hear you directly +- **Windows hosts** plug in **Airhand Microphone**, a virtual USB microphone that Windows drives with its own audio driver, through the same [usbip-win2](https://github.com/vadimgrn/usbip-win2) driver as [gamepads](#gamepads) (the Airhand installer offers it; the microphone menu says so when the remote computer doesn't have it, and there's no need to restart Airhand after installing it). Nothing else to install, no administrator rights, no sound settings changed. It's plugged in when you first turn on forwarding and is ready about a second later (about 6 s the very first time on a computer, while Windows sets it up). Turning forwarding off or switching to another connection doesn't unplug it, so a meeting app that chose it doesn't switch to the remote computer's own microphone: it just records silence. It's unplugged when you disconnect (30 s after a dropped connection that doesn't come back) +- In programs on the remote computer, choose "Microphone (Airhand Microphone)" as the recording device, or make it the default under Sound settings → Input there, so programs that use the default microphone (such as Windows voice typing, Win+H) hear you directly. Windows remembers it, so the choice sticks the next time it's plugged in - Only one controller at a time: another controller sees "Another controller is using the remote microphone" and takes over when that one stops - **macOS 14.2+ and Linux with PipeWire** publish **Airhand Microphone** when forwarding starts. Choose it as the input in the remote app. macOS may ask for permission for that app to record system audio. Turning forwarding off or disconnecting removes the device. PipeWire also removes it when Airhand exits. After a forced quit on Mac, reopening Airhand or choosing **Uninstall Airhand…** cleans up any leftover device and tap. - Android hosts and the native Android controller do not yet support microphone forwarding. @@ -355,7 +355,7 @@ Keeps the people at the remote computer from seeing what you do: all of its moni Gamepads connected to the computer or phone you control from (Xbox, PlayStation, Switch Pro, the built-in pad of a handheld…) are plugged into the remote computer as wired **Xbox 360 controllers**: games see a real USB gamepad (XInput, DirectInput, Windows.Gaming.Input, SDL, Steam, evdev), and when a game makes it vibrate, your gamepad vibrates. On by default; each connection has its own switch. -- **Windows hosts** need [usbip-win2](https://github.com/vadimgrn/usbip-win2) (a free, open-source USB/IP driver, BSD license, signed by Microsoft) installed once, and **the Airhand installer comes with it**: when it isn't installed yet and the computer runs x64 Windows 10 1903 or later, installing Airhand asks whether to install it (also when installing just for you; Windows then asks for administrator rights). While it installs, the computer's USB devices disconnect for a second or two; usbip-win2 recommends restarting once afterwards +- **Windows hosts** need [usbip-win2](https://github.com/vadimgrn/usbip-win2) (a free, open-source USB/IP driver, BSD license, signed by Microsoft; the [microphone](#microphone) uses it too) installed once, and **the Airhand installer comes with it**: when it isn't installed yet and the computer runs x64 Windows 10 1903 or later, installing Airhand asks whether to install it (also when installing just for you; Windows then asks for administrator rights). While it installs, the computer's USB devices disconnect for a second or two; usbip-win2 recommends restarting once afterwards - If you said No, running the Airhand installer again asks again; you can also install it from its [Releases](https://github.com/vadimgrn/usbip-win2/releases). Silent (`/S`) and passive (`/P`, used by updates) installs don't ask and don't install it; add `/USBIP` to the command line to install it without asking - It's a separate program (USBip under Settings → Apps): an existing installation is left alone, and uninstalling Airhand keeps it. No administrator rights are needed afterwards, and it also works for the lock screen and the system service. Airhand notices when it gets installed, no restart needed - **Linux hosts** use the kernel's `vhci-hcd` when Airhand runs as root, otherwise `uinput`: Airhand needs access to `/dev/uinput`. Steam's controller rules (`steam-devices`) already grant it to the user at the seat; otherwise add a udev rule: diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index e5faa0ed..b0bf4373 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -53,7 +53,7 @@ Windows 上用安装程序安装,可以为所有用户安装,也可以仅为 - **第一次安装**:管理员账户在安装程序里选择安装方式(默认为所有用户安装)。普通账户运行时安装程序先问一句:选“是”就以管理员身份重新运行(要输入管理员密码),为所有用户安装;选“否”仅为你安装 - **升级、重新安装**:按原来的方式安装,不再询问。为所有用户安装的那份需要管理员权限,普通账户运行时会先说明,再要求输入管理员密码。升级前托盘开着的话,装好后自动重新打开(远程帮别人升级时,连接随之恢复) - **换安装方式**:先卸载,再重新安装 -- **手柄驱动**:安装包里带着 [usbip-win2](https://github.com/vadimgrn/usbip-win2),这台电脑还没装的话安装时问要不要装(两种安装方式都问),见[手柄](#手柄) +- **手柄和麦克风的驱动**:安装包里带着 [usbip-win2](https://github.com/vadimgrn/usbip-win2),这台电脑还没装的话安装时问要不要装(两种安装方式都问),见[手柄](#手柄)和[麦克风](#麦克风) ### 为所有用户安装 @@ -152,7 +152,7 @@ Airhand 要保存的东西都在一个 `config.toml` 里(里面有注释)。 装过[虚拟显示器](#虚拟显示器)驱动的话,卸载程序在确认卸载之前有一页“同时删除虚拟显示器驱动”,默认不勾:不勾就留着停用了的驱动(还有注册表里认得它的记录 `HKLM\SOFTWARE\Airhand\VirtualDisplay` 和它的设置 `%ProgramData%\Airhand\VirtualDisplay`),重新安装 Airhand 时接着用;勾上就一起删掉。 -安装时装上的[手柄驱动 usbip-win2](#手柄)是单独的程序,卸载 Airhand 时留着;不用了的话在“设置 → 应用”里卸载 USBip(卸载时所有 USB 设备会断开一下,它建议之后重新启动)。 +安装时装上的[手柄和麦克风的驱动 usbip-win2](#手柄)是单独的程序,卸载 Airhand 时留着;不用了的话在“设置 → 应用”里卸载 USBip(卸载时所有 USB 设备会断开一下,它建议之后重新启动)。 (升级时选择“先卸载旧版本”不算卸载:会保留 `config.toml`,见 [Windows 安装版](#windows-安装版)。) @@ -332,8 +332,8 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 把这台电脑的麦克风发给对方:对方电脑上的程序(开会、语音输入、发语音消息)把录音设备选成它的虚拟麦克风,就能听到你说话。默认关闭,每个连接单独打开(工具栏的麦克风按钮 → **把本机麦克风发给对方**),只在正在查看那个连接时发送;第一次打开时浏览器会问能不能用麦克风(桌面版不问)。 -- Windows 被控端使用 Steam 自带的 **Steam Streaming Microphone**(Valve 提供、微软签名的虚拟麦克风驱动)。打开转发时,如果设备尚未就绪,Airhand 会从对方电脑的 Steam 安装目录查找并安装驱动。设备就绪后会自动开始转发。对方电脑上缺少 Steam 时,麦克风菜单会提示安装 Steam -- 在对方电脑的程序里把录音设备选成“麦克风 (Steam Streaming Microphone)”(英文系统是 “Microphone (Steam Streaming Microphone)”),或者在那台电脑的“声音设置 → 输入”里把它设为默认,Windows 的语音输入(Win+H)等用默认麦克风的程序就直接听得到 +- **Windows 被控端**插上一个虚拟的 USB 麦克风 **Airhand Microphone**,Windows 用自带的声卡驱动驱动它,经的是和[手柄](#手柄)同一个 [usbip-win2](https://github.com/vadimgrn/usbip-win2) 驱动(Airhand 的安装包里带着;对方没装时麦克风菜单会提示,装好后不用重启 Airhand)。不用再装别的东西,不要管理员权限,也不改声音设置。第一次打开转发时插上,一秒左右就绪(一台电脑上的第一次约 6 秒,Windows 要先装好它)。关掉转发、切到别的连接时不拔掉,选了它的会议软件不会换成对方电脑自己的麦克风,只是录到静音。断开连接时拔掉(连接断掉了的,30 秒内没连回来再拔) +- 在对方电脑的程序里把录音设备选成“麦克风 (Airhand Microphone)”(英文系统是 “Microphone (Airhand Microphone)”),或者在那台电脑的“声音设置 → 输入”里把它设为默认,Windows 的语音输入(Win+H)等用默认麦克风的程序就直接听得到。Windows 记得它,下次插上时这些选择都还在 - 同一时刻只给一个控制端;别的控制端打开时会显示“另一个控制端正在用”,那个关掉之后自动换过来 - **macOS 14.2+ 和 Linux(PipeWire)**:打开转发后,在对方的会议或录音软件里选择 **Airhand Microphone**。Mac 首次使用时可能要允许该软件录制系统音频。关闭转发或断开连接后设备会移除。Linux 结束 Airhand 进程后由 PipeWire 自动移除;Mac 强制退出后,重新打开 Airhand 或使用菜单里的“卸载 Airhand…”会清理残留。 - Android 被控端和 Android 控制端目前还不支持麦克风转发。 @@ -355,7 +355,7 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 接在你这边的电脑或手机上的手柄(Xbox、PlayStation、Switch Pro、掌机自带的手柄……)会作为有线的 **Xbox 360 手柄**插到对方电脑上:游戏看到的就是一个真的 USB 手柄(XInput、DirectInput、Windows.Gaming.Input、SDL、Steam、evdev),游戏让它震动时,你手里的手柄跟着震。默认打开,每个连接各有一个开关。 -- **Windows 被控端**要装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2)(免费的开源 USB/IP 驱动,BSD 许可,有微软的签名),**Airhand 的安装包里带着它**:这台电脑还没装、是 x64 的 Windows 10 1903 以上时,安装 Airhand 时会问要不要装(仅为我安装时也问,Windows 会要求管理员权限)。装的时候这台电脑的 USB 设备会断开一两秒再恢复;usbip-win2 建议装好后重新启动一次电脑 +- **Windows 被控端**要装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2)(免费的开源 USB/IP 驱动,BSD 许可,有微软的签名;[麦克风](#麦克风)也用它),**Airhand 的安装包里带着它**:这台电脑还没装、是 x64 的 Windows 10 1903 以上时,安装 Airhand 时会问要不要装(仅为我安装时也问,Windows 会要求管理员权限)。装的时候这台电脑的 USB 设备会断开一两秒再恢复;usbip-win2 建议装好后重新启动一次电脑 - 当时没装的话,重新运行 Airhand 的安装程序会再问;也可以从它的 [Releases](https://github.com/vadimgrn/usbip-win2/releases) 下载安装。静默(`/S`)、被动(`/P`,自动更新用的)安装不问也不装,命令行里加上 `/USBIP` 就不问直接装 - 它是单独的程序(“设置 → 应用”里的 USBip),已经装了的不动它,卸载 Airhand 时也留着。装好之后不需要管理员权限,锁屏界面、系统服务里也能用;Airhand 自己会发现装好了,不用重启 - **Linux 被控端**:Airhand 以 root 运行时用内核的 `vhci-hcd`,否则用 `uinput`,需要能读写 `/dev/uinput`。装了 Steam 的手柄规则(`steam-devices`)就已经给了坐在电脑前的用户;否则加一条 udev 规则: