diff --git a/crates/benilla-app/src/sound/output/cpal.rs b/crates/benilla-app/src/sound/output/cpal.rs index c5490a199..dc56f0a63 100644 --- a/crates/benilla-app/src/sound/output/cpal.rs +++ b/crates/benilla-app/src/sound/output/cpal.rs @@ -1,11 +1,14 @@ //! The non-macOS half of [`super`]: the same surface as `coreaudio.rs` ([`Device`], [`Stream`], //! [`Cycle`], [`Notices`], [`Listeners`], [`set_realtime`], [`now_ns`]) over cpal, which speaks -//! ALSA, PipeWire, WASAPI and the rest. Where cpal differs from CoreAudio: +//! ALSA (and through its PCMs PipeWire and PulseAudio), WASAPI and the rest. Where cpal differs +//! from CoreAudio: //! +//! - The device: when the host default will not open, another output stands in +//! ([`default_output`]). //! - Cycle timestamps: cpal gives `callback` and `playback` instants, so //! [`Cycle::output_time_ns`] is `now + (playback - callback)` on our own clock. //! - Device notices: cpal has no notification API, so [`Listeners`] polls the default device's -//! identity and rate, backed by cpal's stream error callback. Nothing is an analogue of +//! identity and the open device's rate, backed by cpal's stream error callback. Nothing is an analogue of //! `kAudioDeviceProcessorOverload`, so the overload meter reads zero. //! - Realtime: no workgroups; [`set_realtime`] is `SCHED_FIFO` on unix and MMCSS on Windows. //! @@ -53,9 +56,13 @@ pub(super) struct Device { /// The cpal handle and the config we open with. device: cpal::Device, config: cpal::SupportedStreamConfig, - /// The host's stable id, when it has one: what [`Listeners`] compares, since a display name - /// is neither unique nor fixed. + /// The host's stable id, when it has one. id: Option, + /// The host default when this device was chosen, which [`Listeners`] watches; `None` when the + /// host had none. + default: Option, + /// Whether this is that default rather than a stand-in for it. + is_default: bool, } impl std::fmt::Debug for Device { @@ -70,16 +77,125 @@ impl std::fmt::Debug for Device { } } -/// The host's default output device; with none (headless, no sound server, an unsupported -/// target) the caller runs silent. +/// Who a device is: the host's id where it has one, since a display name is neither unique nor +/// fixed, else the name. +#[derive(Clone)] +struct Identity { + id: Option, + name: String, +} + +impl Identity { + /// `None` when the device cannot be read, which is a transient, not a change. + fn of(device: &cpal::Device) -> Option { + let id = device.id().ok(); + let name = device.description().ok().map(|d| d.name().to_string()); + match (id, name) { + (None, None) => None, + (id, name) => Some(Self { + id, + name: name.unwrap_or_default(), + }), + } + } + + fn same_as(&self, other: &Self) -> bool { + match (&self.id, &other.id) { + (Some(a), Some(b)) => a == b, + _ => self.name == other.name, + } + } +} + +/// The stand-in search's memory across calls: devices whose stream would not open (skipped by +/// the next search, forgotten once any stream opens) and the stand-in last announced. +struct Choice { + refused: Vec, + announced: Option, +} + +static CHOICE: std::sync::Mutex = std::sync::Mutex::new(Choice { + refused: Vec::new(), + announced: None, +}); + +fn choice() -> std::sync::MutexGuard<'static, Choice> { + CHOICE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The host's default output device, or, when it will not open, the first other output that +/// does (`fallback.rs` orders them on ALSA; other hosts in their own order). With none +/// (headless, an unsupported target) the caller runs silent. +/// +/// Deviation: 1.12.1 sets FMOD up on driver 0 and, when that fails, runs silent for the session +/// (`Sound::Initialize` `0x7a4330`, the driver −1 → 0 at `0x7a445f`); here another output stands +/// in, because on Linux the default is often a stock `dmix` whose card a sound server holds. pub(super) fn default_output() -> Result { // Prime the clock's epoch on the main thread, not first in the audio callback. now_ns(); let host = cpal::default_host(); - let device = host - .default_output_device() - .context("no default output device")?; - describe(device) + let default = host.default_output_device(); + let watched = default.as_ref().and_then(Identity::of); + let refused = choice().refused.clone(); + let is_refused = |d: &cpal::Device| d.id().is_ok_and(|id| refused.contains(&id)); + + let why = match &default { + None => anyhow::anyhow!("no default output device"), + Some(d) if is_refused(d) => anyhow::anyhow!("its last stream would not open"), + Some(d) => match describe(d.clone()) { + Ok(mut device) => { + device.default = watched; + device.is_default = true; + choice().announced = None; + return Ok(device); + } + Err(e) => e, + }, + }; + + let alsa = host.id().name() == "ALSA"; + let others = host.devices().into_iter().flatten().filter(|d| { + d.description() + .is_ok_and(|desc| desc.direction() != cpal::DeviceDirection::Input) + && watched + .as_ref() + .is_none_or(|w| Identity::of(d).is_none_or(|i| !i.same_as(w))) + && !is_refused(d) + }); + let ranked = super::fallback::by_rank(others, |d| { + if !alsa { + return Some(0); + } + let id = d.id().ok()?; + let desc = d.description().ok()?; + super::fallback::alsa_rank(&id.1, &desc.extended().join("\n")) + }); + for candidate in ranked { + match describe(candidate) { + Ok(mut device) => { + device.default = watched; + let mut choice = choice(); + if choice.announced != device.id { + let id = device + .id + .as_ref() + .map_or(String::new(), |id| format!(" ({id})")); + bevy::log::warn!( + "audio: the default output will not open ({why:#}); playing on {}{id}", + device.name + ); + choice.announced.clone_from(&device.id); + } + return Ok(device); + } + Err(e) => bevy::log::debug!("audio: no stand-in there either: {e:#}"), + } + } + // Nothing else opens: forget the refusals, so the next search starts again at the default. + choice().refused.clear(); + Err(why.context("the default output will not open, and no other output does")) } fn describe(device: cpal::Device) -> Result { @@ -112,6 +228,8 @@ fn describe(device: cpal::Device) -> Result { id: device.id().ok(), device, config, + default: None, + is_default: false, }) } @@ -191,7 +309,7 @@ impl Stream { scratch: vec![0.0; MAX_CYCLE_FRAMES * CHANNELS as usize], }; // Every output format cpal can hand a typed callback for. - let stream = match device.config.sample_format() { + let built = match device.config.sample_format() { cpal::SampleFormat::F32 => build::(device, &config, ctx, on_error), cpal::SampleFormat::F64 => build::(device, &config, ctx, on_error), cpal::SampleFormat::I8 => build::(device, &config, ctx, on_error), @@ -203,11 +321,26 @@ impl Stream { cpal::SampleFormat::U16 => build::(device, &config, ctx, on_error), cpal::SampleFormat::U32 => build::(device, &config, ctx, on_error), cpal::SampleFormat::U64 => build::(device, &config, ctx, on_error), - other => bail!("device {} wants sample format {other}", device.name), - }?; - stream.play().context("starting the output stream")?; + other => Err(anyhow::anyhow!( + "device {} wants sample format {other}", + device.name + )), + }; + let started = built.and_then(|stream| { + stream.play().context("starting the output stream")?; + Ok(stream) + }); + // A refusal steers the next [`default_output`] search past this device; an open clears + // them, so a later search starts again at the default. + let mut choice = choice(); + match (&started, &device.id) { + (Ok(_), _) => choice.refused.clear(), + (Err(_), Some(id)) => choice.refused.push(id.clone()), + (Err(_), None) => {} + } + drop(choice); Ok(Self { - _stream: stream, + _stream: started?, observed_frames, }) } @@ -329,9 +462,9 @@ pub(super) struct Notices { pub last_overload_ns: AtomicU64, } -/// The device watch: a thread that re-reads the host's default output every [`WATCH_EVERY`] and -/// raises a notice when it changes. One-shot: the backend answers a notice by rebuilding the -/// stream, which arms a fresh watch. +/// The device watch: a thread that re-reads the host's default output and the open device's rate +/// every [`WATCH_EVERY`] and raises a notice when either changes. One-shot: the backend answers a +/// notice by rebuilding the stream, which arms a fresh watch. /// /// Deviation: a change of the default output device is followed (here and in `coreaudio.rs`), where /// 1.12.1 initialises its sound device once and never again (`Sound::Initialize` `0x7a4330` @@ -348,8 +481,12 @@ impl Listeners { pub(super) fn arm(device: &Device, notices: Arc) -> Self { let stop = Arc::new(AtomicBool::new(false)); let watching = Arc::clone(&stop); - let (was_id, was_name, was_rate) = - (device.id.clone(), device.name.clone(), device.sample_rate); + let (watched, is_default, ours, was_rate) = ( + device.default.clone(), + device.is_default, + device.device.clone(), + device.sample_rate, + ); let thread = std::thread::Builder::new() .name("audio-devwatch".into()) .spawn(move || { @@ -358,21 +495,27 @@ impl Listeners { if watching.load(Ordering::Acquire) { return; } - let Some(now) = cpal::default_host().default_output_device() else { - notices.device_died.store(true, Ordering::Release); - return; - }; - // By the host's id where there is one, else by name; an unreadable device - // is a transient (`None`), not a change. - let changed = match (&was_id, now.id()) { - (Some(was), Ok(is_now)) => Some(*was != is_now), - _ => now.description().ok().map(|d| d.name() != was_name), - }; - if changed == Some(true) { - notices.default_changed.store(true, Ordering::Release); - return; + // Compared with the default this device was chosen against, so a stand-in is + // not rebuilt every poll for a default that still will not open. + match cpal::default_host().default_output_device() { + None if is_default => { + notices.device_died.store(true, Ordering::Release); + return; + } + None => {} + Some(now) => { + let changed = match (&watched, Identity::of(&now)) { + (Some(was), Some(is_now)) => !is_now.same_as(was), + (None, Some(_)) => true, + (_, None) => false, + }; + if changed { + notices.default_changed.store(true, Ordering::Release); + return; + } + } } - if now + if ours .default_output_config() .is_ok_and(|c| c.sample_rate() != was_rate) { diff --git a/crates/benilla-app/src/sound/output/fallback.rs b/crates/benilla-app/src/sound/output/fallback.rs new file mode 100644 index 000000000..d3d72f010 --- /dev/null +++ b/crates/benilla-app/src/sound/output/fallback.rs @@ -0,0 +1,171 @@ +//! Which outputs stand in for a default output that will not open, decided from names alone so +//! it is tested on every platform; `cpal.rs` applies it to the devices its host enumerates. + +/// Where an ALSA PCM ranks as a stand-in for `default`, by its hint name and description, lowest +/// first; `None` is never tried. +/// +/// - A sound server's PCM first (`pipewire`, then `pulse`): when one holds the cards, a `default` +/// left as the stock `dmix` cannot open its slave, and the server's PCM is what plays. +/// - Then each card's own default (`sysdefault:CARD=…`), then the card with conversions +/// (`plughw:CARD=…`): the cards themselves when no server holds them. +/// - HDMI and DisplayPort cards after the rest: a monitor often has no speakers. +/// - Never `default` (already tried) or `null` (accepts everything, plays nothing); nor a card's +/// other routes (`hw`, `dmix`, `front`, `surround*`, `iec958`), which reach the same card as its +/// `sysdefault` and `plughw`, nor the capture, rate and mix plugins, nor `jack`. +pub(super) fn alsa_rank(pcm: &str, desc: &str) -> Option { + let (kind, args) = pcm.split_once(':').unwrap_or((pcm, "")); + let display = [pcm, desc].iter().any(|s| { + let s = s.to_ascii_lowercase(); + s.contains("hdmi") || s.contains("displayport") + }); + match (kind, args.is_empty()) { + ("pipewire", true) => Some(0), + ("pulse", true) => Some(1), + ("sysdefault" | "default", false) => Some(if display { 4 } else { 2 }), + ("plughw", false) => Some(if display { 5 } else { 3 }), + _ => None, + } +} + +/// `items` lowest rank first, in their given order within a rank, without the unranked. +pub(super) fn by_rank( + items: impl IntoIterator, + rank: impl Fn(&T) -> Option, +) -> Vec { + let mut ranked: Vec<(u8, T)> = items + .into_iter() + .filter_map(|item| rank(&item).map(|r| (r, item))) + .collect(); + ranked.sort_by_key(|(r, _)| *r); + ranked.into_iter().map(|(_, item)| item).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn order(hints: &[(&'static str, &'static str)]) -> Vec<&'static str> { + by_rank(hints.iter().copied(), |(pcm, desc)| alsa_rank(pcm, desc)) + .into_iter() + .map(|(pcm, _)| pcm) + .collect() + } + + /// An `aplay -L` with PipeWire's and Pulse's PCMs, an onboard card and an NVIDIA HDMI card, + /// each hint's description cut to its first line. + #[test] + fn a_sound_server_comes_before_the_cards() { + let hints = [ + ( + "null", + "Discard all samples (playback) or generate zero samples (capture)", + ), + ("hw:CARD=NVidia,DEV=3", "HDA NVidia, HDMI 0"), + ("plughw:CARD=NVidia,DEV=3", "HDA NVidia, HDMI 0"), + ("sysdefault:CARD=NVidia", "HDA NVidia, HDMI 0"), + ("hdmi:CARD=NVidia,DEV=0", "HDA NVidia, HDMI 0"), + ("pulse", "PulseAudio Sound Server"), + ( + "default", + "Default ALSA Output (currently PipeWire Media Server)", + ), + ("pipewire", "PipeWire Sound Server"), + ("hw:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Analog"), + ("plughw:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Analog"), + ("sysdefault:CARD=PCH", "HDA Intel PCH, ALC892 Analog"), + ("front:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Analog"), + ("surround51:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Analog"), + ("dmix:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Analog"), + ("dsnoop:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Analog"), + ("iec958:CARD=PCH,DEV=0", "HDA Intel PCH, ALC892 Digital"), + ]; + assert_eq!( + order(&hints), + [ + "pipewire", + "pulse", + "sysdefault:CARD=PCH", + "plughw:CARD=PCH,DEV=0", + "sysdefault:CARD=NVidia", + "plughw:CARD=NVidia,DEV=3", + ] + ); + } + + /// A PipeWire system whose `default` is left as the stock card route, as one player's + /// `aplay -L` lists it: the plugins ahead of `pipewire` are never stand-ins. + #[test] + fn the_plugins_listed_first_are_passed_over() { + let hints = [ + ( + "null", + "Discard all samples (playback) or generate zero samples (capture)", + ), + ( + "lavrate", + "Rate Converter Plugin Using Libav/FFmpeg Library", + ), + ( + "samplerate", + "Rate Converter Plugin Using Samplerate Library", + ), + ("speexrate", "Rate Converter Plugin Using Speex Resampler"), + ("jack", "JACK Audio Connection Kit"), + ("oss", "Open Sound System"), + ("pipewire", "PipeWire Sound Server"), + ("pulse", "PulseAudio Sound Server"), + ( + "speex", + "Plugin using Speex DSP (resample, agc, denoise, echo, dereverb)", + ), + ("upmix", "Plugin for channel upmix (4,6,8)"), + ( + "vdownmix", + "Plugin for channel downmix (stereo) with a simple spacialization", + ), + ("hdmi:CARD=NVidia,DEV=0", "HDA NVidia, PL2288H"), + ("hdmi:CARD=NVidia,DEV=1", "HDA NVidia, HDMI 1"), + ]; + assert_eq!(order(&hints), ["pipewire", "pulse"]); + } + + /// Two cards and no sound server's PCM: each card's default before either card raw, in the + /// host's card order. + #[test] + fn without_a_server_each_cards_default_comes_first() { + let hints = [ + ("default", "Default Audio Device"), + ( + "sysdefault:CARD=Generic", + "HD-Audio Generic, ALC1220 Analog", + ), + ( + "plughw:CARD=Generic,DEV=0", + "HD-Audio Generic, ALC1220 Analog", + ), + ("sysdefault:CARD=Audio", "USB Audio, USB Audio"), + ("plughw:CARD=Audio,DEV=0", "USB Audio, USB Audio"), + ( + "lavrate", + "Rate Converter Plugin Using Libav/FFmpeg Library", + ), + ("jack", "JACK Audio Connection Kit"), + ]; + assert_eq!( + order(&hints), + [ + "sysdefault:CARD=Generic", + "sysdefault:CARD=Audio", + "plughw:CARD=Generic,DEV=0", + "plughw:CARD=Audio,DEV=0", + ] + ); + } + + #[test] + fn the_default_and_silent_sinks_are_never_stand_ins() { + for pcm in ["default", "null", "pipewire:NODE=x", "sysdefault", "plughw"] { + assert_eq!(alsa_rank(pcm, ""), None, "{pcm}"); + } + } +} diff --git a/crates/benilla-app/src/sound/output/mod.rs b/crates/benilla-app/src/sound/output/mod.rs index ab9e51780..a218cb323 100644 --- a/crates/benilla-app/src/sound/output/mod.rs +++ b/crates/benilla-app/src/sound/output/mod.rs @@ -35,6 +35,9 @@ mod device; #[cfg(not(target_os = "macos"))] #[path = "cpal.rs"] mod device; +// The stand-ins `cpal.rs` tries for a default that will not open; tested on every platform. +#[cfg(any(test, not(target_os = "macos")))] +mod fallback; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 9d74a07e6..f7c8b6580 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -29,7 +29,7 @@ A setting boots at the reference's default unless it is listed here (`docs/METHO Each entry is the first sentence of a `Deviation:` comment, linking to where it lives. -- [benilla-app](#benilla-app): 223 +- [benilla-app](#benilla-app): 224 - [benilla-assets](#benilla-assets): 6 - [benilla-blp](#benilla-blp): 1 - [benilla-formats](#benilla-formats): 17 @@ -255,7 +255,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - `SoundOutputLimiter`, not a 1.12 CVar, default on, so overlapping full-scale kits are limited rather than clipped. ([`src/sound/mod.rs:119`](../crates/benilla-app/src/sound/mod.rs#L119)) - With no character the reference leaves the listener where it was; benilla seats it on the camera, where the view is. ([`src/sound/mod.rs:470`](../crates/benilla-app/src/sound/mod.rs#L470)) - The reference also plays an optimistic coin at the loot-money click, so looted money sounds twice; benilla plays the watcher's coin alone, because one coin on the confirmed change reads cleanly and the round trip the early coin hides is imperceptible on a local server. ([`src/sound/money.rs:7`](../crates/benilla-app/src/sound/money.rs#L7)) -- A change of the default output device is followed (here and in `coreaudio.rs`), where 1.12.1 initialises its sound device once and never again (`Sound::Initialize` `0x7a4330` refuses a second call; the driver-enumeration functions `0x7a6320`-`0x7a6380` have no caller), because a headset plugged in mid-session should play at once. ([`src/sound/output/cpal.rs:336`](../crates/benilla-app/src/sound/output/cpal.rs#L336)) +- 1.12.1 sets FMOD up on driver 0 and, when that fails, runs silent for the session (`Sound::Initialize` `0x7a4330`, the driver −1 → 0 at `0x7a445f`); here another output stands in, because on Linux the default is often a stock `dmix` whose card a sound server holds. ([`src/sound/output/cpal.rs:132`](../crates/benilla-app/src/sound/output/cpal.rs#L132)) +- A change of the default output device is followed (here and in `coreaudio.rs`), where 1.12.1 initialises its sound device once and never again (`Sound::Initialize` `0x7a4330` refuses a second call; the driver-enumeration functions `0x7a6320`-`0x7a6380` have no caller), because a headset plugged in mid-session should play at once. ([`src/sound/output/cpal.rs:469`](../crates/benilla-app/src/sound/output/cpal.rs#L469)) #### spell