Implement ALSA hardware mixer volume control

Added set_hardware_volume() to AlsaDirectStream:
- Tries common mixer control names (Master, PCM, Speaker, Headphone, Digital)
- Returns error if DAC doesn't support mixer (doesn't break playback)
- Stores device_id in struct for mixer access

This enables bit-perfect volume control via DAC hardware when supported.
Falls back gracefully if not supported.
This commit is contained in:
vicrodh committed 2026-01-19 03:53:41 -06:00
1 parent 31798432cb
commit c87b41894d
1 file changed
+47
+47
View File
@@ -18,6 +18,7 @@ pub struct AlsaDirectStream {
sample_rate: u32, sample_rate: u32,
channels: u16, channels: u16,
format: Format, format: Format,
device_id: String,
} }
impl AlsaDirectStream { impl AlsaDirectStream {
@@ -111,6 +112,7 @@ impl AlsaDirectStream {
sample_rate, sample_rate,
channels, channels,
format: selected_format, format: selected_format,
device_id: device_id.to_string(),
}) })
} }
@@ -233,6 +235,51 @@ impl AlsaDirectStream {
self.channels self.channels
} }
/// Try to set hardware volume via ALSA mixer
///
/// Returns error if:
/// - DAC doesn't have mixer controls (common for USB DACs)
/// - Mixer API fails
///
/// NOTE: Failure doesn't break playback, just means volume can't be controlled.
#[cfg(target_os = "linux")]
pub fn set_hardware_volume(&self, volume: f32) -> Result<(), String> {
use alsa::mixer::{Mixer, SelemId};
use alsa::mixer::SelemChannelId::*;
// Open mixer for device
let mixer = Mixer::new(&self.device_id, false)
.map_err(|e| format!("Failed to open mixer for {}: {}", self.device_id, e))?;
// Try to find a volume control element
// Common names: "Master", "PCM", "Speaker", "Headphone"
let control_names = ["Master", "PCM", "Speaker", "Headphone", "Digital"];
for name in &control_names {
let selem_id = SelemId::new(name, 0);
if let Some(selem) = mixer.find_selem(&selem_id) {
// Check if this element has playback volume control
if selem.has_playback_volume() {
let (min, max) = selem.get_playback_volume_range();
let target = min + ((max - min) as f32 * volume) as i64;
log::info!("[ALSA Direct] Setting hardware volume via '{}': {:.0}% (raw: {}/{})",
name, volume * 100.0, target, max);
// Set volume on all channels
for channel in &[FrontLeft, FrontRight, FrontCenter, RearLeft, RearRight] {
let _ = selem.set_playback_volume(*channel, target);
}
return Ok(());
}
}
}
Err(format!("No volume control found for {}. DAC may not support hardware mixer.", self.device_id))
}
/// Check if device is hw: device /// Check if device is hw: device
pub fn is_hw_device(device_id: &str) -> bool { pub fn is_hw_device(device_id: &str) -> bool {
device_id.starts_with("hw:") || device_id.starts_with("plughw:") device_id.starts_with("hw:") || device_id.starts_with("plughw:")