diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index e64cd3f92..70d26d71a 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -67,6 +67,7 @@ lofty = "0.18" rusqlite = { version = "0.31", features = ["bundled"] } dirs = "5" filetime = "0.2" +glob = "0.3" # File dialogs - platform specific (see target dependencies below) diff --git a/src-tauri/src/commands/audio_diagnostics.rs b/src-tauri/src/commands/audio_diagnostics.rs new file mode 100644 index 000000000..eda0834cb --- /dev/null +++ b/src-tauri/src/commands/audio_diagnostics.rs @@ -0,0 +1,73 @@ +//! Audio diagnostics commands for detecting actual hardware sample rate + +use std::fs; + +/// Hardware audio status +#[derive(Debug, Clone, serde::Serialize)] +pub struct HardwareAudioStatus { + /// Actual sample rate being used by hardware (Hz) + pub hardware_sample_rate: Option, + /// Audio format (e.g., "S32_LE") + pub hardware_format: Option, + /// Whether hardware is currently active + pub is_active: bool, +} + +/// Get actual hardware audio status by reading /proc/asound +#[tauri::command] +pub fn get_hardware_audio_status() -> Result { + // Read all hw_params files from /proc/asound + let proc_pattern = "/proc/asound/card*/pcm*/sub*/hw_params"; + + // Use glob to find all matching files + let paths = glob::glob(proc_pattern) + .map_err(|e| format!("Failed to glob hw_params: {}", e))?; + + for path in paths.flatten() { + if let Ok(contents) = fs::read_to_string(&path) { + // Parse the hw_params file + let mut sample_rate: Option = None; + let mut format: Option = None; + + for line in contents.lines() { + let line = line.trim(); + + // Parse rate line: "rate: 192000 (192000/1)" + if line.starts_with("rate:") { + if let Some(rate_str) = line.split_whitespace().nth(1) { + sample_rate = rate_str.parse().ok(); + } + } + + // Parse format line: "format: S32_LE" + if line.starts_with("format:") { + if let Some(fmt) = line.split_whitespace().nth(1) { + format = Some(fmt.to_string()); + } + } + } + + // If we found both, return it + if sample_rate.is_some() { + log::info!( + "Hardware audio status: {}Hz, format: {:?}", + sample_rate.unwrap_or(0), + format + ); + + return Ok(HardwareAudioStatus { + hardware_sample_rate: sample_rate, + hardware_format: format, + is_active: true, + }); + } + } + } + + // No active hardware found + Ok(HardwareAudioStatus { + hardware_sample_rate: None, + hardware_format: None, + is_active: false, + }) +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 590c51015..1f289d206 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -2,6 +2,7 @@ //! //! Exposes backend functionality to the frontend via IPC +pub mod audio_diagnostics; pub mod auth; pub mod cache; pub mod favorites; @@ -14,6 +15,7 @@ pub mod queue; pub mod search; pub mod share; +pub use audio_diagnostics::*; pub use auth::*; pub use cache::*; pub use favorites::*; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2632f7cce..0668219ec 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -335,6 +335,7 @@ pub fn run() { commands::get_pipewire_sinks, commands::set_pipewire_default_sink, commands::reinit_audio_device, + commands::get_hardware_audio_status, // Queue commands commands::add_to_queue, commands::add_to_queue_next, diff --git a/src/lib/components/AudioOutputBadges.svelte b/src/lib/components/AudioOutputBadges.svelte index 1f3aeab64..4efc286be 100644 --- a/src/lib/components/AudioOutputBadges.svelte +++ b/src/lib/components/AudioOutputBadges.svelte @@ -2,6 +2,7 @@ import { invoke } from '@tauri-apps/api/core'; import { onMount } from 'svelte'; import { getDevicePrettyName, isExternalDevice } from '$lib/utils/audioDeviceNames'; + import { currentTrack } from '$lib/stores/playerStore'; interface AudioSettings { output_device: string | null; @@ -22,6 +23,12 @@ is_default: boolean; } + interface HardwareAudioStatus { + hardware_sample_rate: number | null; + hardware_format: string | null; + is_active: boolean; + } + // Props interface Props { showTooltips?: boolean; @@ -33,6 +40,7 @@ let settings = $state(null); let outputStatus = $state(null); let pipewireSinks = $state([]); + let hardwareStatus = $state(null); let isHovering = $state(false); // Derived state @@ -59,14 +67,63 @@ const isExternal = $derived(currentDevice ? isExternalDevice(currentDevice) : false); - // Badge states - based on settings - const dacPassthroughActive = $derived( - settings?.dac_passthrough === true - ); + // Get track sample rate from metadata + const trackSampleRate = $derived.by(() => { + if (!$currentTrack) return null; + return $currentTrack.sampling_rate ?? null; + }); + + // DAC badge state logic - 3 states: green, yellow, gray + const dacBadgeState = $derived.by(() => { + if (!settings?.dac_passthrough) { + return 'off'; // Gray - setting disabled + } + + // DAC passthrough is ON + if (!hardwareStatus?.is_active || !hardwareStatus.hardware_sample_rate) { + return 'active'; // Green - DAC on but no way to verify (trust it works) + } + + // We have hardware info - check for resampling + if (trackSampleRate && hardwareStatus.hardware_sample_rate) { + const hwRate = hardwareStatus.hardware_sample_rate; + const trackRate = trackSampleRate * 1000; // Convert kHz to Hz + + if (Math.abs(hwRate - trackRate) < 100) { + // Rates match (within 100Hz tolerance) + return 'active'; // Green - working correctly + } else { + // Rates don't match - resampling detected + return 'warning'; // Yellow - resampling despite DAC passthrough + } + } + + return 'active'; // Default to green when DAC is on + }); + const exclusiveModeActive = $derived( settings?.exclusive_mode === true ); + // Dynamic tooltip for DAC badge + const dacTooltip = $derived.by(() => { + if (!settings?.dac_passthrough) { + return 'DAC Passthrough desactivado - el sistema puede resamplear'; + } + + if (dacBadgeState === 'warning' && hardwareStatus?.hardware_sample_rate && trackSampleRate) { + const hwRate = (hardwareStatus.hardware_sample_rate / 1000).toFixed(1); + return `⚠ DAC Passthrough activo pero hay resampling\nArchivo: ${trackSampleRate} kHz → Hardware: ${hwRate} kHz`; + } + + if (hardwareStatus?.hardware_sample_rate) { + const hwRate = (hardwareStatus.hardware_sample_rate / 1000).toFixed(1); + return `DAC Passthrough activo - ${hwRate} kHz bit-perfect`; + } + + return 'DAC Passthrough activo'; + }); + // Whether to show badges at all (only if at least one setting is enabled or device is external) const shouldShowBadges = $derived( settings?.dac_passthrough || settings?.exclusive_mode || isExternal @@ -74,14 +131,16 @@ async function loadStatus() { try { - const [settingsResult, statusResult, sinksResult] = await Promise.all([ + const [settingsResult, statusResult, sinksResult, hwStatus] = await Promise.all([ invoke('get_audio_settings'), invoke('get_audio_output_status'), - invoke('get_pipewire_sinks').catch(() => [] as PipewireSink[]) + invoke('get_pipewire_sinks').catch(() => [] as PipewireSink[]), + invoke('get_hardware_audio_status').catch(() => null) ]); settings = settingsResult; outputStatus = statusResult; pipewireSinks = sinksResult; + hardwareStatus = hwStatus; } catch (err) { console.error('Failed to load audio status:', err); } @@ -100,9 +159,11 @@ >
DAC
@@ -158,14 +219,28 @@ color: rgba(255, 255, 255, 0.15); border: 1px solid rgba(255, 255, 255, 0.06); transition: all 200ms ease; + cursor: help; } + /* DAC Badge States */ .badge.active { background: rgba(34, 197, 94, 0.2); color: #22c55e; border-color: rgba(34, 197, 94, 0.4); } + .badge.warning { + background: rgba(234, 179, 8, 0.2); + color: #eab308; + border-color: rgba(234, 179, 8, 0.4); + } + + .badge.off { + background: transparent; + color: rgba(255, 255, 255, 0.15); + border-color: rgba(255, 255, 255, 0.06); + } + .badge-label { line-height: 1; } @@ -181,8 +256,9 @@ min-width: 180px; max-width: 300px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4); - z-index: 200; + z-index: 9999; animation: tooltip-appear 150ms ease; + pointer-events: none; } @keyframes tooltip-appear { diff --git a/src/lib/components/QualityBadge.svelte b/src/lib/components/QualityBadge.svelte index c9d47fc52..2b3f995b4 100644 --- a/src/lib/components/QualityBadge.svelte +++ b/src/lib/components/QualityBadge.svelte @@ -86,7 +86,7 @@ const isHiRes = $derived(tier === 'max' || tier === 'hires'); -
+
([]); + let hardwareStatus = $state(null); // Map of description -> sink name (for looking up sink name when user selects) const sinkDescriptionToName = $derived.by(() => { @@ -764,7 +771,12 @@ const sinks = await invoke('get_pipewire_sinks').catch(() => [] as PipewireSink[]); pipewireSinks = sinks; + // Load hardware audio status + const hwStatus = await invoke('get_hardware_audio_status').catch(() => null); + hardwareStatus = hwStatus; + console.log('[Audio] PipeWire sinks:', sinks.map(s => ({ name: s.name, desc: s.description }))); + console.log('[Audio] Hardware status:', hwStatus); } catch (err) { console.error('Failed to load audio devices:', err); } @@ -1161,7 +1173,16 @@
{$t('settings.audio.currentSampleRate')} - 192 kHz + + {#if hardwareStatus?.is_active && hardwareStatus.hardware_sample_rate} + {(hardwareStatus.hardware_sample_rate / 1000).toFixed(1)} kHz + {#if hardwareStatus.hardware_format} + ({hardwareStatus.hardware_format}) + {/if} + {:else} + {$t('settings.audio.noActivePlayback')} + {/if} +
@@ -1909,6 +1930,17 @@ color: var(--text-muted); } + .setting-value.muted { + opacity: 0.5; + font-style: italic; + } + + .format-detail { + font-size: 12px; + opacity: 0.7; + margin-left: 4px; + } + .label-with-tooltip { display: flex; align-items: center; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index a28cc4268..a6431e310 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -303,7 +303,8 @@ "exclusiveModeDesc": "Lock audio device for exclusive use", "dacPassthrough": "DAC Passthrough", "dacPassthroughDesc": "Bypass system mixer for bit-perfect output", - "currentSampleRate": "Current Sample Rate" + "currentSampleRate": "Current Sample Rate", + "noActivePlayback": "No active playback" }, "playback": { "title": "Playback", diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 7f5a1b646..0f813bd8c 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -303,7 +303,8 @@ "exclusiveModeDesc": "Bloquear dispositivo de audio para uso exclusivo", "dacPassthrough": "Passthrough DAC", "dacPassthroughDesc": "Bypass del mixer del sistema para salida bit-perfect", - "currentSampleRate": "Tasa de Muestreo Actual" + "currentSampleRate": "Tasa de Muestreo Actual", + "noActivePlayback": "Sin reproducción activa" }, "playback": { "title": "Reproducción",