From 0e8614fe370e27fd018352973cddfe8b1d093f94 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:14:16 -0600 Subject: [PATCH 1/3] feat(audio): add guarded ALSA hardware volume control Probe exact mixer element identities, retain stable device routes, and fail closed for ambiguous or switch-only controls. Synchronize player volume through ALSA events without changing direct PCM configuration. cx --- crates/Cargo.lock | 1 + crates/qbz-app/src/diagnostics.rs | 18 + crates/qbz-app/src/playback_driver.rs | 1 + crates/qbz-app/src/settings/bundle.rs | 23 +- crates/qbz-app/src/settings/bundle/tests.rs | 37 + crates/qbz-audio/Cargo.toml | 1 + crates/qbz-audio/src/alsa_direct.rs | 243 +- crates/qbz-audio/src/alsa_hardware_volume.rs | 2347 +++++++++++++++++ crates/qbz-audio/src/backend.rs | 12 +- crates/qbz-audio/src/lib.rs | 1 + crates/qbz-audio/src/settings.rs | 203 +- crates/qbz-player/src/player/mod.rs | 218 +- .../qbz-player/src/player/playback_engine.rs | 83 +- 13 files changed, 2935 insertions(+), 253 deletions(-) create mode 100644 crates/qbz-audio/src/alsa_hardware_volume.rs diff --git a/crates/Cargo.lock b/crates/Cargo.lock index 5cfe9ddc8..241ef3286 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -4066,6 +4066,7 @@ dependencies = [ "dirs 6.0.0", "ebur128", "jack", + "libc", "log", "objc2-core-audio", "qbz-models", diff --git a/crates/qbz-app/src/diagnostics.rs b/crates/qbz-app/src/diagnostics.rs index 30f5de09a..4dfd5f46b 100644 --- a/crates/qbz-app/src/diagnostics.rs +++ b/crates/qbz-app/src/diagnostics.rs @@ -28,6 +28,14 @@ pub struct RuntimeDiagnostics { pub audio_preferred_sample_rate: Option, pub audio_alsa_plugin: Option, pub audio_alsa_hardware_volume: bool, + pub audio_alsa_hardware_volume_controls: std::collections::HashMap< + qbz_audio::alsa_hardware_volume::StableAlsaRouteKey, + qbz_audio::alsa_hardware_volume::AlsaMixerControlId, + >, + /// Full read-only inventory for the active direct route, including + /// rejected controls and their typed reasons. + pub audio_alsa_hardware_volume_probe: + Option, pub audio_normalization_enabled: bool, pub audio_normalization_target_lufs: f32, pub audio_gapless_enabled: bool, @@ -121,6 +129,16 @@ pub fn runtime_diagnostics(i: &DiagnosticsInputs<'_>) -> RuntimeDiagnostics { audio_preferred_sample_rate: audio.preferred_sample_rate, audio_alsa_plugin: audio.alsa_plugin.map(|p| format!("{:?}", p)), audio_alsa_hardware_volume: audio.alsa_hardware_volume, + audio_alsa_hardware_volume_controls: audio.alsa_hardware_volume_controls.clone(), + audio_alsa_hardware_volume_probe: qbz_audio::alsa_direct::uses_alsa_direct_route(audio) + .then(|| { + qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls( + audio + .output_device + .as_deref() + .expect("direct ALSA route has a device id"), + ) + }), audio_normalization_enabled: audio.normalization_enabled, audio_normalization_target_lufs: audio.normalization_target_lufs, audio_gapless_enabled: audio.gapless_enabled, diff --git a/crates/qbz-app/src/playback_driver.rs b/crates/qbz-app/src/playback_driver.rs index 6c3f8e14e..6828361d8 100644 --- a/crates/qbz-app/src/playback_driver.rs +++ b/crates/qbz-app/src/playback_driver.rs @@ -1012,6 +1012,7 @@ mod tests { duration: dur, track_id: track, volume: 1.0, + hardware_volume_active: false, sample_rate: None, bit_depth: None, shuffle: None, diff --git a/crates/qbz-app/src/settings/bundle.rs b/crates/qbz-app/src/settings/bundle.rs index 2c8238cce..faf6c4f7d 100644 --- a/crates/qbz-app/src/settings/bundle.rs +++ b/crates/qbz-app/src/settings/bundle.rs @@ -736,6 +736,7 @@ fn plan_audio( | "output_device" | "alsa_plugin" | "alsa_hardware_volume" + | "alsa_hardware_volume_controls" | "dsd_mode" ) || k.eq_ignore_ascii_case("volume"); @@ -922,15 +923,22 @@ fn plan_audio_machine( } } - // alsa_plugin / alsa_hardware_volume — apply only with a validated ALSA device. + // ALSA plugin / hardware-volume flag / exact route map — apply only with + // a validated ALSA device. Imported identities are data only; the active + // route is probed again before any mixer write. let resolved_backend_alsa = resolved_backend_is_alsa(map, current, fallback, forced_device); - for key in ["alsa_plugin", "alsa_hardware_volume"] { + for key in [ + "alsa_plugin", + "alsa_hardware_volume", + "alsa_hardware_volume_controls", + ] { let Some(v) = map.get(key) else { continue }; let no_change = alsa_field_no_change(current, key, v); if no_change { applied_line(plan, &format!("audio.{key}"), v, ""); } else if device_survives && resolved_backend_alsa { applied_line(plan, &format!("audio.{key}"), v, "rides the ALSA device"); + plan.routing_critical_changed = true; } else { plan.skipped.push(skip_line( &format!("audio.{key}"), @@ -997,6 +1005,12 @@ fn intent_flag_current(current: &AudioSettings, flag: &str) -> bool { fn alsa_field_no_change(current: &AudioSettings, key: &str, v: &Value) -> bool { match key { "alsa_hardware_volume" => v.as_bool() == Some(current.alsa_hardware_volume), + "alsa_hardware_volume_controls" => { + serde_json::to_value(¤t.alsa_hardware_volume_controls) + .ok() + .as_ref() + == Some(v) + } "alsa_plugin" => { let cur = serde_json::to_value(current.alsa_plugin).unwrap_or(Value::Null); *v == cur @@ -1166,6 +1180,11 @@ fn apply_audio_writes(data_root: &Path, writes: &[(&str, &Value)]) -> Result<(), store.set_alsa_plugin(p)?; } "alsa_hardware_volume" => store.set_alsa_hardware_volume(as_bool(value))?, + "alsa_hardware_volume_controls" => { + let controls = serde_json::from_value((*value).clone()) + .map_err(|e| format!("alsa_hardware_volume_controls: {e}"))?; + store.set_alsa_hardware_volume_controls(controls)?; + } "exclusive_mode" => store.set_exclusive_mode(as_bool(value))?, "dac_passthrough" => store.set_dac_passthrough(as_bool(value))?, "pw_force_bitperfect" => store.set_pw_force_bitperfect(as_bool(value))?, diff --git a/crates/qbz-app/src/settings/bundle/tests.rs b/crates/qbz-app/src/settings/bundle/tests.rs index f5b76574d..f90471d90 100644 --- a/crates/qbz-app/src/settings/bundle/tests.rs +++ b/crates/qbz-app/src/settings/bundle/tests.rs @@ -483,6 +483,43 @@ fn apply_writes_are_idempotent_and_persist() { cleanup(&p); } +#[test] +fn exact_alsa_mixer_route_map_survives_bundle_plan_and_apply() { + let p = scratch("alsa-mixer-map"); + let route = "alsa-route-v1|card=by-id:usb-D50-00|pcm=hw|DEV=0"; + let bundle = bundle_with(json!({ + "audio": { + "output_device": "hw:1,0", + "backend_type": "Alsa", + "alsa_hardware_volume": false, + "alsa_hardware_volume_controls": { + (route): { "name": "D50 III", "index": 0 } + } + } + })); + + let plan = plan(&bundle, &p, &ImportOptions::default(), &live()).expect("plan"); + assert!( + find(&plan.applied, "audio.alsa_hardware_volume_controls").is_some(), + "exact route map must be classified" + ); + assert!(plan.routing_critical_changed); + apply(&plan, &p, None).expect("apply map"); + + let audio = AudioSettingsStore::new_at(&p.data_root).unwrap().get_settings().unwrap(); + let route_key = + serde_json::from_value::(json!(route)) + .unwrap(); + assert_eq!( + audio + .alsa_hardware_volume_controls + .get(&route_key) + .map(|control| (control.name.as_str(), control.index)), + Some(("D50 III", 0)) + ); + cleanup(&p); +} + #[test] fn bundle_json_roundtrips_flat() { // The on-disk shape is flat (§2.9): header + domains at the top level. diff --git a/crates/qbz-audio/Cargo.toml b/crates/qbz-audio/Cargo.toml index e79a76d92..393d83355 100644 --- a/crates/qbz-audio/Cargo.toml +++ b/crates/qbz-audio/Cargo.toml @@ -50,6 +50,7 @@ alsa = "0.11" # Kept in lockstep with alsa (0.11 -> alsa-sys 0.4); a single alsa-sys is # required because of the `links = "alsa"` constraint shared with cpal. alsa-sys = "0.4" +libc = "0.2" # zbus for org.freedesktop.ReserveDevice1 D-Bus client (device reservation). # Pinned to v4 to share the transitive copy already pulled in by # secret-service/souvlaki and avoid duplicate zbus compiles. diff --git a/crates/qbz-audio/src/alsa_direct.rs b/crates/qbz-audio/src/alsa_direct.rs index 65d0c2f4c..b2b937115 100644 --- a/crates/qbz-audio/src/alsa_direct.rs +++ b/crates/qbz-audio/src/alsa_direct.rs @@ -905,30 +905,13 @@ impl AlsaDirectStream { /// - Mixer API fails /// /// NOTE: Failure doesn't break playback, just means volume can't be controlled. - pub fn set_hardware_volume(&self, volume: f32) -> Result<(), String> { - let mixer = open_hardware_mixer(&self.device_id)?; - let (selem, name) = find_hardware_volume_control(&mixer, &self.device_id)?; - let (min, max) = usable_volume_range(&selem, &self.device_id, &name)?; - let volume = volume.clamp(0.0, 1.0); - let target = min + (((max - min) as f32 * volume).round() as i64); - - log::info!( - "[ALSA Direct] Setting hardware volume via '{}': {:.0}% (raw: {}/{})", - name, - volume * 100.0, - target, - max - ); - - // The ALSA helper addresses every playback channel the element owns - // and, unlike the old hand-written five-channel loop, propagates a - // write failure instead of reporting success after ignoring it. - selem.set_playback_volume_all(target).map_err(|error| { - format!( - "Failed to set ALSA hardware volume via '{}' for {}: {}", - name, self.device_id, error - ) - }) + pub fn set_hardware_volume( + &self, + control: &crate::alsa_hardware_volume::AlsaMixerControlId, + volume: f32, + ) -> Result<(), String> { + crate::alsa_hardware_volume::set_hardware_volume(&self.device_id, control, volume) + .map(|_| ()) } /// Check if device is a bit-perfect hardware device @@ -940,143 +923,32 @@ impl AlsaDirectStream { } } -#[cfg(target_os = "linux")] -fn open_hardware_mixer(device_id: &str) -> Result { - use alsa::mixer::Mixer; - - // Mixer controls live on the CARD ctl device, not on the PCM alias the - // stream opened: `iec958:CARD=x,DEV=0` (HiFiBerry Digi, #331/#659), - // `hdmi:`, `front:`… are PCM plugin ids the mixer can't attach to, and a - // `DEV`-qualified `hw:` id isn't a valid ctl name either. - let ctl_name = mixer_ctl_name(device_id); - Mixer::new(&ctl_name, false).map_err(|error| { - format!( - "Failed to open mixer for {} (ctl {}): {}", - device_id, ctl_name, error - ) - }) -} - -/// Rank playback elements conservatively. ALSA devices are inconsistent: -/// many expose `DAC` or `Line Out` instead of the five names the old code -/// hard-coded. Capture/sidetone elements are never acceptable fallbacks. -fn hardware_volume_rank(name: &str) -> u8 { - let lower = name.to_ascii_lowercase(); - if ["capture", "mic", "boost", "sidetone", "loopback"] - .iter() - .any(|token| lower.contains(token)) - { - return 0; - } - - [ - ("master", 100), - ("pcm", 90), - ("speaker", 80), - ("headphone", 70), - ("digital", 60), - ("dac", 50), - ("line out", 40), - ("playback", 30), - ] - .into_iter() - .find_map(|(token, score)| lower.contains(token).then_some(score)) - .unwrap_or(1) -} - -#[cfg(target_os = "linux")] -fn find_hardware_volume_control<'a>( - mixer: &'a alsa::mixer::Mixer, - device_id: &str, -) -> Result<(alsa::mixer::Selem<'a>, String), String> { - use alsa::mixer::Selem; - - let mut candidates = mixer - .iter() - .filter_map(Selem::new) - .filter(|selem| selem.has_playback_volume()) - .filter_map(|selem| { - let name = selem.get_id().get_name().ok()?.to_string(); - let rank = hardware_volume_rank(&name); - (rank > 0).then_some((rank, name, selem)) - }) - .collect::>(); - - candidates.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| left.1.cmp(&right.1))); - - let Some((top_rank, _, _)) = candidates.first() else { - return Err(format!( - "No writable playback-volume control found for {}", - device_id - )); - }; - if candidates.get(1).is_some_and(|next| next.0 == *top_rank) { - let names = candidates - .iter() - .filter(|candidate| candidate.0 == *top_rank) - .map(|candidate| candidate.1.as_str()) - .collect::>() - .join(", "); - return Err(format!( - "Ambiguous playback-volume controls for {}: {}", - device_id, names - )); - } - - let (_, name, selem) = candidates.remove(0); - Ok((selem, name)) -} - -#[cfg(target_os = "linux")] -fn usable_volume_range( - selem: &alsa::mixer::Selem<'_>, - device_id: &str, - control_name: &str, -) -> Result<(i64, i64), String> { - let (min, max) = selem.get_playback_volume_range(); - (max > min).then_some((min, max)).ok_or_else(|| { - format!( - "ALSA playback-volume control '{}' for {} has no usable range ({min}..{max})", - control_name, device_id - ) - }) -} - /// Read-only capability probe used before the UI enables hardware volume. -#[cfg(target_os = "linux")] pub fn probe_hardware_volume(device_id: &str) -> Result { - use alsa::mixer::SelemChannelId; - - let mixer = open_hardware_mixer(device_id)?; - let (selem, name) = find_hardware_volume_control(&mixer, device_id)?; - let (min, max) = usable_volume_range(&selem, device_id, &name)?; - let channel = SelemChannelId::all() - .iter() - .copied() - .find(|channel| selem.has_playback_channel(*channel)) - .ok_or_else(|| { - format!( - "ALSA playback-volume control '{}' for {} has no playback channel", - name, device_id - ) - })?; - let raw = selem.get_playback_volume(channel).map_err(|error| { - format!( - "Failed to read ALSA hardware volume via '{}' for {}: {}", - name, device_id, error - ) - })?; - let volume = ((raw - min) as f32 / (max - min) as f32).clamp(0.0, 1.0); - - Ok(HardwareVolumeInfo { - control_name: name, - volume, - }) -} - -#[cfg(not(target_os = "linux"))] -pub fn probe_hardware_volume(_device_id: &str) -> Result { - Err("ALSA hardware volume is only available on Linux".to_string()) + use crate::alsa_hardware_volume::{ + resolve_hardware_volume, HardwareVolumeDecision, HardwareVolumeUnsupportedReason, + }; + let decision = resolve_hardware_volume(device_id, &Default::default()); + match decision { + HardwareVolumeDecision::Selected { selection } => Ok(HardwareVolumeInfo { + control_name: selection.control.name, + volume: selection.candidate.current_volume.unwrap_or(1.0), + }), + HardwareVolumeDecision::NeedsChoice { candidates, .. } => Err(format!( + "Ambiguous playback-volume controls for {device_id}: {}", + candidates + .iter() + .map(|candidate| candidate.label.as_str()) + .collect::>() + .join(", ") + )), + HardwareVolumeDecision::Unsupported { reason, .. } => match reason { + HardwareVolumeUnsupportedReason::Probe(error) => Err(error.message), + other => Err(format!( + "No compatible ALSA hardware volume for {device_id}: {other:?}" + )), + }, + } } /// Mirrors the exact route predicate used by the player: ALSA plus a direct @@ -1132,38 +1004,10 @@ impl AlsaDirectStream { } } -/// Derive the ALSA **card** ctl id from a PCM device id for mixer access. -/// -/// Mixer elements are per-card; attaching a mixer to a PCM plugin alias -/// (`iec958:`, `hdmi:`, `front:`, `sysdefault:`…) or a `DEV`-qualified `hw:` -/// id fails. Maps every shape to `hw:CARD=` when a `CARD=` argument is -/// present, to `hw:` for the numeric `hw:N,M` / `plughw:N,M` forms, and -/// falls back to the raw id otherwise (e.g. `default` — which then fails with -/// the same "no mixer" outcome as before, no regression). -#[cfg(any(target_os = "linux", test))] -pub(crate) fn mixer_ctl_name(device_id: &str) -> String { - if let Some((_, args)) = device_id.split_once(':') { - for arg in args.split(',') { - if let Some(name) = arg.trim().strip_prefix("CARD=") { - if !name.is_empty() { - return format!("hw:CARD={name}"); - } - } - } - // Numeric form: `hw:1,0` / `plughw:1` → `hw:1` (card index only). - if let Some(first) = args.split(',').next() { - let first = first.trim(); - if first.parse::().is_ok() { - return format!("hw:{first}"); - } - } - } - device_id.to_string() -} - #[cfg(test)] mod tests { - use super::{hardware_volume_rank, mixer_ctl_name, uses_alsa_direct_route}; + use super::uses_alsa_direct_route; + use crate::alsa_hardware_volume::mixer_ctl_name; use crate::backend::{AlsaPlugin, AudioBackendType}; use crate::settings::AudioSettings; @@ -1194,15 +1038,6 @@ mod tests { assert_eq!(mixer_ctl_name("pulse"), "pulse"); } - #[test] - fn hardware_volume_ranking_prefers_output_controls_and_rejects_capture_paths() { - assert!(hardware_volume_rank("Master") > hardware_volume_rank("PCM")); - assert!(hardware_volume_rank("PCM") > hardware_volume_rank("USB DAC")); - assert!(hardware_volume_rank("Speaker Playback") > 1); - assert_eq!(hardware_volume_rank("Mic Playback Volume"), 0); - assert_eq!(hardware_volume_rank("Capture"), 0); - } - #[test] fn direct_route_requires_alsa_direct_device_and_non_pcm_plugin() { let mut audio = AudioSettings::default(); @@ -1258,11 +1093,19 @@ impl crate::backend::DirectSink for AlsaDirectStream { fn log_label(&self) -> &'static str { "ALSA Direct Engine" } + #[cfg(target_os = "linux")] + fn alsa_device_id(&self) -> Option<&str> { + Some(self.device_id()) + } /// Linux only, because the inherent method is: the non-Linux stub of this /// type has no mixer at all, and there the trait default refusal is the /// honest answer. #[cfg(target_os = "linux")] - fn set_hardware_volume(&self, volume: f32) -> Result<(), String> { - AlsaDirectStream::set_hardware_volume(self, volume) + fn set_hardware_volume( + &self, + control: &crate::alsa_hardware_volume::AlsaMixerControlId, + volume: f32, + ) -> Result<(), String> { + AlsaDirectStream::set_hardware_volume(self, control, volume) } } diff --git a/crates/qbz-audio/src/alsa_hardware_volume.rs b/crates/qbz-audio/src/alsa_hardware_volume.rs new file mode 100644 index 000000000..2de0cf3f0 --- /dev/null +++ b/crates/qbz-audio/src/alsa_hardware_volume.rs @@ -0,0 +1,2347 @@ +//! ALSA hardware-volume discovery, identity, selection and control. +//! +//! This module is intentionally separate from `alsa_direct`: mixer probing is +//! control-plane work and must not change PCM open/configure/write/drain or any +//! sample-rate decision in the protected direct-output path. + +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::sync::Arc; + +/// The complete ALSA simple-mixer identity. Names alone are not unique. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct AlsaMixerControlId { + pub name: String, + pub index: u32, +} + +impl fmt::Display for AlsaMixerControlId { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{},{}", self.name, self.index) + } +} + +/// Opaque, serializable key for one physical card and one PCM route. +/// +/// The string form is deliberate: JSON maps only support string keys. Values +/// are versioned and contain a stable card identity, the PCM kind and `DEV=`. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct StableAlsaRouteKey(String); + +impl StableAlsaRouteKey { + pub fn as_str(&self) -> &str { + &self.0 + } + + fn from_parts(identity: &StableAlsaCardIdentity, pcm: &str, device: u32) -> Self { + let (kind, value) = match identity { + StableAlsaCardIdentity::ById(value) => ("by-id", value.as_str()), + StableAlsaCardIdentity::ByPath(value) => ("by-path", value.as_str()), + StableAlsaCardIdentity::Card(value) => ("card", value.as_str()), + }; + Self(format!( + "alsa-route-v1|card={kind}:{}|pcm={}|DEV={device}", + escape_key_component(value), + escape_key_component(pcm) + )) + } +} + +impl fmt::Display for StableAlsaRouteKey { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum StableAlsaCardIdentity { + ById(String), + ByPath(String), + Card(String), +} + +fn select_stable_card_identity( + has_real_serial: bool, + by_id: Option, + by_path: Option, + short_id: String, +) -> StableAlsaCardIdentity { + if has_real_serial { + if let Some(by_id) = by_id { + return StableAlsaCardIdentity::ById(by_id); + } + } + by_path + .map(StableAlsaCardIdentity::ByPath) + .unwrap_or(StableAlsaCardIdentity::Card(short_id)) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct HardwareVolumeRange { + pub min: i64, + pub max: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HardwareVolumeChannelValue { + pub channel: String, + pub raw: i64, + pub db_millibels: Option, + pub playback_switch: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HardwareVolumeWritability { + Verified, + NeedsEnableCheck, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "detail", rename_all = "snake_case")] +pub enum HardwareVolumeRejectionReason { + Inactive, + CaptureOnly, + UnsafeInputPath, + CommonPlaybackCaptureVolume, + NoPlaybackVolume, + InvalidRange { min: i64, max: i64 }, + NoPlaybackChannels, + ReadFailed(String), + ReadOnly, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HardwareVolumeCandidate { + pub id: AlsaMixerControlId, + pub label: String, + pub channels: Vec, + pub raw_range: Option, + /// ALSA millibels (1/100 dB). `None` means raw-linear fallback. + pub db_range: Option, + pub current_values: Vec, + pub current_volume: Option, + pub has_playback_switch: bool, + pub recommended: bool, + pub writability: HardwareVolumeWritability, + pub rejection_reason: Option, +} + +impl HardwareVolumeCandidate { + pub fn is_valid(&self) -> bool { + self.rejection_reason.is_none() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HardwareVolumeProbeErrorKind { + InvalidDevice, + PermissionDenied, + DeviceBusy, + DeviceUnavailable, + NoMixer, + UnsupportedPlatform, + Other, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HardwareVolumeProbeError { + pub kind: HardwareVolumeProbeErrorKind, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HardwareVolumeProbe { + pub device_id: String, + pub ctl_name: String, + pub route_key: Option, + /// Every simple element, including rejected controls for diagnostics. + pub candidates: Vec, + /// Read-only UCM hints that resolve to simple-mixer identities. + pub ucm_controls: Vec, + pub error: Option, +} + +impl HardwareVolumeProbe { + pub fn valid_candidates(&self) -> impl Iterator { + self.candidates + .iter() + .filter(|candidate| candidate.is_valid()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HardwareVolumeSelectionSource { + Persisted, + Ucm, + OnlyCandidate, + UserChoice, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HardwareVolumeSelection { + pub route_key: StableAlsaRouteKey, + pub control: AlsaMixerControlId, + pub candidate: HardwareVolumeCandidate, + pub source: HardwareVolumeSelectionSource, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HardwareVolumeChoiceReason { + Ambiguous, + UcmAmbiguous, + PersistedSelectionStale, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "detail", rename_all = "snake_case")] +pub enum HardwareVolumeUnsupportedReason { + Probe(HardwareVolumeProbeError), + NoValidControls, + PersistedSelectionStale(AlsaMixerControlId), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum HardwareVolumeDecision { + Selected { + selection: HardwareVolumeSelection, + }, + NeedsChoice { + route_key: StableAlsaRouteKey, + candidates: Vec, + reason: HardwareVolumeChoiceReason, + }, + Unsupported { + route_key: Option, + reason: HardwareVolumeUnsupportedReason, + }, +} + +/// A fresh physical-mixer snapshot after an exact read or write. +#[derive(Debug, Clone, PartialEq)] +pub struct HardwareVolumeSnapshot { + pub control: AlsaMixerControlId, + pub channels: Vec, + pub volume: f32, + pub muted: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HardwareVolumeEvent { + Changed(HardwareVolumeSnapshot), + Unavailable(String), +} + +pub type HardwareVolumeEventCallback = Arc; + +/// Owns the ctl event thread. Dropping it stops and joins the subscription. +pub struct HardwareVolumeEventSubscription { + #[cfg(target_os = "linux")] + stop: Arc, + #[cfg(target_os = "linux")] + thread: Option>, +} + +#[cfg(target_os = "linux")] +impl Drop for HardwareVolumeEventSubscription { + fn drop(&mut self) { + use std::sync::atomic::Ordering; + self.stop.store(true, Ordering::SeqCst); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// Decide without touching hardware. A stale persisted identity is a hard +/// stop: it must never silently fall through to a different control. +pub fn decide_hardware_volume( + probe: &HardwareVolumeProbe, + persisted: &HashMap, +) -> HardwareVolumeDecision { + if let Some(error) = &probe.error { + return HardwareVolumeDecision::Unsupported { + route_key: probe.route_key.clone(), + reason: HardwareVolumeUnsupportedReason::Probe(error.clone()), + }; + } + + let Some(route_key) = probe.route_key.clone() else { + return HardwareVolumeDecision::Unsupported { + route_key: None, + reason: HardwareVolumeUnsupportedReason::Probe(HardwareVolumeProbeError { + kind: HardwareVolumeProbeErrorKind::InvalidDevice, + message: "ALSA route has no stable identity".to_string(), + }), + }; + }; + + let valid = probe + .valid_candidates() + .cloned() + .collect::>(); + + if let Some(saved) = persisted.get(&route_key) { + if let Some(candidate) = valid.iter().find(|candidate| candidate.id == *saved) { + return HardwareVolumeDecision::Selected { + selection: HardwareVolumeSelection { + route_key, + control: saved.clone(), + candidate: candidate.clone(), + source: HardwareVolumeSelectionSource::Persisted, + }, + }; + } + if valid.is_empty() { + return HardwareVolumeDecision::Unsupported { + route_key: Some(route_key), + reason: HardwareVolumeUnsupportedReason::PersistedSelectionStale(saved.clone()), + }; + } + return HardwareVolumeDecision::NeedsChoice { + route_key, + candidates: valid, + reason: HardwareVolumeChoiceReason::PersistedSelectionStale, + }; + } + + let ucm_ids = probe.ucm_controls.iter().cloned().collect::>(); + let ucm_matches = valid + .iter() + .filter(|candidate| ucm_ids.contains(&candidate.id)) + .cloned() + .collect::>(); + if ucm_matches.len() == 1 { + let candidate = ucm_matches.into_iter().next().expect("length checked"); + return HardwareVolumeDecision::Selected { + selection: HardwareVolumeSelection { + route_key, + control: candidate.id.clone(), + candidate, + source: HardwareVolumeSelectionSource::Ucm, + }, + }; + } + if ucm_matches.len() > 1 { + return HardwareVolumeDecision::NeedsChoice { + route_key, + candidates: valid, + reason: HardwareVolumeChoiceReason::UcmAmbiguous, + }; + } + + match valid.len() { + 0 => HardwareVolumeDecision::Unsupported { + route_key: Some(route_key), + reason: HardwareVolumeUnsupportedReason::NoValidControls, + }, + 1 => { + let candidate = valid.into_iter().next().expect("length checked"); + HardwareVolumeDecision::Selected { + selection: HardwareVolumeSelection { + route_key, + control: candidate.id.clone(), + candidate, + source: HardwareVolumeSelectionSource::OnlyCandidate, + }, + } + } + _ => HardwareVolumeDecision::NeedsChoice { + route_key, + candidates: valid, + reason: HardwareVolumeChoiceReason::Ambiguous, + }, + } +} + +pub fn resolve_hardware_volume( + device_id: &str, + persisted: &HashMap, +) -> HardwareVolumeDecision { + decide_hardware_volume(&enumerate_hardware_volume_controls(device_id), persisted) +} + +fn escape_key_component(value: &str) -> String { + let mut escaped = String::with_capacity(value.len()); + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.') { + escaped.push(char::from(byte)); + } else { + use std::fmt::Write; + let _ = write!(escaped, "%{byte:02X}"); + } + } + escaped +} + +fn hardware_volume_rank(name: &str) -> u8 { + let lower = name.to_ascii_lowercase(); + [ + ("master", 100), + ("pcm", 90), + ("speaker", 80), + ("headphone", 70), + ("digital", 60), + ("dac", 50), + ("line out", 40), + ("playback", 30), + ] + .into_iter() + .find_map(|(token, score)| lower.contains(token).then_some(score)) + .unwrap_or(1) +} + +fn unsafe_input_name(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + ["capture", "mic", "boost", "sidetone", "loopback"] + .iter() + .any(|token| lower.contains(token)) +} + +#[derive(Debug, Clone, Copy)] +struct CandidateFacts<'a> { + name: &'a str, + active: bool, + has_playback: bool, + has_capture: bool, + has_common_volume: bool, + raw_range: Option, + playback_channels: usize, +} + +/// Pure structural validation, shared by the live ALSA probe and unit tests. +/// Read failures and ctl writability are checked immediately after this gate. +fn structural_rejection(facts: CandidateFacts<'_>) -> Option { + if !facts.active { + return Some(HardwareVolumeRejectionReason::Inactive); + } + if facts.has_common_volume { + return Some(HardwareVolumeRejectionReason::CommonPlaybackCaptureVolume); + } + if facts.has_capture && !facts.has_playback { + return Some(HardwareVolumeRejectionReason::CaptureOnly); + } + if unsafe_input_name(facts.name) { + return Some(HardwareVolumeRejectionReason::UnsafeInputPath); + } + if !facts.has_playback { + return Some(HardwareVolumeRejectionReason::NoPlaybackVolume); + } + let range = facts + .raw_range + .unwrap_or(HardwareVolumeRange { min: 0, max: 0 }); + if range.max <= range.min { + return Some(HardwareVolumeRejectionReason::InvalidRange { + min: range.min, + max: range.max, + }); + } + if facts.playback_channels == 0 { + return Some(HardwareVolumeRejectionReason::NoPlaybackChannels); + } + None +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct HardwareVolumeWritePlan { + playback_switch: Option, + write_level: bool, +} + +fn hardware_volume_write_plan(scalar: f32, has_playback_switch: bool) -> HardwareVolumeWritePlan { + if scalar <= f32::EPSILON && has_playback_switch { + HardwareVolumeWritePlan { + playback_switch: Some(false), + write_level: false, + } + } else { + HardwareVolumeWritePlan { + playback_switch: has_playback_switch.then_some(true), + write_level: true, + } + } +} + +fn suppress_local_write_echo(written: f32, age_millis: u128, observed: f32) -> bool { + age_millis <= 300 && (written - observed).abs() < 0.001 +} + +fn writability_rejection(writable: Option) -> Option { + (writable == Some(false)).then_some(HardwareVolumeRejectionReason::ReadOnly) +} + +fn mark_recommended(candidates: &mut [HardwareVolumeCandidate]) { + let best = candidates + .iter() + .filter(|candidate| candidate.is_valid()) + .map(|candidate| hardware_volume_rank(&candidate.id.name)) + .max(); + for candidate in candidates { + candidate.recommended = + candidate.is_valid() && best == Some(hardware_volume_rank(&candidate.id.name)); + } +} + +fn normalize_level( + raw_range: HardwareVolumeRange, + db_range: Option, + values: &[HardwareVolumeChannelValue], +) -> f32 { + let switches = values + .iter() + .filter_map(|value| value.playback_switch) + .collect::>(); + if !switches.is_empty() && switches.iter().all(|enabled| !enabled) { + return 0.0; + } + + if let Some(db_range) = db_range { + let levels = values + .iter() + .map(|value| value.db_millibels) + .collect::>>(); + if let Some(levels) = levels.filter(|levels| !levels.is_empty()) { + return levels + .into_iter() + .map(|value| normalized(value, db_range)) + .fold(0.0_f32, f32::max); + } + } + + values + .iter() + .map(|value| normalized(value.raw, raw_range)) + .fold(0.0_f32, f32::max) +} + +fn normalized(value: i64, range: HardwareVolumeRange) -> f32 { + if range.max <= range.min { + return 0.0; + } + ((value - range.min) as f32 / (range.max - range.min) as f32).clamp(0.0, 1.0) +} + +fn channel_targets(values: &[i64], range: HardwareVolumeRange, scalar: f32) -> Vec { + if values.is_empty() || range.max <= range.min { + return Vec::new(); + } + let current_peak = values.iter().copied().max().unwrap_or(range.min); + let target_peak = + range.min + (((range.max - range.min) as f32 * scalar.clamp(0.0, 1.0)).round() as i64); + values + .iter() + .map(|value| (target_peak + (*value - current_peak)).clamp(range.min, range.max)) + .collect() +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ParsedAlsaRoute { + card: String, + pcm: String, + device: u32, +} + +fn parse_alsa_route(device_id: &str) -> Option { + let (prefix, arguments) = device_id.split_once(':')?; + let pcm = match prefix { + "hw" | "plughw" => "hw", + "front" => "front", + "iec958" => "iec958", + "hdmi" => "hdmi", + "sysdefault" => "sysdefault", + other => other, + } + .to_string(); + + let mut card = None; + let mut device = None; + for (position, argument) in arguments.split(',').enumerate() { + let argument = argument.trim(); + if let Some(value) = argument.strip_prefix("CARD=") { + card = Some(value.to_string()); + } else if let Some(value) = argument.strip_prefix("DEV=") { + device = value.parse::().ok(); + } else if position == 0 && !argument.is_empty() { + card = Some(argument.to_string()); + } else if position == 1 { + device = argument.parse::().ok(); + } + } + + Some(ParsedAlsaRoute { + card: card?, + pcm, + device: device.unwrap_or(0), + }) +} + +#[cfg(target_os = "linux")] +fn ucm_parser_identifier(value_name: &str) -> Option<&'static str> { + match value_name { + "PlaybackVolume" => Some("PlaybackVolume"), + "PlaybackMasterElem" | "PlaybackMixerElem" => Some("PlaybackMixerId"), + _ => None, + } +} + +/// Resolve a PCM id to the card ctl name accepted by ALSA mixer/control APIs. +pub fn mixer_ctl_name(device_id: &str) -> String { + let Some(route) = parse_alsa_route(device_id) else { + return device_id.to_string(); + }; + if route + .card + .chars() + .all(|character| character.is_ascii_digit()) + { + format!("hw:{}", route.card) + } else { + format!("hw:CARD={}", route.card) + } +} + +#[cfg(target_os = "linux")] +mod linux { + use super::*; + use alsa::ctl::Ctl; + use alsa_sys as ffi; + use std::ffi::{CStr, CString}; + use std::fs; + use std::os::unix::fs::MetadataExt; + use std::path::{Path, PathBuf}; + use std::ptr; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + const DB_GAIN_MUTE: i64 = -9_999_999; + const CHANNELS: &[(ffi::snd_mixer_selem_channel_id_t, &str)] = &[ + (ffi::SND_MIXER_SCHN_FRONT_LEFT, "Front Left"), + (ffi::SND_MIXER_SCHN_FRONT_RIGHT, "Front Right"), + (ffi::SND_MIXER_SCHN_REAR_LEFT, "Rear Left"), + (ffi::SND_MIXER_SCHN_REAR_RIGHT, "Rear Right"), + (ffi::SND_MIXER_SCHN_FRONT_CENTER, "Front Center"), + (ffi::SND_MIXER_SCHN_WOOFER, "Woofer"), + (ffi::SND_MIXER_SCHN_SIDE_LEFT, "Side Left"), + (ffi::SND_MIXER_SCHN_SIDE_RIGHT, "Side Right"), + (ffi::SND_MIXER_SCHN_REAR_CENTER, "Rear Center"), + ]; + + #[cfg(target_pointer_width = "64")] + fn c_long_to_i64(value: libc::c_long) -> i64 { + value + } + + #[cfg(not(target_pointer_width = "64"))] + fn c_long_to_i64(value: libc::c_long) -> i64 { + i64::from(value) + } + + #[repr(C)] + struct SndUseCaseMgr { + _private: [u8; 0], + } + + #[link(name = "asound")] + unsafe extern "C" { + fn snd_use_case_mgr_open( + manager: *mut *mut SndUseCaseMgr, + card_name: *const libc::c_char, + ) -> libc::c_int; + fn snd_use_case_mgr_close(manager: *mut SndUseCaseMgr) -> libc::c_int; + fn snd_use_case_get( + manager: *mut SndUseCaseMgr, + identifier: *const libc::c_char, + value: *mut *const libc::c_char, + ) -> libc::c_int; + fn snd_use_case_get_list( + manager: *mut SndUseCaseMgr, + identifier: *const libc::c_char, + list: *mut *mut *const libc::c_char, + ) -> libc::c_int; + fn snd_use_case_free_list( + list: *const *const libc::c_char, + items: libc::c_int, + ) -> libc::c_int; + fn snd_use_case_parse_selem_id( + destination: *mut ffi::snd_mixer_selem_id_t, + ucm_id: *const libc::c_char, + value: *const libc::c_char, + ) -> libc::c_int; + fn snd_use_case_parse_ctl_elem_id( + destination: *mut ffi::snd_ctl_elem_id_t, + ucm_id: *const libc::c_char, + value: *const libc::c_char, + ) -> libc::c_int; + } + + struct UcmManager(*mut SndUseCaseMgr); + + impl UcmManager { + fn open(card: &str) -> Option { + let card = CString::new(format!("hw:{card}")).ok()?; + let mut manager = ptr::null_mut(); + let result = unsafe { snd_use_case_mgr_open(&mut manager, card.as_ptr()) }; + // Do not express this with bool::then_some(Self(manager)): + // then_some eagerly constructs and drops the owner on failure, + // calling snd_use_case_mgr_close on an invalid pointer. + if result < 0 || manager.is_null() { + return None; + } + Some(Self(manager)) + } + + fn get(&self, identifier: &str) -> Option { + let identifier = CString::new(identifier).ok()?; + let mut value = ptr::null(); + if unsafe { snd_use_case_get(self.0, identifier.as_ptr(), &mut value) } < 0 + || value.is_null() + { + return None; + } + let result = unsafe { CStr::from_ptr(value) } + .to_string_lossy() + .into_owned(); + unsafe { + libc::free(value.cast_mut().cast()); + } + (!result.is_empty()).then_some(result) + } + + fn list(&self, identifier: &str) -> Vec { + let Ok(identifier) = CString::new(identifier) else { + return Vec::new(); + }; + let mut list = ptr::null_mut(); + let count = unsafe { snd_use_case_get_list(self.0, identifier.as_ptr(), &mut list) }; + if count <= 0 || list.is_null() { + return Vec::new(); + } + let values = (0..count) + .filter_map(|index| { + let value = unsafe { *list.add(index as usize) }; + (!value.is_null()).then(|| { + unsafe { CStr::from_ptr(value) } + .to_string_lossy() + .into_owned() + }) + }) + .collect(); + unsafe { + snd_use_case_free_list(list.cast_const(), count); + } + values + } + } + + impl Drop for UcmManager { + fn drop(&mut self) { + unsafe { + snd_use_case_mgr_close(self.0); + } + } + } + + struct RawMixer(*mut ffi::snd_mixer_t); + + impl RawMixer { + fn open(device_id: &str) -> Result { + let ctl_name = mixer_ctl_name(device_id); + let ctl = CString::new(ctl_name.as_str()).map_err(|_| HardwareVolumeProbeError { + kind: HardwareVolumeProbeErrorKind::InvalidDevice, + message: format!("Invalid ALSA ctl name for {device_id}"), + })?; + let mut mixer = ptr::null_mut(); + alsa_call( + unsafe { ffi::snd_mixer_open(&mut mixer, 0) }, + "open ALSA mixer", + )?; + let owner = Self(mixer); + alsa_call( + unsafe { ffi::snd_mixer_attach(owner.0, ctl.as_ptr()) }, + &format!("attach ALSA mixer to {ctl_name}"), + )?; + alsa_call( + unsafe { ffi::snd_mixer_selem_register(owner.0, ptr::null_mut(), ptr::null_mut()) }, + "register ALSA simple mixer elements", + )?; + alsa_call(unsafe { ffi::snd_mixer_load(owner.0) }, "load ALSA mixer")?; + Ok(owner) + } + + fn find(&self, id: &AlsaMixerControlId) -> Option<*mut ffi::snd_mixer_elem_t> { + let mut element = unsafe { ffi::snd_mixer_first_elem(self.0) }; + while !element.is_null() { + if unsafe { ffi::snd_mixer_elem_get_type(element) } == ffi::SND_MIXER_ELEM_SIMPLE { + let candidate = selem_id(element); + if candidate.as_ref() == Some(id) { + return Some(element); + } + } + element = unsafe { ffi::snd_mixer_elem_next(element) }; + } + None + } + } + + impl Drop for RawMixer { + fn drop(&mut self) { + unsafe { + ffi::snd_mixer_close(self.0); + } + } + } + + struct RawCtl(*mut ffi::snd_ctl_t); + + impl RawCtl { + fn open(ctl_name: &str, nonblock: bool) -> Result { + let name = CString::new(ctl_name).map_err(|_| HardwareVolumeProbeError { + kind: HardwareVolumeProbeErrorKind::InvalidDevice, + message: format!("Invalid ALSA ctl name: {ctl_name}"), + })?; + let mut ctl = ptr::null_mut(); + alsa_call( + unsafe { ffi::snd_ctl_open(&mut ctl, name.as_ptr(), i32::from(nonblock)) }, + &format!("open ALSA ctl {ctl_name}"), + )?; + Ok(Self(ctl)) + } + + /// `None` means the Selem -> ctl translation was not reliable enough; + /// the explicit enable path will do a per-channel current-value writeback. + fn writable(&self, id: &AlsaMixerControlId) -> Option { + let raw_names = if id.name.ends_with(" Playback Volume") { + vec![id.name.clone()] + } else { + vec![format!("{} Playback Volume", id.name), id.name.clone()] + }; + for raw_name in raw_names { + let Ok(raw_name) = CString::new(raw_name) else { + continue; + }; + let mut info = ptr::null_mut(); + if unsafe { ffi::snd_ctl_elem_info_malloc(&mut info) } < 0 { + return None; + } + unsafe { + ffi::snd_ctl_elem_info_set_interface(info, ffi::SND_CTL_ELEM_IFACE_MIXER); + ffi::snd_ctl_elem_info_set_name(info, raw_name.as_ptr()); + ffi::snd_ctl_elem_info_set_index(info, id.index); + } + let result = unsafe { ffi::snd_ctl_elem_info(self.0, info) }; + let writable = + (result >= 0).then(|| unsafe { ffi::snd_ctl_elem_info_is_writable(info) > 0 }); + unsafe { + ffi::snd_ctl_elem_info_free(info); + } + if writable.is_some() { + return writable; + } + } + None + } + } + + impl Drop for RawCtl { + fn drop(&mut self) { + unsafe { + ffi::snd_ctl_close(self.0); + } + } + } + + fn alsa_call(code: i32, operation: &str) -> Result<(), HardwareVolumeProbeError> { + if code >= 0 { + return Ok(()); + } + let errno = -code; + let detail = unsafe { + let message = ffi::snd_strerror(code); + if message.is_null() { + format!("ALSA error {code}") + } else { + CStr::from_ptr(message).to_string_lossy().into_owned() + } + }; + let kind = match errno { + libc::EACCES | libc::EPERM => HardwareVolumeProbeErrorKind::PermissionDenied, + libc::EBUSY => HardwareVolumeProbeErrorKind::DeviceBusy, + libc::ENODEV | libc::ENXIO => HardwareVolumeProbeErrorKind::DeviceUnavailable, + libc::ENOENT => HardwareVolumeProbeErrorKind::NoMixer, + _ => HardwareVolumeProbeErrorKind::Other, + }; + Err(HardwareVolumeProbeError { + kind, + message: format!("Failed to {operation}: {detail}"), + }) + } + + fn selem_id(element: *mut ffi::snd_mixer_elem_t) -> Option { + let name = unsafe { ffi::snd_mixer_selem_get_name(element) }; + if name.is_null() { + return None; + } + Some(AlsaMixerControlId { + name: unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned(), + index: unsafe { ffi::snd_mixer_selem_get_index(element) }, + }) + } + + fn playback_channels(element: *mut ffi::snd_mixer_elem_t) -> Vec<(i32, String)> { + CHANNELS + .iter() + .filter(|(channel, _)| unsafe { + ffi::snd_mixer_selem_has_playback_channel(element, *channel) > 0 + }) + .map(|(channel, name)| (*channel, (*name).to_string())) + .collect() + } + + fn finite_db_range( + element: *mut ffi::snd_mixer_elem_t, + raw_range: HardwareVolumeRange, + ) -> Option { + let mut min = 0; + let mut max = 0; + if unsafe { ffi::snd_mixer_selem_get_playback_dB_range(element, &mut min, &mut max) } < 0 + || max <= min + { + return None; + } + let mut min = c_long_to_i64(min); + let max = c_long_to_i64(max); + if min <= DB_GAIN_MUTE { + if raw_range.max <= raw_range.min { + return None; + } + let mut finite = 0; + if unsafe { + ffi::snd_mixer_selem_ask_playback_vol_dB( + element, + (raw_range.min + 1) as _, + &mut finite, + ) + } < 0 + || c_long_to_i64(finite) <= DB_GAIN_MUTE + { + return None; + } + min = c_long_to_i64(finite); + } + (max > min).then_some(HardwareVolumeRange { min, max }) + } + + fn read_channels( + element: *mut ffi::snd_mixer_elem_t, + channels: &[(i32, String)], + db_range: Option, + has_switch: bool, + ) -> Result, String> { + let mut values = Vec::with_capacity(channels.len()); + for (channel, name) in channels { + let mut raw = 0; + let code = + unsafe { ffi::snd_mixer_selem_get_playback_volume(element, *channel, &mut raw) }; + if code < 0 { + return Err(format!("{}: {}", name, alsa_error_text(code))); + } + let db_millibels = db_range.and_then(|_| { + let mut value = 0; + (unsafe { ffi::snd_mixer_selem_get_playback_dB(element, *channel, &mut value) } + >= 0) + .then_some(c_long_to_i64(value)) + }); + let playback_switch = has_switch.then(|| { + let mut enabled = 0; + let code = unsafe { + ffi::snd_mixer_selem_get_playback_switch(element, *channel, &mut enabled) + }; + (code >= 0).then_some(enabled != 0) + }); + if has_switch && playback_switch.flatten().is_none() { + return Err(format!("{}: playback switch read failed", name)); + } + values.push(HardwareVolumeChannelValue { + channel: name.clone(), + raw: c_long_to_i64(raw), + db_millibels, + playback_switch: playback_switch.flatten(), + }); + } + Ok(values) + } + + fn alsa_error_text(code: i32) -> String { + unsafe { + let message = ffi::snd_strerror(code); + if message.is_null() { + format!("ALSA error {code}") + } else { + CStr::from_ptr(message).to_string_lossy().into_owned() + } + } + } + + fn probe_candidate( + element: *mut ffi::snd_mixer_elem_t, + ctl: Option<&RawCtl>, + ) -> Option { + let id = selem_id(element)?; + let mut candidate = HardwareVolumeCandidate { + label: if id.index == 0 { + id.name.clone() + } else { + format!("{} ({})", id.name, id.index) + }, + id, + channels: Vec::new(), + raw_range: None, + db_range: None, + current_values: Vec::new(), + current_volume: None, + has_playback_switch: unsafe { ffi::snd_mixer_selem_has_playback_switch(element) > 0 }, + recommended: false, + writability: HardwareVolumeWritability::NeedsEnableCheck, + rejection_reason: None, + }; + + let active = unsafe { ffi::snd_mixer_selem_is_active(element) } > 0; + let has_playback = unsafe { ffi::snd_mixer_selem_has_playback_volume(element) } > 0; + let has_capture = unsafe { ffi::snd_mixer_selem_has_capture_volume(element) } > 0; + let has_common_volume = unsafe { ffi::snd_mixer_selem_has_common_volume(element) } > 0; + + let mut min = 0; + let mut max = 0; + let raw_range = has_playback.then(|| { + let _ = unsafe { + ffi::snd_mixer_selem_get_playback_volume_range(element, &mut min, &mut max) + }; + HardwareVolumeRange { + min: c_long_to_i64(min), + max: c_long_to_i64(max), + } + }); + candidate.raw_range = raw_range; + let channels = if has_playback { + playback_channels(element) + } else { + Vec::new() + }; + candidate.channels = channels.iter().map(|(_, name)| name.clone()).collect(); + if let Some(reason) = structural_rejection(CandidateFacts { + name: &candidate.id.name, + active, + has_playback, + has_capture, + has_common_volume, + raw_range, + playback_channels: channels.len(), + }) { + candidate.rejection_reason = Some(reason); + return Some(candidate); + } + let raw_range = raw_range.expect("structural validation requires a valid range"); + candidate.db_range = finite_db_range(element, raw_range); + match read_channels( + element, + &channels, + candidate.db_range, + candidate.has_playback_switch, + ) { + Ok(values) => candidate.current_values = values, + Err(error) => { + candidate.rejection_reason = Some(HardwareVolumeRejectionReason::ReadFailed(error)); + return Some(candidate); + } + } + + let writable = ctl.and_then(|ctl| ctl.writable(&candidate.id)); + if let Some(reason) = writability_rejection(writable) { + candidate.rejection_reason = Some(reason); + return Some(candidate); + } + if writable == Some(true) { + candidate.writability = HardwareVolumeWritability::Verified; + } + candidate.current_volume = Some(normalize_level( + raw_range, + candidate.db_range, + &candidate.current_values, + )); + Some(candidate) + } + + fn ucm_identifier(value: &str, device: Option<&str>) -> String { + match device { + Some(device) => format!("={value}/{device}/"), + None => format!("={value}//"), + } + } + + fn ucm_route_matches( + manager: &UcmManager, + route: &ParsedAlsaRoute, + device: Option<&str>, + ) -> bool { + let identifier = ucm_identifier("PlaybackPCM", device); + let Some(pcm) = manager.get(&identifier) else { + return false; + }; + parse_alsa_route(&pcm) + .is_some_and(|ucm_route| ucm_route.device == route.device && ucm_route.pcm == route.pcm) + } + + fn parse_ucm_control( + value_name: &str, + value: &str, + candidates: &[HardwareVolumeCandidate], + ) -> Option { + // The parser API takes a canonical UCM value kind, not the + // `snd_use_case_get()` path used to retrieve it. ALSA names the + // simple-element parser kind `PlaybackMixerId` even when the value + // originated in PlaybackMasterElem or PlaybackMixerElem. + let parser_id = CString::new(ucm_parser_identifier(value_name)?).ok()?; + let value_c = CString::new(value).ok()?; + let parsed = if value_name == "PlaybackVolume" { + let mut raw_id = ptr::null_mut(); + if unsafe { ffi::snd_ctl_elem_id_malloc(&mut raw_id) } < 0 || raw_id.is_null() { + return None; + } + let code = unsafe { + snd_use_case_parse_ctl_elem_id(raw_id, parser_id.as_ptr(), value_c.as_ptr()) + }; + let result = (code >= 0).then(|| { + let name = unsafe { ffi::snd_ctl_elem_id_get_name(raw_id) }; + AlsaMixerControlId { + name: if name.is_null() { + String::new() + } else { + unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned() + }, + index: unsafe { ffi::snd_ctl_elem_id_get_index(raw_id) }, + } + }); + unsafe { + ffi::snd_ctl_elem_id_free(raw_id); + } + result + } else { + let mut selem_id = ptr::null_mut(); + if unsafe { ffi::snd_mixer_selem_id_malloc(&mut selem_id) } < 0 || selem_id.is_null() { + return None; + } + let code = unsafe { + snd_use_case_parse_selem_id(selem_id, parser_id.as_ptr(), value_c.as_ptr()) + }; + let result = (code >= 0).then(|| { + let name = unsafe { ffi::snd_mixer_selem_id_get_name(selem_id) }; + AlsaMixerControlId { + name: if name.is_null() { + String::new() + } else { + unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned() + }, + index: unsafe { ffi::snd_mixer_selem_id_get_index(selem_id) }, + } + }); + unsafe { + ffi::snd_mixer_selem_id_free(selem_id); + } + result + } + .or_else(|| parse_ucm_control_text(value))?; + + candidates + .iter() + .find(|candidate| candidate.id == parsed) + .map(|candidate| candidate.id.clone()) + .or_else(|| { + let selem_name = parsed + .name + .strip_suffix(" Playback Volume") + .or_else(|| parsed.name.strip_suffix(" Volume"))?; + candidates + .iter() + .find(|candidate| { + candidate.id.index == parsed.index && candidate.id.name == selem_name + }) + .map(|candidate| candidate.id.clone()) + }) + } + + fn parse_ucm_control_text(value: &str) -> Option { + let trimmed = value.trim(); + let name = if let Some(position) = trimmed.find("name=") { + let rest = trimmed[position + 5..].trim_start(); + quoted_or_token(rest)? + } else { + quoted_or_token(trimmed)? + }; + let index = trimmed + .find("index=") + .and_then(|position| { + trimmed[position + 6..] + .trim_start() + .split(|character: char| !character.is_ascii_digit()) + .next() + }) + .and_then(|value| value.parse::().ok()) + .or_else(|| { + trimmed + .rsplit_once(',') + .and_then(|(_, value)| value.trim().parse::().ok()) + }) + .unwrap_or(0); + Some(AlsaMixerControlId { name, index }) + } + + fn quoted_or_token(value: &str) -> Option { + let value = value.trim_start(); + let first = value.chars().next()?; + if first == '\'' || first == '"' { + let rest = &value[first.len_utf8()..]; + let end = rest.find(first)?; + return Some(rest[..end].to_string()); + } + let end = value + .find(|character: char| character == ',' || character.is_whitespace()) + .unwrap_or(value.len()); + (end > 0).then(|| value[..end].to_string()) + } + + fn ucm_controls_for_route( + route: &ParsedAlsaRoute, + candidates: &[HardwareVolumeCandidate], + ) -> Vec { + let Some(manager) = UcmManager::open(&route.card) else { + return Vec::new(); + }; + let Some(verb) = manager.get("_verb") else { + return Vec::new(); + }; + if verb.eq_ignore_ascii_case("Inactive") { + return Vec::new(); + } + + let enabled_devices = manager.list("_enadevs"); + let mut contexts = Vec::new(); + if ucm_route_matches(&manager, route, None) { + contexts.push(None); + } + contexts.extend( + enabled_devices + .iter() + .filter(|device| ucm_route_matches(&manager, route, Some(device))) + .map(|device| Some(device.as_str())), + ); + if contexts.is_empty() { + return Vec::new(); + } + + for value_name in ["PlaybackMasterElem", "PlaybackMixerElem", "PlaybackVolume"] { + let mut controls = HashSet::new(); + for device in &contexts { + if value_name == "PlaybackMasterElem" { + let master_type = manager + .get(&ucm_identifier("PlaybackMasterType", *device)) + .or_else(|| { + device + .is_some() + .then(|| manager.get(&ucm_identifier("PlaybackMasterType", None))) + .flatten() + }); + if master_type.is_some_and(|value| value.eq_ignore_ascii_case("soft")) { + continue; + } + } + let identifier = ucm_identifier(value_name, *device); + let Some(value) = manager.get(&identifier) else { + continue; + }; + if let Some(control) = parse_ucm_control(value_name, &value, candidates) { + controls.insert(control); + } + } + if !controls.is_empty() { + let mut controls = controls.into_iter().collect::>(); + controls.sort_by(|left, right| { + left.name + .cmp(&right.name) + .then_with(|| left.index.cmp(&right.index)) + }); + return controls; + } + } + Vec::new() + } + + pub(super) fn stable_route_key( + device_id: &str, + ) -> Result { + let route = parse_alsa_route(device_id).ok_or_else(|| HardwareVolumeProbeError { + kind: HardwareVolumeProbeErrorKind::InvalidDevice, + message: format!("Cannot parse ALSA PCM route: {device_id}"), + })?; + let (card_number, short_id) = + resolve_card(&route.card).ok_or_else(|| HardwareVolumeProbeError { + kind: HardwareVolumeProbeErrorKind::DeviceUnavailable, + message: format!("ALSA card '{}' is not present", route.card), + })?; + let control = PathBuf::from(format!("/dev/snd/controlC{card_number}")); + let identity = select_stable_card_identity( + has_real_card_serial(card_number), + find_stable_link("/dev/snd/by-id", &control), + find_stable_link("/dev/snd/by-path", &control), + short_id, + ); + Ok(StableAlsaRouteKey::from_parts( + &identity, + &route.pcm, + route.device, + )) + } + + /// A udev `by-id` link may exist even when USB's ID_SERIAL was synthesized + /// from vendor + model alone (for example `Fosi_Fosi_Audio_ZH3`). Only a + /// usable serial attribute on the owning USB device is strong enough to + /// distinguish two otherwise-identical DACs; without it, port identity + /// (`by-path`) is the safe key. Some devices publish placeholders such as + /// `0000`, which udev still includes in `ID_SERIAL`; those are not stable + /// identities. Stop at the first USB device so a root hub's own serial + /// cannot be mistaken for the DAC's. + fn has_real_card_serial(card_number: u32) -> bool { + let Ok(device) = fs::canonicalize(format!("/sys/class/sound/card{card_number}/device")) + else { + return false; + }; + has_real_usb_serial(device, Path::new("/sys/devices")) + } + + fn has_real_usb_serial(mut device: PathBuf, devices_root: &Path) -> bool { + while device.starts_with(devices_root) { + if device.join("idVendor").is_file() && device.join("idProduct").is_file() { + return fs::read_to_string(device.join("serial")) + .ok() + .is_some_and(|serial| is_usable_usb_serial(&serial)); + } + if !device.pop() { + break; + } + } + false + } + + fn is_usable_usb_serial(serial: &str) -> bool { + let serial = serial.trim(); + if serial.is_empty() + || matches!( + serial.to_ascii_lowercase().as_str(), + "none" | "null" | "unknown" | "default" | "n/a" | "na" + ) + { + return false; + } + + // A run of zeroes is a common firmware placeholder (the DacMagic Plus + // reports `0000`). Keep zero-padded real identifiers such as `0001`. + serial + .chars() + .any(|character| character.is_ascii_alphanumeric() && character != '0') + } + + fn resolve_card(card: &str) -> Option<(u32, String)> { + if let Ok(number) = card.parse::() { + let short = fs::read_to_string(format!("/proc/asound/card{number}/id")) + .ok()? + .trim() + .to_string(); + return (!short.is_empty()).then_some((number, short)); + } + let entries = fs::read_dir("/proc/asound").ok()?; + for entry in entries.flatten() { + let file_name = entry.file_name(); + let Some(suffix) = file_name + .to_string_lossy() + .strip_prefix("card") + .map(str::to_string) + else { + continue; + }; + let Ok(number) = suffix.parse::() else { + continue; + }; + let Ok(short) = fs::read_to_string(entry.path().join("id")) else { + continue; + }; + if short.trim() == card { + return Some((number, card.to_string())); + } + } + None + } + + fn find_stable_link(directory: &str, control: &Path) -> Option { + let target = fs::canonicalize(control).ok()?; + let target_metadata = fs::metadata(&target).ok(); + let mut matches = fs::read_dir(directory) + .ok()? + .flatten() + .filter_map(|entry| { + let resolved = fs::canonicalize(entry.path()).ok()?; + let same_path = resolved == target; + let same_device = target_metadata.as_ref().is_some_and(|target| { + fs::metadata(&resolved) + .ok() + .is_some_and(|candidate| candidate.rdev() == target.rdev()) + }); + (same_path || same_device).then(|| entry.file_name().to_string_lossy().into_owned()) + }) + .collect::>(); + matches.sort(); + matches.into_iter().next() + } + + pub(super) fn enumerate(device_id: &str) -> HardwareVolumeProbe { + let ctl_name = mixer_ctl_name(device_id); + let route_key = stable_route_key(device_id); + let mixer = match RawMixer::open(device_id) { + Ok(mixer) => mixer, + Err(error) => { + return HardwareVolumeProbe { + device_id: device_id.to_string(), + ctl_name, + route_key: route_key.ok(), + candidates: Vec::new(), + ucm_controls: Vec::new(), + error: Some(error), + }; + } + }; + let ctl = RawCtl::open(&ctl_name, false).ok(); + let mut candidates = Vec::new(); + let mut element = unsafe { ffi::snd_mixer_first_elem(mixer.0) }; + while !element.is_null() { + if unsafe { ffi::snd_mixer_elem_get_type(element) } == ffi::SND_MIXER_ELEM_SIMPLE { + if let Some(candidate) = probe_candidate(element, ctl.as_ref()) { + candidates.push(candidate); + } + } + element = unsafe { ffi::snd_mixer_elem_next(element) }; + } + mark_recommended(&mut candidates); + candidates.sort_by(|left, right| { + right + .is_valid() + .cmp(&left.is_valid()) + .then_with(|| right.recommended.cmp(&left.recommended)) + .then_with(|| left.id.name.cmp(&right.id.name)) + .then_with(|| left.id.index.cmp(&right.id.index)) + }); + + let (route_key, error) = match route_key { + Ok(route_key) => (Some(route_key), None), + Err(error) => (None, Some(error)), + }; + let ucm_controls = parse_alsa_route(device_id) + .map(|route| ucm_controls_for_route(&route, &candidates)) + .unwrap_or_default(); + HardwareVolumeProbe { + device_id: device_id.to_string(), + ctl_name, + route_key, + candidates, + ucm_controls, + error, + } + } + + fn exact_candidate( + device_id: &str, + id: &AlsaMixerControlId, + ) -> Result { + let probe = enumerate(device_id); + if let Some(error) = probe.error { + return Err(error.message); + } + probe + .candidates + .into_iter() + .find(|candidate| candidate.id == *id && candidate.is_valid()) + .ok_or_else(|| format!("ALSA mixer control {id} is missing or no longer valid")) + } + + pub(super) fn activate( + device_id: &str, + id: &AlsaMixerControlId, + ) -> Result { + let candidate = exact_candidate(device_id, id)?; + if candidate.writability == HardwareVolumeWritability::NeedsEnableCheck { + let mixer = RawMixer::open(device_id).map_err(|error| error.message)?; + let element = mixer + .find(id) + .ok_or_else(|| format!("ALSA mixer control {id} disappeared during enable"))?; + let channels = playback_channels(element); + let values = read_channels( + element, + &channels, + candidate.db_range, + candidate.has_playback_switch, + )?; + // Explicit user action only: write each channel's current value + // back independently so the capability check cannot alter balance. + for ((channel, name), value) in channels.iter().zip(&values) { + let code = unsafe { + ffi::snd_mixer_selem_set_playback_volume(element, *channel, value.raw as _) + }; + if code < 0 { + return Err(format!( + "ALSA mixer control {id} is not writable on {name}: {}", + alsa_error_text(code) + )); + } + } + } + read(device_id, id) + } + + pub(super) fn read( + device_id: &str, + id: &AlsaMixerControlId, + ) -> Result { + let mixer = RawMixer::open(device_id).map_err(|error| error.message)?; + let element = mixer + .find(id) + .ok_or_else(|| format!("ALSA mixer control {id} is missing"))?; + let channels = playback_channels(element); + if channels.is_empty() { + return Err(format!("ALSA mixer control {id} has no playback channels")); + } + let mut min = 0; + let mut max = 0; + if unsafe { ffi::snd_mixer_selem_get_playback_volume_range(element, &mut min, &mut max) } + < 0 + || max <= min + { + return Err(format!( + "ALSA mixer control {id} has no usable volume range" + )); + } + let raw_range = HardwareVolumeRange { + min: c_long_to_i64(min), + max: c_long_to_i64(max), + }; + let db_range = finite_db_range(element, raw_range); + let has_switch = unsafe { ffi::snd_mixer_selem_has_playback_switch(element) } > 0; + let values = read_channels(element, &channels, db_range, has_switch)?; + let muted = has_switch + && values + .iter() + .filter_map(|value| value.playback_switch) + .all(|enabled| !enabled); + Ok(HardwareVolumeSnapshot { + control: id.clone(), + volume: normalize_level(raw_range, db_range, &values), + channels: values, + muted, + }) + } + + pub(super) fn set( + device_id: &str, + id: &AlsaMixerControlId, + scalar: f32, + ) -> Result { + let candidate = exact_candidate(device_id, id)?; + let raw_range = candidate + .raw_range + .ok_or_else(|| format!("ALSA mixer control {id} has no usable raw range"))?; + let mixer = RawMixer::open(device_id).map_err(|error| error.message)?; + let element = mixer + .find(id) + .ok_or_else(|| format!("ALSA mixer control {id} disappeared before write"))?; + let channels = playback_channels(element); + let scalar = scalar.clamp(0.0, 1.0); + let write_plan = hardware_volume_write_plan(scalar, candidate.has_playback_switch); + + if write_plan.playback_switch == Some(false) { + for (channel, name) in &channels { + let code = + unsafe { ffi::snd_mixer_selem_set_playback_switch(element, *channel, 0) }; + if code < 0 { + return Err(format!( + "Failed to mute {id} on {name}: {}", + alsa_error_text(code) + )); + } + } + let snapshot = read(device_id, id)?; + remember_local_write(device_id, id, snapshot.volume); + return Ok(snapshot); + } + + if write_plan.playback_switch == Some(true) { + // Restore the hardware route before moving its volume away from zero. + for (channel, name) in &channels { + let code = + unsafe { ffi::snd_mixer_selem_set_playback_switch(element, *channel, 1) }; + if code < 0 { + return Err(format!( + "Failed to unmute {id} on {name}: {}", + alsa_error_text(code) + )); + } + } + } + debug_assert!(write_plan.write_level); + + let values = read_channels( + element, + &channels, + candidate.db_range, + candidate.has_playback_switch, + )?; + let mut used_db = false; + // With no playback switch, UI zero means the raw minimum even when a + // driver's finite dB range deliberately excludes its mute sentinel. + if scalar > f32::EPSILON { + if let Some(db_range) = candidate.db_range { + let current_db = values + .iter() + .map(|value| value.db_millibels) + .collect::>>(); + if let Some(current_db) = current_db { + let targets = channel_targets(¤t_db, db_range, scalar); + if targets.len() == channels.len() { + let mut failed = None; + for ((channel, name), target) in channels.iter().zip(targets) { + let code = unsafe { + ffi::snd_mixer_selem_set_playback_dB( + element, + *channel, + target as _, + 0, + ) + }; + if code < 0 { + failed = Some(format!("{name}: {}", alsa_error_text(code))); + break; + } + } + if let Some(error) = failed { + log::warn!( + "[ALSA HW Volume] dB write failed for {id}; using raw fallback: {error}" + ); + } else { + used_db = true; + } + } + } + } + } + + if !used_db { + let current_raw = values.iter().map(|value| value.raw).collect::>(); + let targets = channel_targets(¤t_raw, raw_range, scalar); + for ((channel, name), target) in channels.iter().zip(targets) { + let code = unsafe { + ffi::snd_mixer_selem_set_playback_volume(element, *channel, target as _) + }; + if code < 0 { + return Err(format!( + "Failed to set raw ALSA volume for {id} on {name}: {}", + alsa_error_text(code) + )); + } + } + } + + let snapshot = read(device_id, id)?; + remember_local_write(device_id, id, snapshot.volume); + Ok(snapshot) + } + + type LocalWriteMap = HashMap; + static LOCAL_WRITES: std::sync::OnceLock> = + std::sync::OnceLock::new(); + + fn runtime_control_key(device_id: &str, id: &AlsaMixerControlId) -> String { + format!("{device_id}\u{1f}{}\u{1f}{}", id.name, id.index) + } + + fn remember_local_write(device_id: &str, id: &AlsaMixerControlId, volume: f32) { + let writes = LOCAL_WRITES.get_or_init(Default::default); + if let Ok(mut writes) = writes.lock() { + writes.insert(runtime_control_key(device_id, id), (volume, Instant::now())); + } + } + + fn is_recent_local_write(device_id: &str, id: &AlsaMixerControlId, volume: f32) -> bool { + let writes = LOCAL_WRITES.get_or_init(Default::default); + let Ok(mut writes) = writes.lock() else { + return false; + }; + let key = runtime_control_key(device_id, id); + let suppress = writes.get(&key).is_some_and(|(written, at)| { + suppress_local_write_echo(*written, at.elapsed().as_millis(), volume) + }); + if suppress { + writes.remove(&key); + } + suppress + } + + pub(super) fn subscribe( + device_id: &str, + id: &AlsaMixerControlId, + callback: HardwareVolumeEventCallback, + ) -> Result { + let ctl_name = mixer_ctl_name(device_id); + let ctl = Ctl::new(&ctl_name, true) + .map_err(|error| format!("Failed to open ALSA ctl {ctl_name}: {error}"))?; + ctl.subscribe_events(true) + .map_err(|error| format!("Failed to subscribe to ALSA ctl {ctl_name}: {error}"))?; + let stop = Arc::new(AtomicBool::new(false)); + let thread_stop = stop.clone(); + let device_id = device_id.to_string(); + let id = id.clone(); + let thread = std::thread::Builder::new() + .name("qbz-alsa-volume-events".to_string()) + .spawn(move || { + let mut last_published = read(&device_id, &id).ok().map(|snapshot| snapshot.volume); + 'events: while !thread_stop.load(Ordering::SeqCst) { + match ctl.wait(Some(100)) { + Ok(true) => { + let mut changed = false; + loop { + match ctl.read() { + Ok(Some(event)) => changed |= event.get_mask().value(), + Ok(None) => break, + Err(error) => { + callback(HardwareVolumeEvent::Unavailable(format!( + "ALSA ctl event read failed: {error}" + ))); + break 'events; + } + } + } + if !changed { + continue; + } + std::thread::sleep(Duration::from_millis(35)); + match read(&device_id, &id) { + Ok(snapshot) => { + if is_recent_local_write(&device_id, &id, snapshot.volume) { + last_published = Some(snapshot.volume); + continue; + } + if last_published.is_some_and(|previous| { + (previous - snapshot.volume).abs() < 0.001 + }) { + continue; + } + last_published = Some(snapshot.volume); + callback(HardwareVolumeEvent::Changed(snapshot)); + } + Err(error) => { + callback(HardwareVolumeEvent::Unavailable(error)); + break; + } + } + } + Ok(false) => {} + Err(error) => { + callback(HardwareVolumeEvent::Unavailable(format!( + "ALSA ctl event subscription failed: {error}" + ))); + break; + } + } + } + let _ = ctl.subscribe_events(false); + }) + .map_err(|error| format!("Failed to start ALSA volume event thread: {error}"))?; + Ok(HardwareVolumeEventSubscription { + stop, + thread: Some(thread), + }) + } + + #[cfg(test)] + mod sysfs_tests { + use super::*; + + #[test] + fn dac_without_serial_does_not_inherit_the_root_hub_serial() { + let root = std::env::temp_dir().join(format!( + "qbz-alsa-serial-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos() + )); + let hub = root.join("usb3"); + let dac = hub.join("3-5"); + let interface = dac.join("3-5:1.1"); + fs::create_dir_all(&interface).expect("create fake sysfs tree"); + for device in [&hub, &dac] { + fs::write(device.join("idVendor"), "1234").expect("write vendor"); + fs::write(device.join("idProduct"), "5678").expect("write product"); + } + fs::write(hub.join("serial"), "0000:00:14.0").expect("write hub serial"); + + assert!(!has_real_usb_serial(interface.clone(), &root)); + fs::write(dac.join("serial"), "0000").expect("write placeholder DAC serial"); + assert!(!has_real_usb_serial(interface.clone(), &root)); + fs::write(dac.join("serial"), "REAL-DAC-SERIAL").expect("write DAC serial"); + assert!(has_real_usb_serial(interface, &root)); + + fs::remove_dir_all(root).expect("remove fake sysfs tree"); + } + + #[test] + fn usb_serial_placeholders_are_not_stable_identities() { + for placeholder in [ + "", " ", "0000", "none", "NULL", "unknown", "default", "N/A", + ] { + assert!(!is_usable_usb_serial(placeholder), "{placeholder:?}"); + } + assert!(is_usable_usb_serial("0001")); + assert!(is_usable_usb_serial("REAL-DAC-SERIAL")); + } + } +} + +/// Enumerate every simple-mixer element and retain rejected candidates for +/// diagnostics. This function never writes to ALSA. +pub fn enumerate_hardware_volume_controls(device_id: &str) -> HardwareVolumeProbe { + #[cfg(target_os = "linux")] + { + linux::enumerate(device_id) + } + #[cfg(not(target_os = "linux"))] + { + HardwareVolumeProbe { + device_id: device_id.to_string(), + ctl_name: device_id.to_string(), + route_key: None, + candidates: Vec::new(), + ucm_controls: Vec::new(), + error: Some(HardwareVolumeProbeError { + kind: HardwareVolumeProbeErrorKind::UnsupportedPlatform, + message: "ALSA hardware volume is only available on Linux".to_string(), + }), + } + } +} + +pub fn stable_alsa_route_key(device_id: &str) -> Result { + #[cfg(target_os = "linux")] + { + linux::stable_route_key(device_id).map_err(|error| error.message) + } + #[cfg(not(target_os = "linux"))] + { + let _ = device_id; + Err("ALSA route identities are only available on Linux".to_string()) + } +} + +/// Explicit enable-time validation. If ctl identity cannot prove writability, +/// this performs a per-channel writeback of the values just read. +pub fn activate_hardware_volume_control( + device_id: &str, + id: &AlsaMixerControlId, +) -> Result { + #[cfg(target_os = "linux")] + { + linux::activate(device_id, id) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (device_id, id); + Err("ALSA hardware volume is only available on Linux".to_string()) + } +} + +pub fn read_hardware_volume( + device_id: &str, + id: &AlsaMixerControlId, +) -> Result { + #[cfg(target_os = "linux")] + { + linux::read(device_id, id) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (device_id, id); + Err("ALSA hardware volume is only available on Linux".to_string()) + } +} + +pub fn set_hardware_volume( + device_id: &str, + id: &AlsaMixerControlId, + volume: f32, +) -> Result { + #[cfg(target_os = "linux")] + { + linux::set(device_id, id, volume) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (device_id, id, volume); + Err("ALSA hardware volume is only available on Linux".to_string()) + } +} + +pub fn subscribe_hardware_volume_events( + device_id: &str, + id: &AlsaMixerControlId, + callback: HardwareVolumeEventCallback, +) -> Result { + #[cfg(target_os = "linux")] + { + linux::subscribe(device_id, id, callback) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (device_id, id, callback); + Err("ALSA hardware volume is only available on Linux".to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn candidate(name: &str, index: u32, valid: bool) -> HardwareVolumeCandidate { + HardwareVolumeCandidate { + id: AlsaMixerControlId { + name: name.to_string(), + index, + }, + label: name.to_string(), + channels: vec!["Front Left".to_string(), "Front Right".to_string()], + raw_range: Some(HardwareVolumeRange { min: 0, max: 100 }), + db_range: Some(HardwareVolumeRange { min: -6000, max: 0 }), + current_values: Vec::new(), + current_volume: Some(0.5), + has_playback_switch: true, + recommended: false, + writability: HardwareVolumeWritability::Verified, + rejection_reason: (!valid).then_some(HardwareVolumeRejectionReason::ReadOnly), + } + } + + fn probe(candidates: Vec) -> HardwareVolumeProbe { + HardwareVolumeProbe { + device_id: "front:CARD=D50,DEV=0".to_string(), + ctl_name: "hw:CARD=D50".to_string(), + route_key: Some(StableAlsaRouteKey( + "alsa-route-v1|card=card:D50|pcm=front|DEV=0".to_string(), + )), + candidates, + ucm_controls: Vec::new(), + error: None, + } + } + + #[test] + fn unknown_single_candidate_is_selected() { + let decision = + decide_hardware_volume(&probe(vec![candidate("D50 III", 0, true)]), &HashMap::new()); + assert!(matches!( + decision, + HardwareVolumeDecision::Selected { + selection: HardwareVolumeSelection { + source: HardwareVolumeSelectionSource::OnlyCandidate, + .. + } + } + )); + } + + #[test] + fn two_unknown_candidates_need_choice() { + let decision = decide_hardware_volume( + &probe(vec![ + candidate("Output A", 0, true), + candidate("Output B", 0, true), + ]), + &HashMap::new(), + ); + assert!(matches!( + decision, + HardwareVolumeDecision::NeedsChoice { + reason: HardwareVolumeChoiceReason::Ambiguous, + .. + } + )); + } + + #[test] + fn same_name_different_indices_remain_distinct() { + let decision = decide_hardware_volume( + &probe(vec![candidate("DAC", 0, true), candidate("DAC", 1, true)]), + &HashMap::new(), + ); + let HardwareVolumeDecision::NeedsChoice { candidates, .. } = decision else { + panic!("expected choice"); + }; + assert_eq!(candidates.len(), 2); + assert_ne!(candidates[0].id, candidates[1].id); + } + + #[test] + fn invalid_master_does_not_block_valid_unknown_control() { + let decision = decide_hardware_volume( + &probe(vec![ + candidate("Master", 0, false), + candidate("D50 III", 0, true), + ]), + &HashMap::new(), + ); + let HardwareVolumeDecision::Selected { selection } = decision else { + panic!("expected selection"); + }; + assert_eq!(selection.control.name, "D50 III"); + } + + #[test] + fn persisted_exact_match_wins_but_stale_does_not_fall_through() { + let probe = probe(vec![ + candidate("Master", 0, true), + candidate("DAC", 0, true), + ]); + let route = probe.route_key.clone().unwrap(); + let mut persisted = HashMap::new(); + persisted.insert( + route.clone(), + AlsaMixerControlId { + name: "DAC".into(), + index: 0, + }, + ); + let selected = decide_hardware_volume(&probe, &persisted); + assert!( + matches!(selected, HardwareVolumeDecision::Selected { selection } if selection.control.name == "DAC") + ); + + persisted.insert( + route, + AlsaMixerControlId { + name: "Gone".into(), + index: 0, + }, + ); + assert!(matches!( + decide_hardware_volume(&probe, &persisted), + HardwareVolumeDecision::NeedsChoice { + reason: HardwareVolumeChoiceReason::PersistedSelectionStale, + .. + } + )); + } + + #[test] + fn ucm_must_be_unambiguous() { + let mut probe = probe(vec![ + candidate("Speaker", 0, true), + candidate("Headphone", 0, true), + ]); + probe.ucm_controls = vec![probe.candidates[1].id.clone()]; + assert!(matches!( + decide_hardware_volume(&probe, &HashMap::new()), + HardwareVolumeDecision::Selected { selection } + if selection.source == HardwareVolumeSelectionSource::Ucm + && selection.control.name == "Headphone" + )); + probe.ucm_controls = probe + .candidates + .iter() + .map(|candidate| candidate.id.clone()) + .collect(); + assert!(matches!( + decide_hardware_volume(&probe, &HashMap::new()), + HardwareVolumeDecision::NeedsChoice { + reason: HardwareVolumeChoiceReason::UcmAmbiguous, + .. + } + )); + } + + #[test] + fn rejected_ucm_hint_does_not_make_one_valid_ucm_control_ambiguous() { + let mut probe = probe(vec![ + candidate("Speaker", 0, true), + candidate("Mic Boost", 0, false), + ]); + probe.ucm_controls = probe + .candidates + .iter() + .map(|candidate| candidate.id.clone()) + .collect(); + + assert!(matches!( + decide_hardware_volume(&probe, &HashMap::new()), + HardwareVolumeDecision::Selected { selection } + if selection.source == HardwareVolumeSelectionSource::Ucm + && selection.control.name == "Speaker" + )); + } + + #[test] + fn stable_keys_prefer_serial_then_path_then_symbolic_card_and_include_route() { + assert_eq!( + select_stable_card_identity( + true, + Some("usb-Fosi_ZH3_REAL123-00".into()), + Some("pci-usb-port-1".into()), + "ZH3".into(), + ), + StableAlsaCardIdentity::ById("usb-Fosi_ZH3_REAL123-00".into()) + ); + assert_eq!( + select_stable_card_identity( + false, + Some("usb-Fosi_Fosi_Audio_ZH3-00".into()), + Some("pci-usb-port-1".into()), + "ZH3".into(), + ), + StableAlsaCardIdentity::ByPath("pci-usb-port-1".into()) + ); + assert_eq!( + select_stable_card_identity( + false, + Some("usb-iBasso_Macaron-01".into()), + None, + "Macaron".into(), + ), + StableAlsaCardIdentity::Card("Macaron".into()) + ); + + let by_id = StableAlsaRouteKey::from_parts( + &StableAlsaCardIdentity::ById("usb-Topping_D50_III_1234-00".into()), + "front", + 0, + ); + let by_path = StableAlsaRouteKey::from_parts( + &StableAlsaCardIdentity::ByPath("pci-0000:00:14.0-usb-0:2:1.0".into()), + "front", + 0, + ); + let card = + StableAlsaRouteKey::from_parts(&StableAlsaCardIdentity::Card("D50".into()), "hdmi", 1); + assert!(by_id.as_str().contains("card=by-id:")); + assert!(by_path.as_str().contains("card=by-path:")); + assert!(card.as_str().contains("card=card:D50")); + assert!(card.as_str().contains("pcm=hdmi|DEV=1")); + assert!(!card.as_str().contains("hw:0")); + } + + #[test] + fn parser_keeps_pcm_device_in_route_identity() { + assert_eq!( + parse_alsa_route("iec958:CARD=PCH,DEV=1"), + Some(ParsedAlsaRoute { + card: "PCH".into(), + pcm: "iec958".into(), + device: 1, + }) + ); + assert_eq!(mixer_ctl_name("hw:2,7"), "hw:2"); + assert_eq!(mixer_ctl_name("front:CARD=USB,DEV=0"), "hw:CARD=USB"); + } + + #[cfg(target_os = "linux")] + #[test] + fn ucm_parser_uses_canonical_alsa_value_identifiers() { + assert_eq!( + ucm_parser_identifier("PlaybackVolume"), + Some("PlaybackVolume") + ); + assert_eq!( + ucm_parser_identifier("PlaybackMasterElem"), + Some("PlaybackMixerId") + ); + assert_eq!( + ucm_parser_identifier("PlaybackMixerElem"), + Some("PlaybackMixerId") + ); + assert_eq!(ucm_parser_identifier("PlaybackSwitch"), None); + } + + #[test] + fn channel_mapping_preserves_balance_and_clamps() { + let range = HardwareVolumeRange { min: -6000, max: 0 }; + assert_eq!( + channel_targets(&[-1200, -1800], range, 0.5), + vec![-3000, -3600] + ); + assert_eq!(channel_targets(&[-1200, -1800], range, 1.0), vec![0, -600]); + assert_eq!( + channel_targets(&[-1200, -1800], range, 0.0), + vec![-6000, -6000] + ); + } + + #[test] + fn recommendation_never_resurrects_rejected_candidate() { + let mut candidates = vec![candidate("Master", 0, false), candidate("D50 III", 0, true)]; + mark_recommended(&mut candidates); + assert!(!candidates[0].recommended); + assert!(candidates[1].recommended); + } + + #[test] + fn structural_validation_rejects_unsafe_candidate_shapes_with_exact_reasons() { + let valid = CandidateFacts { + name: "D50 III", + active: true, + has_playback: true, + has_capture: false, + has_common_volume: false, + raw_range: Some(HardwareVolumeRange { min: 0, max: 100 }), + playback_channels: 2, + }; + assert_eq!(structural_rejection(valid), None); + assert_eq!( + structural_rejection(CandidateFacts { + raw_range: Some(HardwareVolumeRange { min: 7, max: 7 }), + ..valid + }), + Some(HardwareVolumeRejectionReason::InvalidRange { min: 7, max: 7 }) + ); + assert_eq!( + structural_rejection(CandidateFacts { + playback_channels: 0, + ..valid + }), + Some(HardwareVolumeRejectionReason::NoPlaybackChannels) + ); + assert_eq!( + structural_rejection(CandidateFacts { + has_common_volume: true, + ..valid + }), + Some(HardwareVolumeRejectionReason::CommonPlaybackCaptureVolume) + ); + assert_eq!( + structural_rejection(CandidateFacts { + has_playback: false, + has_capture: true, + raw_range: None, + playback_channels: 0, + ..valid + }), + Some(HardwareVolumeRejectionReason::CaptureOnly) + ); + assert_eq!( + structural_rejection(CandidateFacts { + name: "Mic Boost", + ..valid + }), + Some(HardwareVolumeRejectionReason::UnsafeInputPath) + ); + assert_eq!( + writability_rejection(Some(false)), + Some(HardwareVolumeRejectionReason::ReadOnly) + ); + assert_eq!(writability_rejection(Some(true)), None); + assert_eq!(writability_rejection(None), None); + } + + #[test] + fn raw_and_db_normalization_use_db_when_complete_and_raw_as_fallback() { + let raw_range = HardwareVolumeRange { min: 0, max: 100 }; + let db_range = HardwareVolumeRange { min: -6000, max: 0 }; + let db_values = vec![ + HardwareVolumeChannelValue { + channel: "L".into(), + raw: 80, + db_millibels: Some(-3000), + playback_switch: Some(true), + }, + HardwareVolumeChannelValue { + channel: "R".into(), + raw: 70, + db_millibels: Some(-3600), + playback_switch: Some(true), + }, + ]; + assert!((normalize_level(raw_range, Some(db_range), &db_values) - 0.5).abs() < 0.001); + + let mut broken_db = db_values.clone(); + broken_db[0].db_millibels = None; + broken_db[1].db_millibels = None; + assert!((normalize_level(raw_range, Some(db_range), &broken_db) - 0.8).abs() < 0.001); + + let mut partial_db = db_values.clone(); + partial_db[0].db_millibels = None; + assert!((normalize_level(raw_range, Some(db_range), &partial_db) - 0.8).abs() < 0.001); + } + + #[test] + fn mute_unmute_plan_and_partial_channel_switches_are_safe() { + assert_eq!( + hardware_volume_write_plan(0.0, true), + HardwareVolumeWritePlan { + playback_switch: Some(false), + write_level: false, + } + ); + assert_eq!( + hardware_volume_write_plan(0.25, true), + HardwareVolumeWritePlan { + playback_switch: Some(true), + write_level: true, + } + ); + assert_eq!( + hardware_volume_write_plan(0.0, false), + HardwareVolumeWritePlan { + playback_switch: None, + write_level: true, + } + ); + + let range = HardwareVolumeRange { min: 0, max: 100 }; + let mut values = vec![ + HardwareVolumeChannelValue { + channel: "L".into(), + raw: 40, + db_millibels: None, + playback_switch: Some(false), + }, + HardwareVolumeChannelValue { + channel: "R".into(), + raw: 60, + db_millibels: None, + playback_switch: Some(true), + }, + ]; + assert!((normalize_level(range, None, &values) - 0.6).abs() < 0.001); + values[1].playback_switch = Some(false); + assert_eq!(normalize_level(range, None, &values), 0.0); + } + + #[test] + fn local_write_feedback_is_suppressed_only_for_matching_recent_echoes() { + assert!(suppress_local_write_echo(0.42, 10, 0.420_4)); + assert!(!suppress_local_write_echo(0.42, 301, 0.42)); + assert!(!suppress_local_write_echo(0.42, 10, 0.5)); + } +} diff --git a/crates/qbz-audio/src/backend.rs b/crates/qbz-audio/src/backend.rs index b59f33c78..1ac4ebf0d 100644 --- a/crates/qbz-audio/src/backend.rs +++ b/crates/qbz-audio/src/backend.rs @@ -1082,6 +1082,12 @@ pub trait DirectSink: Send + Sync + 'static { /// is exactly what a hard-coded label at four call sites invites. fn log_label(&self) -> &'static str; + /// ALSA PCM identity for control-plane operations. Other direct sinks do + /// not expose an ALSA route and keep the default `None`. + fn alsa_device_id(&self) -> Option<&str> { + None + } + /// Device-side volume, where the sink has one. /// /// The default REFUSES rather than silently succeeding: a sink without a @@ -1089,7 +1095,11 @@ pub trait DirectSink: Send + Sync + 'static { /// already gated on the engine's `hardware_volume` flag, which is false for /// any such sink - permanently so for WASAPI exclusive, where the phase B /// contract rules out ISimpleAudioVolume. - fn set_hardware_volume(&self, _volume: f32) -> Result<(), String> { + fn set_hardware_volume( + &self, + _control: &crate::alsa_hardware_volume::AlsaMixerControlId, + _volume: f32, + ) -> Result<(), String> { Err("this sink has no hardware volume".to_string()) } } diff --git a/crates/qbz-audio/src/lib.rs b/crates/qbz-audio/src/lib.rs index f9f291d7c..c2345d080 100644 --- a/crates/qbz-audio/src/lib.rs +++ b/crates/qbz-audio/src/lib.rs @@ -29,6 +29,7 @@ #[cfg(target_os = "linux")] pub mod alsa_backend; pub mod alsa_direct; +pub mod alsa_hardware_volume; pub mod wasapi_direct; /// Endpoint capabilities: the exclusive-mode rate sweep and the hotplug watch. #[cfg(windows)] diff --git a/crates/qbz-audio/src/settings.rs b/crates/qbz-audio/src/settings.rs index 099465791..7b5f8351e 100644 --- a/crates/qbz-audio/src/settings.rs +++ b/crates/qbz-audio/src/settings.rs @@ -5,6 +5,7 @@ //! NOTE: Tauri command wrappers remain in qbz-nix. This module contains only //! the core types and persistence logic. +use crate::alsa_hardware_volume::{stable_alsa_route_key, AlsaMixerControlId, StableAlsaRouteKey}; use crate::{AlsaPlugin, AudioBackendType}; use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; @@ -21,6 +22,10 @@ pub struct AudioSettings { pub backend_type: Option, // None = auto-detect pub alsa_plugin: Option, // Only used when backend is ALSA pub alsa_hardware_volume: bool, // Use ALSA mixer for volume (only with hw: devices) + /// Exact mixer identity per physical card + PCM route. The empty map is + /// the backward-compatible value for legacy settings databases. + #[serde(default)] + pub alsa_hardware_volume_controls: HashMap, /// When true, uncached tracks start playing via streaming instead of waiting for full download pub stream_first_track: bool, /// Initial buffer size in seconds before starting streaming playback (1-10, default 3) @@ -86,6 +91,19 @@ fn default_dsd_mode() -> String { "convert".to_string() } +impl AudioSettings { + /// Exact control selected for the currently configured physical PCM route. + /// A bare `alsa_hardware_volume=true` from an older database intentionally + /// returns `None` until the shared probe resolves and persists a choice. + pub fn selected_alsa_hardware_volume_control(&self) -> Option { + if !self.alsa_hardware_volume { + return None; + } + let route = stable_alsa_route_key(self.output_device.as_deref()?).ok()?; + self.alsa_hardware_volume_controls.get(&route).cloned() + } +} + impl Default for AudioSettings { fn default() -> Self { Self { @@ -107,6 +125,7 @@ impl Default for AudioSettings { backend_type: Some(AudioBackendType::default()), alsa_plugin: Some(AlsaPlugin::Hw), // Default to hw (bit-perfect) alsa_hardware_volume: false, // Disabled by default (maximum compatibility) + alsa_hardware_volume_controls: HashMap::new(), stream_first_track: true, // On by default (opt-out) stream_buffer_seconds: 2, // 2 seconds initial buffer streaming_only: false, // Disabled by default (cache tracks for instant replay) @@ -153,6 +172,7 @@ impl AudioSettingsStore { backend_type TEXT, alsa_plugin TEXT, alsa_hardware_volume INTEGER NOT NULL DEFAULT 0, + alsa_hardware_volume_controls TEXT NOT NULL DEFAULT '{}', stream_first_track INTEGER NOT NULL DEFAULT 1, stream_buffer_seconds INTEGER NOT NULL DEFAULT 2 );", @@ -169,6 +189,10 @@ impl AudioSettingsStore { "ALTER TABLE audio_settings ADD COLUMN alsa_hardware_volume INTEGER DEFAULT 0", [], ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN alsa_hardware_volume_controls TEXT DEFAULT '{}'", + [], + ); let _ = conn.execute( "ALTER TABLE audio_settings ADD COLUMN stream_first_track INTEGER DEFAULT 1", [], @@ -298,7 +322,7 @@ impl AudioSettingsStore { pub fn get_settings(&self) -> Result { self.conn .query_row( - "SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits, pw_force_bitperfect, sync_audio_on_startup, quality_fallback_behavior, skip_sink_switch, allow_quality_fallback, reserve_dac_while_running, dsd_mode FROM audio_settings WHERE id = 1", + "SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits, pw_force_bitperfect, sync_audio_on_startup, quality_fallback_behavior, skip_sink_switch, allow_quality_fallback, reserve_dac_while_running, dsd_mode, alsa_hardware_volume_controls FROM audio_settings WHERE id = 1", [], |row| { // Parse backend_type from JSON string @@ -317,6 +341,14 @@ impl AudioSettingsStore { .and_then(|s| serde_json::from_str(&s).ok()) .unwrap_or_default(); + let alsa_hardware_volume_controls: HashMap< + StableAlsaRouteKey, + AlsaMixerControlId, + > = row + .get::<_, Option>(23)? + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default(); + Ok(AudioSettings { output_device: row.get(0)?, exclusive_mode: row.get::<_, i64>(1)? != 0, @@ -325,6 +357,7 @@ impl AudioSettingsStore { backend_type, alsa_plugin, alsa_hardware_volume: row.get::<_, Option>(6)?.unwrap_or(0) != 0, + alsa_hardware_volume_controls, stream_first_track: row.get::<_, Option>(7)?.unwrap_or(0) != 0, stream_buffer_seconds: row.get::<_, Option>(8)?.unwrap_or(3) as u8, streaming_only: row.get::<_, Option>(9)?.unwrap_or(0) != 0, @@ -453,6 +486,84 @@ impl AudioSettingsStore { Ok(()) } + /// Persist an exact control for one stable route without changing whether + /// hardware volume is enabled. Used by the explicit "Change control" flow. + pub fn set_alsa_hardware_volume_control( + &self, + route: StableAlsaRouteKey, + control: AlsaMixerControlId, + ) -> Result<(), String> { + let mut controls = self.get_settings()?.alsa_hardware_volume_controls; + controls.insert(route, control); + let json = serde_json::to_string(&controls) + .map_err(|error| format!("Failed to serialize ALSA mixer controls: {error}"))?; + self.conn + .execute( + "UPDATE audio_settings SET alsa_hardware_volume_controls = ?1 WHERE id = 1", + params![json], + ) + .map_err(|error| format!("Failed to set ALSA mixer control: {error}"))?; + Ok(()) + } + + /// Replace the route-scoped exact-control map (settings bundle import). + /// This stores identities only; it never probes or writes a mixer. The + /// normal startup/reload reconciliation validates the active route before + /// hardware volume can be used. + pub fn set_alsa_hardware_volume_controls( + &self, + controls: HashMap, + ) -> Result<(), String> { + let json = serde_json::to_string(&controls) + .map_err(|error| format!("Failed to serialize ALSA mixer controls: {error}"))?; + self.conn + .execute( + "UPDATE audio_settings SET alsa_hardware_volume_controls = ?1 WHERE id = 1", + params![json], + ) + .map_err(|error| format!("Failed to replace ALSA mixer controls: {error}"))?; + Ok(()) + } + + /// Remove the exact control for one route. If that route is currently in + /// use, callers must disable hardware volume first so no enabled setting + /// can remain without an identity. + pub fn clear_alsa_hardware_volume_control( + &self, + route: &StableAlsaRouteKey, + ) -> Result<(), String> { + let mut controls = self.get_settings()?.alsa_hardware_volume_controls; + controls.remove(route); + let json = serde_json::to_string(&controls) + .map_err(|error| format!("Failed to serialize ALSA mixer controls: {error}"))?; + self.conn + .execute( + "UPDATE audio_settings SET alsa_hardware_volume_controls = ?1 WHERE id = 1", + params![json], + ) + .map_err(|error| format!("Failed to clear ALSA mixer control: {error}"))?; + Ok(()) + } + + /// Atomically persist the exact selection and enable the preference. + pub fn enable_alsa_hardware_volume( + &self, + route: StableAlsaRouteKey, + control: AlsaMixerControlId, + ) -> Result<(), String> { + let mut controls = self.get_settings()?.alsa_hardware_volume_controls; + controls.insert(route, control); + let json = serde_json::to_string(&controls) + .map_err(|error| format!("Failed to serialize ALSA mixer controls: {error}"))?; + self.conn + .execute( + "UPDATE audio_settings SET alsa_hardware_volume_controls = ?1, alsa_hardware_volume = 1 WHERE id = 1", + params![json], + ) + .map_err(|error| format!("Failed to enable ALSA hardware volume: {error}"))?; + Ok(()) + } + pub fn set_stream_first_track(&self, enabled: bool) -> Result<(), String> { self.conn .execute( @@ -701,6 +812,8 @@ impl AudioSettingsStore { // Serialize per-device limits (empty on reset) let limits_json = serde_json::to_string(&defaults.device_sample_rate_limits) .map_err(|e| format!("Failed to serialize device sample rate limits: {}", e))?; + let mixer_controls_json = serde_json::to_string(&defaults.alsa_hardware_volume_controls) + .map_err(|e| format!("Failed to serialize ALSA mixer controls: {e}"))?; self.conn .execute( @@ -725,7 +838,8 @@ impl AudioSettingsStore { sync_audio_on_startup = ?18, skip_sink_switch = ?19, allow_quality_fallback = ?20, - reserve_dac_while_running = ?21 + reserve_dac_while_running = ?21, + alsa_hardware_volume_controls = ?22 WHERE id = 1", params![ defaults.output_device, @@ -749,6 +863,7 @@ impl AudioSettingsStore { defaults.skip_sink_switch as i64, defaults.allow_quality_fallback as i64, defaults.reserve_dac_while_running as i64, + mixer_controls_json, ], ) .map_err(|e| format!("Failed to reset audio settings: {}", e))?; @@ -967,6 +1082,7 @@ mod tests { assert_eq!(settings.quality_fallback_behavior, "always_skip"); assert_eq!(settings.output_device, None); assert!(!settings.dac_passthrough); + assert!(settings.alsa_hardware_volume_controls.is_empty()); let _ = std::fs::remove_dir_all(dir); } @@ -1032,5 +1148,88 @@ mod tests { serde_json::from_str(legacy).expect("legacy JSON should deserialize"); assert!(!settings.reserve_dac_while_running); + assert!(settings.alsa_hardware_volume_controls.is_empty()); + } + + #[test] + fn exact_alsa_mixer_controls_round_trip_by_route() { + let (dir, store) = fresh_store("alsa-mixer-controls"); + let route_a: StableAlsaRouteKey = + serde_json::from_str("\"alsa-route-v1|card=by-id:usb-D50-00|pcm=front|DEV=0\"") + .expect("route A"); + let route_b: StableAlsaRouteKey = + serde_json::from_str("\"alsa-route-v1|card=by-id:usb-D50-00|pcm=iec958|DEV=1\"") + .expect("route B"); + let control_a = AlsaMixerControlId { + name: "D50 III".to_string(), + index: 0, + }; + let control_b = AlsaMixerControlId { + name: "Digital".to_string(), + index: 1, + }; + + store + .set_alsa_hardware_volume_control(route_a.clone(), control_a.clone()) + .expect("set route A"); + store + .set_alsa_hardware_volume_control(route_b.clone(), control_b.clone()) + .expect("set route B"); + + let settings = store.get_settings().expect("read settings"); + assert_eq!( + settings.alsa_hardware_volume_controls.get(&route_a), + Some(&control_a) + ); + assert_eq!( + settings.alsa_hardware_volume_controls.get(&route_b), + Some(&control_b) + ); + assert_ne!(route_a, route_b, "PCM DEV is part of the persisted key"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn database_without_mixer_control_map_migrates_to_empty() { + let dir = unique_test_dir("legacy-alsa-mixer-column"); + { + let store = AudioSettingsStore::new_at(&dir).expect("create current store"); + store + .conn + .execute( + "ALTER TABLE audio_settings DROP COLUMN alsa_hardware_volume_controls", + [], + ) + .expect("simulate pre-map database"); + } + + let migrated = AudioSettingsStore::new_at(&dir).expect("migrate old store"); + assert!(migrated + .get_settings() + .expect("read migrated settings") + .alsa_hardware_volume_controls + .is_empty()); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn reset_clears_route_scoped_alsa_mixer_controls() { + let (dir, store) = fresh_store("reset-alsa-mixer-controls"); + let route: StableAlsaRouteKey = + serde_json::from_str("\"alsa-route-v1|card=card:D50|pcm=hw|DEV=0\"").expect("route"); + store + .enable_alsa_hardware_volume( + route, + AlsaMixerControlId { + name: "D50 III".to_string(), + index: 0, + }, + ) + .expect("enable exact control"); + + let reset = store.reset_all().expect("reset"); + assert!(!reset.alsa_hardware_volume); + assert!(reset.alsa_hardware_volume_controls.is_empty()); + let _ = std::fs::remove_dir_all(dir); } } diff --git a/crates/qbz-player/src/player/mod.rs b/crates/qbz-player/src/player/mod.rs index 94e27873f..8aa890afb 100644 --- a/crates/qbz-player/src/player/mod.rs +++ b/crates/qbz-player/src/player/mod.rs @@ -646,6 +646,87 @@ fn apply_engine_volume( engine.set_volume(volume); } +fn reported_volume_after_command( + requested: f32, + direct_output: bool, + hardware_volume_active: bool, +) -> f32 { + #[cfg(target_os = "linux")] + if direct_output && !hardware_volume_active { + return 1.0; + } + + #[cfg(not(target_os = "linux"))] + let _ = (direct_output, hardware_volume_active); + + requested +} + +fn selected_alsa_hardware_volume_control( + settings: &Arc>, +) -> Option { + settings + .lock() + .ok() + .and_then(|settings| settings.selected_alsa_hardware_volume_control()) +} + +fn hardware_volume_event_callback( + state: &SharedState, + initially_active: bool, +) -> qbz_audio::alsa_hardware_volume::HardwareVolumeEventCallback { + use qbz_audio::alsa_hardware_volume::{HardwareVolumeEvent, HardwareVolumeEventCallback}; + + state.set_hardware_volume_active(initially_active); + let state = state.clone(); + // A session that has reported Unavailable must never be revived by an + // already-queued ctl Changed event. Serializing callbacks also guarantees + // that whichever event obtains this latch first completes before the next + // one updates SharedState. + let session_active = Mutex::new(initially_active); + let callback: HardwareVolumeEventCallback = Arc::new(move |event| { + let Ok(mut active) = session_active.lock() else { + state.set_hardware_volume_active(false); + state.volume.store(1.0_f32.to_bits(), Ordering::SeqCst); + state.record_stream_error( + "ALSA hardware volume event state became unavailable. Direct playback remains fixed at 100%." + .to_string(), + ); + return; + }; + match event { + HardwareVolumeEvent::Changed(snapshot) if *active => { + state + .volume + .store(snapshot.volume.to_bits(), Ordering::SeqCst); + state.set_hardware_volume_active(true); + } + HardwareVolumeEvent::Changed(_) => {} + HardwareVolumeEvent::Unavailable(error) => { + *active = false; + state.set_hardware_volume_active(false); + state.volume.store(1.0_f32.to_bits(), Ordering::SeqCst); + state.record_stream_error(format!( + "ALSA hardware volume became unavailable: {error}. Direct playback remains fixed at 100%." + )); + } + } + }); + callback +} + +fn direct_hardware_volume_binding( + settings: &Arc>, + state: &SharedState, +) -> ( + Option, + qbz_audio::alsa_hardware_volume::HardwareVolumeEventCallback, +) { + let control = selected_alsa_hardware_volume_control(settings); + let callback = hardware_volume_event_callback(state, control.is_some()); + (control, callback) +} + #[cfg(target_os = "macos")] fn uses_coreaudio_system_default(settings: &AudioSettings) -> bool { settings @@ -1038,6 +1119,10 @@ pub struct PlaybackEvent { pub duration: u64, pub track_id: u64, pub volume: f32, + /// Whether the exact persisted ALSA mixer control is active for this + /// session. False after a ctl/write/disconnect failure (fail closed). + #[serde(default)] + pub hardware_volume_active: bool, /// Actual sample rate of the current stream (Hz) pub sample_rate: Option, /// Actual bit depth of the current stream @@ -1102,6 +1187,9 @@ pub struct SharedState { /// `normalization_gain`; integer-percent storage quantized the volume /// to 1% on every re-apply) volume: Arc, + /// Session state, separate from the persisted preference. Any control + /// failure flips this off while direct samples remain at unity. + hardware_volume_active: Arc, /// Playback start time (Unix timestamp millis when started/resumed) playback_start_millis: Arc, /// Position when playback was started/resumed (in seconds) @@ -1183,6 +1271,7 @@ impl SharedState { dsd_direct: Arc::new(std::sync::atomic::AtomicU8::new(0)), has_loaded_audio: Arc::new(AtomicBool::new(false)), volume: Arc::new(AtomicU32::new(0.75f32.to_bits())), + hardware_volume_active: Arc::new(AtomicBool::new(false)), playback_start_millis: Arc::new(AtomicU64::new(0)), position_at_start: Arc::new(AtomicU64::new(0)), current_device: Arc::new(std::sync::RwLock::new(None)), @@ -1639,6 +1728,14 @@ impl SharedState { pub fn volume(&self) -> f32 { f32::from_bits(self.volume.load(Ordering::SeqCst)) } + + pub fn set_hardware_volume_active(&self, active: bool) { + self.hardware_volume_active.store(active, Ordering::SeqCst); + } + + pub fn hardware_volume_active(&self) -> bool { + self.hardware_volume_active.load(Ordering::SeqCst) + } } /// Audio player that handles streaming playback @@ -2050,6 +2147,7 @@ impl Player { engine.stop(); std::thread::sleep(Duration::from_millis(50)); } + thread_state.set_hardware_volume_active(false); // Now this drop is the last Arc ref — PCM actually closes drop(stream_opt.take()); // Give kernel time to fully release the ALSA device @@ -2299,6 +2397,7 @@ impl Player { #[cfg(target_os = "linux")] std::thread::sleep(Duration::from_millis(50)); } + thread_state.set_hardware_volume_active(false); *current_audio_data = Some(data.clone()); *current_streaming_source = None; // Clear streaming source for non-streaming playback @@ -2359,15 +2458,16 @@ impl Player { StreamType::Direct(alsa_stream) => { *consecutive_sink_failures = 0; thread_state.set_stream_error(false); - let hardware_volume = thread_settings - .lock() - .ok() - .map(|s| s.alsa_hardware_volume) - .unwrap_or(false); + let (hardware_volume, hardware_volume_events) = + direct_hardware_volume_binding( + &thread_settings, + &thread_state, + ); PlaybackEngine::new_direct( alsa_stream.clone(), hardware_volume, thread_viz_tap.clone(), + hardware_volume_events, ) } #[cfg(target_os = "linux")] @@ -2602,6 +2702,7 @@ impl Player { engine.stop(); std::thread::sleep(Duration::from_millis(50)); } + thread_state.set_hardware_volume_active(false); // Now this drop is the last Arc ref — PCM actually closes drop(stream_opt.take()); // Give kernel time to fully release the ALSA device @@ -2776,6 +2877,7 @@ impl Player { #[cfg(target_os = "linux")] std::thread::sleep(Duration::from_millis(50)); } + thread_state.set_hardware_volume_active(false); // Create PlaybackEngine let mut engine = match stream { @@ -2805,15 +2907,16 @@ impl Player { } } StreamType::Direct(alsa_stream) => { - let hardware_volume = thread_settings - .lock() - .ok() - .map(|s| s.alsa_hardware_volume) - .unwrap_or(false); + let (hardware_volume, hardware_volume_events) = + direct_hardware_volume_binding( + &thread_settings, + &thread_state, + ); PlaybackEngine::new_direct( alsa_stream.clone(), hardware_volume, thread_viz_tap.clone(), + hardware_volume_events, ) } #[cfg(target_os = "linux")] @@ -3121,6 +3224,7 @@ impl Player { engine.stop(); std::thread::sleep(Duration::from_millis(50)); } + thread_state.set_hardware_volume_active(false); drop(stream_opt.take()); std::thread::sleep(Duration::from_millis(50)); @@ -3225,6 +3329,7 @@ impl Player { engine.stop(); std::thread::sleep(Duration::from_millis(50)); } + thread_state.set_hardware_volume_active(false); drop(stream_opt.take()); std::thread::sleep(Duration::from_millis(50)); @@ -3503,17 +3608,18 @@ impl Player { } } StreamType::Direct(alsa_stream) => { - let hardware_volume = thread_settings - .lock() - .ok() - .map(|s| s.alsa_hardware_volume) - .unwrap_or(false); - PlaybackEngine::new_direct( - alsa_stream.clone(), - hardware_volume, - thread_viz_tap.clone(), - ) - } + let (hardware_volume, hardware_volume_events) = + direct_hardware_volume_binding( + &thread_settings, + &thread_state, + ); + PlaybackEngine::new_direct( + alsa_stream.clone(), + hardware_volume, + thread_viz_tap.clone(), + hardware_volume_events, + ) + } #[cfg(target_os = "linux")] StreamType::Jack(jack_stream) => { PlaybackEngine::new_jack(jack_stream.clone()) @@ -3594,6 +3700,7 @@ impl Player { if let Some(engine) = current_engine.take() { engine.stop(); } + thread_state.set_hardware_volume_active(false); *current_audio_data = None; *current_streaming_source = None; *current_normalization_gain = None; @@ -3635,9 +3742,14 @@ impl Player { log::info!("Audio thread: stopped"); } AudioCommand::SetVolume(volume) => { + let reported_volume = reported_volume_after_command( + volume, + matches!(stream_opt.as_ref(), Some(StreamType::Direct(_))), + thread_state.hardware_volume_active(), + ); thread_state .volume - .store(volume.to_bits(), Ordering::SeqCst); + .store(reported_volume.to_bits(), Ordering::SeqCst); if let Some(ref engine) = *current_engine { apply_engine_volume(&stream_opt, &engine, volume); } @@ -3733,6 +3845,7 @@ impl Player { if let Some(engine) = current_engine.take() { engine.stop(); } + thread_state.set_hardware_volume_active(false); let seek_abort = |thread_state: &SharedState, why: &str| { log::error!("Audio thread: seek aborted: {why}"); thread_state.is_playing.store(false, Ordering::SeqCst); @@ -3753,15 +3866,16 @@ impl Player { } } StreamType::Direct(alsa_stream) => { - let hardware_volume = thread_settings - .lock() - .ok() - .map(|s| s.alsa_hardware_volume) - .unwrap_or(false); + let (hardware_volume, hardware_volume_events) = + direct_hardware_volume_binding( + &thread_settings, + &thread_state, + ); PlaybackEngine::new_direct( alsa_stream.clone(), hardware_volume, thread_viz_tap.clone(), + hardware_volume_events, ) } #[cfg(target_os = "linux")] @@ -3910,6 +4024,7 @@ impl Player { if let Some(engine) = current_engine.take() { engine.stop(); } + thread_state.set_hardware_volume_active(false); drop(stream_opt.take()); log::info!("Audio thread: previous stream dropped, device released"); @@ -3975,6 +4090,7 @@ impl Player { if let Some(engine) = current_engine.take() { engine.stop(); } + thread_state.set_hardware_volume_active(false); drop(stream_opt.take()); // Undo anything QBZ parked so PipeWire / WirePlumber can // reclaim the device (e.g. a DAC left invisible to other @@ -4638,6 +4754,7 @@ impl Player { if let Some(engine) = current_engine.take() { engine.stop(); } + thread_state.set_hardware_volume_active(false); drop(stream_opt.take()); pause_suspend_deadline = None; // Reset the PipeWire clock if WE forced it (self-gating; @@ -6360,6 +6477,7 @@ impl Player { duration: self.state.duration(), track_id: self.state.current_track_id(), volume: self.state.volume(), + hardware_volume_active: self.state.hardware_volume_active(), sample_rate: if sample_rate > 0 { Some(sample_rate) } else { @@ -6459,7 +6577,13 @@ pub fn external_content_type(mime: &str, format_id: u32) -> String { mod tests { use super::compute_needs_new_stream; use super::external_content_type; + #[cfg(target_os = "linux")] + use super::{hardware_volume_event_callback, reported_volume_after_command}; use super::{BufferedMediaSource, DsdErrorReport, SharedState, StreamingConfig}; + #[cfg(target_os = "linux")] + use qbz_audio::alsa_hardware_volume::{ + AlsaMixerControlId, HardwareVolumeEvent, HardwareVolumeSnapshot, + }; use std::sync::atomic::Ordering; struct FakeDsdSource { @@ -6467,6 +6591,46 @@ mod tests { error: Option, } + #[cfg(target_os = "linux")] + #[test] + fn inactive_direct_hardware_volume_reports_unity() { + assert_eq!(reported_volume_after_command(0.25, true, false), 1.0); + assert_eq!(reported_volume_after_command(0.25, true, true), 0.25); + assert_eq!(reported_volume_after_command(0.25, false, false), 0.25); + } + + #[cfg(target_os = "linux")] + #[test] + fn unavailable_hardware_volume_session_cannot_be_revived_by_stale_event() { + let state = SharedState::new(); + let callback = hardware_volume_event_callback(&state, true); + let changed = |volume| { + HardwareVolumeEvent::Changed(HardwareVolumeSnapshot { + control: AlsaMixerControlId { + name: "D50 III".to_string(), + index: 0, + }, + channels: Vec::new(), + volume, + muted: false, + }) + }; + + callback(changed(0.42)); + assert!(state.hardware_volume_active()); + assert_eq!(state.volume(), 0.42); + + callback(HardwareVolumeEvent::Unavailable( + "device disappeared".to_string(), + )); + assert!(!state.hardware_volume_active()); + assert_eq!(state.volume(), 1.0); + + callback(changed(0.75)); + assert!(!state.hardware_volume_active()); + assert_eq!(state.volume(), 1.0); + } + impl Iterator for FakeDsdSource { type Item = i32; fn next(&mut self) -> Option { diff --git a/crates/qbz-player/src/player/playback_engine.rs b/crates/qbz-player/src/player/playback_engine.rs index 2c3ac6779..29b0d6eac 100644 --- a/crates/qbz-player/src/player/playback_engine.rs +++ b/crates/qbz-player/src/player/playback_engine.rs @@ -8,6 +8,10 @@ //! to enable gapless playback. When one source ends, the next is picked up //! seamlessly without interrupting the PCM stream. +use qbz_audio::alsa_hardware_volume::{ + read_hardware_volume, subscribe_hardware_volume_events, AlsaMixerControlId, + HardwareVolumeEvent, HardwareVolumeEventCallback, HardwareVolumeEventSubscription, +}; #[cfg(target_os = "linux")] use qbz_audio::AlsaDirectStream; use qbz_audio::VisualizerTap; @@ -92,7 +96,10 @@ pub enum PlaybackEngine { playback_thread: Option>, /// Signals that the writer thread has consumed a source and moved to next source_transition: Arc, - hardware_volume: bool, + hardware_volume_control: Option, + hardware_volume_active: Arc, + hardware_volume_events: HardwareVolumeEventCallback, + _hardware_volume_subscription: Option, }, /// Native JACK output (#263 Tier 3). Mirrors AlsaDirect (gapless source queue /// + a single long-lived feeder thread), but the feeder resamples each source @@ -140,8 +147,9 @@ impl PlaybackEngine { /// site can mislabel it. pub fn new_direct( stream: Arc, - hardware_volume: bool, + hardware_volume_control: Option, visualizer_tap: Option, + hardware_volume_events: HardwareVolumeEventCallback, ) -> Self { let label = stream.log_label(); let is_playing = Arc::new(AtomicBool::new(false)); @@ -150,6 +158,45 @@ impl PlaybackEngine { let duration_frames = Arc::new(AtomicU64::new(0)); let source_queue = Arc::new(SourceQueue::new()); let source_transition = Arc::new(AtomicBool::new(false)); + let hardware_volume_active = Arc::new(AtomicBool::new(hardware_volume_control.is_some())); + + let hardware_volume_subscription = hardware_volume_control.as_ref().and_then(|control| { + let Some(device_id) = stream.alsa_device_id() else { + hardware_volume_active.store(false, Ordering::SeqCst); + hardware_volume_events(HardwareVolumeEvent::Unavailable( + "selected hardware volume has no ALSA device route".to_string(), + )); + return None; + }; + match read_hardware_volume(device_id, control) { + Ok(snapshot) => hardware_volume_events(HardwareVolumeEvent::Changed(snapshot)), + Err(error) => { + hardware_volume_active.store(false, Ordering::SeqCst); + hardware_volume_events(HardwareVolumeEvent::Unavailable(error)); + return None; + } + } + let active = hardware_volume_active.clone(); + let forward = hardware_volume_events.clone(); + let callback: HardwareVolumeEventCallback = Arc::new(move |event| match event { + HardwareVolumeEvent::Unavailable(error) => { + active.store(false, Ordering::SeqCst); + forward(HardwareVolumeEvent::Unavailable(error)); + } + HardwareVolumeEvent::Changed(snapshot) if active.load(Ordering::SeqCst) => { + forward(HardwareVolumeEvent::Changed(snapshot)); + } + HardwareVolumeEvent::Changed(_) => {} + }); + match subscribe_hardware_volume_events(device_id, control, callback) { + Ok(subscription) => Some(subscription), + Err(error) => { + hardware_volume_active.store(false, Ordering::SeqCst); + hardware_volume_events(HardwareVolumeEvent::Unavailable(error)); + None + } + } + }); // Spawn the single long-lived writer thread let handle = { @@ -189,7 +236,10 @@ impl PlaybackEngine { source_queue, playback_thread: Some(handle), source_transition, - hardware_volume, + hardware_volume_control, + hardware_volume_active, + hardware_volume_events, + _hardware_volume_subscription: hardware_volume_subscription, } } @@ -519,26 +569,17 @@ impl PlaybackEngine { Self::Direct { stream, label, - hardware_volume, + hardware_volume_control, + hardware_volume_active, + hardware_volume_events, .. } => { - if *hardware_volume { - #[cfg(target_os = "linux")] - { - if let Err(e) = stream.set_hardware_volume(volume) { - log::warn!("[{label}] Hardware volume failed: {}", e); - } - } - // Additive arm. `set_hardware_volume` is a DirectSink - // method now, so a Windows sink can answer for itself - // instead of the setting silently doing nothing; a sink - // with no hardware volume returns Err and says so. macOS - // and the other targets keep their previous silence -- - // CoreAudio has its own path (set_coreaudio_hardware_volume). - #[cfg(windows)] - { - if let Err(e) = stream.set_hardware_volume(volume) { - log::warn!("[{label}] Hardware volume failed: {}", e); + if hardware_volume_active.load(Ordering::SeqCst) { + if let Some(control) = hardware_volume_control { + if let Err(error) = stream.set_hardware_volume(control, volume) { + log::warn!("[{label}] Hardware volume failed: {error}"); + hardware_volume_active.store(false, Ordering::SeqCst); + hardware_volume_events(HardwareVolumeEvent::Unavailable(error)); } } } else { From 96342e23bc079e29df7c526e4456d24a9fe73c56 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:14:29 -0600 Subject: [PATCH 2/3] feat(qt): expose ALSA hardware volume settings Add capability-aware enablement, exact control selection, diagnostics, live volume synchronization, and translated unsupported-state feedback to the Qt settings surface. cx --- .../translations/de/LC_MESSAGES/qbz-ui.po | 33 + .../translations/en/LC_MESSAGES/qbz-ui.po | 33 + .../translations/es/LC_MESSAGES/qbz-ui.po | 33 + .../translations/fr/LC_MESSAGES/qbz-ui.po | 33 + .../translations/ja/LC_MESSAGES/qbz-ui.po | 33 + .../translations/nl/LC_MESSAGES/qbz-ui.po | 33 + .../translations/pt/LC_MESSAGES/qbz-ui.po | 33 + .../translations/ru/LC_MESSAGES/qbz-ui.po | 33 + crates/qbz-qt/qml/controls/QbzSelect.qml | 49 +- crates/qbz-qt/qml/settings/AudioSettings.qml | 67 ++ crates/qbz-qt/src/diagnostics_qt.rs | 23 + crates/qbz-qt/src/playback_qt.rs | 14 + crates/qbz-qt/src/settings_qt.rs | 780 +++++++++++++++++- 13 files changed, 1156 insertions(+), 41 deletions(-) diff --git a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po index 6b3845a91..afbe1c424 100644 --- a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po @@ -6215,3 +6215,36 @@ msgstr "Hörverlauf gelöscht." msgid "Couldn't clear listening history." msgstr "Hörverlauf konnte nicht gelöscht werden." + +msgid "Checking ALSA mixer controls…" +msgstr "ALSA-Mixerregler werden geprüft…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Dieses Gerät stellt mehrere Wiedergaberegler bereit. Wählen Sie aus, welchen QBZ verwenden soll." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "Der gespeicherte Mixerregler ist nicht mehr verfügbar. Wählen Sie einen anderen Regler." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ hat keine Berechtigung, den ALSA-Mixer dieses Geräts zu lesen." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "Der ALSA-Mixer ist belegt. Schließen Sie die verwendende Anwendung und versuchen Sie es erneut." + +msgid "The selected ALSA device is no longer available." +msgstr "Das ausgewählte ALSA-Gerät ist nicht mehr verfügbar." + +msgid "This ALSA device does not expose a mixer." +msgstr "Dieses ALSA-Gerät stellt keinen Mixer bereit." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ konnte den ausgewählten ALSA-Mixerregler nicht schreiben. Die direkte Wiedergabe bleibt auf 100 % eingestellt." + +msgid "Selected mixer control" +msgstr "Ausgewählter Mixerregler" + +msgid "Choose mixer control" +msgstr "Mixerregler auswählen" + +msgid "Change mixer control" +msgstr "Mixerregler ändern" diff --git a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po index dece75e89..2ca40e693 100644 --- a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po @@ -1835,3 +1835,36 @@ msgstr "Listening history cleared." msgid "Couldn't clear listening history." msgstr "Couldn't clear listening history." + +msgid "Checking ALSA mixer controls…" +msgstr "Checking ALSA mixer controls…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "This device exposes multiple playback controls. Choose which one QBZ should use." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "The saved mixer control is no longer available. Choose another control." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ does not have permission to read this device's ALSA mixer." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "The ALSA mixer is busy. Close the app using it and try again." + +msgid "The selected ALSA device is no longer available." +msgstr "The selected ALSA device is no longer available." + +msgid "This ALSA device does not expose a mixer." +msgstr "This ALSA device does not expose a mixer." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." + +msgid "Selected mixer control" +msgstr "Selected mixer control" + +msgid "Choose mixer control" +msgstr "Choose mixer control" + +msgid "Change mixer control" +msgstr "Change mixer control" diff --git a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po index 7293fd7ba..db59f27a7 100644 --- a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po @@ -6221,3 +6221,36 @@ msgstr "Historial de escucha borrado." msgid "Couldn't clear listening history." msgstr "No se pudo borrar el historial de escucha." + +msgid "Checking ALSA mixer controls…" +msgstr "Comprobando los controles del mezclador ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Este dispositivo expone varios controles de reproducción. Elige cuál debe usar QBZ." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "El control del mezclador guardado ya no está disponible. Elige otro control." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ no tiene permiso para leer el mezclador ALSA de este dispositivo." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "El mezclador ALSA está ocupado. Cierra la aplicación que lo está usando e inténtalo de nuevo." + +msgid "The selected ALSA device is no longer available." +msgstr "El dispositivo ALSA seleccionado ya no está disponible." + +msgid "This ALSA device does not expose a mixer." +msgstr "Este dispositivo ALSA no expone un mezclador." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ no pudo escribir en el control del mezclador ALSA seleccionado. La reproducción directa permanece fija al 100 %." + +msgid "Selected mixer control" +msgstr "Control de mezclador seleccionado" + +msgid "Choose mixer control" +msgstr "Elegir control de mezclador" + +msgid "Change mixer control" +msgstr "Cambiar control de mezclador" diff --git a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po index d77a0dc4d..3ee1a8ccd 100644 --- a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po @@ -6213,3 +6213,36 @@ msgstr "Historique d’écoute effacé." msgid "Couldn't clear listening history." msgstr "Impossible d’effacer l’historique d’écoute." + +msgid "Checking ALSA mixer controls…" +msgstr "Vérification des commandes du mixeur ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Ce périphérique expose plusieurs commandes de lecture. Choisissez celle que QBZ doit utiliser." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "La commande de mixage enregistrée n’est plus disponible. Choisissez-en une autre." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ n’est pas autorisé à lire le mixeur ALSA de ce périphérique." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "Le mixeur ALSA est occupé. Fermez l’application qui l’utilise et réessayez." + +msgid "The selected ALSA device is no longer available." +msgstr "Le périphérique ALSA sélectionné n’est plus disponible." + +msgid "This ALSA device does not expose a mixer." +msgstr "Ce périphérique ALSA n’expose aucun mixeur." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ n’a pas pu modifier la commande du mixeur ALSA sélectionnée. La lecture directe reste fixée à 100 %." + +msgid "Selected mixer control" +msgstr "Commande de mixage sélectionnée" + +msgid "Choose mixer control" +msgstr "Choisir la commande de mixage" + +msgid "Change mixer control" +msgstr "Changer la commande de mixage" diff --git a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po index 6b4d379cd..757c3e5a6 100644 --- a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po @@ -6197,3 +6197,36 @@ msgstr "再生履歴を消去しました。" msgid "Couldn't clear listening history." msgstr "再生履歴を消去できませんでした。" + +msgid "Checking ALSA mixer controls…" +msgstr "ALSA ミキサーコントロールを確認しています…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "このデバイスには複数の再生コントロールがあります。QBZ が使用するものを選択してください。" + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "保存されたミキサーコントロールは利用できなくなりました。別のコントロールを選択してください。" + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ にはこのデバイスの ALSA ミキサーを読み取る権限がありません。" + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "ALSA ミキサーは使用中です。使用しているアプリを閉じて、もう一度お試しください。" + +msgid "The selected ALSA device is no longer available." +msgstr "選択した ALSA デバイスは利用できなくなりました。" + +msgid "This ALSA device does not expose a mixer." +msgstr "この ALSA デバイスにはミキサーがありません。" + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "選択した ALSA ミキサーコントロールに書き込めませんでした。ダイレクト再生は 100% に固定されます。" + +msgid "Selected mixer control" +msgstr "選択中のミキサーコントロール" + +msgid "Choose mixer control" +msgstr "ミキサーコントロールを選択" + +msgid "Change mixer control" +msgstr "ミキサーコントロールを変更" diff --git a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po index 462a3bbec..32975d377 100644 --- a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po @@ -6203,3 +6203,36 @@ msgstr "Luistergeschiedenis gewist." msgid "Couldn't clear listening history." msgstr "Kon de luistergeschiedenis niet wissen." + +msgid "Checking ALSA mixer controls…" +msgstr "ALSA-mixerregelaars controleren…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Dit apparaat biedt meerdere afspeelregelaars. Kies welke QBZ moet gebruiken." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "De opgeslagen mixerregelaar is niet meer beschikbaar. Kies een andere regelaar." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ heeft geen toestemming om de ALSA-mixer van dit apparaat te lezen." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "De ALSA-mixer is bezet. Sluit de app die deze gebruikt en probeer het opnieuw." + +msgid "The selected ALSA device is no longer available." +msgstr "Het geselecteerde ALSA-apparaat is niet meer beschikbaar." + +msgid "This ALSA device does not expose a mixer." +msgstr "Dit ALSA-apparaat biedt geen mixer." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ kon de geselecteerde ALSA-mixerregelaar niet schrijven. Direct afspelen blijft vastgezet op 100%." + +msgid "Selected mixer control" +msgstr "Geselecteerde mixerregelaar" + +msgid "Choose mixer control" +msgstr "Mixerregelaar kiezen" + +msgid "Change mixer control" +msgstr "Mixerregelaar wijzigen" diff --git a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po index 5b7427932..fb2aa0b41 100644 --- a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po @@ -6213,3 +6213,36 @@ msgstr "Histórico de audição limpo." msgid "Couldn't clear listening history." msgstr "Não foi possível limpar o histórico de audição." + +msgid "Checking ALSA mixer controls…" +msgstr "A verificar os controlos do misturador ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Este dispositivo apresenta vários controlos de reprodução. Escolha qual o QBZ deve usar." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "O controlo do misturador guardado já não está disponível. Escolha outro controlo." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "O QBZ não tem permissão para ler o misturador ALSA deste dispositivo." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "O misturador ALSA está ocupado. Feche a aplicação que o está a usar e tente novamente." + +msgid "The selected ALSA device is no longer available." +msgstr "O dispositivo ALSA selecionado já não está disponível." + +msgid "This ALSA device does not expose a mixer." +msgstr "Este dispositivo ALSA não disponibiliza um misturador." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "O QBZ não conseguiu escrever no controlo do misturador ALSA selecionado. A reprodução direta permanece fixa em 100%." + +msgid "Selected mixer control" +msgstr "Controlo do misturador selecionado" + +msgid "Choose mixer control" +msgstr "Escolher controlo do misturador" + +msgid "Change mixer control" +msgstr "Alterar controlo do misturador" diff --git a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po index 47de7e045..b5c06a510 100644 --- a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po @@ -6233,3 +6233,36 @@ msgstr "История прослушиваний очищена." msgid "Couldn't clear listening history." msgstr "Не удалось очистить историю прослушиваний." + +msgid "Checking ALSA mixer controls…" +msgstr "Проверка регуляторов микшера ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Это устройство предоставляет несколько регуляторов воспроизведения. Выберите, какой из них должен использовать QBZ." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "Сохранённый регулятор микшера больше недоступен. Выберите другой регулятор." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "У QBZ нет разрешения на чтение микшера ALSA этого устройства." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "Микшер ALSA занят. Закройте использующее его приложение и повторите попытку." + +msgid "The selected ALSA device is no longer available." +msgstr "Выбранное устройство ALSA больше недоступно." + +msgid "This ALSA device does not expose a mixer." +msgstr "Это устройство ALSA не предоставляет микшер." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ не удалось изменить выбранный регулятор микшера ALSA. Громкость прямого воспроизведения остаётся на уровне 100 %." + +msgid "Selected mixer control" +msgstr "Выбранный регулятор микшера" + +msgid "Choose mixer control" +msgstr "Выбрать регулятор микшера" + +msgid "Change mixer control" +msgstr "Изменить регулятор микшера" diff --git a/crates/qbz-qt/qml/controls/QbzSelect.qml b/crates/qbz-qt/qml/controls/QbzSelect.qml index 7749ff36f..fba0e1f0c 100644 --- a/crates/qbz-qt/qml/controls/QbzSelect.qml +++ b/crates/qbz-qt/qml/controls/QbzSelect.qml @@ -66,6 +66,7 @@ Rectangle { } function optHasBadges() { return options.length > 0 && typeof options[0] !== "string" + && options[0] && options[0].bp !== undefined } function optBp(i) { const o = options[i] @@ -75,6 +76,18 @@ Rectangle { const o = options[i] return (o && o.group !== undefined) ? o.group : "" } + function optDetail(i) { + const o = options[i] + return (o && o.detail !== undefined) ? o.detail : "" + } + function openPopup() { + if (!selectRoot.enabled || selectRoot.options.length === 0) + return + selectRoot.filter = "" + popup.open() + if (selectRoot.searchable) + searchInput.forceActiveFocus() + } Row { anchors.fill: parent @@ -132,8 +145,7 @@ Rectangle { cursorShape: selectRoot.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor onClicked: { if (selectRoot.enabled) { - selectRoot.filter = "" - popup.open() + selectRoot.openPopup() } } } @@ -254,22 +266,39 @@ Rectangle { Rectangle { visible: optRow.shown width: parent.width - height: visible ? selectRoot.rowHeight : 0 + height: visible + ? (selectRoot.optDetail(optRow.index) !== "" ? 50 : selectRoot.rowHeight) + : 0 color: optArea.containsMouse ? theme.surfaceHover : "transparent" Row { anchors.fill: parent anchors.leftMargin: 12 anchors.rightMargin: 12 spacing: 8 - Text { + Column { width: parent.width - rowBadge.width - (rowBadge.visible ? 8 : 0) height: parent.height - text: optRow.label - color: optRow.index === selectRoot.currentIndex - ? theme.accent : theme.textSecondary - font.pixelSize: selectRoot.sm ? 12 : theme.fontBody - verticalAlignment: Text.AlignVCenter - elide: Text.ElideRight + anchors.verticalCenter: parent.verticalCenter + Text { + width: parent.width + height: selectRoot.optDetail(optRow.index) !== "" ? 26 : parent.height + text: optRow.label + color: optRow.index === selectRoot.currentIndex + ? theme.accent : theme.textSecondary + font.pixelSize: selectRoot.sm ? 12 : theme.fontBody + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + Text { + visible: selectRoot.optDetail(optRow.index) !== "" + width: parent.width + height: visible ? 18 : 0 + text: selectRoot.optDetail(optRow.index) + color: theme.textMuted + font.pixelSize: theme.fontLegal + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } } Item { id: rowBadge diff --git a/crates/qbz-qt/qml/settings/AudioSettings.qml b/crates/qbz-qt/qml/settings/AudioSettings.qml index c96ab4a43..d5ed0868a 100644 --- a/crates/qbz-qt/qml/settings/AudioSettings.qml +++ b/crates/qbz-qt/qml/settings/AudioSettings.qml @@ -25,6 +25,24 @@ Column { id: root property var doc: ({}) + property string openedHardwareVolumeChoice: "" + + function maybeOpenHardwareVolumeChoice() { + const status = root.doc.alsaHardwareVolumeStatus || "" + const needsChoice = status === "ambiguous" || status === "stale" + const token = root.doc.alsaHardwareVolumeChoiceToken || "" + if (!needsChoice) { + root.openedHardwareVolumeChoice = "" + return + } + if (token !== "" && token !== root.openedHardwareVolumeChoice) { + root.openedHardwareVolumeChoice = token + Qt.callLater(function () { hardwareVolumeSelect.openPopup() }) + } + } + + onDocChanged: maybeOpenHardwareVolumeChoice() + Component.onCompleted: maybeOpenHardwareVolumeChoice() QbzTheme { id: theme } @@ -149,6 +167,55 @@ Column { onToggled: function (v) { QbzBridge.settingsBool("alsa-hardware-volume", v) } } } + Text { + visible: root.doc.backendIsAlsa === true + && root.doc.alsaDirectSelected === true + && (root.doc.alsaHardwareVolumeMessage || "") !== "" + width: parent.width + text: root.doc.alsaHardwareVolumeMessage || "" + color: (root.doc.alsaHardwareVolumeStatus || "") === "probing" + ? theme.textMuted : theme.warning + font.pixelSize: 12 + wrapMode: Text.WordWrap + } + SettingRow { + visible: root.doc.backendIsAlsa === true + && root.doc.alsaDirectSelected === true + && (root.doc.alsaHardwareVolumeSelected || "") !== "" + label: QbzSession.tr("Selected mixer control", QbzSession.trRev) + Text { + text: root.doc.alsaHardwareVolumeSelected || "" + color: theme.textPrimary + font.pixelSize: theme.fontBody + font.weight: theme.weightMedium + verticalAlignment: Text.AlignVCenter + } + } + SettingRow { + visible: root.doc.backendIsAlsa === true + && root.doc.alsaDirectSelected === true + && ((root.doc.alsaHardwareVolumeStatus || "") === "ambiguous" + || (root.doc.alsaHardwareVolumeStatus || "") === "stale" + || (root.doc.alsaHardwareVolume === true + && root.doc.alsaHardwareVolumeCanChange === true)) + && (root.doc.alsaHardwareVolumeOptions || []).length > 0 + label: ((root.doc.alsaHardwareVolumeStatus || "") === "ambiguous" + || (root.doc.alsaHardwareVolumeStatus || "") === "stale") + ? QbzSession.tr("Choose mixer control", QbzSession.trRev) + : QbzSession.tr("Change mixer control", QbzSession.trRev) + QbzSelect { + id: hardwareVolumeSelect + menuWidth: 260 + popupWidth: 480 + searchable: (root.doc.alsaHardwareVolumeOptions || []).length > 8 + options: root.doc.alsaHardwareVolumeOptions || [] + currentIndex: root.doc.alsaHardwareVolumeIndex !== undefined + ? root.doc.alsaHardwareVolumeIndex : -1 + onSelected: function (i) { + QbzBridge.settingsSelect("alsa-hardware-volume-control", i) + } + } + } SettingRow { // ALSA only. fc0d35e29 opened this to WASAPI expecting plan B Task 6 // (DoP over exclusive mode); the spike then measured this DAC refusing diff --git a/crates/qbz-qt/src/diagnostics_qt.rs b/crates/qbz-qt/src/diagnostics_qt.rs index 2376a3387..3a4d3fc5b 100644 --- a/crates/qbz-qt/src/diagnostics_qt.rs +++ b/crates/qbz-qt/src/diagnostics_qt.rs @@ -706,6 +706,26 @@ fn build_system_rows( fn build_audio_rows(g: &Gathered) -> Vec { let d = &g.diag; + let selected_mixer = d + .audio_alsa_hardware_volume_probe + .as_ref() + .and_then(|probe| probe.route_key.as_ref()) + .and_then(|route| d.audio_alsa_hardware_volume_controls.get(route)) + .map(ToString::to_string) + .unwrap_or_else(|| "—".to_string()); + let mixer_probe = d + .audio_alsa_hardware_volume_probe + .as_ref() + .map(|probe| { + let valid = probe.valid_candidates().count(); + let rejected = probe.candidates.len().saturating_sub(valid); + if let Some(error) = &probe.error { + format!("{:?}: {}", error.kind, error.message) + } else { + format!("{valid} valid · {rejected} rejected") + } + }) + .unwrap_or_else(|| "—".to_string()); let sample_rate = match d.audio_preferred_sample_rate { Some(hz) => format!("{hz} Hz"), None => "Auto".to_string(), @@ -763,6 +783,7 @@ fn build_audio_rows(g: &Gathered) -> Vec { row("Active Format", "—", active_fmt, 0), row("ALSA Plugin", &opt(&d.audio_alsa_plugin), "—", 0), row("ALSA HW Volume", yn(d.audio_alsa_hardware_volume), "—", 0), + row("ALSA HW Control", &selected_mixer, &mixer_probe, 0), row("Normalization", yn(d.audio_normalization_enabled), "—", 0), row( "Normalization Target", @@ -1067,6 +1088,8 @@ fn build_export_json(g: &Gathered) -> Value { "preferredSampleRate": d.audio_preferred_sample_rate, "alsaPlugin": d.audio_alsa_plugin, "alsaHardwareVolume": d.audio_alsa_hardware_volume, + "alsaHardwareVolumeControls": d.audio_alsa_hardware_volume_controls, + "alsaHardwareVolumeProbe": d.audio_alsa_hardware_volume_probe, "normalizationEnabled": d.audio_normalization_enabled, "normalizationTargetLufs": d.audio_normalization_target_lufs, "gaplessEnabled": d.audio_gapless_enabled, diff --git a/crates/qbz-qt/src/playback_qt.rs b/crates/qbz-qt/src/playback_qt.rs index 7916d6d84..af7b84a66 100644 --- a/crates/qbz-qt/src/playback_qt.rs +++ b/crates/qbz-qt/src/playback_qt.rs @@ -3211,6 +3211,10 @@ pub fn start_poll_loop(runtime: Arc>) { // meta refresh just reset the bar's position to 0). Reset to None // whenever another owner (local/cast poll) may have written the bar. let mut last_remote_ui_push: Option<(u64, u64, u64, bool, u32, bool, i32)> = None; + // Physical ALSA knob events update the Player's shared volume atomics. + // Mirror only hardware-volume edges onto QML; ordinary local slider + // writes already publish immediately at their command boundary. + let mut last_hardware_volume: Option<(bool, u32)> = None; let mut ticker = tokio::time::interval(std::time::Duration::from_secs(1)); loop { @@ -3443,6 +3447,15 @@ pub fn start_poll_loop(runtime: Arc>) { let duration = event.duration; let is_playing = event.is_playing; let cache = event.buffer_progress.unwrap_or(0.0); + let hardware_volume = (event.hardware_volume_active, event.volume.to_bits()); + if last_hardware_volume != Some(hardware_volume) { + if event.hardware_volume_active + || last_hardware_volume.is_some_and(|(active, _)| active) + { + crate::now_playing::set_volume(event.volume); + } + last_hardware_volume = Some(hardware_volume); + } // Seek lock (PARITY-DEBT #15, playback.rs:5304): while streaming // (`buffer_progress` is Some) the user can only seek up to what // has downloaded; a fully-available track (None) seeks freely. @@ -3979,6 +3992,7 @@ mod tests { duration: 0, track_id, volume: 1.0, + hardware_volume_active: false, sample_rate: None, bit_depth: None, shuffle: None, diff --git a/crates/qbz-qt/src/settings_qt.rs b/crates/qbz-qt/src/settings_qt.rs index 871883e13..ae261ecac 100644 --- a/crates/qbz-qt/src/settings_qt.rs +++ b/crates/qbz-qt/src/settings_qt.rs @@ -30,6 +30,12 @@ use qbz_app::settings::playback::{ AutoplayMode, PlaybackPreferencesState, PlaybackPreferencesStore, }; use qbz_app::shell::AppRuntime; +use qbz_audio::alsa_hardware_volume::{ + AlsaMixerControlId, HardwareVolumeCandidate, HardwareVolumeChoiceReason, + HardwareVolumeDecision, HardwareVolumeProbe, HardwareVolumeProbeErrorKind, + HardwareVolumeSelection, HardwareVolumeSelectionSource, HardwareVolumeSnapshot, + HardwareVolumeUnsupportedReason, StableAlsaRouteKey, +}; use qbz_audio::backend::{AlsaPlugin, AudioBackendType, BackendManager}; use qbz_audio::settings::{AudioSettingsState, AudioSettingsStore}; use qbz_core::LoggingAdapter; @@ -1687,6 +1693,206 @@ pub struct DeviceOption { pub group: String, } +#[derive(Clone, Default, Serialize)] +pub struct HardwareVolumeOption { + pub label: String, + pub detail: String, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +enum HardwareVolumeUiStatus { + #[default] + Disabled, + Probing, + Selected, + Ambiguous, + Stale, + PermissionDenied, + DeviceBusy, + DeviceUnavailable, + NoMixer, + Unsupported, + WriteFailed, +} + +impl HardwareVolumeUiStatus { + fn key(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Probing => "probing", + Self::Selected => "selected", + Self::Ambiguous => "ambiguous", + Self::Stale => "stale", + Self::PermissionDenied => "permission_denied", + Self::DeviceBusy => "device_busy", + Self::DeviceUnavailable => "device_unavailable", + Self::NoMixer => "no_mixer", + Self::Unsupported => "unsupported", + Self::WriteFailed => "write_failed", + } + } + + fn message(self) -> String { + match self { + Self::Disabled | Self::Selected => String::new(), + Self::Probing => qbz_i18n::t("Checking ALSA mixer controls…"), + Self::Ambiguous => qbz_i18n::t( + "This device exposes multiple playback controls. Choose which one QBZ should use.", + ), + Self::Stale => qbz_i18n::t( + "The saved mixer control is no longer available. Choose another control.", + ), + Self::PermissionDenied => { + qbz_i18n::t("QBZ does not have permission to read this device's ALSA mixer.") + } + Self::DeviceBusy => { + qbz_i18n::t("The ALSA mixer is busy. Close the app using it and try again.") + } + Self::DeviceUnavailable => { + qbz_i18n::t("The selected ALSA device is no longer available.") + } + Self::NoMixer => qbz_i18n::t("This ALSA device does not expose a mixer."), + Self::Unsupported => qbz_i18n::t( + "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%.", + ), + Self::WriteFailed => qbz_i18n::t( + "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%.", + ), + } + } +} + +#[derive(Clone, Default)] +struct HardwareVolumeUiState { + device_id: Option, + route_key: Option, + candidates: Vec, + selected: Option, + status: HardwareVolumeUiStatus, +} + +#[derive(Default)] +struct HardwareVolumeUiSnapshot { + options: Vec, + selected_index: i32, + selected: String, + status: &'static str, + message: String, + can_change: bool, + choice_token: String, +} + +static HARDWARE_VOLUME_UI: Mutex = Mutex::new(HardwareVolumeUiState { + device_id: None, + route_key: None, + candidates: Vec::new(), + selected: None, + status: HardwareVolumeUiStatus::Disabled, +}); + +fn hardware_volume_candidate_detail(candidate: &HardwareVolumeCandidate) -> String { + let range = if let Some(range) = candidate.db_range { + format!( + "{:.2}–{:.2} dB", + range.min as f64 / 100.0, + range.max as f64 / 100.0 + ) + } else if let Some(range) = candidate.raw_range { + format!("{}–{}", range.min, range.max) + } else { + String::new() + }; + let channels = candidate.channels.join(", "); + match (candidate.recommended, range.is_empty(), channels.is_empty()) { + (true, false, false) => format!("★ {range} · {channels}"), + (true, false, true) => format!("★ {range}"), + (true, true, false) => format!("★ {channels}"), + (true, true, true) => "★".to_string(), + (false, false, false) => format!("{range} · {channels}"), + (false, false, true) => range, + (false, true, false) => channels, + (false, true, true) => String::new(), + } +} + +fn hardware_volume_ui_snapshot( + audio: &qbz_audio::settings::AudioSettings, +) -> HardwareVolumeUiSnapshot { + let Ok(state) = HARDWARE_VOLUME_UI.lock() else { + return HardwareVolumeUiSnapshot::default(); + }; + if state.device_id.as_deref() != audio.output_device.as_deref() { + return HardwareVolumeUiSnapshot { + status: if audio.alsa_hardware_volume { + HardwareVolumeUiStatus::Probing.key() + } else { + HardwareVolumeUiStatus::Disabled.key() + }, + message: if audio.alsa_hardware_volume { + HardwareVolumeUiStatus::Probing.message() + } else { + String::new() + }, + ..Default::default() + }; + } + + let options = state + .candidates + .iter() + .map(|candidate| HardwareVolumeOption { + label: candidate.id.to_string(), + detail: hardware_volume_candidate_detail(candidate), + }) + .collect::>(); + let selected_index = state + .selected + .as_ref() + .and_then(|selected| { + state + .candidates + .iter() + .position(|candidate| candidate.id == *selected) + }) + .map(|index| index as i32) + .unwrap_or(-1); + let choice_token = if matches!( + state.status, + HardwareVolumeUiStatus::Ambiguous | HardwareVolumeUiStatus::Stale + ) { + format!( + "{}|{}", + state + .route_key + .as_ref() + .map(StableAlsaRouteKey::as_str) + .unwrap_or_default(), + state + .candidates + .iter() + .map(|candidate| candidate.id.to_string()) + .collect::>() + .join("|") + ) + } else { + String::new() + }; + + HardwareVolumeUiSnapshot { + selected: state + .selected + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + status: state.status.key(), + message: state.status.message(), + can_change: state.candidates.len() > 1 && state.selected.is_some(), + choice_token, + options, + selected_index, + } +} + #[derive(Default, Serialize)] pub struct SettingsDoc { // Audio @@ -1721,6 +1927,20 @@ pub struct SettingsDoc { pub alsa_direct_selected: bool, #[serde(rename = "alsaHardwareVolume")] pub alsa_hardware_volume: bool, + #[serde(rename = "alsaHardwareVolumeOptions")] + pub alsa_hardware_volume_options: Vec, + #[serde(rename = "alsaHardwareVolumeIndex")] + pub alsa_hardware_volume_index: i32, + #[serde(rename = "alsaHardwareVolumeSelected")] + pub alsa_hardware_volume_selected: String, + #[serde(rename = "alsaHardwareVolumeStatus")] + pub alsa_hardware_volume_status: &'static str, + #[serde(rename = "alsaHardwareVolumeMessage")] + pub alsa_hardware_volume_message: String, + #[serde(rename = "alsaHardwareVolumeCanChange")] + pub alsa_hardware_volume_can_change: bool, + #[serde(rename = "alsaHardwareVolumeChoiceToken")] + pub alsa_hardware_volume_choice_token: String, #[serde(rename = "dsdModes")] pub dsd_modes: Vec, #[serde(rename = "dsdModeIndex")] @@ -2202,6 +2422,7 @@ pub async fn publish_snapshot() { .iter() .position(|k| *k == streaming_key) .unwrap_or(STREAMING_QUALITY_KEYS.len() - 1); + let hardware_volume_ui = hardware_volume_ui_snapshot(&audio_settings); let mut maps = MAPS.lock().unwrap(); maps.0 = backend_types.clone(); @@ -2228,6 +2449,13 @@ pub async fn publish_snapshot() { alsa_plugin_is_hw: alsa_plugin == AlsaPlugin::Hw, alsa_direct_selected: qbz_audio::alsa_direct::uses_alsa_direct_route(&audio_settings), alsa_hardware_volume: audio_settings.alsa_hardware_volume, + alsa_hardware_volume_options: hardware_volume_ui.options, + alsa_hardware_volume_index: hardware_volume_ui.selected_index, + alsa_hardware_volume_selected: hardware_volume_ui.selected, + alsa_hardware_volume_status: hardware_volume_ui.status, + alsa_hardware_volume_message: hardware_volume_ui.message, + alsa_hardware_volume_can_change: hardware_volume_ui.can_change, + alsa_hardware_volume_choice_token: hardware_volume_ui.choice_token, dsd_modes: DSD_MODE_LABELS.iter().map(|l| qbz_i18n::t(l)).collect(), dsd_mode_index: DSD_MODE_VALUES .iter() @@ -2465,7 +2693,7 @@ enum Apply { async fn probe_selected_hardware_volume( audio: &qbz_audio::settings::AudioSettings, -) -> Result { +) -> Result<(HardwareVolumeProbe, HardwareVolumeDecision), String> { if !qbz_audio::alsa_direct::uses_alsa_direct_route(audio) { return Err( "hardware volume requires an explicitly selected ALSA Direct device".to_string(), @@ -2475,50 +2703,219 @@ async fn probe_selected_hardware_volume( .output_device .clone() .ok_or_else(|| "ALSA Direct device is missing".to_string())?; - tokio::task::spawn_blocking(move || qbz_audio::alsa_direct::probe_hardware_volume(&device_id)) - .await - .map_err(|error| format!("ALSA hardware-volume probe task failed: {error}"))? + let persisted = audio.alsa_hardware_volume_controls.clone(); + tokio::task::spawn_blocking(move || { + let probe = qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls(&device_id); + let decision = qbz_audio::alsa_hardware_volume::decide_hardware_volume(&probe, &persisted); + (probe, decision) + }) + .await + .map_err(|error| format!("ALSA hardware-volume probe task failed: {error}")) } fn seed_hardware_volume( runtime: &Arc>, - info: &qbz_audio::alsa_direct::HardwareVolumeInfo, + control: &AlsaMixerControlId, + volume: f32, ) { // Update SharedState without touching the old output. The new direct // engine reads this after Reinit and writes back the same level the probe // sampled, instead of copying the locked path's synthetic 100% into the // physical mixer (or writing the new device's level through the old one). - runtime.core().player().seed_volume_state(info.volume); - save_pref("volume", serde_json::json!(info.volume)); - crate::now_playing::set_volume(info.volume); + runtime.core().player().seed_volume_state(volume); + save_pref("volume", serde_json::json!(volume)); + crate::now_playing::set_volume(volume); log::info!( "[qbz-qt] ALSA hardware volume: '{}' available at {:.0}%", - info.control_name, - info.volume * 100.0 + control, + volume * 100.0 ); } +fn set_hardware_volume_ui_status(device_id: Option, status: HardwareVolumeUiStatus) { + if let Ok(mut state) = HARDWARE_VOLUME_UI.lock() { + if state.device_id != device_id { + *state = HardwareVolumeUiState { + device_id, + status, + ..Default::default() + }; + } else { + state.status = status; + } + } +} + +fn set_hardware_volume_ui_probe( + device_id: String, + probe: &HardwareVolumeProbe, + selected: Option, + status: HardwareVolumeUiStatus, +) { + if let Ok(mut state) = HARDWARE_VOLUME_UI.lock() { + *state = HardwareVolumeUiState { + device_id: Some(device_id), + route_key: probe.route_key.clone(), + candidates: probe.valid_candidates().cloned().collect(), + selected, + status, + }; + } +} + +fn hardware_volume_unsupported_status( + reason: &HardwareVolumeUnsupportedReason, +) -> HardwareVolumeUiStatus { + match reason { + HardwareVolumeUnsupportedReason::Probe(error) => match error.kind { + HardwareVolumeProbeErrorKind::PermissionDenied => { + HardwareVolumeUiStatus::PermissionDenied + } + HardwareVolumeProbeErrorKind::DeviceBusy => HardwareVolumeUiStatus::DeviceBusy, + HardwareVolumeProbeErrorKind::DeviceUnavailable => { + HardwareVolumeUiStatus::DeviceUnavailable + } + HardwareVolumeProbeErrorKind::NoMixer => HardwareVolumeUiStatus::NoMixer, + HardwareVolumeProbeErrorKind::InvalidDevice + | HardwareVolumeProbeErrorKind::UnsupportedPlatform + | HardwareVolumeProbeErrorKind::Other => HardwareVolumeUiStatus::Unsupported, + }, + // No valid alternative exists in this decision variant. Reserve the + // actionable Stale state for NeedsChoice, where a closed selector can + // actually offer another enumerated control. + HardwareVolumeUnsupportedReason::PersistedSelectionStale(_) => { + HardwareVolumeUiStatus::Unsupported + } + HardwareVolumeUnsupportedReason::NoValidControls => HardwareVolumeUiStatus::Unsupported, + } +} + +fn hardware_volume_choice_status(reason: HardwareVolumeChoiceReason) -> HardwareVolumeUiStatus { + match reason { + HardwareVolumeChoiceReason::PersistedSelectionStale => HardwareVolumeUiStatus::Stale, + HardwareVolumeChoiceReason::Ambiguous | HardwareVolumeChoiceReason::UcmAmbiguous => { + HardwareVolumeUiStatus::Ambiguous + } + } +} + +fn current_hardware_volume_route_is( + expected_device_id: &str, +) -> Result { + let current = with_audio(|store| store.get_settings())?; + if !qbz_audio::alsa_direct::uses_alsa_direct_route(¤t) + || current.output_device.as_deref() != Some(expected_device_id) + { + return Err( + "the selected ALSA route changed while its mixer was being checked".to_string(), + ); + } + Ok(current) +} + +async fn activate_hardware_volume_selection( + device_id: &str, + control: &AlsaMixerControlId, +) -> Result { + let device_id = device_id.to_string(); + let control = control.clone(); + tokio::task::spawn_blocking(move || { + qbz_audio::alsa_hardware_volume::activate_hardware_volume_control(&device_id, &control) + }) + .await + .map_err(|error| format!("ALSA hardware-volume validation task failed: {error}"))? +} + +async fn enable_hardware_volume_selection( + runtime: &Arc>, + device_id: String, + probe: HardwareVolumeProbe, + selection: HardwareVolumeSelection, +) -> Result { + current_hardware_volume_route_is(&device_id)?; + let snapshot = match activate_hardware_volume_selection(&device_id, &selection.control).await { + Ok(snapshot) => snapshot, + Err(error) => { + log::warn!( + "[qbz-qt] ALSA hardware-volume control '{}' failed enable validation: {error}", + selection.control + ); + with_audio(|store| store.set_alsa_hardware_volume(false))?; + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::WriteFailed, + ); + return Ok(Apply::Reinit); + } + }; + current_hardware_volume_route_is(&device_id)?; + with_audio(|store| { + store.enable_alsa_hardware_volume(selection.route_key, selection.control.clone()) + })?; + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control.clone()), + HardwareVolumeUiStatus::Selected, + ); + seed_hardware_volume(runtime, &selection.control, snapshot.volume); + Ok(Apply::Reinit) +} + async fn set_alsa_hardware_volume( runtime: &Arc>, enabled: bool, ) -> Result { if !enabled { - return with_audio(|store| store.set_alsa_hardware_volume(false)).map(|_| Apply::Reinit); + let audio = with_audio(|store| { + store.set_alsa_hardware_volume(false)?; + store.get_settings() + })?; + set_hardware_volume_ui_status(audio.output_device, HardwareVolumeUiStatus::Disabled); + return Ok(Apply::Reinit); } let audio = with_audio(|store| store.get_settings())?; - let info = match probe_selected_hardware_volume(&audio).await { - Ok(info) => info, + let device_id = audio + .output_device + .clone() + .ok_or_else(|| "ALSA Direct device is missing".to_string())?; + set_hardware_volume_ui_status(Some(device_id.clone()), HardwareVolumeUiStatus::Probing); + publish_snapshot().await; + + let (probe, decision) = match probe_selected_hardware_volume(&audio).await { + Ok(result) => result, Err(error) => { - // An old build or an external settings edit may already have left - // this true. Fail closed so the UI cannot advertise an enabled, - // inert slider after the probe rejects the device. let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); - return Err(error); + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Unsupported); + log::warn!("[qbz-qt] ALSA hardware-volume probe failed: {error}"); + return Ok(Apply::Reinit); } }; - seed_hardware_volume(runtime, &info); - with_audio(|store| store.set_alsa_hardware_volume(true)).map(|_| Apply::Reinit) + current_hardware_volume_route_is(&device_id)?; + match decision { + HardwareVolumeDecision::Selected { selection } => { + enable_hardware_volume_selection(runtime, device_id, probe, selection).await + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + with_audio(|store| store.set_alsa_hardware_volume(false))?; + let status = hardware_volume_choice_status(reason); + set_hardware_volume_ui_probe(device_id, &probe, None, status); + log::info!( + "[qbz-qt] ALSA hardware volume needs an explicit control choice ({reason:?}); no mixer write performed" + ); + Ok(Apply::Reinit) + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + with_audio(|store| store.set_alsa_hardware_volume(false))?; + let status = hardware_volume_unsupported_status(&reason); + set_hardware_volume_ui_probe(device_id, &probe, None, status); + log::warn!("[qbz-qt] ALSA hardware volume is unavailable: {reason:?}"); + Ok(Apply::Reinit) + } + } } fn apply_audio(runtime: &Arc>, apply: Apply) { @@ -2618,27 +3015,181 @@ pub(crate) async fn reconcile_alsa_hardware_volume( return None; } }; - if !audio.alsa_hardware_volume || !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + if !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + if audio.alsa_hardware_volume { + if let Err(error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { + log::error!("[qbz-qt] failed to disable hardware volume off ALSA Direct: {error}"); + } + } + set_hardware_volume_ui_status(None, HardwareVolumeUiStatus::Disabled); return None; } - match probe_selected_hardware_volume(&audio).await { - Ok(info) => { - seed_hardware_volume(runtime, &info); - Some(info.volume) + let device_id = audio + .output_device + .clone() + .expect("direct route has a device"); + if !audio.alsa_hardware_volume { + let has_saved_control = qbz_audio::alsa_hardware_volume::stable_alsa_route_key(&device_id) + .ok() + .is_some_and(|route| audio.alsa_hardware_volume_controls.contains_key(&route)); + if !has_saved_control { + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Disabled); + return None; } + } + + set_hardware_volume_ui_status(Some(device_id.clone()), HardwareVolumeUiStatus::Probing); + let (probe, decision) = match probe_selected_hardware_volume(&audio).await { + Ok(result) => result, Err(error) => { - log::warn!("[qbz-qt] ALSA hardware volume unavailable; disabling the setting: {error}"); - if let Err(persist_error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { - log::error!( - "[qbz-qt] failed to disable unavailable hardware volume: {persist_error}" + log::warn!("[qbz-qt] ALSA hardware-volume reconciliation failed: {error}"); + if audio.alsa_hardware_volume { + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + } + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Unsupported); + if audio.alsa_hardware_volume { + apply_audio(runtime, Apply::Reinit); + } + return None; + } + }; + + if !audio.alsa_hardware_volume { + match decision { + HardwareVolumeDecision::Selected { selection } + if selection.source == HardwareVolumeSelectionSource::Persisted => + { + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::Disabled, ); + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + log::warn!( + "[qbz-qt] saved ALSA hardware-volume control needs a new choice ({reason:?})" + ); + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + HardwareVolumeUiStatus::Disabled, + ); + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + log::warn!( + "[qbz-qt] saved ALSA hardware-volume control no longer validates: {reason:?}" + ); + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + HardwareVolumeUiStatus::Disabled, + ); + } + HardwareVolumeDecision::Selected { .. } => { + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + HardwareVolumeUiStatus::Disabled, + ); + } + } + publish_snapshot().await; + return None; + } + + match decision { + HardwareVolumeDecision::Selected { selection } => { + let Some(volume) = selection.candidate.current_volume else { + log::warn!( + "[qbz-qt] selected ALSA control '{}' had no readable level", + selection.control + ); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::Unsupported, + ); + apply_audio(runtime, Apply::Reinit); + return None; + }; + let migrated = selection.source != HardwareVolumeSelectionSource::Persisted; + if migrated { + if let Err(error) = with_audio(|store| { + store.set_alsa_hardware_volume_control( + selection.route_key.clone(), + selection.control.clone(), + ) + }) { + log::error!( + "[qbz-qt] failed to migrate ALSA hardware-volume selection: {error}" + ); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::Unsupported, + ); + apply_audio(runtime, Apply::Reinit); + return None; + } + } + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control.clone()), + HardwareVolumeUiStatus::Selected, + ); + seed_hardware_volume(runtime, &selection.control, volume); + if migrated { + // Legacy `alsa_hardware_volume=true` had no exact identity in + // the Player's startup snapshot. Reload the newly migrated map + // without reopening the protected PCM route. + apply_audio(runtime, Apply::Reload); + } else { + publish_snapshot().await; + } + Some(volume) + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + log::warn!( + "[qbz-qt] persisted ALSA hardware volume needs an explicit choice ({reason:?}); disabling without writing" + ); + if let Err(error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { + log::error!("[qbz-qt] failed to disable ambiguous hardware volume: {error}"); return None; } + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + hardware_volume_choice_status(reason), + ); + apply_audio(runtime, Apply::Reinit); + None + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + log::warn!( + "[qbz-qt] persisted ALSA hardware volume is unavailable; disabling: {reason:?}" + ); + if let Err(error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { + log::error!("[qbz-qt] failed to disable unavailable hardware volume: {error}"); + return None; + } + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + hardware_volume_unsupported_status(&reason), + ); apply_audio(runtime, Apply::Reinit); - crate::toast_qt::error(qbz_i18n::t( - "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%.", - )); None } } @@ -2997,8 +3548,108 @@ pub async fn settings_bool(runtime: &Arc>, key: &str, } } +async fn select_alsa_hardware_volume_control( + runtime: &Arc>, + index: usize, +) { + let audio = match with_audio(|store| store.get_settings()) { + Ok(audio) => audio, + Err(error) => { + log::error!("[qbz-qt] read audio settings for mixer selection failed: {error}"); + return; + } + }; + if !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + log::warn!("[qbz-qt] ignored mixer selection outside ALSA Direct"); + return; + } + let device_id = audio + .output_device + .clone() + .expect("ALSA Direct route has a device id"); + let requested = HARDWARE_VOLUME_UI.lock().ok().and_then(|state| { + (state.device_id.as_deref() == Some(device_id.as_str())) + .then(|| { + state + .candidates + .get(index) + .map(|candidate| candidate.id.clone()) + }) + .flatten() + }); + let Some(requested) = requested else { + log::warn!("[qbz-qt] ignored stale ALSA mixer option index {index}"); + publish_snapshot().await; + return; + }; + + set_hardware_volume_ui_status(Some(device_id.clone()), HardwareVolumeUiStatus::Probing); + publish_snapshot().await; + + let (probe, _) = match probe_selected_hardware_volume(&audio).await { + Ok(result) => result, + Err(error) => { + log::warn!("[qbz-qt] ALSA mixer revalidation failed: {error}"); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Unsupported); + apply_audio(runtime, Apply::Reinit); + publish_snapshot().await; + return; + } + }; + if let Err(error) = current_hardware_volume_route_is(&device_id) { + log::warn!("[qbz-qt] discarded stale ALSA mixer selection: {error}"); + publish_snapshot().await; + return; + } + let candidate = probe + .valid_candidates() + .find(|candidate| candidate.id == requested) + .cloned(); + let Some(candidate) = candidate else { + log::warn!( + "[qbz-qt] ALSA mixer control '{}' disappeared before selection; no fallback chosen", + requested + ); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe(device_id, &probe, None, HardwareVolumeUiStatus::Stale); + apply_audio(runtime, Apply::Reinit); + publish_snapshot().await; + return; + }; + let Some(route_key) = probe.route_key.clone() else { + log::warn!("[qbz-qt] ALSA mixer selection has no stable route identity"); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe(device_id, &probe, None, HardwareVolumeUiStatus::Unsupported); + apply_audio(runtime, Apply::Reinit); + publish_snapshot().await; + return; + }; + let selection = HardwareVolumeSelection { + route_key, + control: requested, + candidate, + source: HardwareVolumeSelectionSource::UserChoice, + }; + match enable_hardware_volume_selection(runtime, device_id, probe, selection).await { + Ok(apply) => { + apply_audio(runtime, apply); + maybe_force_bitperfect_volume(runtime).await; + } + Err(error) => { + log::error!("[qbz-qt] persist ALSA mixer selection failed: {error}"); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + apply_audio(runtime, Apply::Reinit); + } + } + publish_snapshot().await; +} + pub async fn settings_select(runtime: &Arc>, key: &str, index: usize) { match key { + "alsa-hardware-volume-control" => { + select_alsa_hardware_volume_control(runtime, index).await; + } "streaming-quality" => { let Some(key) = STREAMING_QUALITY_KEYS.get(index) else { return; @@ -3535,6 +4186,31 @@ pub async fn refresh_devices(runtime: &Arc>) { mod local_tab_order_tests { use super::*; + fn mixer_candidate() -> HardwareVolumeCandidate { + HardwareVolumeCandidate { + id: AlsaMixerControlId { + name: "D50 III".to_string(), + index: 2, + }, + label: "D50 III,2".to_string(), + channels: vec!["front_left".to_string(), "front_right".to_string()], + raw_range: Some(qbz_audio::alsa_hardware_volume::HardwareVolumeRange { + min: 0, + max: 255, + }), + db_range: Some(qbz_audio::alsa_hardware_volume::HardwareVolumeRange { + min: -12_700, + max: 0, + }), + current_values: Vec::new(), + current_volume: Some(0.5), + has_playback_switch: true, + recommended: true, + writability: qbz_audio::alsa_hardware_volume::HardwareVolumeWritability::Verified, + rejection_reason: None, + } + } + #[test] fn absent_or_invalid_order_uses_the_complete_default() { let expected: Vec = LOCAL_TAB_DEFAULT_ORDER @@ -3586,6 +4262,48 @@ mod local_tab_order_tests { assert_eq!(large_spectrum_mode_for_tier(4, true), 4); } + #[test] + fn hardware_volume_statuses_are_typed_and_user_visible() { + let statuses = [ + HardwareVolumeUiStatus::Probing, + HardwareVolumeUiStatus::Ambiguous, + HardwareVolumeUiStatus::Stale, + HardwareVolumeUiStatus::PermissionDenied, + HardwareVolumeUiStatus::DeviceBusy, + HardwareVolumeUiStatus::DeviceUnavailable, + HardwareVolumeUiStatus::NoMixer, + HardwareVolumeUiStatus::Unsupported, + HardwareVolumeUiStatus::WriteFailed, + ]; + let mut keys = std::collections::HashSet::new(); + for status in statuses { + assert!(keys.insert(status.key()), "duplicate status key"); + assert!(!status.message().is_empty(), "missing status message"); + } + } + + #[test] + fn hardware_volume_option_exposes_exact_identity_range_and_channels() { + let candidate = mixer_candidate(); + assert_eq!(candidate.id.to_string(), "D50 III,2"); + let detail = hardware_volume_candidate_detail(&candidate); + assert!(detail.contains("-127.00–0.00 dB"), "{detail}"); + assert!(detail.contains("front_left"), "{detail}"); + assert!(detail.starts_with('★'), "{detail}"); + } + + #[test] + fn qml_uses_the_shared_closed_select_for_mixer_identity() { + let audio_qml = include_str!("../qml/settings/AudioSettings.qml"); + let select_qml = include_str!("../qml/controls/QbzSelect.qml"); + assert!(audio_qml.contains("alsaHardwareVolumeOptions")); + assert!(audio_qml.contains("QbzSelect")); + assert!(!audio_qml.contains("TextInput")); + assert!(select_qml.contains("function openPopup")); + assert!(select_qml.contains("function optDetail")); + assert!(select_qml.contains("selectRoot.optDetail(optRow.index)")); + } + #[test] fn only_alsa_direct_without_a_hardware_mixer_requires_unity_volume() { let mut audio = qbz_audio::settings::AudioSettings::default(); From c3556fe3ec699fee915c5bc29d6533fde8dd1feb Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:14:39 -0600 Subject: [PATCH 3/3] feat(qbzd): expose ALSA hardware volume controls Carry hardware-volume capability, selection, diagnostics, and status through the daemon API, CLI, and TUI while preserving fail-closed behavior on unsupported devices. cx --- crates/qbzd/src/api/playback.rs | 1 + crates/qbzd/src/api/status.rs | 16 + crates/qbzd/src/cli/settings.rs | 561 +++++++++++++++++++++--- crates/qbzd/src/cli/status.rs | 22 +- crates/qbzd/src/daemon.rs | 103 ++++- crates/qbzd/src/main.rs | 3 + crates/qbzd/src/tui/app.rs | 326 +++++++++++--- crates/qbzd/src/tui/screens/audio.rs | 623 ++++++++++++++++++++++++--- crates/qbzd/src/tui/strings.rs | 1 + 9 files changed, 1490 insertions(+), 166 deletions(-) diff --git a/crates/qbzd/src/api/playback.rs b/crates/qbzd/src/api/playback.rs index 348414a70..ce5a5f9d7 100644 --- a/crates/qbzd/src/api/playback.rs +++ b/crates/qbzd/src/api/playback.rs @@ -503,6 +503,7 @@ mod tests { duration: 200, track_id: 42, volume, + hardware_volume_active: false, sample_rate: None, bit_depth: None, shuffle: Some(false), diff --git a/crates/qbzd/src/api/status.rs b/crates/qbzd/src/api/status.rs index da9cc3c39..839e55105 100644 --- a/crates/qbzd/src/api/status.rs +++ b/crates/qbzd/src/api/status.rs @@ -45,6 +45,9 @@ pub struct AudioStatus { pub bit_perfect: Option, pub sample_rate: Option, pub bit_depth: Option, + pub hardware_volume_enabled: bool, + pub hardware_volume_active: bool, + pub hardware_volume_control: Option, } #[derive(Debug, Clone, Serialize)] @@ -152,6 +155,13 @@ fn assemble_live(state: &super::ApiState) -> StatusDoc { let settings = state.audio.get_settings().ok(); let backend = settings.as_ref().and_then(|s| backend_label(s.backend_type)); let configured_device = settings.as_ref().and_then(|s| s.output_device.clone()); + let hardware_volume_enabled = settings + .as_ref() + .is_some_and(|settings| settings.alsa_hardware_volume); + let hardware_volume_control = settings + .as_ref() + .and_then(|settings| settings.selected_alsa_hardware_volume_control()) + .map(|control| control.to_string()); let device_present = match &configured_device { None => true, // system default is always "present" Some(dev) => device_open || device_is_present(state, dev), @@ -193,6 +203,9 @@ fn assemble_live(state: &super::ApiState) -> StatusDoc { bit_perfect: bitperfect_label(ev.bit_perfect_mode), sample_rate: ev.sample_rate, bit_depth: ev.bit_depth, + hardware_volume_enabled, + hardware_volume_active: ev.hardware_volume_active, + hardware_volume_control, }, playback: PlaybackStatus { state: pstate.to_string(), @@ -307,6 +320,9 @@ mod tests { bit_perfect: None, sample_rate: None, bit_depth: None, + hardware_volume_enabled: false, + hardware_volume_active: false, + hardware_volume_control: None, }, playback: PlaybackStatus { state: "stopped".into(), diff --git a/crates/qbzd/src/cli/settings.rs b/crates/qbzd/src/cli/settings.rs index 331d2f1ce..2a2d6e56f 100644 --- a/crates/qbzd/src/cli/settings.rs +++ b/crates/qbzd/src/cli/settings.rs @@ -32,6 +32,10 @@ use qbz_app::settings::bundle::{ }; use qbz_app::settings::daemon_prefs; use qbz_app::settings::playback::{AutoplayMode, PlaybackPreferencesStore}; +use qbz_audio::alsa_hardware_volume::{ + AlsaMixerControlId, HardwareVolumeDecision, HardwareVolumeProbe, + HardwareVolumeUnsupportedReason, +}; use qbz_audio::settings::AudioSettingsStore; use qbz_audio::{AlsaPlugin, AudioBackendType, BackendManager}; @@ -64,6 +68,7 @@ const KEY_TABLE: &[(&str, ApplyClass)] = &[ ("audio.device", ApplyClass::Reinit), ("audio.alsa_plugin", ApplyClass::Reinit), ("audio.alsa_hardware_volume", ApplyClass::Reinit), + ("audio.alsa_hardware_volume_control", ApplyClass::Reinit), ("audio.exclusive_mode", ApplyClass::Reinit), ("audio.dac_passthrough", ApplyClass::Reinit), ("audio.skip_sink_switch", ApplyClass::Reinit), @@ -181,6 +186,42 @@ fn render_alsa_plugin(v: Option) -> String { } } +/// Canonical simple-mixer identity printed by `settings mixer-controls`. +/// Split at the final comma so names containing commas remain round-trippable. +fn parse_alsa_mixer_control(v: &str) -> Result, String> { + let trimmed = v.trim(); + if trimmed.eq_ignore_ascii_case("none") || trimmed.is_empty() { + return Ok(None); + } + let (name, index) = trimmed.rsplit_once(',').ok_or_else(|| { + format!( + "invalid ALSA mixer control '{trimmed}' — expected NAME,INDEX from `qbzd settings mixer-controls`" + ) + })?; + let name = name.trim(); + if name.is_empty() { + return Err("invalid ALSA mixer control — NAME cannot be empty".to_string()); + } + let index = index.trim().parse::().map_err(|_| { + format!("invalid ALSA mixer control '{trimmed}' — INDEX must be an unsigned integer") + })?; + Ok(Some(AlsaMixerControlId { + name: name.to_string(), + index, + })) +} + +fn render_alsa_mixer_control(audio: &qbz_audio::settings::AudioSettings) -> String { + let selected = audio + .output_device + .as_deref() + .and_then(|device| qbz_audio::alsa_hardware_volume::stable_alsa_route_key(device).ok()) + .and_then(|route| audio.alsa_hardware_volume_controls.get(&route)); + selected + .map(ToString::to_string) + .unwrap_or_else(|| "none".to_string()) +} + /// `audio.device`: empty / "system" / "default" clears to `None` (system /// default); anything else is the device id verbatim (`hw:CARD=D30,DEV=0`, /// a PipeWire node name, ...) — free text, not validated against a live @@ -188,7 +229,9 @@ fn render_alsa_plugin(v: Option) -> String { /// must work with no device attached to check against). fn parse_output_device(v: &str) -> Option { let trimmed = v.trim(); - if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("system") || trimmed.eq_ignore_ascii_case("default") + if trimmed.is_empty() + || trimmed.eq_ignore_ascii_case("system") + || trimmed.eq_ignore_ascii_case("default") { None } else { @@ -224,13 +267,13 @@ fn parse_opt_u32(v: &str) -> Result, String> { if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("none") { return Ok(None); } - trimmed - .parse::() - .map(Some) - .map_err(|_| format!("invalid sample rate '{trimmed}' — expected a Hz integer (e.g. 192000) or none")) + trimmed.parse::().map(Some).map_err(|_| { + format!("invalid sample rate '{trimmed}' — expected a Hz integer (e.g. 192000) or none") + }) } fn render_opt_u32(v: Option) -> String { - v.map(|r| r.to_string()).unwrap_or_else(|| "none".to_string()) + v.map(|r| r.to_string()) + .unwrap_or_else(|| "none".to_string()) } fn parse_dsd_mode(v: &str) -> Result { @@ -329,6 +372,7 @@ fn read_all(roots: &ProfileRoots) -> Result, String> "audio.device" => render_opt_string(&audio.output_device), "audio.alsa_plugin" => render_alsa_plugin(audio.alsa_plugin), "audio.alsa_hardware_volume" => render_bool(audio.alsa_hardware_volume), + "audio.alsa_hardware_volume_control" => render_alsa_mixer_control(&audio), "audio.exclusive_mode" => render_bool(audio.exclusive_mode), "audio.dac_passthrough" => render_bool(audio.dac_passthrough), "audio.skip_sink_switch" => render_bool(audio.skip_sink_switch), @@ -391,19 +435,184 @@ impl std::fmt::Display for SetError { } } +fn hardware_volume_probe_for( + audio: &qbz_audio::settings::AudioSettings, +) -> Result<(String, HardwareVolumeProbe, HardwareVolumeDecision), SetError> { + if !qbz_audio::alsa_direct::uses_alsa_direct_route(audio) { + return Err(SetError::Usage( + "hardware volume requires audio.backend=alsa, a direct ALSA device, and alsa_plugin=hw or plughw" + .to_string(), + )); + } + let device_id = audio.output_device.clone().ok_or_else(|| { + SetError::Usage("hardware volume requires an explicitly selected ALSA device".to_string()) + })?; + let probe = qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls(&device_id); + let decision = qbz_audio::alsa_hardware_volume::decide_hardware_volume( + &probe, + &audio.alsa_hardware_volume_controls, + ); + Ok((device_id, probe, decision)) +} + +fn unsupported_hardware_volume_message(reason: &HardwareVolumeUnsupportedReason) -> String { + match reason { + HardwareVolumeUnsupportedReason::Probe(error) => error.message.clone(), + HardwareVolumeUnsupportedReason::NoValidControls => { + "the selected ALSA route exposes no compatible playback-volume controls".to_string() + } + HardwareVolumeUnsupportedReason::PersistedSelectionStale(control) => format!( + "saved ALSA mixer control '{control}' is no longer available; run `qbzd settings mixer-controls`" + ), + } +} + +fn valid_control_list(probe: &HardwareVolumeProbe) -> String { + let controls = probe + .valid_candidates() + .map(|candidate| candidate.id.to_string()) + .collect::>(); + if controls.is_empty() { + "none".to_string() + } else { + controls.join(", ") + } +} + +fn write_alsa_hardware_volume_enabled(roots: &ProfileRoots, enabled: bool) -> Result<(), SetError> { + let store = open_audio(roots).map_err(SetError::Io)?; + if !enabled { + return store.set_alsa_hardware_volume(false).map_err(SetError::Io); + } + let audio = store.get_settings().map_err(SetError::Io)?; + let (device_id, _probe, decision) = match hardware_volume_probe_for(&audio) { + Ok(result) => result, + Err(error) => { + store + .set_alsa_hardware_volume(false) + .map_err(SetError::Io)?; + return Err(error); + } + }; + match decision { + HardwareVolumeDecision::Selected { selection } => { + if let Err(error) = qbz_audio::alsa_hardware_volume::activate_hardware_volume_control( + &device_id, + &selection.control, + ) { + store + .set_alsa_hardware_volume(false) + .map_err(SetError::Io)?; + return Err(SetError::Io(error)); + } + store + .enable_alsa_hardware_volume(selection.route_key, selection.control) + .map_err(SetError::Io) + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + store + .set_alsa_hardware_volume(false) + .map_err(SetError::Io)?; + Err(SetError::Usage(format!( + "multiple ALSA playback-volume controls require an explicit choice ({reason:?})\n → list: qbzd settings mixer-controls\n → choose: qbzd settings set audio.alsa_hardware_volume_control NAME,INDEX" + ))) + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + store + .set_alsa_hardware_volume(false) + .map_err(SetError::Io)?; + Err(SetError::Io(unsupported_hardware_volume_message(&reason))) + } + } +} + +fn write_alsa_hardware_volume_control(roots: &ProfileRoots, raw: &str) -> Result<(), SetError> { + let requested = parse_alsa_mixer_control(raw).map_err(SetError::Usage)?; + let store = open_audio(roots).map_err(SetError::Io)?; + let audio = store.get_settings().map_err(SetError::Io)?; + if requested.is_none() && !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + // The canonical default (`none`) must round-trip on a system-default + // route. There is no route-scoped selection to clear in this case. + store + .set_alsa_hardware_volume(false) + .map_err(SetError::Io)?; + return Ok(()); + } + if !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + return Err(SetError::Usage( + "an ALSA mixer control can only be selected for the current ALSA Direct route" + .to_string(), + )); + } + let device_id = audio.output_device.clone().ok_or_else(|| { + SetError::Usage( + "select an ALSA Direct device before choosing its mixer control".to_string(), + ) + })?; + let route = + qbz_audio::alsa_hardware_volume::stable_alsa_route_key(&device_id).map_err(SetError::Io)?; + let Some(requested) = requested else { + // Never leave an enabled preference without its exact identity. + store + .set_alsa_hardware_volume(false) + .map_err(SetError::Io)?; + return store + .clear_alsa_hardware_volume_control(&route) + .map_err(SetError::Io); + }; + + let probe = qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls(&device_id); + if let Some(error) = &probe.error { + return Err(SetError::Io(error.message.clone())); + } + if probe.route_key.as_ref() != Some(&route) { + return Err(SetError::Io( + "the ALSA route identity changed during mixer validation".to_string(), + )); + } + let candidate = probe + .valid_candidates() + .find(|candidate| candidate.id == requested) + .cloned() + .ok_or_else(|| { + SetError::Usage(format!( + "ALSA mixer control '{requested}' was not enumerated as valid for this route\n → valid controls: {}", + valid_control_list(&probe) + )) + })?; + qbz_audio::alsa_hardware_volume::activate_hardware_volume_control(&device_id, &candidate.id) + .map_err(SetError::Io)?; + if audio.alsa_hardware_volume { + store + .enable_alsa_hardware_volume(route, candidate.id) + .map_err(SetError::Io) + } else { + store + .set_alsa_hardware_volume_control(route, candidate.id) + .map_err(SetError::Io) + } +} + /// Validate + write ONE canonical key. Returns its [`ApplyClass`] on success /// (the CLI's own success-line hint — see module doc). `pub(crate)` so the T13 /// setup TUI persists every screen through this SAME validated writer (03 §6 — /// the TUI adds no persistence of its own). Every arm parses (`Usage` on /// failure) BEFORE it opens/writes a store (`Io` on failure) — see [`SetError`]. -pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { +pub(crate) fn write_one( + roots: &ProfileRoots, + key: &str, + raw: &str, +) -> Result { let Some(class) = classify(key) else { return Err(SetError::Usage(unknown_key_error(key))); }; match key { "audio.backend" => { let v = parse_backend(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_backend_type(v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_backend_type(v) + .map_err(SetError::Io)? } "audio.device" => { let v = parse_output_device(raw); @@ -414,22 +623,29 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { let v = parse_alsa_plugin(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_alsa_plugin(v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_alsa_plugin(v) + .map_err(SetError::Io)? } "audio.alsa_hardware_volume" => { let v = parse_bool(raw).map_err(SetError::Usage)?; - open_audio(roots) - .map_err(SetError::Io)? - .set_alsa_hardware_volume(v) - .map_err(SetError::Io)? + write_alsa_hardware_volume_enabled(roots, v)? } + "audio.alsa_hardware_volume_control" => write_alsa_hardware_volume_control(roots, raw)?, "audio.exclusive_mode" => { let v = parse_bool(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_exclusive_mode(v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_exclusive_mode(v) + .map_err(SetError::Io)? } "audio.dac_passthrough" => { let v = parse_bool(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_dac_passthrough(v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_dac_passthrough(v) + .map_err(SetError::Io)? } "audio.skip_sink_switch" => { let v = parse_bool(raw).map_err(SetError::Usage)?; @@ -440,7 +656,10 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { let v = parse_dsd_mode(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_dsd_mode(&v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_dsd_mode(&v) + .map_err(SetError::Io)? } "audio.device_max_sample_rate" => { let v = parse_opt_u32(raw).map_err(SetError::Usage)?; @@ -465,7 +684,10 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { let v = parse_bool(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_streaming_only(v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_streaming_only(v) + .map_err(SetError::Io)? } "audio.limit_quality_to_device" => { let v = parse_bool(raw).map_err(SetError::Usage)?; @@ -490,7 +712,10 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { let v = parse_bool(raw).map_err(SetError::Usage)?; - open_audio(roots).map_err(SetError::Io)?.set_gapless_enabled(v).map_err(SetError::Io)? + open_audio(roots) + .map_err(SetError::Io)? + .set_gapless_enabled(v) + .map_err(SetError::Io)? } "audio.normalization_enabled" => { let v = parse_bool(raw).map_err(SetError::Usage)?; @@ -541,7 +766,10 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { let v = parse_autoplay(raw).map_err(SetError::Usage)?; - open_playback(roots).map_err(SetError::Io)?.set_autoplay_mode(v).map_err(SetError::Io)? + open_playback(roots) + .map_err(SetError::Io)? + .set_autoplay_mode(v) + .map_err(SetError::Io)? } "playback.persist_session" => { let v = parse_bool(raw).map_err(SetError::Usage)?; @@ -564,9 +792,10 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result { - qconnect_kv::persist_device_name_at(&qconnect_db(roots), parse_output_device(raw).as_deref()) - } + "qconnect.device_name" => qconnect_kv::persist_device_name_at( + &qconnect_db(roots), + parse_output_device(raw).as_deref(), + ), "qconnect.startup_mode" => { let mode = match raw.to_ascii_lowercase().as_str() { "on" => qconnect_app::QconnectStartupMode::On, @@ -643,7 +872,10 @@ pub fn show(json: bool, roots: &ProfileRoots) -> i32 { for (k, v) in &values { map.insert((*k).to_string(), serde_json::Value::String(v.clone())); } - println!("{}", serde_json::to_string(&serde_json::Value::Object(map)).unwrap_or_default()); + println!( + "{}", + serde_json::to_string(&serde_json::Value::Object(map)).unwrap_or_default() + ); } else { let width = values.iter().map(|(k, _)| k.len()).max().unwrap_or(0); for (k, v) in &values { @@ -653,6 +885,99 @@ pub fn show(json: bool, roots: &ProfileRoots) -> i32 { 0 } +/// `qbzd settings mixer-controls [--json]` — read-only enumeration for the +/// currently selected ALSA Direct route. The printed `id`/first column is the +/// exact value accepted by `audio.alsa_hardware_volume_control`. +pub fn mixer_controls(json: bool, roots: &ProfileRoots) -> i32 { + let audio = match open_audio(roots).and_then(|store| store.get_settings()) { + Ok(audio) => audio, + Err(error) => { + eprintln!("error: {error}"); + return 1; + } + }; + let (device_id, probe, _) = match hardware_volume_probe_for(&audio) { + Ok(result) => result, + Err(error) => { + eprintln!("error: {error}"); + return match error { + SetError::Usage(_) => 2, + SetError::Io(_) => 1, + }; + } + }; + if let Some(error) = &probe.error { + eprintln!("error: {}", error.message); + return 1; + } + let candidates = probe.valid_candidates().collect::>(); + if json { + let controls = candidates + .iter() + .map(|candidate| { + serde_json::json!({ + "id": candidate.id.to_string(), + "name": candidate.id.name, + "index": candidate.id.index, + "channels": candidate.channels, + "raw_range": candidate.raw_range, + "db_range": candidate.db_range, + "recommended": candidate.recommended, + }) + }) + .collect::>(); + println!( + "{}", + serde_json::json!({ + "device": device_id, + "ctl": probe.ctl_name, + "route_key": probe.route_key.as_ref().map(ToString::to_string), + "controls": controls, + }) + ); + return 0; + } + + println!("ALSA route: {device_id}"); + println!( + "Stable key: {}", + probe + .route_key + .as_ref() + .map(ToString::to_string) + .unwrap_or_else(|| "unavailable".to_string()) + ); + if candidates.is_empty() { + println!("No compatible playback-volume controls."); + return 1; + } + for candidate in candidates { + let recommended = if candidate.recommended { + " [recommended]" + } else { + "" + }; + println!("{}{}", candidate.id, recommended); + let range = candidate + .db_range + .map(|range| { + format!( + "{:.2}..{:.2} dB", + range.min as f64 / 100.0, + range.max as f64 / 100.0 + ) + }) + .or_else(|| { + candidate + .raw_range + .map(|range| format!("raw {}..{}", range.min, range.max)) + }) + .unwrap_or_else(|| "range unavailable".to_string()); + println!(" {range} · {}", candidate.channels.join(", ")); + } + 0 +} + /// `qbzd settings set ` (⬇). Unknown key → exit 2 listing valid /// keys; invalid value for a known key → exit 2 naming the valid values; /// the key/value classified and parsed fine but the backing store failed to @@ -692,7 +1017,9 @@ pub fn qconnect_enable(roots: &ProfileRoots) -> i32 { let db = qconnect_db(roots); qconnect_kv::save_startup_mode_at(&db, qconnect_app::QconnectStartupMode::On); nudge(roots); - let name = qconnect_kv::resolve_qconnect_friendly_name(qconnect_kv::load_device_name_at(&db).as_deref()); + let name = qconnect_kv::resolve_qconnect_friendly_name( + qconnect_kv::load_device_name_at(&db).as_deref(), + ); println!("qconnect enabled — device \"{name}\" will appear in the Qobuz app once logged in"); 0 } @@ -715,7 +1042,8 @@ pub fn qconnect_name(roots: &ProfileRoots, name: &str) -> i32 { let db = qconnect_db(roots); qconnect_kv::persist_device_name_at(&db, parse_output_device(name).as_deref()); nudge(roots); - let effective = qconnect_kv::resolve_qconnect_friendly_name(parse_output_device(name).as_deref()); + let effective = + qconnect_kv::resolve_qconnect_friendly_name(parse_output_device(name).as_deref()); println!("qconnect device name set to \"{effective}\" — applies on the next connection"); 0 } @@ -727,7 +1055,10 @@ pub fn config_path(roots: &ProfileRoots) -> i32 { println!("config : {}", roots.config.display()); println!("data : {}", roots.data.display()); println!("cache : {}", roots.cache.display()); - println!("cred : {}", roots.config.join(".qbz-oauth-token").display()); + println!( + "cred : {}", + roots.config.join(".qbz-oauth-token").display() + ); println!("unit : {}", unit_path().display()); 0 } @@ -756,14 +1087,24 @@ pub fn config_show(json: bool, roots: &ProfileRoots) -> i32 { } let present = present_keys(&path); let line = |label: &str, dotted: &str, value: String| { - let marker = if present.contains(dotted) { "" } else { " (default)" }; + let marker = if present.contains(dotted) { + "" + } else { + " (default)" + }; println!("{label:<24}= {value}{marker}"); }; - line("config_version", "config_version", cfg.config_version.to_string()); + line( + "config_version", + "config_version", + cfg.config_version.to_string(), + ); line( "data_root", "data_root", - cfg.data_root.clone().unwrap_or_else(|| "(auto)".to_string()), + cfg.data_root + .clone() + .unwrap_or_else(|| "(auto)".to_string()), ); line("server.bind", "server.bind", cfg.server.bind.clone()); line("server.port", "server.port", cfg.server.port.to_string()); @@ -776,7 +1117,11 @@ pub fn config_show(json: bool, roots: &ProfileRoots) -> i32 { }, ); line("log.level", "log.level", cfg.log.level.clone()); - line("mpris.enabled", "mpris.enabled", cfg.mpris.enabled.to_string()); + line( + "mpris.enabled", + "mpris.enabled", + cfg.mpris.enabled.to_string(), + ); 0 } @@ -916,7 +1261,10 @@ pub async fn import( // Steps 2–4: plan. let mut plan = match bundle::plan(&bundle, &target, &opts, &live) { Ok(p) => p, - Err(bundle::BundleError::VersionTooNew { bundle: b, supported }) => { + Err(bundle::BundleError::VersionTooNew { + bundle: b, + supported, + }) => { eprintln!("{}", crate::cli::copy::bundle_version_too_new(b, supported)); return 1; } @@ -949,8 +1297,10 @@ pub async fn import( match crate::login::validate_token(&token).await { Ok(session) => { validated_uid = Some(session.user_id); - let mut note = - format!("Qobuz token validated — logged in as user {}", session.user_id); + let mut note = format!( + "Qobuz token validated — logged in as user {}", + session.user_id + ); if let Some(bid) = plan.bundle_user_id { if bid != session.user_id { note.push_str(&format!( @@ -987,8 +1337,7 @@ pub async fn import( // Step 7: reload-nudge a running daemon. Three states (04 §5.3 step 7): // reloaded / not running (fine) / up-but-refused (exit 1, restart hint). let outcome = nudge_outcome(roots); - let (done_line, stderr_msg, exit) = - reload_disposition(outcome, plan.routing_critical_changed); + let (done_line, stderr_msg, exit) = reload_disposition(outcome, plan.routing_critical_changed); print_buckets(&plan, &bundle, auth_note.as_deref(), Some(&done_line)); if let Some(msg) = stderr_msg { @@ -1037,7 +1386,11 @@ fn reload_disposition( fn build_live_system(bundle: &Bundle) -> LiveSystem { let backends: Vec = BackendManager::available_backends() .into_iter() - .filter_map(|b| serde_json::to_value(b).ok().and_then(|v| v.as_str().map(str::to_string))) + .filter_map(|b| { + serde_json::to_value(b) + .ok() + .and_then(|v| v.as_str().map(str::to_string)) + }) .collect(); let wanted: Option = bundle @@ -1147,7 +1500,11 @@ fn print_buckets( // Shared-device-name advisory: only for a desktop-sourced bundle (§2.4/§5.4). if bundle.source.profile == "desktop" { - if let Some(dn) = plan.applied.iter().find(|l| l.key == "qconnect.device_name") { + if let Some(dn) = plan + .applied + .iter() + .find(|l| l.key == "qconnect.device_name") + { println!("\nadvisory"); println!( " qconnect.device_name \"{}\" is also the exporting desktop's Connect name — two nodes with", @@ -1207,9 +1564,15 @@ mod tests { let err = write_one(&roots, "audio.bogus", "x").unwrap_err(); // 02 §1.3: an unknown key is a USAGE mistake (exit 2), never Io. assert!(matches!(err, SetError::Usage(_)), "{err:?}"); - assert!(err.message().contains("unknown setting key 'audio.bogus'"), "{err}"); + assert!( + err.message().contains("unknown setting key 'audio.bogus'"), + "{err}" + ); for (k, _) in KEY_TABLE { - assert!(err.message().contains(k), "missing '{k}' from the listed keys:\n{err}"); + assert!( + err.message().contains(k), + "missing '{k}' from the listed keys:\n{err}" + ); } cleanup(&roots); } @@ -1265,7 +1628,10 @@ mod tests { let err = write_one(&roots, "hooks.script", "relative.sh").unwrap_err(); assert!(matches!(err, SetError::Usage(_)), "{err:?}"); write_one(&roots, "hooks.script", "/opt/hook.sh").expect("absolute path writes"); - assert_eq!(daemon_prefs::load_at(&roots.data).hook_script, "/opt/hook.sh"); + assert_eq!( + daemon_prefs::load_at(&roots.data).hook_script, + "/opt/hook.sh" + ); write_one(&roots, "hooks.script", "").expect("empty clears"); assert_eq!(daemon_prefs::load_at(&roots.data).hook_script, ""); cleanup(&roots); @@ -1279,7 +1645,11 @@ mod tests { // round-trip against temp on-disk stores, not just "same key names"). let roots = scratch_roots("roundtrip"); let values = read_all(&roots).expect("read_all opens fresh stores with defaults"); - assert_eq!(values.len(), KEY_TABLE.len(), "read_all must cover every canonical key"); + assert_eq!( + values.len(), + KEY_TABLE.len(), + "read_all must cover every canonical key" + ); for (key, value) in &values { // The one documented exception (03-setup-tui.md §3.3.2): a fresh // (or desktop-imported) store's `quality_fallback_behavior` @@ -1290,8 +1660,9 @@ mod tests { if *key == "audio.quality_fallback_behavior" && value == "ask" { continue; } - write_one(&roots, key, value) - .unwrap_or_else(|e| panic!("show's own value for '{key}' ('{value}') was rejected by set: {e}")); + write_one(&roots, key, value).unwrap_or_else(|e| { + panic!("show's own value for '{key}' ('{value}') was rejected by set: {e}") + }); } cleanup(&roots); } @@ -1306,7 +1677,8 @@ mod tests { write_one(&roots, "qconnect.device_name", "Kitchen").expect("set device name"); write_one(&roots, "qconnect.startup_mode", "on").expect("set startup mode"); - let values: std::collections::HashMap<_, _> = read_all(&roots).unwrap().into_iter().collect(); + let values: std::collections::HashMap<_, _> = + read_all(&roots).unwrap().into_iter().collect(); assert_eq!(values["audio.backend"], "alsa"); assert_eq!(values["audio.exclusive_mode"], "true"); assert_eq!(values["playback.quality"], "cd"); @@ -1321,7 +1693,8 @@ mod tests { let roots = scratch_roots("qc-clear"); write_one(&roots, "qconnect.device_name", "Studio").expect("set name"); write_one(&roots, "qconnect.device_name", "").expect("clear name"); - let values: std::collections::HashMap<_, _> = read_all(&roots).unwrap().into_iter().collect(); + let values: std::collections::HashMap<_, _> = + read_all(&roots).unwrap().into_iter().collect(); assert_eq!(values["qconnect.device_name"], "system"); cleanup(&roots); } @@ -1338,21 +1711,85 @@ mod tests { assert!(parse_bool("maybe").is_err()); } + #[test] + fn mixer_control_parser_round_trips_exact_name_and_index() { + let expected = AlsaMixerControlId { + name: "DAC, Playback".to_string(), + index: 7, + }; + assert_eq!( + parse_alsa_mixer_control("DAC, Playback,7"), + Ok(Some(expected)) + ); + assert_eq!(parse_alsa_mixer_control("none"), Ok(None)); + assert_eq!(parse_alsa_mixer_control(""), Ok(None)); + assert!(parse_alsa_mixer_control("Master").is_err()); + assert!(parse_alsa_mixer_control("Master,-1").is_err()); + assert!(parse_alsa_mixer_control(",0").is_err()); + } + + #[test] + fn mixer_control_change_is_routing_critical() { + assert_eq!( + classify("audio.alsa_hardware_volume_control"), + Some(ApplyClass::Reinit) + ); + } + + #[test] + fn hardware_volume_enable_outside_direct_fails_closed() { + let roots = scratch_roots("hardware-volume-fail-closed"); + let store = AudioSettingsStore::new_at(&roots.data).expect("open audio store"); + store + .set_alsa_hardware_volume(true) + .expect("simulate stale enabled preference"); + + let error = write_one(&roots, "audio.alsa_hardware_volume", "true") + .expect_err("system-default output is not ALSA Direct"); + assert!(matches!(error, SetError::Usage(_)), "{error:?}"); + assert!( + !store.get_settings().unwrap().alsa_hardware_volume, + "a refused enable must not leave the preference active" + ); + cleanup(&roots); + } + #[test] fn parse_backend_accepts_the_concrete_backends_only() { assert_eq!(parse_backend("alsa"), Ok(Some(AudioBackendType::Alsa))); - assert_eq!(parse_backend("PipeWire"), Ok(Some(AudioBackendType::PipeWire))); - assert_eq!(parse_backend("system"), Ok(Some(AudioBackendType::SystemDefault))); - assert_eq!(parse_backend("wasapi"), Ok(Some(AudioBackendType::WasapiExclusive))); - assert_eq!(render_backend(Some(AudioBackendType::WasapiExclusive)), "wasapi"); - assert!(parse_backend("auto").is_err(), "Auto is omitted in v1 (03-setup-tui.md §3.2.1)"); + assert_eq!( + parse_backend("PipeWire"), + Ok(Some(AudioBackendType::PipeWire)) + ); + assert_eq!( + parse_backend("system"), + Ok(Some(AudioBackendType::SystemDefault)) + ); + assert_eq!( + parse_backend("wasapi"), + Ok(Some(AudioBackendType::WasapiExclusive)) + ); + assert_eq!( + render_backend(Some(AudioBackendType::WasapiExclusive)), + "wasapi" + ); + assert!( + parse_backend("auto").is_err(), + "Auto is omitted in v1 (03-setup-tui.md §3.2.1)" + ); assert!(parse_backend("bogus").is_err()); } #[test] fn parse_quality_fallback_behavior_rejects_ask() { - assert_eq!(parse_quality_fallback_behavior("always_fallback"), Ok("always_fallback".into())); - assert_eq!(parse_quality_fallback_behavior("always_skip"), Ok("always_skip".into())); + assert_eq!( + parse_quality_fallback_behavior("always_fallback"), + Ok("always_fallback".into()) + ); + assert_eq!( + parse_quality_fallback_behavior("always_skip"), + Ok("always_skip".into()) + ); let err = parse_quality_fallback_behavior("ask").unwrap_err(); assert!(err.contains("needs a UI"), "{err}"); } @@ -1362,14 +1799,26 @@ mod tests { for ok in ["mp3", "cd", "hires", "hires_plus"] { assert!(parse_streaming_quality(ok).is_ok(), "{ok}"); } - assert!(parse_streaming_quality("hires192").is_err(), "not a real key — see report"); + assert!( + parse_streaming_quality("hires192").is_err(), + "not a real key — see report" + ); } #[test] fn parse_autoplay_matches_the_playback_preferences_wire_values() { - assert_eq!(parse_autoplay("continue").unwrap(), AutoplayMode::ContinueWithinSource); - assert_eq!(parse_autoplay("track_only").unwrap(), AutoplayMode::PlayTrackOnly); - assert_eq!(parse_autoplay("infinite").unwrap(), AutoplayMode::InfiniteRadio); + assert_eq!( + parse_autoplay("continue").unwrap(), + AutoplayMode::ContinueWithinSource + ); + assert_eq!( + parse_autoplay("track_only").unwrap(), + AutoplayMode::PlayTrackOnly + ); + assert_eq!( + parse_autoplay("infinite").unwrap(), + AutoplayMode::InfiniteRadio + ); assert!(parse_autoplay("bogus").is_err()); } diff --git a/crates/qbzd/src/cli/status.rs b/crates/qbzd/src/cli/status.rs index 71c6bcf41..d3c713b47 100644 --- a/crates/qbzd/src/cli/status.rs +++ b/crates/qbzd/src/cli/status.rs @@ -159,6 +159,23 @@ fn render_audio(p: &Value) -> String { if let (Some(sr), Some(bd)) = (sr, bd) { parts.push(format!("{sr} Hz / {bd}-bit")); } + if p.pointer("/audio/hardware_volume_enabled") + .and_then(|v| v.as_bool()) + .unwrap_or(false) + { + let active = p + .pointer("/audio/hardware_volume_active") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let control = p + .pointer("/audio/hardware_volume_control") + .and_then(|v| v.as_str()) + .unwrap_or("unknown control"); + parts.push(format!( + "hardware volume: {control} ({})", + if active { "active" } else { "inactive" } + )); + } parts.join(" · ") } @@ -276,7 +293,9 @@ mod tests { "auth": {"state": "logged_in", "user_id": 1234567, "subscription": "studio"}, "audio": {"backend": "alsa", "configured_device": "hw:CARD=D30,DEV=0", "device_present": true, "device_open": true, - "bit_perfect": "DirectHardware", "sample_rate": 192000, "bit_depth": 24}, + "bit_perfect": "DirectHardware", "sample_rate": 192000, "bit_depth": 24, + "hardware_volume_enabled": true, "hardware_volume_active": true, + "hardware_volume_control": "D50 III,0"}, "playback": {"state": "playing", "track_id": 176544871, "title": "Spain", "artist": "Chick Corea", "position": 192, "duration": 581, "volume": 0.8, "muted": false, "queue_len": 14}, @@ -317,6 +336,7 @@ mod tests { assert!(block.contains("qbzd 2.1.0 · api v1 · up 3d 0h · 127.0.0.1:8182"), "{block}"); assert!(block.contains("auth : logged in (user 1234567, studio)"), "{block}"); assert!(block.contains("alsa hw:CARD=D30,DEV=0 · present · bit-perfect: DirectHardware · 192000 Hz / 24-bit"), "{block}"); + assert!(block.contains("hardware volume: D50 III,0 (active)"), "{block}"); assert!(block.contains("playback : playing · \"Spain\" — Chick Corea · 3:12 / 9:41 · vol 80% · queue 14"), "{block}"); assert!(block.contains("qconnect : connected · session active · name \"QBZ (kitchen-pi)\""), "{block}"); assert!(block.contains("last error: none"), "{block}"); diff --git a/crates/qbzd/src/daemon.rs b/crates/qbzd/src/daemon.rs index 9c6c23400..ec66466ac 100644 --- a/crates/qbzd/src/daemon.rs +++ b/crates/qbzd/src/daemon.rs @@ -334,6 +334,79 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec) -> Re /// Steps 6-9 of §8.1: open the daemon-root stores, compose the runtime with the /// two NORMATIVE substitutions (`with_audio_settings` + `activate_at`), and /// restore the saved session per the §6.2 clearing taxonomy. +fn revalidate_alsa_hardware_volume( + store: &qbz_audio::settings::AudioSettingsStore, +) -> Result<(qbz_audio::settings::AudioSettings, Option), String> { + use qbz_audio::alsa_hardware_volume::{ + HardwareVolumeDecision, HardwareVolumeSelectionSource, HardwareVolumeUnsupportedReason, + }; + + let audio = store.get_settings()?; + if !audio.alsa_hardware_volume { + return Ok((audio, None)); + } + if !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + log::warn!( + "[ALSA HW Volume] enabled outside ALSA Direct; disabling without touching a mixer" + ); + store.set_alsa_hardware_volume(false)?; + return Ok((store.get_settings()?, None)); + } + let device_id = audio + .output_device + .as_deref() + .expect("ALSA Direct route has a device id"); + let probe = qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls(device_id); + let decision = qbz_audio::alsa_hardware_volume::decide_hardware_volume( + &probe, + &audio.alsa_hardware_volume_controls, + ); + match decision { + HardwareVolumeDecision::Selected { selection } => { + let Some(volume) = selection.candidate.current_volume else { + log::warn!( + "[ALSA HW Volume] selected control '{}' has no readable level; disabling", + selection.control + ); + store.set_alsa_hardware_volume(false)?; + return Ok((store.get_settings()?, None)); + }; + if selection.source != HardwareVolumeSelectionSource::Persisted { + // Backward-compatible migration for an old bare boolean. The + // probe is read-only; persist only an unequivocal identity. + store.set_alsa_hardware_volume_control( + selection.route_key, + selection.control.clone(), + )?; + } + log::info!( + "[ALSA HW Volume] validated '{}' at {:.0}%", + selection.control, + volume * 100.0 + ); + Ok((store.get_settings()?, Some(volume))) + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + log::warn!( + "[ALSA HW Volume] explicit mixer choice required ({reason:?}); disabling without writing" + ); + store.set_alsa_hardware_volume(false)?; + Ok((store.get_settings()?, None)) + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + let detail = match &reason { + HardwareVolumeUnsupportedReason::Probe(error) => error.message.clone(), + other => format!("{other:?}"), + }; + log::warn!( + "[ALSA HW Volume] saved mixer control unavailable ({detail}); disabling without fallback" + ); + store.set_alsa_hardware_volume(false)?; + Ok((store.get_settings()?, None)) + } + } +} + async fn boot(roots: &ProfileRoots, cfg: &QbzdConfig, warn_count: usize) -> Result { // 6.+7. stores + runtime composition. The two substitutions (01 §2.2): // - with_audio_settings, NOT AppRuntime::new (which hardcodes the @@ -342,7 +415,7 @@ async fn boot(roots: &ProfileRoots, cfg: &QbzdConfig, warn_count: usize) -> Resu // UserDataPaths — shell.rs:195-203). // Everything routes through the T2 daemon roots. let store = qbz_audio::settings::AudioSettingsStore::new_at(&roots.data)?; // settings.rs:263 - let settings = store.get_settings()?; + let (settings, hardware_volume) = revalidate_alsa_hardware_volume(&store)?; let (adapter, _rx) = DaemonAdapter::new(); let bus = adapter.sender(); let runtime = Arc::new(AppRuntime::with_audio_settings( @@ -351,6 +424,9 @@ async fn boot(roots: &ProfileRoots, cfg: &QbzdConfig, warn_count: usize) -> Resu settings, None, )); // shell.rs:64 + if let Some(volume) = hardware_volume { + runtime.core().player().seed_volume_state(volume); + } // Offline-tolerant (§8.1-8): a network failure here still leaves a locally // usable core; a missing DAC is likewise non-fatal (Player starts deviceless @@ -846,14 +922,19 @@ pub(crate) async fn reload(state: &crate::api::ApiState) { /// 87-94`, per-key classification `:877-967,1134-1290`; 03-setup-tui.md §4.3 /// lists the same 9 fields). pub(crate) fn reload_audio(state: &crate::api::ApiState) { - let fresh = match state.audio.get_settings() { - Ok(s) => s, + let (fresh, hardware_volume) = match revalidate_alsa_hardware_volume(&state.audio) { + Ok(result) => result, Err(e) => { log::warn!("[reload] could not re-read audio settings: {e}"); return; } }; let player = state.runtime.core().player(); + if let Some(volume) = hardware_volume { + // Seed before a routing-critical reinit so the new engine starts at + // the physical level just read, never at synthetic unity. + player.seed_volume_state(volume); + } if let Err(e) = player.reload_settings(fresh.clone()) { log::warn!("[reload] player.reload_settings failed: {e}"); } @@ -886,6 +967,7 @@ pub(crate) fn audio_routing_changed( || old.output_device != new.output_device || old.alsa_plugin != new.alsa_plugin || old.alsa_hardware_volume != new.alsa_hardware_volume + || old.alsa_hardware_volume_controls != new.alsa_hardware_volume_controls || old.exclusive_mode != new.exclusive_mode || old.dac_passthrough != new.dac_passthrough || old.skip_sink_switch != new.skip_sink_switch @@ -1194,6 +1276,21 @@ mod tests { hw_vol.alsa_hardware_volume = !base.alsa_hardware_volume; assert!(audio_routing_changed(&base, &hw_vol), "alsa_hardware_volume"); + let mut hw_control = base.clone(); + let route = serde_json::from_str("\"alsa-route-v1|card=card:D50|pcm=hw|DEV=0\"") + .expect("stable route key"); + hw_control.alsa_hardware_volume_controls.insert( + route, + qbz_audio::alsa_hardware_volume::AlsaMixerControlId { + name: "D50 III".to_string(), + index: 0, + }, + ); + assert!( + audio_routing_changed(&base, &hw_control), + "alsa_hardware_volume_controls" + ); + let mut excl = base.clone(); excl.exclusive_mode = !base.exclusive_mode; assert!(audio_routing_changed(&base, &excl), "exclusive_mode"); diff --git a/crates/qbzd/src/main.rs b/crates/qbzd/src/main.rs index a1ddd6d38..72a871b20 100644 --- a/crates/qbzd/src/main.rs +++ b/crates/qbzd/src/main.rs @@ -226,6 +226,8 @@ enum SettingsCmd { #[arg(long)] dry_run: bool, }, Show { #[arg(long)] json: bool }, + /// List canonical ALSA playback-volume controls for the selected route + MixerControls { #[arg(long)] json: bool }, Set { key: String, value: String }, } @@ -505,6 +507,7 @@ async fn main() { let roots = login_roots(); match cmd { SettingsCmd::Show { json } => cli::settings::show(json, &roots), + SettingsCmd::MixerControls { json } => cli::settings::mixer_controls(json, &roots), SettingsCmd::Set { key, value } => cli::settings::set(&roots, &key, &value), SettingsCmd::Export { file, diff --git a/crates/qbzd/src/tui/app.rs b/crates/qbzd/src/tui/app.rs index 20d631688..d835f0e3d 100644 --- a/crates/qbzd/src/tui/app.rs +++ b/crates/qbzd/src/tui/app.rs @@ -15,9 +15,12 @@ use std::sync::mpsc::{Receiver, Sender}; use serde_json::{json, Value}; use tokio::runtime::Handle; -use qbz_app::settings::bundle::{self, Bundle, ExportOptions, ExportSource, ImportOptions, LiveSystem, ProfilePaths}; +use qbz_app::settings::bundle::{ + self, Bundle, ExportOptions, ExportSource, ImportOptions, LiveSystem, ProfilePaths, +}; use qbz_app::settings::daemon_prefs; use qbz_app::settings::playback::PlaybackPreferencesStore; +use qbz_audio::alsa_hardware_volume::{HardwareVolumeDecision, HardwareVolumeProbe}; use qbz_audio::settings::{AudioSettings, AudioSettingsStore}; use qbz_audio::{AudioBackendType, AudioDevice, BackendManager, NegotiatedRate}; @@ -216,12 +219,16 @@ pub enum ScreenAction { Save, Back, RefreshDevices, + ProbeHardwareVolume, LoginBrowser, LoginToken(String), Logout, ImportPlan(String), ImportApply, - Export { dest: String, include_auth: bool }, + Export { + dest: String, + include_auth: bool, + }, // ---- HiFi Wizard (FB4) worker requests ---- /// Run the heavy audio-stack health probe (Check step). WizardProbeHealth, @@ -265,10 +272,23 @@ pub enum LoopCmd { pub enum Msg { Devices(Result, String>), - Saved { lines: Vec, status: Option, reachable: bool, success: bool }, + HardwareVolume { + device_id: String, + result: Result<(HardwareVolumeProbe, HardwareVolumeDecision), String>, + }, + Saved { + lines: Vec, + status: Option, + reachable: bool, + success: bool, + }, TokenLogin(Result<(String, Option), String>), ImportPlanned(Result, String>), - ImportApplied { lines: Vec, status: Option, reachable: bool }, + ImportApplied { + lines: Vec, + status: Option, + reachable: bool, + }, Exported(Result, String>), // ---- HiFi Wizard (FB4) worker results ---- WizardHealth(qbz_audio::AudioStackHealth), @@ -297,8 +317,13 @@ enum Active { enum Overlay { None, Help, - Result { title: String, lines: Vec }, - DirtyLeave { target: LeaveTarget }, + Result { + title: String, + lines: Vec, + }, + DirtyLeave { + target: LeaveTarget, + }, /// FB4: Esc mid-wizard — leaving discards the wizard's transient selections. ConfirmAbandon, } @@ -395,7 +420,10 @@ impl App { fn derive_auth(&self) -> AuthSnapshot { if self.reachable { if let Some(st) = &self.status { - let state = st.pointer("/auth/state").and_then(Value::as_str).unwrap_or(""); + let state = st + .pointer("/auth/state") + .and_then(Value::as_str) + .unwrap_or(""); if state == "logged_in" { let id = st.pointer("/auth/user_id").and_then(Value::as_u64); let plan = st @@ -447,7 +475,12 @@ impl App { .and_then(|s| s.get_preferences()) .unwrap_or_default(); let dp = daemon_prefs::load_at(&self.roots.data); - Active::Playback(PlaybackState::new(&dp.streaming_quality, dp.mpris_enabled, &audio, &playback)) + Active::Playback(PlaybackState::new( + &dp.streaming_quality, + dp.mpris_enabled, + &audio, + &playback, + )) } Screen::QConnect => { let db = self.roots.data.join("qconnect_settings.db"); @@ -479,7 +512,9 @@ impl App { return; } if self.active_is_dirty() { - self.overlay = Overlay::DirtyLeave { target: LeaveTarget::Section(target) }; + self.overlay = Overlay::DirtyLeave { + target: LeaveTarget::Section(target), + }; return; } self.enter_screen(target); @@ -490,7 +525,9 @@ impl App { /// section opens the Save/Discard/Stay modal targeting `Quit`. fn leave_quit(&mut self) { if self.active_is_dirty() { - self.overlay = Overlay::DirtyLeave { target: LeaveTarget::Quit }; + self.overlay = Overlay::DirtyLeave { + target: LeaveTarget::Quit, + }; } else { self.should_quit = true; } @@ -576,7 +613,10 @@ impl App { // Overlays capture keys first. match &self.overlay { Overlay::Help => { - if matches!(key.code, KeyCode::Esc | KeyCode::Char('?') | KeyCode::Char('q')) { + if matches!( + key.code, + KeyCode::Esc | KeyCode::Char('?') | KeyCode::Char('q') + ) { self.overlay = Overlay::None; } return LoopCmd::None; @@ -691,6 +731,23 @@ impl App { } LoopCmd::None } + ScreenAction::ProbeHardwareVolume => { + let request = match &self.active { + Active::Audio(screen) => screen.hardware_volume_probe_request(), + _ => return LoopCmd::None, + }; + match request { + Ok((device_id, persisted)) => { + self.spawn_hardware_volume_probe(device_id, persisted); + } + Err(error) => { + if let Active::Audio(screen) = &mut self.active { + screen.set_hardware_volume_probe(Err(error)); + } + } + } + LoopCmd::None + } ScreenAction::LoginBrowser => LoopCmd::BrowserLogin, ScreenAction::LoginToken(token) => { self.spawn_token_login(token); @@ -795,7 +852,12 @@ impl App { return; } let (lines, status, reachable) = do_reload(&roots, is_network, reinit).await; - let _ = tx.send(Msg::Saved { lines, status, reachable, success }); + let _ = tx.send(Msg::Saved { + lines, + status, + reachable, + success, + }); }); } @@ -808,6 +870,27 @@ impl App { }); } + fn spawn_hardware_volume_probe( + &mut self, + device_id: String, + persisted: std::collections::HashMap< + qbz_audio::alsa_hardware_volume::StableAlsaRouteKey, + qbz_audio::alsa_hardware_volume::AlsaMixerControlId, + >, + ) { + let tx = self.tx.clone(); + self.handle.spawn_blocking(move || { + let probe = + qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls(&device_id); + let decision = + qbz_audio::alsa_hardware_volume::decide_hardware_volume(&probe, &persisted); + let _ = tx.send(Msg::HardwareVolume { + device_id, + result: Ok((probe, decision)), + }); + }); + } + fn spawn_token_login(&mut self, token: String) { self.busy = Some(s::ACCOUNT_VALIDATING.to_string()); let roots = self.roots.clone(); @@ -935,11 +1018,13 @@ impl App { tokio::time::sleep(std::time::Duration::from_millis(1200)).await; } Err(CliError::Unreachable(_)) => { - note = Some("daemon not reachable — start it, then try the test".to_string()); + note = + Some("daemon not reachable — start it, then try the test".to_string()); } Err(_) => { note = Some( - "nothing to play — queue a track or cast to the daemon first".to_string(), + "nothing to play — queue a track or cast to the daemon first" + .to_string(), ); } } @@ -947,12 +1032,19 @@ impl App { // Requested (what QBZ asked the daemon for), while playing. let requested = client.get("/api/status").await.ok().and_then(|st| { let sr = st.pointer("/audio/sample_rate").and_then(Value::as_u64)?; - let bd = st.pointer("/audio/bit_depth").and_then(Value::as_u64).unwrap_or(0); + let bd = st + .pointer("/audio/bit_depth") + .and_then(Value::as_u64) + .unwrap_or(0); Some((sr as u32, bd as u32)) }); // Negotiated (the DAC's real hardware clock). let negotiated = qbz_audio::negotiated_active_rate(); - let _ = tx.send(Msg::WizardTest { requested, negotiated, note }); + let _ = tx.send(Msg::WizardTest { + requested, + negotiated, + note, + }); }); } @@ -971,7 +1063,23 @@ impl App { s.set_devices(result); } } - Msg::Saved { lines, status, reachable, success } => { + Msg::HardwareVolume { device_id, result } => { + if let Active::Audio(screen) = &mut self.active { + let still_current = screen + .hardware_volume_probe_request() + .ok() + .is_some_and(|(current, _)| current == device_id); + if still_current { + screen.set_hardware_volume_probe(result); + } + } + } + Msg::Saved { + lines, + status, + reachable, + success, + } => { self.busy = None; self.reachable = reachable; if status.is_some() { @@ -1041,7 +1149,11 @@ impl App { } } } - Msg::ImportApplied { lines, status, reachable } => { + Msg::ImportApplied { + lines, + status, + reachable, + } => { self.busy = None; self.reachable = reachable; if status.is_some() { @@ -1086,7 +1198,11 @@ impl App { w.set_configs(configs); } } - Msg::WizardTest { requested, negotiated, note } => { + Msg::WizardTest { + requested, + negotiated, + note, + } => { self.busy = None; if let Active::Wizard(w) = &mut self.active { w.set_test_result(requested, negotiated, note); @@ -1205,7 +1321,10 @@ impl App { f, area, s::HELP_TITLE, - s::HELP_OVERLAY.lines().map(|l| Line::from(l.to_string())).collect(), + s::HELP_OVERLAY + .lines() + .map(|l| Line::from(l.to_string())) + .collect(), 0, ), Overlay::Result { title, lines } => { @@ -1216,7 +1335,13 @@ impl App { widgets::modal(f, area, s::DIRTY_TITLE, s::DIRTY_BODY, s::DIRTY_HINT); } Overlay::ConfirmAbandon => { - widgets::modal(f, area, s::WIZ_ABANDON_TITLE, s::WIZ_ABANDON_BODY, s::WIZ_ABANDON_HINT); + widgets::modal( + f, + area, + s::WIZ_ABANDON_TITLE, + s::WIZ_ABANDON_BODY, + s::WIZ_ABANDON_HINT, + ); } Overlay::None => {} } @@ -1281,7 +1406,11 @@ impl App { let is_active = *screen == self.active_section; let dirty = sidebar_dirty_marker(*screen, self.active_section, active_dirty); let highlighted = self.focus == Focus::Nav && i == self.nav_cursor; - let label = if wide { s::SIDEBAR_LABELS_WIDE[i] } else { s::SIDEBAR_LABELS[i] }; + let label = if wide { + s::SIDEBAR_LABELS_WIDE[i] + } else { + s::SIDEBAR_LABELS[i] + }; let marker = if is_active { "▸ " } else { " " }; if highlighted { @@ -1295,11 +1424,19 @@ impl App { let mut spans = vec![ Span::styled( marker.to_string(), - if is_active { theme::accent() } else { Style::default() }, + if is_active { + theme::accent() + } else { + Style::default() + }, ), Span::styled( label.to_string(), - if is_active { theme::accent_bold() } else { Style::default() }, + if is_active { + theme::accent_bold() + } else { + Style::default() + }, ), ]; if dirty { @@ -1323,10 +1460,7 @@ impl App { fn draw_footer(&self, f: &mut Frame, area: Rect) { let playing = self.status.as_ref().and_then(playing_extra); let (text, style) = footer_state(self.reachable, self.auth.logged_in, playing); - f.render_widget( - Paragraph::new(Line::from(Span::styled(text, style))), - area, - ); + f.render_widget(Paragraph::new(Line::from(Span::styled(text, style))), area); } fn help_text(&self) -> &'static str { @@ -1389,14 +1523,22 @@ fn write_keys(roots: &ProfileRoots, keys: &[(String, String)]) -> (Option) -> Option { +fn save_network( + roots: &ProfileRoots, + bind: &str, + port: u16, + token: Option<&str>, +) -> Option { let path = roots.config.join("qbzd.toml"); let existing = std::fs::read_to_string(&path).unwrap_or_default(); match network_screen::rewrite_toml(&existing, bind, port, token) { @@ -1529,7 +1671,8 @@ async fn apply_import( }; } - let (mut lines, status, reachable) = do_reload(roots, false, plan.routing_critical_changed).await; + let (mut lines, status, reachable) = + do_reload(roots, false, plan.routing_critical_changed).await; let mut out = vec![s::b_import_done( plan.applied.len(), plan.adapted.len(), @@ -1539,10 +1682,18 @@ async fn apply_import( if uid.is_some() { out.push("logged in with the bundled account".to_string()); } - Msg::ImportApplied { lines: out, status, reachable } + Msg::ImportApplied { + lines: out, + status, + reachable, + } } -fn export_bundle(roots: &ProfileRoots, dest: &str, include_auth: bool) -> Result, String> { +fn export_bundle( + roots: &ProfileRoots, + dest: &str, + include_auth: bool, +) -> Result, String> { let source = ExportSource::Daemon(ProfilePaths { config_root: roots.config.clone(), data_root: roots.data.clone(), @@ -1558,7 +1709,10 @@ fn export_bundle(roots: &ProfileRoots, dest: &str, include_auth: bool) -> Result .to_string(); let mut lines = vec![s::b_export_success(&name)]; if b.contains_secrets() { - lines.push("this file contains your Qobuz token — 0600, move it privately, delete after import".to_string()); + lines.push( + "this file contains your Qobuz token — 0600, move it privately, delete after import" + .to_string(), + ); } if desktop_profile_present() { for l in s::B_DESKTOP_HINT.lines() { @@ -1575,7 +1729,11 @@ fn export_bundle(roots: &ProfileRoots, dest: &str, include_auth: bool) -> Result fn build_live(bundle: &Bundle) -> (LiveSystem, AudioBackendType, Vec) { let backends: Vec = BackendManager::available_backends() .into_iter() - .filter_map(|b| serde_json::to_value(b).ok().and_then(|v| v.as_str().map(str::to_string))) + .filter_map(|b| { + serde_json::to_value(b) + .ok() + .and_then(|v| v.as_str().map(str::to_string)) + }) .collect(); let wanted: Option = bundle .domains @@ -1584,10 +1742,15 @@ fn build_live(bundle: &Bundle) -> (LiveSystem, AudioBackendType, Vec = - devices.iter().map(|d| (d.id.clone(), d.name.clone())).collect(); + let live_devices: Vec<(String, String)> = devices + .iter() + .map(|d| (d.id.clone(), d.name.clone())) + .collect(); ( - LiveSystem { backends, devices: live_devices }, + LiveSystem { + backends, + devices: live_devices, + }, backend, devices, ) @@ -1623,17 +1786,24 @@ fn footer_state( /// A "playing 192000 Hz / 24 bit" tail from a status body (§4.3), if playing. fn playing_extra(status: &Value) -> Option { - let state = status.pointer("/playback/state").and_then(Value::as_str).unwrap_or(""); + let state = status + .pointer("/playback/state") + .and_then(Value::as_str) + .unwrap_or(""); if state != "playing" { return None; } - let sr = status.pointer("/audio/sample_rate").and_then(Value::as_u64)?; + let sr = status + .pointer("/audio/sample_rate") + .and_then(Value::as_u64)?; let bd = status.pointer("/audio/bit_depth").and_then(Value::as_u64)?; Some(format!("playing {sr} Hz / {bd} bit")) } fn desktop_profile_present() -> bool { - dirs::data_dir().map(|d| d.join("qbz").exists()).unwrap_or(false) + dirs::data_dir() + .map(|d| d.join("qbz").exists()) + .unwrap_or(false) } fn expand_tilde(path: &str) -> PathBuf { @@ -1682,7 +1852,10 @@ mod tests { #[test] fn breadcrumb_is_section_then_field_when_editing() { - assert_eq!(breadcrumb_nodes("Audio", Some("Backend")), ("Audio", "Backend")); + assert_eq!( + breadcrumb_nodes("Audio", Some("Backend")), + ("Audio", "Backend") + ); } // ---- sidebar dirty marker: only the active section can show `*` ---- @@ -1758,23 +1931,46 @@ mod tests { #[test] fn number_keys_jump_from_any_focus_but_not_while_editing() { // 1-7 jump from nav and from content (not editing). - assert_eq!(classify_key(Focus::Nav, KeyCode::Char('3'), false, false), NavIntent::JumpSection(2)); - assert_eq!(classify_key(Focus::Content, KeyCode::Char('1'), false, false), NavIntent::JumpSection(0)); - assert_eq!(classify_key(Focus::Content, KeyCode::Char('6'), false, false), NavIntent::JumpSection(5)); + assert_eq!( + classify_key(Focus::Nav, KeyCode::Char('3'), false, false), + NavIntent::JumpSection(2) + ); + assert_eq!( + classify_key(Focus::Content, KeyCode::Char('1'), false, false), + NavIntent::JumpSection(0) + ); + assert_eq!( + classify_key(Focus::Content, KeyCode::Char('6'), false, false), + NavIntent::JumpSection(5) + ); // 7 reaches the FB4 Wizard section (the seventh). - assert_eq!(classify_key(Focus::Content, KeyCode::Char('7'), false, false), NavIntent::JumpSection(6)); + assert_eq!( + classify_key(Focus::Content, KeyCode::Char('7'), false, false), + NavIntent::JumpSection(6) + ); // While a field editor is open, digits are typed into it, not swallowed. - assert_eq!(classify_key(Focus::Content, KeyCode::Char('5'), true, false), NavIntent::ToScreen); + assert_eq!( + classify_key(Focus::Content, KeyCode::Char('5'), true, false), + NavIntent::ToScreen + ); // ...and so is every other key while editing. - assert_eq!(classify_key(Focus::Content, KeyCode::Tab, true, false), NavIntent::ToScreen); - assert_eq!(classify_key(Focus::Content, KeyCode::Esc, true, false), NavIntent::ToScreen); + assert_eq!( + classify_key(Focus::Content, KeyCode::Tab, true, false), + NavIntent::ToScreen + ); + assert_eq!( + classify_key(Focus::Content, KeyCode::Esc, true, false), + NavIntent::ToScreen + ); } // ---- 80×24 floor: every section renders inside the frames shell ---- fn bare_app(section: Screen, focus: Focus) -> App { let (tx, rx) = std::sync::mpsc::channel(); - let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); let active = match section { Screen::Account => Active::Account(AccountState::new(AuthSnapshot::default())), Screen::Audio => Active::Audio(AudioState::new(&AudioSettings::default())), @@ -1785,7 +1981,9 @@ mod tests { &qbz_app::settings::playback::PlaybackPreferences::default(), )), Screen::QConnect => Active::QConnect(QConnectState::new(false, None, None)), - Screen::Network => Active::Network(NetworkState::new(&QbzdConfig::default(), Vec::new())), + Screen::Network => { + Active::Network(NetworkState::new(&QbzdConfig::default(), Vec::new())) + } Screen::Bundle => Active::Bundle(BundleState::new(false)), Screen::Wizard => Active::Wizard(WizardState::new()), Screen::Scrobbler => Active::Scrobbler(ScrobblerState::new(&ProfileRoots { @@ -1850,7 +2048,10 @@ mod tests { // The sidebar and version chrome are present. assert!(out.contains("Account"), "sidebar missing for {screen:?}"); let version = format!("qbzd {}", env!("CARGO_PKG_VERSION")); - assert!(out.contains(&version), "version chrome missing for {screen:?}"); + assert!( + out.contains(&version), + "version chrome missing for {screen:?}" + ); } } } @@ -1862,7 +2063,6 @@ mod tests { assert!(out.contains("terminal too small")); } - // ---- 120×30 wide: the roomy sidebar tier + every section still renders (FB5) ---- #[test] @@ -1871,13 +2071,19 @@ mod tests { for focus in [Focus::Nav, Focus::Content] { let app = bare_app(screen, focus); let out = render(&app, 120, 30); - assert!(out.contains("QBZ Daemon Setup"), "header missing {screen:?}/{focus:?}"); + assert!( + out.contains("QBZ Daemon Setup"), + "header missing {screen:?}/{focus:?}" + ); assert!( !out.contains("terminal too small"), "120x30 must not trip the resize guard for {screen:?}" ); // Wide tier: labels spell out and each name carries a dim summary. - assert!(out.contains("Import / Export"), "wide sidebar label missing {screen:?}"); + assert!( + out.contains("Import / Export"), + "wide sidebar label missing {screen:?}" + ); assert!( out.contains("output · bit-perfect"), "wide sidebar summary missing {screen:?}" @@ -1891,7 +2097,10 @@ mod tests { // At the 80-col floor the compact label is used, not the spelled-out one. let floor = render(&bare_app(Screen::Audio, Focus::Nav), 80, 24); assert!(floor.contains("Import/Exp"), "compact label at the floor"); - assert!(!floor.contains("Import / Export"), "no wide label at the floor"); + assert!( + !floor.contains("Import / Export"), + "no wide label at the floor" + ); // The 28-col sidebar is at least double the 14-col compact one. assert!(widgets::sidebar_width(120) >= 2 * widgets::sidebar_width(80)); } @@ -1905,7 +2114,10 @@ mod tests { // Reachable but not signed in → warn, names the missing auth. let (text, style) = footer_state(true, false, None); - assert_eq!(text, format!(" {} · {}", s::FOOTER_RUNNING, s::FOOTER_NEEDS_AUTH)); + assert_eq!( + text, + format!(" {} · {}", s::FOOTER_RUNNING, s::FOOTER_NEEDS_AUTH) + ); assert_eq!(style, theme::warn()); // Running + signed in → ok, with and without the playing tail. diff --git a/crates/qbzd/src/tui/screens/audio.rs b/crates/qbzd/src/tui/screens/audio.rs index 25d126174..ba9f3b233 100644 --- a/crates/qbzd/src/tui/screens/audio.rs +++ b/crates/qbzd/src/tui/screens/audio.rs @@ -11,6 +11,13 @@ // `device_is_bit_perfect` / `group_alsa_devices` 1:1, including the // is_default-vs-section badge edge case. +use std::collections::HashMap; + +use qbz_audio::alsa_hardware_volume::{ + AlsaMixerControlId, HardwareVolumeCandidate, HardwareVolumeChoiceReason, + HardwareVolumeDecision, HardwareVolumeProbe, HardwareVolumeSelectionSource, + HardwareVolumeUnsupportedReason, StableAlsaRouteKey, +}; use qbz_audio::settings::AudioSettings; use qbz_audio::{AlsaPlugin, AudioBackendType, AudioDevice, BackendManager}; use ratatui::crossterm::event::{KeyCode, KeyEvent}; @@ -31,6 +38,8 @@ pub struct StagedAudio { pub output_device: Option, pub alsa_plugin: AlsaPlugin, pub alsa_hardware_volume: bool, + pub alsa_hardware_volume_control: Option, + pub alsa_hardware_volume_controls: HashMap, pub dsd_mode: String, pub exclusive_mode: bool, pub reserve_dac: bool, @@ -47,11 +56,18 @@ pub struct StagedAudio { impl StagedAudio { pub fn from_settings(a: &AudioSettings) -> Self { + let alsa_hardware_volume_control = a + .output_device + .as_deref() + .and_then(|device| qbz_audio::alsa_hardware_volume::stable_alsa_route_key(device).ok()) + .and_then(|route| a.alsa_hardware_volume_controls.get(&route).cloned()); Self { backend: a.backend_type.unwrap_or_default(), output_device: a.output_device.clone(), alsa_plugin: a.alsa_plugin.unwrap_or_default(), alsa_hardware_volume: a.alsa_hardware_volume, + alsa_hardware_volume_control, + alsa_hardware_volume_controls: a.alsa_hardware_volume_controls.clone(), dsd_mode: a.dsd_mode.clone(), exclusive_mode: a.exclusive_mode, reserve_dac: a.reserve_dac_while_running, @@ -74,6 +90,7 @@ pub enum AField { Device, AlsaPlugin, HwVolume, + HwVolumeControl, Dsd, Exclusive, Reserve, @@ -95,14 +112,29 @@ pub fn row_state(field: AField, a: &StagedAudio) -> (bool, bool, Option<&'static Device => (true, true, None), AlsaPlugin => (alsa, true, None), // shown only on ALSA // NB: `use AField::*` shadows the AlsaPlugin type here — qualify it. - HwVolume => (alsa && a.alsa_plugin == qbz_audio::AlsaPlugin::Hw, true, None), + HwVolume => ( + alsa && a.alsa_plugin != qbz_audio::AlsaPlugin::Pcm, + true, + None, + ), + HwVolumeControl => ( + alsa && a.alsa_plugin != qbz_audio::AlsaPlugin::Pcm + && a.alsa_hardware_volume + && a.alsa_hardware_volume_control.is_some(), + true, + None, + ), Dsd => (alsa, true, None), Exclusive => (true, alsa, if alsa { None } else { Some(s::R_ALSA_ONLY) }), Reserve => (true, true, None), Passthrough => ( true, pipewire, - if pipewire { None } else { Some(s::R_PIPEWIRE_ONLY) }, + if pipewire { + None + } else { + Some(s::R_PIPEWIRE_ONLY) + }, ), // shown only when passthrough on AND PipeWire. ForceBp => (a.dac_passthrough && pipewire, true, None), @@ -110,7 +142,11 @@ pub fn row_state(field: AField, a: &StagedAudio) -> (bool, bool, Option<&'static LockOutput => ( pipewire, !a.dac_passthrough, - if a.dac_passthrough { Some(s::R_PASSTHROUGH_OFF) } else { None }, + if a.dac_passthrough { + Some(s::R_PASSTHROUGH_OFF) + } else { + None + }, ), StreamUncached => (true, true, None), Buffer => (a.stream_first_track, true, None), // shown when stream uncached on @@ -122,8 +158,20 @@ pub fn row_state(field: AField, a: &StagedAudio) -> (bool, bool, Option<&'static pub fn visible_fields(a: &StagedAudio) -> Vec { use AField::*; [ - Backend, Device, AlsaPlugin, HwVolume, Dsd, Exclusive, Reserve, Passthrough, ForceBp, - LockOutput, StreamUncached, Buffer, StreamingOnly, + Backend, + Device, + AlsaPlugin, + HwVolume, + HwVolumeControl, + Dsd, + Exclusive, + Reserve, + Passthrough, + ForceBp, + LockOutput, + StreamUncached, + Buffer, + StreamingOnly, ] .into_iter() .filter(|f| row_state(*f, a).0) @@ -165,6 +213,8 @@ pub fn cascade_on_backend_change(a: &mut StagedAudio) { a.gapless_enabled = false; // item 6 } a.output_device = None; // item 7: never carry the old backend's device id + a.alsa_hardware_volume = false; + a.alsa_hardware_volume_control = None; } // ============================ device picker grouping (§3.2.2) ============================ @@ -285,9 +335,13 @@ enum Editor { Backend(SelectPopup), Device(SelectPopup), AlsaPlugin(SelectPopup), + HardwareVolume(SelectPopup), Dsd(SelectPopup), /// The §3.2.4 DSD guard: `prev` is restored on Esc. - DsdConfirm { new: String, prev: String }, + DsdConfirm { + new: String, + prev: String, + }, } pub struct AudioState { @@ -296,6 +350,11 @@ pub struct AudioState { focus: usize, devices: Vec, scanning: bool, + hardware_volume_candidates: Vec, + hardware_volume_route_key: Option, + hardware_volume_status: Option, + hardware_volume_probing: bool, + probe_for_control_change: bool, editor: Option, } @@ -308,6 +367,11 @@ impl AudioState { focus: 0, devices: Vec::new(), scanning: true, + hardware_volume_candidates: Vec::new(), + hardware_volume_route_key: None, + hardware_volume_status: None, + hardware_volume_probing: false, + probe_for_control_change: false, editor: None, } } @@ -330,6 +394,107 @@ impl AudioState { self.scanning = true; } + pub fn hardware_volume_probe_request( + &self, + ) -> Result<(String, HashMap), String> { + if self.staged.backend != AudioBackendType::Alsa + || self.staged.alsa_plugin == AlsaPlugin::Pcm + { + return Err("hardware volume requires ALSA Direct (hw or plughw)".to_string()); + } + let device_id = self + .staged + .output_device + .clone() + .ok_or_else(|| "select an explicit ALSA Direct device first".to_string())?; + if !qbz_audio::alsa_direct::AlsaDirectStream::is_hw_device(&device_id) { + return Err("the selected output is not an ALSA Direct route".to_string()); + } + Ok((device_id, self.staged.alsa_hardware_volume_controls.clone())) + } + + pub fn begin_hardware_volume_probe(&mut self, for_control_change: bool) { + self.hardware_volume_probing = true; + self.hardware_volume_status = Some("checking ALSA mixer controls…".to_string()); + self.probe_for_control_change = for_control_change; + } + + pub fn set_hardware_volume_probe( + &mut self, + result: Result<(HardwareVolumeProbe, HardwareVolumeDecision), String>, + ) { + self.hardware_volume_probing = false; + let (probe, decision) = match result { + Ok(result) => result, + Err(error) => { + self.staged.alsa_hardware_volume = false; + self.hardware_volume_status = Some(error); + self.probe_for_control_change = false; + return; + } + }; + self.hardware_volume_candidates = probe.valid_candidates().cloned().collect(); + self.hardware_volume_route_key = probe.route_key.clone(); + match decision { + HardwareVolumeDecision::Selected { selection } => { + let change = + self.probe_for_control_change && self.hardware_volume_candidates.len() > 1; + self.staged + .alsa_hardware_volume_controls + .insert(selection.route_key, selection.control.clone()); + self.staged.alsa_hardware_volume_control = Some(selection.control); + self.staged.alsa_hardware_volume = true; + self.hardware_volume_status = Some(match selection.source { + HardwareVolumeSelectionSource::Persisted => { + "saved mixer control validated".to_string() + } + HardwareVolumeSelectionSource::Ucm => { + "mixer control resolved from ALSA UCM".to_string() + } + HardwareVolumeSelectionSource::OnlyCandidate => { + "only compatible mixer control selected".to_string() + } + HardwareVolumeSelectionSource::UserChoice => { + "mixer control selected".to_string() + } + }); + if change { + self.open_hardware_volume_picker(); + } + } + HardwareVolumeDecision::NeedsChoice { + route_key: _, + reason, + .. + } => { + self.staged.alsa_hardware_volume = false; + self.hardware_volume_status = Some(match reason { + HardwareVolumeChoiceReason::PersistedSelectionStale => { + "saved control is unavailable — choose another".to_string() + } + HardwareVolumeChoiceReason::Ambiguous + | HardwareVolumeChoiceReason::UcmAmbiguous => { + "multiple playback controls — choose one".to_string() + } + }); + self.open_hardware_volume_picker(); + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + self.staged.alsa_hardware_volume = false; + self.hardware_volume_status = Some(match reason { + HardwareVolumeUnsupportedReason::Probe(error) => error.message, + HardwareVolumeUnsupportedReason::NoValidControls => { + "no compatible playback-volume control".to_string() + } + HardwareVolumeUnsupportedReason::PersistedSelectionStale(control) => { + format!("saved mixer control '{control}' is unavailable") + } + }); + } + } + self.probe_for_control_change = false; + } + pub fn is_dirty(&self) -> bool { self.staged != self.baseline } @@ -345,6 +510,7 @@ impl AudioState { Some(Editor::Backend(_)) => Some(s::A_BACKEND), Some(Editor::Device(_)) => Some(s::A_DEVICE), Some(Editor::AlsaPlugin(_)) => Some(s::A_ALSA_PLUGIN), + Some(Editor::HardwareVolume(_)) => Some(s::A_HW_VOLUME_CONTROL), Some(Editor::Dsd(_)) | Some(Editor::DsdConfirm { .. }) => Some(s::A_DSD), None => None, } @@ -372,12 +538,25 @@ impl AudioState { if a.output_device != b.output_device { push( "device", - a.output_device.clone().unwrap_or_else(|| "system".to_string()), + a.output_device + .clone() + .unwrap_or_else(|| "system".to_string()), ); } if a.alsa_plugin != b.alsa_plugin { push("alsa_plugin", alsa_plugin_value(a.alsa_plugin).to_string()); } + if a.alsa_hardware_volume_control != b.alsa_hardware_volume_control + && a.alsa_hardware_volume_control.is_some() + { + push( + "alsa_hardware_volume_control", + a.alsa_hardware_volume_control + .as_ref() + .map(ToString::to_string) + .expect("checked above"), + ); + } if a.alsa_hardware_volume != b.alsa_hardware_volume { push("alsa_hardware_volume", a.alsa_hardware_volume.to_string()); } @@ -473,7 +652,7 @@ impl AudioState { KeyCode::Enter | KeyCode::Char(' ') => { let field = fields.get(self.focus).copied(); if let Some(f) = field { - self.activate(f); + return self.activate(f); } ScreenAction::Consumed } @@ -485,17 +664,29 @@ impl AudioState { /// Act on the focused field (toggle in place / open a popup). Any device /// re-enumeration triggered by a backend change is returned from /// `handle_editor_key` when the picker resolves, not here. - fn activate(&mut self, field: AField) { + fn activate(&mut self, field: AField) -> ScreenAction { let (_, enabled, _) = row_state(field, &self.staged); if !enabled && !matches!(field, AField::Backend | AField::Device) { - return; // disabled row: inert + return ScreenAction::Consumed; // disabled row: inert } match field { AField::Backend => self.open_backend_picker(), AField::Device => self.open_device_picker(false), AField::AlsaPlugin => self.open_alsa_plugin_picker(), AField::Dsd => self.open_dsd_picker(), - AField::HwVolume => self.staged.alsa_hardware_volume ^= true, + AField::HwVolume => { + if self.staged.alsa_hardware_volume { + self.staged.alsa_hardware_volume = false; + self.hardware_volume_status = None; + } else { + self.begin_hardware_volume_probe(false); + return ScreenAction::ProbeHardwareVolume; + } + } + AField::HwVolumeControl => { + self.begin_hardware_volume_probe(true); + return ScreenAction::ProbeHardwareVolume; + } AField::Reserve => self.staged.reserve_dac ^= true, AField::Exclusive => self.staged.exclusive_mode ^= true, AField::Passthrough => { @@ -511,12 +702,16 @@ impl AudioState { } AField::Buffer => {} } + ScreenAction::Consumed } fn open_backend_picker(&mut self) { let backends = BackendManager::available_backends(); let options: Vec = backends.iter().map(|b| backend_label(*b)).collect(); - let sel = backends.iter().position(|b| *b == self.staged.backend).unwrap_or(0); + let sel = backends + .iter() + .position(|b| *b == self.staged.backend) + .unwrap_or(0); self.editor = Some(Editor::Backend(SelectPopup::new( s::A_BACKEND, options, @@ -529,15 +724,25 @@ impl AudioState { let options: Vec = self .devices .iter() - .map(|d| if d.bp { format!("{} {}", d.label, s::BP_BADGE) } else { d.label.clone() }) + .map(|d| { + if d.bp { + format!("{} {}", d.label, s::BP_BADGE) + } else { + d.label.clone() + } + }) .collect(); let headers: Vec> = self.devices.iter().map(|d| d.header.clone()).collect(); let sel = self .devices .iter() - .position(|d| Some(&d.id) == self.staged.output_device.as_ref() || (d.id.is_empty() && self.staged.output_device.is_none())) + .position(|d| { + Some(&d.id) == self.staged.output_device.as_ref() + || (d.id.is_empty() && self.staged.output_device.is_none()) + }) .unwrap_or(0); - let mut popup = SelectPopup::new(s::DEVICE_PICKER_TITLE, options, sel, true).with_headers(headers); + let mut popup = + SelectPopup::new(s::DEVICE_PICKER_TITLE, options, sel, true).with_headers(headers); if filter { popup.filter = String::new(); } @@ -545,17 +750,57 @@ impl AudioState { } fn open_alsa_plugin_picker(&mut self) { - let opts = vec![s::ALSA_HW.to_string(), s::ALSA_PLUGHW.to_string(), s::ALSA_PCM.to_string()]; + let opts = vec![ + s::ALSA_HW.to_string(), + s::ALSA_PLUGHW.to_string(), + s::ALSA_PCM.to_string(), + ]; let sel = match self.staged.alsa_plugin { AlsaPlugin::Hw => 0, AlsaPlugin::PlugHw => 1, AlsaPlugin::Pcm => 2, }; - self.editor = Some(Editor::AlsaPlugin(SelectPopup::new(s::A_ALSA_PLUGIN, opts, sel, false))); + self.editor = Some(Editor::AlsaPlugin(SelectPopup::new( + s::A_ALSA_PLUGIN, + opts, + sel, + false, + ))); + } + + fn open_hardware_volume_picker(&mut self) { + if self.hardware_volume_candidates.is_empty() { + return; + } + let options = self + .hardware_volume_candidates + .iter() + .map(hardware_volume_candidate_label) + .collect::>(); + let selected = self + .staged + .alsa_hardware_volume_control + .as_ref() + .and_then(|control| { + self.hardware_volume_candidates + .iter() + .position(|candidate| candidate.id == *control) + }) + .unwrap_or(0); + self.editor = Some(Editor::HardwareVolume(SelectPopup::new( + s::A_HW_VOLUME_CONTROL, + options, + selected, + self.hardware_volume_candidates.len() > 8, + ))); } fn open_dsd_picker(&mut self) { - let opts = vec![s::DSD_CONVERT.to_string(), s::DSD_DOP.to_string(), s::DSD_NATIVE.to_string()]; + let opts = vec![ + s::DSD_CONVERT.to_string(), + s::DSD_DOP.to_string(), + s::DSD_NATIVE.to_string(), + ]; let sel = match self.staged.dsd_mode.as_str() { "dop" => 1, "native" => 2, @@ -610,8 +855,19 @@ impl AudioState { Editor::Device(mut p) => match p.handle_key(key) { SelectOutcome::Chosen(i) => { if let Some(d) = self.devices.get(i) { - self.staged.output_device = - if d.id.is_empty() { None } else { Some(d.id.clone()) }; + let output_device = if d.id.is_empty() { + None + } else { + Some(d.id.clone()) + }; + if output_device != self.staged.output_device { + self.staged.output_device = output_device; + self.staged.alsa_hardware_volume = false; + self.staged.alsa_hardware_volume_control = None; + self.hardware_volume_candidates.clear(); + self.hardware_volume_route_key = None; + self.hardware_volume_status = None; + } } ScreenAction::Consumed } @@ -623,11 +879,19 @@ impl AudioState { }, Editor::AlsaPlugin(mut p) => match p.handle_key(key) { SelectOutcome::Chosen(i) => { - self.staged.alsa_plugin = match i { + let plugin = match i { 1 => AlsaPlugin::PlugHw, 2 => AlsaPlugin::Pcm, _ => AlsaPlugin::Hw, }; + if plugin != self.staged.alsa_plugin { + self.staged.alsa_plugin = plugin; + self.staged.alsa_hardware_volume = false; + self.staged.alsa_hardware_volume_control = None; + self.hardware_volume_candidates.clear(); + self.hardware_volume_route_key = None; + self.hardware_volume_status = None; + } ScreenAction::Consumed } SelectOutcome::Cancelled => ScreenAction::Consumed, @@ -636,6 +900,27 @@ impl AudioState { ScreenAction::Consumed } }, + Editor::HardwareVolume(mut p) => match p.handle_key(key) { + SelectOutcome::Chosen(i) => { + if let (Some(candidate), Some(route_key)) = ( + self.hardware_volume_candidates.get(i), + self.hardware_volume_route_key.clone(), + ) { + self.staged.alsa_hardware_volume_control = Some(candidate.id.clone()); + self.staged + .alsa_hardware_volume_controls + .insert(route_key, candidate.id.clone()); + self.staged.alsa_hardware_volume = true; + self.hardware_volume_status = Some(format!("selected {}", candidate.id)); + } + ScreenAction::Consumed + } + SelectOutcome::Cancelled => ScreenAction::Consumed, + SelectOutcome::Pending => { + self.editor = Some(Editor::HardwareVolume(p)); + ScreenAction::Consumed + } + }, Editor::Dsd(mut p) => match p.handle_key(key) { SelectOutcome::Chosen(i) => { let new = match i { @@ -672,7 +957,9 @@ impl AudioState { let fields = visible_fields(&self.staged); let focused_field = fields.get(self.focus).copied(); let active = |members: &[AField]| { - focused_field.map(|ff| members.contains(&ff)).unwrap_or(false) + focused_field + .map(|ff| members.contains(&ff)) + .unwrap_or(false) }; // ONE control column for the whole screen (owner's "misma área de columna"). let labels: Vec<&str> = fields.iter().map(|f| self.field_display(*f).0).collect(); @@ -682,25 +969,49 @@ impl AudioState { let mut secs: Vec = Vec::new(); let mut anchor: Option = None; - let out_members: &[AField] = &[Backend, Device, AlsaPlugin, HwVolume, Dsd]; - let (mut out_lines, out_a) = self.group_block(&fields, out_members, focused_field, ctrl_col, width); + let out_members: &[AField] = &[Backend, Device, AlsaPlugin, HwVolume, HwVolumeControl, Dsd]; + let (mut out_lines, out_a) = + self.group_block(&fields, out_members, focused_field, ctrl_col, width); if self.staged.backend == AudioBackendType::Jack { out_lines.extend(widgets::wrapped_note(s::JACK_WARNING, width, theme::warn())); } if !out_lines.is_empty() { - widgets::push_section(&mut secs, &mut anchor, s::AUDIO_GROUP_OUTPUT, active(out_members), out_lines, out_a); + widgets::push_section( + &mut secs, + &mut anchor, + s::AUDIO_GROUP_OUTPUT, + active(out_members), + out_lines, + out_a, + ); } let bp_members: &[AField] = &[Exclusive, Reserve, Passthrough, ForceBp, LockOutput]; - let (bp_lines, bp_a) = self.group_block(&fields, bp_members, focused_field, ctrl_col, width); + let (bp_lines, bp_a) = + self.group_block(&fields, bp_members, focused_field, ctrl_col, width); if !bp_lines.is_empty() { - widgets::push_section(&mut secs, &mut anchor, s::AUDIO_GROUP_BITPERFECT, active(bp_members), bp_lines, bp_a); + widgets::push_section( + &mut secs, + &mut anchor, + s::AUDIO_GROUP_BITPERFECT, + active(bp_members), + bp_lines, + bp_a, + ); } let tr_members: &[AField] = &[StreamUncached, Buffer, StreamingOnly]; - let (tr_lines, tr_a) = self.group_block(&fields, tr_members, focused_field, ctrl_col, width); + let (tr_lines, tr_a) = + self.group_block(&fields, tr_members, focused_field, ctrl_col, width); if !tr_lines.is_empty() { - widgets::push_section(&mut secs, &mut anchor, s::AUDIO_GROUP_TRANSPORT, active(tr_members), tr_lines, tr_a); + widgets::push_section( + &mut secs, + &mut anchor, + s::AUDIO_GROUP_TRANSPORT, + active(tr_members), + tr_lines, + tr_a, + ); } widgets::sections_scroll(f, area, &secs, anchor); @@ -709,19 +1020,32 @@ impl AudioState { match &self.editor { Some(Editor::Backend(p)) | Some(Editor::AlsaPlugin(p)) + | Some(Editor::HardwareVolume(p)) | Some(Editor::Dsd(p)) => p.draw(f, area), Some(Editor::Device(p)) => { if self.scanning { widgets::busy_overlay(f, area, s::AUDIO_SCANNING, 0); } else if self.devices.len() <= 1 { // Only the synthetic "System default" — the §5.1 hint panel. - widgets::modal(f, area, s::DEVICE_PICKER_TITLE, s::NO_DEVICES, s::HELP_SELECT); + widgets::modal( + f, + area, + s::DEVICE_PICKER_TITLE, + s::NO_DEVICES, + s::HELP_SELECT, + ); } else { p.draw(f, area); } } Some(Editor::DsdConfirm { .. }) => { - widgets::modal(f, area, s::DSD_GUARD_TITLE, s::DSD_GUARD_BODY, s::DSD_GUARD_HINT); + widgets::modal( + f, + area, + s::DSD_GUARD_TITLE, + s::DSD_GUARD_BODY, + s::DSD_GUARD_HINT, + ); } None => {} } @@ -753,7 +1077,13 @@ impl AudioState { (lines, within) } - fn field_block(&self, field: AField, focus_pos: usize, ctrl_col: u16, width: u16) -> Vec> { + fn field_block( + &self, + field: AField, + focus_pos: usize, + ctrl_col: u16, + width: u16, + ) -> Vec> { let (_, enabled, reason) = row_state(field, &self.staged); let focused = focus_pos == self.focus && self.editor.is_none(); let (label, value, widget) = self.field_display(field); @@ -771,7 +1101,13 @@ impl AudioState { fn field_display(&self, field: AField) -> (&'static str, String, &'static str) { let a = &self.staged; - let on_off = |b: bool| if b { "on".to_string() } else { "off".to_string() }; + let on_off = |b: bool| { + if b { + "on".to_string() + } else { + "off".to_string() + } + }; match field { AField::Backend => (s::A_BACKEND, backend_label(a.backend), "[select]"), AField::Device => { @@ -782,16 +1118,45 @@ impl AudioState { }; (s::A_DEVICE, dev, "[select]") } - AField::AlsaPlugin => (s::A_ALSA_PLUGIN, alsa_plugin_label(a.alsa_plugin).to_string(), "[select]"), - AField::HwVolume => (s::A_HW_VOLUME, on_off(a.alsa_hardware_volume), "[toggle]"), + AField::AlsaPlugin => ( + s::A_ALSA_PLUGIN, + alsa_plugin_label(a.alsa_plugin).to_string(), + "[select]", + ), + AField::HwVolume => { + let value = if self.hardware_volume_probing { + "checking…".to_string() + } else if let Some(status) = &self.hardware_volume_status { + format!("{} · {status}", on_off(a.alsa_hardware_volume)) + } else { + on_off(a.alsa_hardware_volume) + }; + (s::A_HW_VOLUME, value, "[toggle]") + } + AField::HwVolumeControl => ( + s::A_HW_VOLUME_CONTROL, + a.alsa_hardware_volume_control + .as_ref() + .map(ToString::to_string) + .unwrap_or_else(|| "none".to_string()), + "[select]", + ), AField::Dsd => (s::A_DSD, dsd_label(&a.dsd_mode).to_string(), "[select]"), AField::Exclusive => (s::A_EXCLUSIVE, on_off(a.exclusive_mode), "[toggle]"), AField::Reserve => (s::A_RESERVE, on_off(a.reserve_dac), "[toggle]"), AField::Passthrough => (s::A_PASSTHROUGH, on_off(a.dac_passthrough), "[toggle]"), AField::ForceBp => (s::A_FORCE_BP, on_off(a.pw_force_bitperfect), "[toggle]"), AField::LockOutput => (s::A_LOCK_OUTPUT, on_off(a.skip_sink_switch), "[toggle]"), - AField::StreamUncached => (s::A_STREAM_UNCACHED, on_off(a.stream_first_track), "[toggle]"), - AField::Buffer => (s::A_BUFFER, format!("{} s", a.stream_buffer_seconds), "[slider]"), + AField::StreamUncached => ( + s::A_STREAM_UNCACHED, + on_off(a.stream_first_track), + "[toggle]", + ), + AField::Buffer => ( + s::A_BUFFER, + format!("{} s", a.stream_buffer_seconds), + "[slider]", + ), AField::StreamingOnly => (s::A_STREAMING_ONLY, on_off(a.streaming_only), "[toggle]"), } } @@ -803,7 +1168,13 @@ impl AudioState { .devices .iter() .find(|d| &d.id == id) - .map(|d| if d.bp { format!("{} {}", d.label, s::BP_BADGE) } else { d.label.clone() }) + .map(|d| { + if d.bp { + format!("{} {}", d.label, s::BP_BADGE) + } else { + d.label.clone() + } + }) .unwrap_or_else(|| short_device(id)), } } @@ -857,6 +1228,32 @@ fn dsd_label(mode: &str) -> &'static str { } } +fn hardware_volume_candidate_label(candidate: &HardwareVolumeCandidate) -> String { + let range = candidate + .db_range + .map(|range| { + format!( + "{:.2}..{:.2} dB", + range.min as f64 / 100.0, + range.max as f64 / 100.0 + ) + }) + .or_else(|| { + candidate + .raw_range + .map(|range| format!("raw {}..{}", range.min, range.max)) + }) + .unwrap_or_else(|| "range unavailable".to_string()); + let recommended = if candidate.recommended { " ★" } else { "" }; + format!( + "{}{} · {} · {}", + candidate.id, + recommended, + range, + candidate.channels.join(", ") + ) +} + /// Compact a long device id for menu/summary lines (char-safe). fn short_device(id: &str) -> String { let count = id.chars().count(); @@ -889,6 +1286,52 @@ mod tests { StagedAudio::from_settings(&AudioSettings::default()) } + fn route_key() -> StableAlsaRouteKey { + serde_json::from_str(r#""alsa-route-v1|card=card:D50|pcm=hw|DEV=0""#) + .expect("valid opaque route key") + } + + fn mixer_candidate(name: &str, index: u32) -> HardwareVolumeCandidate { + HardwareVolumeCandidate { + id: AlsaMixerControlId { + name: name.to_string(), + index, + }, + label: format!("{name},{index}"), + channels: vec!["front_left".to_string(), "front_right".to_string()], + raw_range: Some(qbz_audio::alsa_hardware_volume::HardwareVolumeRange { + min: 0, + max: 100, + }), + db_range: None, + current_values: Vec::new(), + current_volume: Some(0.5), + has_playback_switch: false, + recommended: name == "Master", + writability: qbz_audio::alsa_hardware_volume::HardwareVolumeWritability::Verified, + rejection_reason: None, + } + } + + fn mixer_probe(candidates: Vec) -> HardwareVolumeProbe { + HardwareVolumeProbe { + device_id: "hw:CARD=D50,DEV=0".to_string(), + ctl_name: "hw:CARD=D50".to_string(), + route_key: Some(route_key()), + candidates, + ucm_controls: Vec::new(), + error: None, + } + } + + fn alsa_screen() -> AudioState { + let mut settings = AudioSettings::default(); + settings.backend_type = Some(AudioBackendType::Alsa); + settings.output_device = Some("hw:CARD=D50,DEV=0".to_string()); + settings.alsa_plugin = Some(AlsaPlugin::Hw); + AudioState::new(&settings) + } + // ---- cascades §3.2.3 items 1-3 (toggle) ---- #[test] @@ -897,7 +1340,10 @@ mod tests { a.skip_sink_switch = true; a.dac_passthrough = true; cascade_on_toggle(&mut a, AField::Passthrough); - assert!(!a.skip_sink_switch, "item 1: passthrough ON forces lock-output off"); + assert!( + !a.skip_sink_switch, + "item 1: passthrough ON forces lock-output off" + ); } #[test] @@ -906,7 +1352,10 @@ mod tests { a.pw_force_bitperfect = true; a.dac_passthrough = false; cascade_on_toggle(&mut a, AField::Passthrough); - assert!(!a.pw_force_bitperfect, "item 2: passthrough OFF forces force-BP off"); + assert!( + !a.pw_force_bitperfect, + "item 2: passthrough OFF forces force-BP off" + ); } #[test] @@ -915,7 +1364,10 @@ mod tests { a.gapless_enabled = true; a.streaming_only = true; cascade_on_toggle(&mut a, AField::StreamingOnly); - assert!(!a.gapless_enabled, "item 3: streaming-only ON forces gapless off"); + assert!( + !a.gapless_enabled, + "item 3: streaming-only ON forces gapless off" + ); } // ---- cascades §3.2.3 items 4-7 (backend switch) ---- @@ -956,7 +1408,10 @@ mod tests { a.output_device = Some("hw:CARD=D30,DEV=0".to_string()); a.backend = AudioBackendType::PipeWire; cascade_on_backend_change(&mut a); - assert_eq!(a.output_device, None, "item 7: stale device id must never survive"); + assert_eq!( + a.output_device, None, + "item 7: stale device id must never survive" + ); } // ---- constraint matrix §3.2.3 ---- @@ -986,9 +1441,15 @@ mod tests { let mut a = base(); a.backend = AudioBackendType::PipeWire; a.dac_passthrough = false; - assert!(!row_state(AField::ForceBp, &a).0, "hidden when passthrough off"); + assert!( + !row_state(AField::ForceBp, &a).0, + "hidden when passthrough off" + ); a.dac_passthrough = true; - assert!(row_state(AField::ForceBp, &a).0, "shown when passthrough on + PW"); + assert!( + row_state(AField::ForceBp, &a).0, + "shown when passthrough on + PW" + ); a.backend = AudioBackendType::Alsa; assert!(!row_state(AField::ForceBp, &a).0, "hidden off PW"); } @@ -1012,11 +1473,22 @@ mod tests { a.backend = AudioBackendType::Alsa; a.alsa_plugin = AlsaPlugin::Hw; assert!(row_state(AField::AlsaPlugin, &a).0); - assert!(row_state(AField::HwVolume, &a).0, "hw volume shown on ALSA hw"); + assert!( + row_state(AField::HwVolume, &a).0, + "hw volume shown on ALSA hw" + ); a.alsa_plugin = AlsaPlugin::PlugHw; - assert!(!row_state(AField::HwVolume, &a).0, "hw volume hidden off hw plugin"); + assert!( + row_state(AField::HwVolume, &a).0, + "hardware volume remains available on the direct plughw route" + ); + a.alsa_plugin = AlsaPlugin::Pcm; + assert!(!row_state(AField::HwVolume, &a).0, "hidden for named PCM"); a.backend = AudioBackendType::PipeWire; - assert!(!row_state(AField::AlsaPlugin, &a).0, "alsa plugin hidden off ALSA"); + assert!( + !row_state(AField::AlsaPlugin, &a).0, + "alsa plugin hidden off ALSA" + ); } #[test] @@ -1035,7 +1507,10 @@ mod tests { let devices = vec![dev("pw-node-1", "USB DAC", false, true)]; let rows = group_devices(AudioBackendType::PipeWire, devices); assert_eq!(rows[0].id, "", "System default leads"); - assert!(rows.iter().all(|r| r.header.is_none()), "no headers off ALSA"); + assert!( + rows.iter().all(|r| r.header.is_none()), + "no headers off ALSA" + ); assert!(rows[1].bp, "PipeWire hardware node is BP"); } @@ -1094,6 +1569,56 @@ mod tests { assert!(st.save_keys().is_empty(), "clean screen writes nothing"); st.staged.exclusive_mode = true; let keys = st.save_keys(); - assert_eq!(keys, vec![("audio.exclusive_mode".to_string(), "true".to_string())]); + assert_eq!( + keys, + vec![("audio.exclusive_mode".to_string(), "true".to_string())] + ); + } + + #[test] + fn ambiguous_probe_opens_a_closed_choice_without_staging_a_write() { + let mut state = alsa_screen(); + let probe = mixer_probe(vec![ + mixer_candidate("Master", 0), + mixer_candidate("PCM", 1), + ]); + let decision = + qbz_audio::alsa_hardware_volume::decide_hardware_volume(&probe, &HashMap::new()); + + state.set_hardware_volume_probe(Ok((probe, decision))); + + assert!(!state.staged.alsa_hardware_volume); + assert!(state.staged.alsa_hardware_volume_control.is_none()); + assert!(matches!(state.editor, Some(Editor::HardwareVolume(_)))); + assert!(state.save_keys().is_empty(), "probing alone must not write"); + } + + #[test] + fn unique_probe_stages_exact_identity_before_enabling() { + let mut state = alsa_screen(); + let expected = AlsaMixerControlId { + name: "D50 III".to_string(), + index: 7, + }; + let probe = mixer_probe(vec![mixer_candidate(&expected.name, expected.index)]); + let decision = + qbz_audio::alsa_hardware_volume::decide_hardware_volume(&probe, &HashMap::new()); + + state.set_hardware_volume_probe(Ok((probe, decision))); + + assert!(state.staged.alsa_hardware_volume); + assert_eq!( + state.staged.alsa_hardware_volume_control.as_ref(), + Some(&expected) + ); + assert_eq!( + state.staged.alsa_hardware_volume_controls.get(&route_key()), + Some(&expected) + ); + let keys = state.save_keys(); + assert_eq!(keys[0].0, "audio.alsa_hardware_volume_control"); + assert_eq!(keys[0].1, "D50 III,7"); + assert_eq!(keys[1].0, "audio.alsa_hardware_volume"); + assert_eq!(keys[1].1, "true"); } } diff --git a/crates/qbzd/src/tui/strings.rs b/crates/qbzd/src/tui/strings.rs index a5e06125c..1bdc15c20 100644 --- a/crates/qbzd/src/tui/strings.rs +++ b/crates/qbzd/src/tui/strings.rs @@ -160,6 +160,7 @@ pub const A_BACKEND: &str = "Backend"; pub const A_DEVICE: &str = "Output device"; pub const A_ALSA_PLUGIN: &str = "ALSA plugin"; pub const A_HW_VOLUME: &str = "Hardware volume"; +pub const A_HW_VOLUME_CONTROL: &str = "Mixer control"; pub const A_DSD: &str = "DSD playback"; pub const A_EXCLUSIVE: &str = "Exclusive mode"; pub const A_RESERVE: &str = "Reserve DAC";