diff --git a/src-tauri/src/audio/alsa_backend.rs b/src-tauri/src/audio/alsa_backend.rs index 097fce6c6..eff252c8e 100644 --- a/src-tauri/src/audio/alsa_backend.rs +++ b/src-tauri/src/audio/alsa_backend.rs @@ -1,22 +1,95 @@ //! ALSA audio backend (direct hardware access) //! -//! TODO: To be implemented by Copilot -//! - Direct ALSA access using alsa-rs crate -//! - Support for hw, plughw, pcm plugins -//! - True exclusive mode (blocks device) -//! - Bit-perfect playback +//! Provides direct access to ALSA hardware devices for: +//! - True exclusive mode (blocks device for other apps) +//! - Bit-perfect playback (no resampling) +//! - Low-latency audio output +//! +//! Uses CPAL's ALSA host with specific device selection. use super::backend::{AlsaPlugin, AudioBackend, AudioBackendType, AudioDevice, BackendConfig, BackendResult}; -use rodio::{OutputStream, OutputStreamHandle}; +use rodio::{ + cpal::{ + traits::{DeviceTrait, HostTrait}, + BufferSize, SampleFormat, SampleRate, StreamConfig, SupportedBufferSize, SupportedStreamConfig, + }, + OutputStream, OutputStreamHandle, +}; pub struct AlsaBackend { - // TODO: Add ALSA-specific fields + host: rodio::cpal::Host, } impl AlsaBackend { pub fn new() -> BackendResult { - // TODO: Initialize ALSA backend - Err("ALSA backend not yet implemented".to_string()) + // Try to get ALSA host + let available_hosts = rodio::cpal::available_hosts(); + + // Check if ALSA is available + if !available_hosts.iter().any(|h| h.name() == "ALSA") { + return Err("ALSA host not available on this system".to_string()); + } + + // Get ALSA host + let host = rodio::cpal::host_from_id( + available_hosts + .into_iter() + .find(|h| h.name() == "ALSA") + .ok_or("ALSA host not found".to_string())? + ).map_err(|e| format!("Failed to create ALSA host: {}", e))?; + + log::info!("[ALSA Backend] Initialized successfully"); + + Ok(Self { host }) + } + + /// Enumerate ALSA devices with hardware IDs + fn enumerate_alsa_devices(&self) -> BackendResult> { + let mut devices = Vec::new(); + + // Get all output devices from ALSA host + let output_devices = self.host + .output_devices() + .map_err(|e| format!("Failed to enumerate ALSA devices: {}", e))?; + + for (idx, device) in output_devices.enumerate() { + let name = device.name().unwrap_or_else(|_| format!("ALSA Device {}", idx)); + + // Try to get device ID (hardware name) + let id = name.clone(); + + // Check if this is the default device + let is_default = self.host + .default_output_device() + .and_then(|d| d.name().ok()) + .map(|default_name| default_name == name) + .unwrap_or(false); + + // Try to get max sample rate from supported configs + let max_sample_rate = device + .supported_output_configs() + .ok() + .and_then(|mut configs| { + configs + .max_by_key(|c| c.max_sample_rate().0) + .map(|c| c.max_sample_rate().0) + }); + + devices.push(AudioDevice { + id: id.clone(), + name: name.clone(), + description: Some(format!("ALSA device: {}", name)), + is_default, + max_sample_rate, + }); + } + + log::info!("[ALSA Backend] Enumerated {} devices", devices.len()); + for (idx, dev) in devices.iter().enumerate() { + log::info!(" [{}] {} (max_rate: {:?})", idx, dev.name, dev.max_sample_rate); + } + + Ok(devices) } } @@ -26,26 +99,121 @@ impl AudioBackend for AlsaBackend { } fn enumerate_devices(&self) -> BackendResult> { - // TODO: Enumerate ALSA devices - // Should return devices in format: hw:X,Y - Err("ALSA device enumeration not yet implemented".to_string()) + self.enumerate_alsa_devices() } fn create_output_stream( &self, - _config: &BackendConfig, + config: &BackendConfig, ) -> BackendResult<(OutputStream, OutputStreamHandle)> { - // TODO: Create ALSA stream - // Use alsa-rs to open device directly - Err("ALSA stream creation not yet implemented".to_string()) + log::info!( + "[ALSA Backend] Creating stream: {}Hz, {} channels, exclusive: {}, plugin: {:?}", + config.sample_rate, + config.channels, + config.exclusive_mode, + config.alsa_plugin + ); + + // Find the device by name/id + let device = if let Some(device_id) = &config.device_id { + log::info!("[ALSA Backend] Looking for device: {}", device_id); + self.host + .output_devices() + .map_err(|e| format!("Failed to enumerate devices: {}", e))? + .find(|d| { + d.name() + .ok() + .map(|n| n == *device_id) + .unwrap_or(false) + }) + .ok_or_else(|| format!("Device '{}' not found", device_id))? + } else { + log::info!("[ALSA Backend] Using default device"); + self.host + .default_output_device() + .ok_or("No default ALSA device available")? + }; + + let device_name = device.name().unwrap_or_else(|_| "unknown".to_string()); + log::info!("[ALSA Backend] Using device: {}", device_name); + + // Create StreamConfig with requested sample rate + let stream_config = StreamConfig { + channels: config.channels, + sample_rate: SampleRate(config.sample_rate), + buffer_size: if config.exclusive_mode { + // Smaller buffer for exclusive mode = lower latency + BufferSize::Fixed(512) + } else { + BufferSize::Default + }, + }; + + // Check if device supports this configuration + let supported_configs = device + .supported_output_configs() + .map_err(|e| format!("Failed to get supported configs: {}", e))?; + + let mut found_matching = false; + for range in supported_configs { + if range.channels() == config.channels + && config.sample_rate >= range.min_sample_rate().0 + && config.sample_rate <= range.max_sample_rate().0 + { + found_matching = true; + log::info!( + "[ALSA Backend] Device supports {}Hz (range: {}-{}Hz)", + config.sample_rate, + range.min_sample_rate().0, + range.max_sample_rate().0 + ); + break; + } + } + + if !found_matching { + log::warn!( + "[ALSA Backend] Device may not support {}Hz, attempting anyway", + config.sample_rate + ); + } + + // Create SupportedStreamConfig + let supported_config = SupportedStreamConfig::new( + stream_config.channels, + stream_config.sample_rate, + SupportedBufferSize::Range { min: 64, max: 8192 }, + SampleFormat::F32, + ); + + // Create OutputStream with custom config + let stream = OutputStream::try_from_device_config(&device, supported_config) + .map_err(|e| { + if config.exclusive_mode { + format!( + "Failed to create exclusive ALSA stream at {}Hz: {}. Device may be in use by another application.", + config.sample_rate, e + ) + } else { + format!("Failed to create ALSA stream at {}Hz: {}", config.sample_rate, e) + } + })?; + + log::info!( + "[ALSA Backend] ✓ Output stream created successfully at {}Hz (exclusive: {})", + config.sample_rate, + config.exclusive_mode + ); + + Ok(stream) } fn is_available(&self) -> bool { - // ALSA is always available on Linux - cfg!(target_os = "linux") + // Check if we can enumerate devices (ALSA is working) + self.host.output_devices().is_ok() } fn description(&self) -> &'static str { - "ALSA Direct - Bit-perfect with exclusive hardware access" + "ALSA Direct - Bit-perfect with optional exclusive hardware access" } } diff --git a/src/lib/components/Toggle.svelte b/src/lib/components/Toggle.svelte index 38fcba917..737cf36ca 100644 --- a/src/lib/components/Toggle.svelte +++ b/src/lib/components/Toggle.svelte @@ -2,17 +2,27 @@ interface Props { enabled: boolean; onchange: (enabled: boolean) => void; + disabled?: boolean; } - let { enabled, onchange }: Props = $props(); + let { enabled, onchange, disabled = false }: Props = $props(); + + function handleClick() { + if (!disabled) { + onchange(!enabled); + } + } @@ -35,6 +45,15 @@ background-color: var(--accent-primary); } + .toggle.disabled { + opacity: 0.4; + cursor: not-allowed; + } + + .toggle.disabled.enabled { + background-color: #555555; + } + .thumb { position: absolute; top: 2px; diff --git a/src/lib/components/views/SettingsView.svelte b/src/lib/components/views/SettingsView.svelte index a180132a0..4e6a1087a 100644 --- a/src/lib/components/views/SettingsView.svelte +++ b/src/lib/components/views/SettingsView.svelte @@ -226,6 +226,20 @@ // Show ALSA plugin selector only when ALSA backend is selected (derived) let showAlsaPluginSelector = $derived(selectedBackend === 'ALSA Direct'); + // Smart toggle states - auto-disable incompatible features + let exclusiveModeDisabled = $derived(selectedBackend === 'PipeWire' || selectedBackend === 'Auto'); + let exclusiveModeTooltipOverride = $derived( + exclusiveModeDisabled + ? 'Exclusive mode is only available with ALSA Direct backend. PipeWire is a multiplexed audio server and cannot provide true exclusive access.' + : null + ); + let gaplessDisabled = $derived(dacPassthrough); + let gaplessTooltipOverride = $derived( + gaplessDisabled + ? 'Gapless playback is disabled when DAC Passthrough is enabled. Bit-perfect audio requires recreating streams for each sample rate change.' + : null + ); + // Playback settings let gaplessPlayback = $state(true); let crossfade = $state(0); @@ -989,6 +1003,15 @@ const backend = availableBackends.find(b => b.name === backendName); const backendType = backendName === 'Auto' ? null : backend?.backend_type ?? null; + // Auto-disable incompatible features + if (backendName === 'PipeWire' || backendName === 'Auto') { + if (exclusiveMode) { + exclusiveMode = false; + await invoke('set_audio_exclusive_mode', { enabled: false }); + console.log('[Audio] Disabled exclusive mode (incompatible with PipeWire)'); + } + } + try { // Save backend preference await invoke('set_audio_backend_type', { backendType }); @@ -1385,9 +1408,9 @@
{$t('settings.audio.exclusiveMode')} - +
- +
@@ -1415,8 +1438,13 @@

{$t('settings.playback.title')}

- {$t('settings.playback.gapless')} - +
+ {$t('settings.playback.gapless')} + {#if gaplessTooltipOverride} + + {/if} +
+
{$t('settings.playback.crossfade')}