fix(audio): select the managed default capture source explicitly

This commit is contained in:
Xuc Pan committed 2026-11-09 23:26:21 +08:00
1 parent 98af6fce28
commit eb862b5529
12 files changed
+203 -32

No files matched your search

+111 -1
View File
@@ -4,6 +4,116 @@ use anyhow::{Context, Result};
use std::path::Path;
use std::process::{Command, Stdio};
fn pactl(arguments: &[&str]) -> Result<String> {
let output = Command::new("pactl")
.args(arguments)
.env("LC_ALL", "C")
.stdin(Stdio::null())
.output()
.context("querying PulseAudio; install pactl and enable PulseAudio or pipewire-pulse")?;
anyhow::ensure!(
output.status.success(),
"pactl failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
Ok(String::from_utf8(output.stdout)?.trim().to_owned())
}
/// Resolve only a real, available source. Explicit loopback selection must
/// fail if unavailable rather than silently capturing a physical microphone.
pub fn capture_source(selection: Option<&str>) -> Result<Option<String>> {
let Some(selection) = selection else {
return Ok(None);
};
anyhow::ensure!(
!selection.is_empty() && !selection.chars().any(char::is_control),
"invalid audio source name"
);
let sources: Vec<serde_json::Value> =
serde_json::from_str(&pactl(&["--format=json", "list", "sources"])?)?;
let name = if selection == "system" {
let default = pactl(&["get-default-sink"])?;
let sinks: Vec<serde_json::Value> =
serde_json::from_str(&pactl(&["--format=json", "list", "sinks"])?)?;
sinks
.iter()
.find(|sink| sink["name"].as_str() == Some(&default))
.and_then(|sink| sink["monitor_source"].as_str())
.context("the default output has no system-audio monitor source")?
.to_owned()
} else {
selection.to_owned()
};
anyhow::ensure!(sources.iter().any(|source| source["name"].as_str() == Some(&name)),
"audio source {name:?} is unavailable; use `uur audio sources` to choose an available source");
Ok(Some(name))
}
pub fn print_sources() -> Result<()> {
let sources: Vec<serde_json::Value> =
serde_json::from_str(&pactl(&["--format=json", "list", "sources"])?)?;
println!("Default source: {}", pactl(&["get-default-source"])?);
for source in sources {
let name = source["name"]
.as_str()
.context("audio source has no name")?;
let description = source["description"].as_str().unwrap_or(name);
let monitor = source["monitor_source"].as_str().is_some()
|| source["monitor_of_sink"]
.as_u64()
.is_some_and(|index| index != u64::from(u32::MAX));
println!(
"{name}\t{}\t{description}",
if monitor {
"system monitor"
} else {
"capture input"
}
);
}
Ok(())
}
pub fn configure_source(selection: &str) -> Result<()> {
let choice = (selection != "default").then_some(selection);
let resolved = capture_source(choice)?;
crate::config::Config::update(|stored| {
stored.audio_capture_source = choice.map(ToOwned::to_owned)
})?;
println!(
"Wine default audio capture: {}; applies after `uur stop` and `uur run`",
resolved
.as_deref()
.unwrap_or("follow the existing audio environment")
);
if choice == Some("system") {
println!("The fallback capture input will carry system sound. Separate simultaneous microphone and speaker channels still require the official audio driver.");
}
Ok(())
}
pub(crate) fn apply_capture_env(
command: &mut Command,
config: &crate::config::Config,
) -> Result<()> {
if config.audio_capture_source.is_none() {
return Ok(());
}
// Each process resolves once, before starting the managed wineserver/SCM.
static SOURCE: std::sync::OnceLock<std::result::Result<Option<String>, String>> =
std::sync::OnceLock::new();
match SOURCE.get_or_init(|| {
capture_source(config.audio_capture_source.as_deref()).map_err(|e| format!("{e:#}"))
}) {
Ok(Some(source)) => {
command.env("PULSE_SOURCE", source);
}
Ok(None) => {}
Err(error) => anyhow::bail!("Wine audio capture unavailable: {error}"),
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
PipeWirePulse,
@@ -52,7 +162,7 @@ pub fn sync_wine(prefix: &Path) -> Result<Backend> {
Backend::None => None,
};
if let Some(driver) = driver {
let status = crate::wine::command(prefix)
let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args([
+4
View File
@@ -34,6 +34,9 @@ pub struct Config {
pub capture_backend: String,
/// Named Wayland output for direct capture; a single-output session needs no name.
pub capture_output: Option<String>,
/// Override Wine's default capture source: "system" or a PulseAudio source
/// name. None follows the user's existing audio environment.
pub audio_capture_source: Option<String>,
/// Strip these X11 modifier bits from key events handed to the managed
/// client. Wine reconciles its asynchronous keyboard state against the
/// modifier bits on every key event and, when the client's low-level hook
@@ -58,6 +61,7 @@ impl Default for Config {
capture_multiple: false,
capture_backend: "portal".into(),
capture_output: None,
audio_capture_source: None,
strip_lock_mods: Some("auto".into()),
}
}
+11
View File
@@ -247,6 +247,17 @@ pub fn report() -> Result<()> {
let audio = crate::audio::detect();
line("info", "audio backend", audio.label());
let audio_config = crate::config::Config::load()?;
match crate::audio::capture_source(audio_config.audio_capture_source.as_deref()) {
Ok(source) => line(
"info",
"Wine default audio capture",
source
.as_deref()
.unwrap_or("existing audio environment; may be a microphone"),
),
Err(error) => line("warn", "Wine default audio capture", &format!("{error:#}")),
}
let video = crate::video::detect();
line(
+1 -1
View File
@@ -66,7 +66,7 @@ pub fn prepare(prefix: &Path, proxy: &Path) -> Result<usize> {
std::fs::write(root.with_extension("keys"), keys.join("\n") + "\n")?;
let registry_path = prefix.join("drive_c/uur-linux-apps.reg");
write_utf16_registry(&registry_path, &registry)?;
let status = crate::wine::command(prefix)
let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args(["reg", "import"])
+17
View File
@@ -89,6 +89,11 @@ enum Command {
#[command(subcommand)]
action: DisplayAction,
},
/// Select Wine's default microphone/system-audio capture source.
Audio {
#[command(subcommand)]
action: AudioAction,
},
/// Internal input bridge process. Not part of the public CLI.
#[command(hide = true, name = "__bridge")]
InternalBridge,
@@ -174,6 +179,14 @@ enum DisplayAction {
Outputs,
}
#[derive(Subcommand)]
enum AudioAction {
/// List real capture inputs and system-audio monitor sources.
Sources,
/// Use system sound, a source name, or default to follow the existing environment.
Source { source: String },
}
#[derive(Clone, ValueEnum)]
enum CaptureBackend {
Portal,
@@ -212,6 +225,10 @@ fn main() -> Result<()> {
Command::Doctor => doctor::report(),
Command::Pointer => bridge::print_pointer(),
Command::Capture => capture::run_standalone(),
Command::Audio { action } => match action {
AudioAction::Sources => audio::print_sources(),
AudioAction::Source { source } => audio::configure_source(&source),
},
Command::Run => session::start(),
Command::Stop => session::stop(),
Command::Uninstall {
+1 -1
View File
@@ -60,7 +60,7 @@ fn proxy_endpoint(value: &str) -> Option<String> {
}
fn reg_add(prefix: &Path, value: &str, kind: &str, data: &str) -> Result<()> {
let status = crate::wine::command(prefix)
let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args([
+18 -11
View File
@@ -300,8 +300,8 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
/// bootstrapper ships inside the client's bin directory.
const WEBVIEW2_DLL_OVERRIDES: &str = "wtsapi32=b,wevtapi=b";
fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command {
let mut command = crate::wine::command(prefix);
fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Result<Command> {
let mut command = crate::wine::command(prefix)?;
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
@@ -311,7 +311,7 @@ fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command {
.env("WINEDLLOVERRIDES", WEBVIEW2_DLL_OVERRIDES)
.arg(bootstrapper)
.args(["/silent", "/install"]);
command
Ok(command)
}
fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
@@ -324,7 +324,7 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
anyhow::bail!("{}", t!("session.webview_missing"));
}
println!("{}", t!("session.installing_webview"));
let status = webview2_install_command(prefix, &bootstrapper)
let status = webview2_install_command(prefix, &bootstrapper)?
.status()
.context("running the WebView2 bootstrapper")?;
if !status.success() || !crate::wine::webview2_installed(prefix) {
@@ -501,7 +501,10 @@ pub fn start() -> Result<()> {
anyhow::bail!("{}", t!("setup.service_incomplete"));
}
let mut resources = SessionResources::new(prefix.clone());
if lock_mods_mask(&config)?.is_some() && lock_mods_shim().is_some() {
let selected_audio = crate::audio::capture_source(config.audio_capture_source.as_deref())?;
if selected_audio.is_some()
|| (lock_mods_mask(&config)?.is_some() && lock_mods_shim().is_some())
{
// A server left by setup or an older client has the old environment.
// The session lock excludes a running uur session; restart only this
// managed prefix so its SCM-spawned clients inherit the same shim.
@@ -626,7 +629,7 @@ pub fn start() -> Result<()> {
// Windows process table without repeatedly initializing Wine utilities.
use std::os::unix::process::CommandExt;
let marker = hook_dir()?.join("winlogon.exe");
let mut monitor = crate::wine::command(&prefix)
let mut monitor = crate::wine::command(&prefix)?
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
@@ -655,7 +658,7 @@ pub fn start() -> Result<()> {
// waits forever.
if !service_running(&prefix) {
let _ = run_with_timeout(
crate::wine::command(&prefix)
crate::wine::command(&prefix)?
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
@@ -679,7 +682,7 @@ pub fn start() -> Result<()> {
println!("{}", t!("session.launching_client"));
let ui = install_dir.join("GameViewer.exe");
let launch = || -> Result<Child> {
let mut command = crate::wine::command(&prefix);
let mut command = crate::wine::command(&prefix)?;
command
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
@@ -852,8 +855,11 @@ fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Opti
/// True when the Windows service reports STATE 4 (RUNNING) via `sc query`.
fn service_running(prefix: &Path) -> bool {
let Ok(mut command) = crate::wine::command(prefix) else {
return false;
};
let output = run_with_timeout(
crate::wine::command(prefix)
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
@@ -911,7 +917,7 @@ pub(crate) fn show_client() -> Result<()> {
if process_start_time(pid).ok() != Some(start) {
anyhow::bail!("managed session is not running");
}
let mut command = crate::wine::command(&prefix);
let mut command = crate::wine::command(&prefix)?;
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
@@ -1346,7 +1352,8 @@ mod tests {
let command = webview2_install_command(
Path::new("/tmp/uur-wine-prefix"),
Path::new("/tmp/MicrosoftEdgeWebview2Setup.exe"),
);
)
.unwrap();
let overrides = command
.get_envs()
.find_map(|(name, value)| (name == OsStr::new("WINEDLLOVERRIDES")).then_some(value))
+1
View File
@@ -72,6 +72,7 @@ fn installed_version() -> Option<String> {
let prefix = crate::config::data_dir().ok()?.join("wine");
crate::wine::find_client_dir(&prefix)?;
let output = crate::wine::command(&prefix)
.ok()?
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", "-all")
.args([
+1 -1
View File
@@ -90,7 +90,7 @@ pub fn sync(prefix: &Path) -> Result<Option<Wallpaper>> {
};
let compatible = windows_compatible_path(&wallpaper.path)?;
let windows_path = format!("Z:{}", compatible.display()).replace('/', "\\");
let status = crate::wine::command(prefix)
let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args([
+15 -15
View File
@@ -11,18 +11,18 @@ const SETUP_DLL_OVERRIDES: &str = "wevtapi=b,wtsapi32=b";
/// Apply process-local compatibility to every managed-prefix Wine launch,
/// including the first utility that starts wineserver and its service manager.
pub(crate) fn command(prefix: &Path) -> Command {
pub(crate) fn command(prefix: &Path) -> Result<Command> {
let mut command = Command::new("wine");
command.env("WINEPREFIX", prefix);
let managed = crate::config::data_dir().is_ok_and(|data| data.join("wine") == prefix);
if managed {
if let Ok(config) = Config::load() {
if let Err(error) = crate::session::apply_lock_mods_env(&mut command, &config) {
eprintln!("Wine keyboard compatibility unavailable: {error}");
}
let config = Config::load()?;
crate::audio::apply_capture_env(&mut command, &config)?;
if let Err(error) = crate::session::apply_lock_mods_env(&mut command, &config) {
eprintln!("Wine keyboard compatibility unavailable: {error}");
}
}
command
Ok(command)
}
struct SetupPrefix(PathBuf);
@@ -106,7 +106,7 @@ pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
}
println!("{}", t!("setup.installing_client"));
let status = command(&prefix)
let status = command(&prefix)?
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
@@ -190,7 +190,7 @@ pub fn client_service_registered(prefix: &Path) -> bool {
}
fn query_client_service(prefix: &Path) -> Result<bool> {
let output = command(prefix)
let output = command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
@@ -276,7 +276,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
format!("HKCU\\{key}")
};
for (value, reg_type, data) in &values {
let status = command(prefix)
let status = command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
@@ -296,7 +296,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
}
pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
let status = command(prefix)
let status = command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
@@ -323,7 +323,7 @@ pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
}
pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
let status = log_pixels_command(prefix, dpi)
let status = log_pixels_command(prefix, dpi)?
.status()
.context("setting the Wine system DPI")?;
if !status.success() {
@@ -332,8 +332,8 @@ pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
Ok(())
}
fn log_pixels_command(prefix: &Path, dpi: u32) -> Command {
let mut command = command(prefix);
fn log_pixels_command(prefix: &Path, dpi: u32) -> Result<Command> {
let mut command = command(prefix)?;
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
@@ -352,7 +352,7 @@ fn log_pixels_command(prefix: &Path, dpi: u32) -> Command {
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
command
Ok(command)
}
fn wine_debug() -> String {
@@ -848,7 +848,7 @@ mod tests {
#[test]
fn system_dpi_command_writes_winecfg_logpixels_value() {
let command = log_pixels_command(Path::new("/tmp/wine-prefix"), 192);
let command = log_pixels_command(Path::new("/tmp/wine-prefix"), 192).unwrap();
let args = command
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())