From ff23a1aa7b87d9d67bce48744fcdbbbb6d36f724 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 14 Oct 2026 21:50:32 +0200 Subject: [PATCH] feat(M4.3): select one capable audio authority Add typed manual/auto backend selection, capability diagnostics, compiled-feature probes, Pulse server identity reporting, and bounded same-authority reconnect scheduling. Prevent hardware-only adapters from satisfying application-stream requirements. Tests: cargo test -p volume_lib --all-targets --all-features; cargo check -p volume_lib --all-targets --no-default-features; cargo fmt --all -- --check --- sound/src/lib.rs | 12 +- sound/src/policy.rs | 625 ++++++++++++++++++++++++++++++++++++++ sound/src/pulse.rs | 21 ++ sound/src/pulse_worker.rs | 2 + 4 files changed, 659 insertions(+), 1 deletion(-) create mode 100644 sound/src/policy.rs diff --git a/sound/src/lib.rs b/sound/src/lib.rs index fe43ab5..f1ae638 100644 --- a/sound/src/lib.rs +++ b/sound/src/lib.rs @@ -2,13 +2,19 @@ #![forbid(unsafe_code)] +mod policy; #[cfg(feature = "pulse")] mod pulse; #[cfg(feature = "pulse")] mod pulse_worker; +pub use policy::{ + AdapterAuthority, AdapterChoice, AdapterProbe, AudioBackend, Capability, CompiledAdapterProbe, + ProbeDiagnostic, ProbeOutcome, ReconnectAttempt, SelectedAdapter, SelectionError, + SelectionPolicy, SelectionPolicyError, TargetRequirements, TargetScope, select_adapter, +}; #[cfg(feature = "pulse")] -pub use pulse::{PulseClient, PulseError, PulseNotification, PulseStream}; +pub use pulse::{PulseClient, PulseError, PulseNotification, PulseServerIdentity, PulseStream}; #[cfg(feature = "pulse")] pub use pulse_worker::PulseWorker; @@ -23,6 +29,8 @@ use fader_core::{AdapterCommand, AdapterEvent, BackendEpoch, ChannelGains, Mute, /// Capabilities reported before an adapter becomes authoritative. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct AdapterCapabilities { + pub application_streams: bool, + pub hardware_targets: bool, pub volume: bool, pub mute: bool, pub subscriptions: bool, @@ -251,6 +259,8 @@ impl FakeAdapter { #[must_use] pub const fn capabilities(&self) -> AdapterCapabilities { AdapterCapabilities { + application_streams: true, + hardware_targets: false, volume: true, mute: true, subscriptions: true, diff --git a/sound/src/policy.rs b/sound/src/policy.rs new file mode 100644 index 0000000..bcd58ca --- /dev/null +++ b/sound/src/policy.rs @@ -0,0 +1,625 @@ +use std::{collections::BTreeSet, error::Error, fmt}; + +use thiserror::Error; + +use crate::{AdapterCapabilities, RetrySchedule}; + +/// A concrete audio backend that can become the sole graph authority. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum AudioBackend { + Pulse, + PipeWire, + AlsaMixer, +} + +impl fmt::Display for AudioBackend { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Pulse => "pulse", + Self::PipeWire => "pipewire", + Self::AlsaMixer => "alsa-mixer", + }) + } +} + +/// Configured or session-only adapter selection. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AdapterChoice { + Auto, + Manual(AudioBackend), +} + +/// Target family that a backend must expose. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TargetScope { + ApplicationStreams, + HardwareMixer, +} + +/// Capabilities required by the active profile before a backend can be selected. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct TargetRequirements { + pub scope: TargetScope, + pub volume: bool, + pub mute: bool, + pub subscriptions: bool, +} + +impl TargetRequirements { + /// Requirements for the application/group mixer implemented by fader_master. + pub const APPLICATION_MIXER: Self = Self { + scope: TargetScope::ApplicationStreams, + volume: true, + mute: true, + subscriptions: true, + }; +} + +/// One missing capability reported in selection diagnostics. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum Capability { + ApplicationStreams, + HardwareTargets, + Volume, + Mute, + Subscriptions, +} + +impl fmt::Display for Capability { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::ApplicationStreams => "application streams", + Self::HardwareTargets => "hardware mixer targets", + Self::Volume => "volume writes", + Self::Mute => "mute writes", + Self::Subscriptions => "change subscriptions", + }) + } +} + +/// Outcome of a bounded connection/capability probe. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ProbeOutcome { + Available { + capabilities: AdapterCapabilities, + server_name: Option, + server_version: Option, + }, + Unavailable { + message: String, + }, + NotBuilt { + feature: &'static str, + }, +} + +/// Diagnostic retained for every backend considered before selection stopped. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ProbeDiagnostic { + pub backend: AudioBackend, + pub outcome: ProbeOutcome, + pub missing: Vec, +} + +/// Probe boundary used by production feature checks and deterministic tests. +pub trait AdapterProbe { + fn probe(&mut self, backend: AudioBackend) -> ProbeOutcome; +} + +/// Selection request with a non-persistent CLI/session override. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SelectionPolicy { + configured: AdapterChoice, + preference: Vec, + session_override: Option, +} + +/// Invalid programmatic selection policy. +#[derive(Clone, Debug, Error, Eq, PartialEq)] +pub enum SelectionPolicyError { + #[error("adapter preference contains duplicate backend {0}")] + Duplicate(AudioBackend), +} + +impl SelectionPolicy { + /// Builds a policy after rejecting ambiguous duplicate probe entries. + pub fn new( + configured: AdapterChoice, + preference: Vec, + session_override: Option, + ) -> Result { + let preference = if preference.is_empty() { + vec![AudioBackend::Pulse, AudioBackend::PipeWire] + } else { + preference + }; + let mut seen = BTreeSet::new(); + for backend in &preference { + if !seen.insert(*backend) { + return Err(SelectionPolicyError::Duplicate(*backend)); + } + } + Ok(Self { + configured, + preference, + session_override, + }) + } + + /// Effective choice; the session override never mutates the configured value. + #[must_use] + pub const fn effective_choice(&self) -> AdapterChoice { + match self.session_override { + Some(choice) => choice, + None => self.configured, + } + } + + #[must_use] + pub fn preference(&self) -> &[AudioBackend] { + &self.preference + } +} + +/// The one backend authorized to control the active audio graph. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SelectedAdapter { + pub backend: AudioBackend, + pub capabilities: AdapterCapabilities, + pub server_name: Option, + pub server_version: Option, + pub diagnostics: Vec, +} + +/// A failed manual or automatic selection, including every attempted probe. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SelectionError { + choice: AdapterChoice, + diagnostics: Vec, +} + +impl SelectionError { + #[must_use] + pub fn diagnostics(&self) -> &[ProbeDiagnostic] { + &self.diagnostics + } +} + +impl fmt::Display for SelectionError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.choice { + AdapterChoice::Auto => formatter.write_str("no capable audio backend is available")?, + AdapterChoice::Manual(backend) => { + write!( + formatter, + "manually selected {backend} backend is unavailable" + )?; + } + } + for diagnostic in &self.diagnostics { + write!(formatter, "; {}: ", diagnostic.backend)?; + match &diagnostic.outcome { + ProbeOutcome::Available { .. } => { + formatter.write_str("missing ")?; + for (index, capability) in diagnostic.missing.iter().enumerate() { + if index > 0 { + formatter.write_str(", ")?; + } + capability.fmt(formatter)?; + } + } + ProbeOutcome::Unavailable { message } => formatter.write_str(message)?, + ProbeOutcome::NotBuilt { feature } => { + write!(formatter, "not built; enable the {feature:?} Cargo feature")?; + } + } + } + Ok(()) + } +} + +impl Error for SelectionError {} + +/// Selects at most one capable backend and retains all probe diagnostics. +pub fn select_adapter( + policy: &SelectionPolicy, + requirements: TargetRequirements, + probe: &mut impl AdapterProbe, +) -> Result { + let choice = policy.effective_choice(); + let candidates = match choice { + AdapterChoice::Auto => policy.preference().to_vec(), + AdapterChoice::Manual(backend) => vec![backend], + }; + let mut diagnostics = Vec::new(); + for backend in candidates { + let outcome = probe.probe(backend); + let missing = match &outcome { + ProbeOutcome::Available { capabilities, .. } => { + missing_capabilities(*capabilities, requirements) + } + ProbeOutcome::Unavailable { .. } | ProbeOutcome::NotBuilt { .. } => Vec::new(), + }; + diagnostics.push(ProbeDiagnostic { + backend, + outcome: outcome.clone(), + missing: missing.clone(), + }); + if missing.is_empty() + && let ProbeOutcome::Available { + capabilities, + server_name, + server_version, + } = outcome + { + return Ok(SelectedAdapter { + backend, + capabilities, + server_name, + server_version, + diagnostics, + }); + } + } + Err(SelectionError { + choice, + diagnostics, + }) +} + +fn missing_capabilities( + capabilities: AdapterCapabilities, + requirements: TargetRequirements, +) -> Vec { + let mut missing = Vec::new(); + match requirements.scope { + TargetScope::ApplicationStreams if !capabilities.application_streams => { + missing.push(Capability::ApplicationStreams); + } + TargetScope::HardwareMixer if !capabilities.hardware_targets => { + missing.push(Capability::HardwareTargets); + } + TargetScope::ApplicationStreams | TargetScope::HardwareMixer => {} + } + if requirements.volume && !capabilities.volume { + missing.push(Capability::Volume); + } + if requirements.mute && !capabilities.mute { + missing.push(Capability::Mute); + } + if requirements.subscriptions && !capabilities.subscriptions { + missing.push(Capability::Subscriptions); + } + missing +} + +/// Production probe for the adapters compiled into this binary. +#[derive(Clone, Debug, Default)] +pub struct CompiledAdapterProbe { + pulse_server: Option, +} + +impl CompiledAdapterProbe { + /// Uses an explicit Pulse server address for isolated fixtures. + #[must_use] + pub fn with_pulse_server(server: impl Into) -> Self { + Self { + pulse_server: Some(server.into()), + } + } +} + +impl AdapterProbe for CompiledAdapterProbe { + fn probe(&mut self, backend: AudioBackend) -> ProbeOutcome { + match backend { + AudioBackend::Pulse => probe_pulse(self.pulse_server.as_deref()), + AudioBackend::PipeWire => ProbeOutcome::NotBuilt { + feature: "pipewire", + }, + AudioBackend::AlsaMixer => ProbeOutcome::NotBuilt { + feature: "alsa-mixer", + }, + } + } +} + +#[cfg(feature = "pulse")] +fn probe_pulse(server: Option<&str>) -> ProbeOutcome { + match crate::PulseClient::connect_to(server).and_then(|mut client| client.server_identity()) { + Ok(identity) => ProbeOutcome::Available { + capabilities: AdapterCapabilities { + application_streams: true, + hardware_targets: false, + volume: true, + mute: true, + subscriptions: true, + }, + server_name: identity.name, + server_version: identity.version, + }, + Err(error) => ProbeOutcome::Unavailable { + message: error.to_string(), + }, + } +} + +#[cfg(not(feature = "pulse"))] +fn probe_pulse(_server: Option<&str>) -> ProbeOutcome { + ProbeOutcome::NotBuilt { feature: "pulse" } +} + +/// Keeps the selected authority stable while producing bounded reconnect delays. +#[derive(Clone, Debug)] +pub struct AdapterAuthority { + selected: SelectedAdapter, + retries: RetrySchedule, +} + +/// One reconnect attempt against the existing authority. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ReconnectAttempt { + pub backend: AudioBackend, + pub delay_ms: u64, +} + +impl AdapterAuthority { + #[must_use] + pub fn new(selected: SelectedAdapter, initial_ms: u64, maximum_ms: u64) -> Self { + Self { + selected, + retries: RetrySchedule::new(initial_ms, maximum_ms), + } + } + + #[must_use] + pub const fn selected(&self) -> &SelectedAdapter { + &self.selected + } + + /// Retains the selected backend and schedules its next reconnect attempt. + pub fn disconnected(&mut self) -> ReconnectAttempt { + ReconnectAttempt { + backend: self.selected.backend, + delay_ms: self.retries.next_delay_ms(), + } + } + + /// Resets backoff only after a connection becomes ready again. + pub fn connected(&mut self) { + self.retries.reset(); + } +} + +#[cfg(test)] +mod tests { + use std::collections::{BTreeMap, VecDeque}; + + use super::*; + + struct FakeProbe { + outcomes: BTreeMap>, + calls: Vec, + } + + impl FakeProbe { + fn new(outcomes: impl IntoIterator) -> Self { + let mut grouped = BTreeMap::>::new(); + for (backend, outcome) in outcomes { + grouped.entry(backend).or_default().push_back(outcome); + } + Self { + outcomes: grouped, + calls: Vec::new(), + } + } + } + + impl AdapterProbe for FakeProbe { + fn probe(&mut self, backend: AudioBackend) -> ProbeOutcome { + self.calls.push(backend); + self.outcomes + .get_mut(&backend) + .and_then(VecDeque::pop_front) + .unwrap_or_else(|| ProbeOutcome::Unavailable { + message: "not scripted".into(), + }) + } + } + + fn application_capabilities() -> AdapterCapabilities { + AdapterCapabilities { + application_streams: true, + hardware_targets: false, + volume: true, + mute: true, + subscriptions: true, + } + } + + fn hardware_capabilities() -> AdapterCapabilities { + AdapterCapabilities { + application_streams: false, + hardware_targets: true, + volume: true, + mute: true, + subscriptions: true, + } + } + + fn available(capabilities: AdapterCapabilities) -> ProbeOutcome { + ProbeOutcome::Available { + capabilities, + server_name: Some("fixture".into()), + server_version: Some("1".into()), + } + } + + #[test] + fn manual_failure_is_actionable_and_never_falls_back() { + let policy = SelectionPolicy::new( + AdapterChoice::Manual(AudioBackend::PipeWire), + vec![AudioBackend::Pulse], + None, + ) + .unwrap(); + let mut probe = FakeProbe::new([ + ( + AudioBackend::PipeWire, + ProbeOutcome::NotBuilt { + feature: "pipewire", + }, + ), + (AudioBackend::Pulse, available(application_capabilities())), + ]); + + let error = + select_adapter(&policy, TargetRequirements::APPLICATION_MIXER, &mut probe).unwrap_err(); + assert_eq!(probe.calls, vec![AudioBackend::PipeWire]); + assert!( + error + .to_string() + .contains("enable the \"pipewire\" Cargo feature") + ); + } + + #[test] + fn session_override_wins_without_mutating_configured_choice() { + let policy = SelectionPolicy::new( + AdapterChoice::Manual(AudioBackend::Pulse), + vec![AudioBackend::Pulse, AudioBackend::PipeWire], + Some(AdapterChoice::Manual(AudioBackend::PipeWire)), + ) + .unwrap(); + let mut probe = FakeProbe::new([ + ( + AudioBackend::PipeWire, + available(application_capabilities()), + ), + (AudioBackend::Pulse, available(application_capabilities())), + ]); + + let selected = + select_adapter(&policy, TargetRequirements::APPLICATION_MIXER, &mut probe).unwrap(); + assert_eq!(selected.backend, AudioBackend::PipeWire); + assert_eq!(probe.calls, vec![AudioBackend::PipeWire]); + assert_eq!( + policy.configured, + AdapterChoice::Manual(AudioBackend::Pulse) + ); + } + + #[test] + fn auto_skips_unavailable_and_incapable_backends_then_stops() { + let policy = SelectionPolicy::new( + AdapterChoice::Auto, + vec![ + AudioBackend::Pulse, + AudioBackend::AlsaMixer, + AudioBackend::PipeWire, + ], + None, + ) + .unwrap(); + let mut probe = FakeProbe::new([ + ( + AudioBackend::Pulse, + ProbeOutcome::Unavailable { + message: "daemon absent".into(), + }, + ), + (AudioBackend::AlsaMixer, available(hardware_capabilities())), + ( + AudioBackend::PipeWire, + available(application_capabilities()), + ), + ]); + + let selected = + select_adapter(&policy, TargetRequirements::APPLICATION_MIXER, &mut probe).unwrap(); + assert_eq!(selected.backend, AudioBackend::PipeWire); + assert_eq!(selected.diagnostics.len(), 3); + assert_eq!( + selected.diagnostics[1].missing, + vec![Capability::ApplicationStreams] + ); + assert_eq!( + probe.calls, + vec![ + AudioBackend::Pulse, + AudioBackend::AlsaMixer, + AudioBackend::PipeWire + ] + ); + } + + #[test] + fn auto_selects_exactly_one_authority_without_probing_later_candidates() { + let policy = SelectionPolicy::new( + AdapterChoice::Auto, + vec![AudioBackend::Pulse, AudioBackend::PipeWire], + None, + ) + .unwrap(); + let mut probe = FakeProbe::new([ + (AudioBackend::Pulse, available(application_capabilities())), + ( + AudioBackend::PipeWire, + available(application_capabilities()), + ), + ]); + + let selected = + select_adapter(&policy, TargetRequirements::APPLICATION_MIXER, &mut probe).unwrap(); + assert_eq!(selected.backend, AudioBackend::Pulse); + assert_eq!(probe.calls, vec![AudioBackend::Pulse]); + assert_eq!(selected.server_name.as_deref(), Some("fixture")); + } + + #[test] + fn disconnect_retries_the_same_authority_with_bounded_backoff() { + let selected = SelectedAdapter { + backend: AudioBackend::Pulse, + capabilities: application_capabilities(), + server_name: Some("fixture".into()), + server_version: Some("1".into()), + diagnostics: Vec::new(), + }; + let mut authority = AdapterAuthority::new(selected, 100, 400); + assert_eq!( + (0..4).map(|_| authority.disconnected()).collect::>(), + vec![ + ReconnectAttempt { + backend: AudioBackend::Pulse, + delay_ms: 100, + }, + ReconnectAttempt { + backend: AudioBackend::Pulse, + delay_ms: 200, + }, + ReconnectAttempt { + backend: AudioBackend::Pulse, + delay_ms: 400, + }, + ReconnectAttempt { + backend: AudioBackend::Pulse, + delay_ms: 400, + }, + ] + ); + authority.connected(); + assert_eq!(authority.disconnected().delay_ms, 100); + assert_eq!(authority.selected().backend, AudioBackend::Pulse); + } + + #[test] + fn duplicate_probe_entries_are_rejected() { + assert_eq!( + SelectionPolicy::new( + AdapterChoice::Auto, + vec![AudioBackend::Pulse, AudioBackend::Pulse], + None, + ), + Err(SelectionPolicyError::Duplicate(AudioBackend::Pulse)) + ); + } +} diff --git a/sound/src/pulse.rs b/sound/src/pulse.rs index 8330812..fb82138 100644 --- a/sound/src/pulse.rs +++ b/sound/src/pulse.rs @@ -30,6 +30,13 @@ pub struct PulseStream { pub volume_writable: bool, } +/// Copied identity reported by the connected PulseAudio-compatible server. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PulseServerIdentity { + pub name: Option, + pub version: Option, +} + /// One subscribed playback-stream change. #[derive(Clone, Debug, PartialEq)] pub enum PulseNotification { @@ -182,6 +189,20 @@ impl PulseClient { Ok(std::mem::take(&mut result.items)) } + /// Copies the server name/version for adapter diagnostics. + pub fn server_identity(&mut self) -> Result { + let result = Rc::new(RefCell::new(None)); + let callback = Rc::clone(&result); + self.context.introspect().get_server_info(move |info| { + *callback.borrow_mut() = Some(PulseServerIdentity { + name: info.server_name.as_deref().map(str::to_owned), + version: info.server_version.as_deref().map(str::to_owned), + }); + }); + self.wait_for(|| result.borrow().is_some())?; + result.borrow_mut().take().ok_or(PulseError::Introspection) + } + /// Reads one sink input after a write or subscription notification. pub fn stream(&mut self, index: u32) -> Result { let result = Rc::new(RefCell::new(ListState::::default())); diff --git a/sound/src/pulse_worker.rs b/sound/src/pulse_worker.rs index 73ce10d..df123c6 100644 --- a/sound/src/pulse_worker.rs +++ b/sound/src/pulse_worker.rs @@ -242,6 +242,8 @@ fn run_connection( if !events.emit(WorkerEvent::Ready { epoch, capabilities: AdapterCapabilities { + application_streams: true, + hardware_targets: false, volume: true, mute: true, subscriptions: true,