merge: ALSA hardware volume hardening

cx
This commit is contained in:
vicrodh committed 2026-08-30 09:14:57 -06:00
commit c059c12bf3
35 files changed
+5581 -460

No files matched your search

+1
View File
@@ -4066,6 +4066,7 @@ dependencies = [
"dirs 6.0.0",
"ebur128",
"jack",
"libc",
"log",
"objc2-core-audio",
"qbz-models",
+18
View File
@@ -28,6 +28,14 @@ pub struct RuntimeDiagnostics {
pub audio_preferred_sample_rate: Option<u32>,
pub audio_alsa_plugin: Option<String>,
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<qbz_audio::alsa_hardware_volume::HardwareVolumeProbe>,
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,
+1
View File
@@ -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,
+21 -2
View File
@@ -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(&current.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))?,
@@ -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::<qbz_audio::alsa_hardware_volume::StableAlsaRouteKey>(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.
+1
View File
@@ -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.
+43 -200
View File
@@ -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<alsa::mixer::Mixer, String> {
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::<Vec<_>>();
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::<Vec<_>>()
.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<HardwareVolumeInfo, String> {
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<HardwareVolumeInfo, String> {
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::<Vec<_>>()
.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=<name>` when a `CARD=` argument is
/// present, to `hw:<n>` 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::<u32>().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)
}
}
File diff suppressed because it is too large. Load diff
+11 -1
View File
@@ -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())
}
}
+1
View File
@@ -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)]
+201 -2
View File
@@ -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<AudioBackendType>, // None = auto-detect
pub alsa_plugin: Option<AlsaPlugin>, // 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<StableAlsaRouteKey, AlsaMixerControlId>,
/// 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<AlsaMixerControlId> {
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<AudioSettings, String> {
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<String>>(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<i64>>(6)?.unwrap_or(0) != 0,
alsa_hardware_volume_controls,
stream_first_track: row.get::<_, Option<i64>>(7)?.unwrap_or(0) != 0,
stream_buffer_seconds: row.get::<_, Option<i64>>(8)?.unwrap_or(3) as u8,
streaming_only: row.get::<_, Option<i64>>(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<StableAlsaRouteKey, AlsaMixerControlId>,
) -> 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);
}
}
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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 "ミキサーコントロールを変更"
@@ -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"
@@ -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"
@@ -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 "Изменить регулятор микшера"
+191 -27
View File
@@ -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<Mutex<AudioSettings>>,
) -> Option<qbz_audio::alsa_hardware_volume::AlsaMixerControlId> {
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<Mutex<AudioSettings>>,
state: &SharedState,
) -> (
Option<qbz_audio::alsa_hardware_volume::AlsaMixerControlId>,
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<u32>,
/// 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<AtomicU32>,
/// Session state, separate from the persisted preference. Any control
/// failure flips this off while direct samples remain at unity.
hardware_volume_active: Arc<AtomicBool>,
/// Playback start time (Unix timestamp millis when started/resumed)
playback_start_millis: Arc<AtomicU64>,
/// 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<String>,
}
#[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<i32> {
+62 -21
View File
@@ -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<thread::JoinHandle<()>>,
/// Signals that the writer thread has consumed a source and moved to next
source_transition: Arc<AtomicBool>,
hardware_volume: bool,
hardware_volume_control: Option<AlsaMixerControlId>,
hardware_volume_active: Arc<AtomicBool>,
hardware_volume_events: HardwareVolumeEventCallback,
_hardware_volume_subscription: Option<HardwareVolumeEventSubscription>,
},
/// 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<dyn qbz_audio::backend::DirectSink>,
hardware_volume: bool,
hardware_volume_control: Option<AlsaMixerControlId>,
visualizer_tap: Option<VisualizerTap>,
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 {
+39 -10
View File
@@ -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
@@ -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
+23
View File
@@ -706,6 +706,26 @@ fn build_system_rows(
fn build_audio_rows(g: &Gathered) -> Vec<Row> {
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> {
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,
+14
View File
@@ -3211,6 +3211,10 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
// 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<AppRuntime<LoggingAdapter>>) {
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,
+749 -31
View File
@@ -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<String>,
route_key: Option<StableAlsaRouteKey>,
candidates: Vec<HardwareVolumeCandidate>,
selected: Option<AlsaMixerControlId>,
status: HardwareVolumeUiStatus,
}
#[derive(Default)]
struct HardwareVolumeUiSnapshot {
options: Vec<HardwareVolumeOption>,
selected_index: i32,
selected: String,
status: &'static str,
message: String,
can_change: bool,
choice_token: String,
}
static HARDWARE_VOLUME_UI: Mutex<HardwareVolumeUiState> = 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::<Vec<_>>();
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::<Vec<_>>()
.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<HardwareVolumeOption>,
#[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<String>,
#[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<qbz_audio::alsa_direct::HardwareVolumeInfo, String> {
) -> 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<AppRuntime<LoggingAdapter>>,
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<String>, 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<AlsaMixerControlId>,
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<qbz_audio::settings::AudioSettings, String> {
let current = with_audio(|store| store.get_settings())?;
if !qbz_audio::alsa_direct::uses_alsa_direct_route(&current)
|| 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<HardwareVolumeSnapshot, String> {
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<AppRuntime<LoggingAdapter>>,
device_id: String,
probe: HardwareVolumeProbe,
selection: HardwareVolumeSelection,
) -> Result<Apply, String> {
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<AppRuntime<LoggingAdapter>>,
enabled: bool,
) -> Result<Apply, String> {
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<AppRuntime<LoggingAdapter>>, 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<AppRuntime<LoggingAdapter>>, key: &str,
}
}
async fn select_alsa_hardware_volume_control(
runtime: &Arc<AppRuntime<LoggingAdapter>>,
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<AppRuntime<LoggingAdapter>>, 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<AppRuntime<LoggingAdapter>>) {
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<String> = 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();
+1
View File
@@ -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),
+16
View File
@@ -45,6 +45,9 @@ pub struct AudioStatus {
pub bit_perfect: Option<String>,
pub sample_rate: Option<u32>,
pub bit_depth: Option<u32>,
pub hardware_volume_enabled: bool,
pub hardware_volume_active: bool,
pub hardware_volume_control: Option<String>,
}
#[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(),
+505 -56
View File
@@ -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<AlsaPlugin>) -> 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<Option<AlsaMixerControlId>, 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::<u32>().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<AlsaPlugin>) -> String {
/// must work with no device attached to check against).
fn parse_output_device(v: &str) -> Option<String> {
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<Option<u32>, String> {
if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("none") {
return Ok(None);
}
trimmed
.parse::<u32>()
.map(Some)
.map_err(|_| format!("invalid sample rate '{trimmed}' — expected a Hz integer (e.g. 192000) or none"))
trimmed.parse::<u32>().map(Some).map_err(|_| {
format!("invalid sample rate '{trimmed}' — expected a Hz integer (e.g. 192000) or none")
})
}
fn render_opt_u32(v: Option<u32>) -> 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<String, String> {
@@ -329,6 +372,7 @@ fn read_all(roots: &ProfileRoots) -> Result<Vec<(&'static str, String)>, 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::<Vec<_>>();
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<ApplyClass, SetError> {
pub(crate) fn write_one(
roots: &ProfileRoots,
key: &str,
raw: &str,
) -> Result<ApplyClass, SetError> {
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<Ap
}
"audio.alsa_plugin" => {
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<Ap
}
"audio.dsd_mode" => {
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<Ap
}
"audio.streaming_only" => {
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<Ap
}
"audio.gapless_enabled" => {
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<Ap
}
"playback.autoplay" => {
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<Ap
.set_show_context_icon(v)
.map_err(SetError::Io)?
}
"qconnect.device_name" => {
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::<Vec<_>>();
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::<Vec<_>>();
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 <KEY> <VALUE>` (⬇). 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<String> = 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<AudioBackendType> = 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());
}
+21 -1
View File
@@ -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}");
+100 -3
View File
@@ -334,6 +334,79 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> 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<f32>), 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<BootedRuntime, String> {
// 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");
+3
View File
@@ -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,
+269 -57
View File
@@ -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<Vec<AudioDevice>, String>),
Saved { lines: Vec<String>, status: Option<Value>, reachable: bool, success: bool },
HardwareVolume {
device_id: String,
result: Result<(HardwareVolumeProbe, HardwareVolumeDecision), String>,
},
Saved {
lines: Vec<String>,
status: Option<Value>,
reachable: bool,
success: bool,
},
TokenLogin(Result<(String, Option<String>), String>),
ImportPlanned(Result<Box<PendingImport>, String>),
ImportApplied { lines: Vec<String>, status: Option<Value>, reachable: bool },
ImportApplied {
lines: Vec<String>,
status: Option<Value>,
reachable: bool,
},
Exported(Result<Vec<String>, 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<String> },
DirtyLeave { target: LeaveTarget },
Result {
title: String,
lines: Vec<String>,
},
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<String
// The TUI only displays the message — it doesn't need the
// Usage/Io exit-code split `settings set` maps to (see
// `cli::settings::SetError`).
return (Some(format!("failed to save {k}: {}", e.to_string().trim())), reinit);
return (
Some(format!("failed to save {k}: {}", e.to_string().trim())),
reinit,
);
}
}
}
(None, reinit)
}
fn save_network(roots: &ProfileRoots, bind: &str, port: u16, token: Option<&str>) -> Option<String> {
fn save_network(
roots: &ProfileRoots,
bind: &str,
port: u16,
token: Option<&str>,
) -> Option<String> {
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<Vec<String>, String> {
fn export_bundle(
roots: &ProfileRoots,
dest: &str,
include_auth: bool,
) -> Result<Vec<String>, 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<AudioDevice>) {
let backends: Vec<String> = 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<AudioBackendType> = bundle
.domains
@@ -1584,10 +1742,15 @@ fn build_live(bundle: &Bundle) -> (LiveSystem, AudioBackendType, Vec<AudioDevice
.and_then(|v| serde_json::from_value(v.clone()).ok());
let backend = wanted.unwrap_or(AudioBackendType::SystemDefault);
let devices = enumerate_devices(backend).unwrap_or_default();
let live_devices: Vec<(String, String)> =
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<String> {
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.
+574 -49
View File
@@ -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<String>,
pub alsa_plugin: AlsaPlugin,
pub alsa_hardware_volume: bool,
pub alsa_hardware_volume_control: Option<AlsaMixerControlId>,
pub alsa_hardware_volume_controls: HashMap<StableAlsaRouteKey, AlsaMixerControlId>,
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<AField> {
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<DeviceEntry>,
scanning: bool,
hardware_volume_candidates: Vec<HardwareVolumeCandidate>,
hardware_volume_route_key: Option<StableAlsaRouteKey>,
hardware_volume_status: Option<String>,
hardware_volume_probing: bool,
probe_for_control_change: bool,
editor: Option<Editor>,
}
@@ -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<StableAlsaRouteKey, AlsaMixerControlId>), 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<String> = 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<String> = 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<Option<String>> = 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::<Vec<_>>();
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<widgets::Section> = Vec::new();
let mut anchor: Option<widgets::FocusAnchor> = 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<Line<'static>> {
fn field_block(
&self,
field: AField,
focus_pos: usize,
ctrl_col: u16,
width: u16,
) -> Vec<Line<'static>> {
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<HardwareVolumeCandidate>) -> 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");
}
}
+1
View File
@@ -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";