diff --git a/src-tauri/src/commands/playback.rs b/src-tauri/src/commands/playback.rs index 1cc9824d1..66cd71856 100644 --- a/src-tauri/src/commands/playback.rs +++ b/src-tauri/src/commands/playback.rs @@ -392,8 +392,50 @@ pub fn get_playback_state(state: State<'_, AppState>) -> Result, // "USB", "PCI", "HDMI", etc. +} + +/// Get friendly device names from PipeWire/PulseAudio +#[cfg(target_os = "linux")] +fn get_pipewire_device_descriptions() -> std::collections::HashMap { + use std::process::Command; + + let mut map = std::collections::HashMap::new(); + + // Try pactl (PipeWire/PulseAudio) + if let Ok(output) = Command::new("pactl").args(&["list", "sinks"]).output() { + if let Ok(text) = String::from_utf8(output.stdout) { + let mut current_name: Option = None; + + for line in text.lines() { + let line = line.trim(); + + // Extract Name: field + if let Some(name) = line.strip_prefix("Name: ") { + current_name = Some(name.to_string()); + } + + // Extract Description: field + if let Some(desc) = line.strip_prefix("Description: ") { + if let Some(name) = ¤t_name { + map.insert(name.clone(), desc.to_string()); + log::debug!("Device mapping: {} -> {}", name, desc); + } + } + } + } + } + + log::info!("Found {} device descriptions from PipeWire/PulseAudio", map.len()); + map +} + +#[cfg(not(target_os = "linux"))] +fn get_pipewire_device_descriptions() -> std::collections::HashMap { + std::collections::HashMap::new() } /// Get available audio output devices @@ -409,13 +451,56 @@ pub fn get_audio_devices() -> Result, String> { .default_output_device() .and_then(|d| d.name().ok()); + // Get friendly names from PipeWire/PulseAudio + let friendly_names = get_pipewire_device_descriptions(); + let devices: Vec = host .output_devices() .map_err(|e| format!("Failed to enumerate devices: {}", e))? .filter_map(|device| { device.name().ok().map(|name| { let is_default = default_device_name.as_ref().map(|d| d == &name).unwrap_or(false); - AudioDevice { name, is_default } + + // Try to get friendly name from PipeWire/PulseAudio + let display_name = friendly_names + .get(&name) + .cloned() + .unwrap_or_else(|| { + // Fallback: clean up technical name slightly + name.replace("alsa_output.", "") + .replace("_", " ") + .replace("pro-output", "") + .trim() + .to_string() + }); + + // Detect device type from technical name + let device_type = if name.contains("usb") || name.contains("USB") { + Some("USB".to_string()) + } else if name.contains("hdmi") || name.contains("HDMI") { + Some("HDMI".to_string()) + } else if name.contains("pci") || name.contains("PCI") { + Some("PCI".to_string()) + } else if name.contains("bluetooth") || name.contains("bluez") { + Some("Bluetooth".to_string()) + } else { + None + }; + + log::debug!( + "Device: {} -> {} (type: {:?}, default: {})", + name, + display_name, + device_type, + is_default + ); + + AudioDevice { + name, + display_name, + is_default, + device_type, + } }) }) .collect(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc459406c..28652767d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -52,10 +52,17 @@ pub struct AppState { impl AppState { pub fn new() -> Self { - Self::with_device(None) + Self::with_device_and_settings(None, config::audio_settings::AudioSettings::default()) } pub fn with_device(device_name: Option) -> Self { + Self::with_device_and_settings(device_name, config::audio_settings::AudioSettings::default()) + } + + pub fn with_device_and_settings( + device_name: Option, + audio_settings: config::audio_settings::AudioSettings, + ) -> Self { // Create playback cache (L2 - disk, 500MB) let playback_cache = match PlaybackCache::new(500 * 1024 * 1024) { Ok(cache) => Some(Arc::new(cache)), @@ -74,7 +81,7 @@ impl AppState { Self { client: Arc::new(Mutex::new(QobuzClient::default())), - player: Player::new(device_name), + player: Player::new(device_name, audio_settings), queue: QueueManager::new(), media_controls: MediaControlsManager::new(), audio_cache, @@ -164,23 +171,36 @@ pub fn run() { let offline_state = offline::OfflineState::new() .expect("Failed to initialize offline state"); - // Read saved audio device setting for player initialization - let saved_device = audio_settings_state + // Read saved audio device and settings for player initialization + let (saved_device, audio_settings) = audio_settings_state .store .lock() .ok() - .and_then(|store| store.get_settings().ok()) - .and_then(|settings| settings.output_device); + .and_then(|store| { + store.get_settings().ok().map(|settings| { + (settings.output_device.clone(), settings) + }) + }) + .unwrap_or_else(|| { + log::info!("No saved audio settings found, using defaults"); + (None, config::audio_settings::AudioSettings::default()) + }); if let Some(ref device) = saved_device { log::info!("Initializing player with saved device: {}", device); } + log::info!( + "Audio settings: exclusive_mode={}, dac_passthrough={}, sample_rate={:?}", + audio_settings.exclusive_mode, + audio_settings.dac_passthrough, + audio_settings.preferred_sample_rate + ); tauri::Builder::default() .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_clipboard_manager::init()) - .manage(AppState::with_device(saved_device)) + .manage(AppState::with_device_and_settings(saved_device, audio_settings)) .setup(|app| { // Initialize system tray icon if let Err(e) = tray::init_tray(app.handle()) { diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 2307ae239..bffe33eae 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,6 +1,26 @@ // Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +#[cfg(target_os = "linux")] +fn is_nvidia_gpu() -> bool { + // Method 1: Check for NVIDIA driver via /proc + if std::path::Path::new("/proc/driver/nvidia/version").exists() { + return true; + } + + // Method 2: Check for loaded NVIDIA kernel modules + if let Ok(modules) = std::fs::read_to_string("/proc/modules") { + if modules.lines().any(|line| line.starts_with("nvidia")) { + return true; + } + } + + // Method 3: Check for NVIDIA devices in lspci output (requires external command) + // Skip this for now to avoid external dependencies + + false +} + fn main() { // Use xdg-desktop-portal for file dialogs on Linux // This makes GTK apps use native file pickers (e.g., KDE's on Plasma) @@ -20,5 +40,70 @@ fn main() { } } + // Wayland and WebKit compatibility fixes for Linux + // Addresses: https://github.com/vicrodh/qbz/issues/6 + // + // NVIDIA GPUs have known issues with WebKit's DMA-BUF renderer on Wayland, + // causing fatal protocol errors (Error 71) that cannot be recovered from. + // This must be mitigated BEFORE the WebView is initialized. + #[cfg(target_os = "linux")] + { + let is_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").as_deref() == Ok("wayland"); + let has_nvidia = is_nvidia_gpu(); + + // User overrides - these ALWAYS take precedence + let force_dmabuf = std::env::var("QBZ_FORCE_DMABUF").as_deref() == Ok("1"); + let disable_dmabuf = std::env::var("QBZ_DISABLE_DMABUF").as_deref() == Ok("1"); + let force_x11 = std::env::var("QBZ_FORCE_X11").as_deref() == Ok("1"); + + // Diagnostic logging for transparency and support + eprintln!("[QBZ] Display server: {}", if is_wayland { "Wayland" } else { "X11" }); + if has_nvidia { + eprintln!("[QBZ] NVIDIA GPU detected"); + } + + // Handle user overrides first + if force_x11 && is_wayland { + eprintln!("[QBZ] User override: Forcing X11 backend (QBZ_FORCE_X11=1)"); + std::env::set_var("GDK_BACKEND", "x11"); + } else if is_wayland && std::env::var_os("GDK_BACKEND").is_none() { + // Force Wayland backend to avoid fallback issues + std::env::set_var("GDK_BACKEND", "wayland"); + + // Disable WebKit's compositing mode which can cause protocol errors + // with transparent windows on Wayland + std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1"); + + // Prefer client-side decorations (we use custom titlebar anyway) + std::env::set_var("GTK_CSD", "1"); + } + + // DMA-BUF renderer control (the critical NVIDIA fix) + if force_dmabuf { + eprintln!("[QBZ] User override: Forcing DMA-BUF renderer enabled (QBZ_FORCE_DMABUF=1)"); + eprintln!("[QBZ] Warning: This may cause crashes on NVIDIA + Wayland"); + // Do NOT set WEBKIT_DISABLE_DMABUF_RENDERER + } else if disable_dmabuf { + eprintln!("[QBZ] User override: Forcing DMA-BUF renderer disabled (QBZ_DISABLE_DMABUF=1)"); + std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); + } else if is_wayland && has_nvidia { + // Automatic mitigation: NVIDIA + Wayland = known issue + eprintln!("[QBZ] Applying NVIDIA + Wayland workaround: disabling WebKit DMA-BUF renderer"); + eprintln!("[QBZ] This prevents fatal protocol errors on NVIDIA GPUs"); + eprintln!("[QBZ] To override: set QBZ_FORCE_DMABUF=1 (not recommended)"); + std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); + } else if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() { + // Non-NVIDIA systems: keep default behavior unless already set + // This ensures Intel/AMD systems maintain full hardware acceleration + if has_nvidia { + eprintln!("[QBZ] NVIDIA GPU on X11: applying DMA-BUF workaround for compatibility"); + std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); + } else { + eprintln!("[QBZ] Non-NVIDIA GPU: using default WebKit renderer (hardware accelerated)"); + } + } + } + qbz_nix_lib::run() } diff --git a/src-tauri/src/player/mod.rs b/src-tauri/src/player/mod.rs index 4e537ebc3..68318f0f2 100644 --- a/src-tauri/src/player/mod.rs +++ b/src-tauri/src/player/mod.rs @@ -13,13 +13,14 @@ use std::io::{BufReader, Cursor, Read, Seek, SeekFrom}; use std::panic::{self, AssertUnwindSafe}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{self, Sender, RecvTimeoutError}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use rodio::{Decoder, OutputStream, Sink, Source}; use rodio::buffer::SamplesBuffer; use rodio::decoder::Mp4Type; use rodio::cpal::traits::{DeviceTrait, HostTrait}; +use rodio::cpal::{StreamConfig, SampleRate, BufferSize, SupportedStreamConfig, SupportedBufferSize, SampleFormat}; use symphonia::core::audio::SampleBuffer; use symphonia::core::codecs::DecoderOptions; use symphonia::core::errors::Error as SymphoniaError; @@ -30,11 +31,18 @@ use symphonia::core::probe::Hint; use symphonia::default::{get_codecs, get_probe}; use crate::api::{client::QobuzClient, models::Quality}; +use crate::config::audio_settings::AudioSettings; /// Commands sent to the audio thread enum AudioCommand { - /// Play audio data with track ID and duration - Play { data: Vec, track_id: u64, duration_secs: u64 }, + /// Play audio data with track ID, duration, and audio specs + Play { + data: Vec, + track_id: u64, + duration_secs: u64, + sample_rate: u32, + channels: u16, + }, /// Pause playback Pause, /// Resume playback @@ -83,7 +91,14 @@ impl Seek for CursorMediaSource { } } -fn decode_with_symphonia(data: &[u8]) -> Result, String> { +/// Audio specifications extracted from decoded audio +struct AudioSpecs { + samples: SamplesBuffer, + sample_rate: u32, + channels: u16, +} + +fn decode_with_symphonia(data: &[u8]) -> Result { let source = Box::new(CursorMediaSource::new(data.to_vec())) as Box; let mss = MediaSourceStream::new(source, Default::default()); @@ -150,7 +165,11 @@ fn decode_with_symphonia(data: &[u8]) -> Result, String> { return Err("Symphonia decode produced no audio".to_string()); } - Ok(SamplesBuffer::new(channels, sample_rate, samples)) + Ok(AudioSpecs { + samples: SamplesBuffer::new(channels, sample_rate, samples), + sample_rate, + channels, + }) } fn is_isomp4(data: &[u8]) -> bool { @@ -166,9 +185,9 @@ fn decode_with_fallback( ) -> Result + Send>, String> { if is_isomp4(data) { return decode_with_symphonia(data) - .map(|buffer| { + .map(|specs| { log::info!("Decoded audio using symphonia fallback (isomp4)"); - Box::new(buffer) as Box + Send> + Box::new(specs.samples) as Box + Send> }); } @@ -208,14 +227,89 @@ fn decode_with_fallback( } match decode_with_symphonia(data) { - Ok(buffer) => { + Ok(specs) => { log::info!("Decoded audio using symphonia fallback"); - Ok(Box::new(buffer)) + Ok(Box::new(specs.samples)) } Err(err) => Err(err), } } +/// Create OutputStream with custom sample rate configuration +fn create_output_stream_with_config( + device: &rodio::cpal::Device, + sample_rate: u32, + channels: u16, + exclusive_mode: bool, +) -> Result<(OutputStream, rodio::OutputStreamHandle), String> { + log::info!( + "Creating OutputStream: {}Hz, {} channels, exclusive: {}", + sample_rate, + channels, + exclusive_mode + ); + + // Create StreamConfig with desired sample rate + let config = StreamConfig { + channels, + sample_rate: SampleRate(sample_rate), + buffer_size: if exclusive_mode { + BufferSize::Fixed(512) // Lower latency for exclusive mode + } 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() == channels + && sample_rate >= range.min_sample_rate().0 + && sample_rate <= range.max_sample_rate().0 + { + found_matching = true; + log::info!( + "Device supports {}Hz (range: {}-{}Hz)", + sample_rate, + range.min_sample_rate().0, + range.max_sample_rate().0 + ); + break; + } + } + + if !found_matching { + log::warn!( + "Device may not support {}Hz, attempting anyway", + sample_rate + ); + } + + // Create SupportedStreamConfig + let supported_config = SupportedStreamConfig::new( + config.channels, + config.sample_rate, + SupportedBufferSize::Range { min: 64, max: 8192 }, + SampleFormat::F32, + ); + + // Create OutputStream with custom config + match OutputStream::try_from_device_config(device, supported_config) { + Ok((stream, handle)) => { + log::info!("✅ OutputStream created successfully at {}Hz", sample_rate); + Ok((stream, handle)) + } + Err(e) => { + log::error!("❌ Failed to create OutputStream at {}Hz: {}", sample_rate, e); + Err(format!("Failed to create output stream: {}", e)) + } + } +} + /// Event payload for playback state updates #[derive(Debug, Clone, serde::Serialize)] pub struct PlaybackEvent { @@ -358,22 +452,28 @@ pub struct Player { tx: Sender, /// Shared state accessible from any thread pub state: SharedState, + /// Audio settings (exclusive mode, DAC passthrough, etc.) + audio_settings: Arc>, } impl Default for Player { fn default() -> Self { - Self::new(None) + Self::new(None, AudioSettings::default()) } } impl Player { - /// Create a new player with an optional specific output device + /// Create a new player with an optional specific output device and audio settings /// If device_name is None, uses the system default device - pub fn new(device_name: Option) -> Self { + pub fn new(device_name: Option, audio_settings: AudioSettings) -> Self { let (tx, rx) = mpsc::channel::(); let state = SharedState::new(); let thread_state = state.clone(); + // Clone settings for thread + let settings = Arc::new(Mutex::new(audio_settings.clone())); + let thread_settings = settings.clone(); + // Spawn dedicated audio thread thread::spawn(move || { log::info!("Audio thread starting..."); @@ -457,6 +557,8 @@ impl Player { // Initialize audio device lazily on first playback to avoid idle CPU usage. let mut current_device_name = device_name.clone(); let mut stream_opt: Option<(OutputStream, rodio::OutputStreamHandle)> = None; + let mut current_sample_rate: Option = None; + let mut current_channels: Option = None; const MAX_INIT_RETRIES: u32 = 5; const RETRY_DELAY_MS: u64 = 500; @@ -480,39 +582,120 @@ impl Player { stream_opt: &mut Option<(OutputStream, rodio::OutputStreamHandle)>, current_device_name: &mut Option, consecutive_sink_failures: &mut u32, - pause_suspend_deadline: &mut Option| { + pause_suspend_deadline: &mut Option, + current_sample_rate: &mut Option, + current_channels: &mut Option| { match command { - AudioCommand::Play { data, track_id, duration_secs } => { - log::info!("Audio thread: playing track {}", track_id); + AudioCommand::Play { data, track_id, duration_secs, sample_rate, channels } => { + log::info!( + "Audio thread: playing track {} ({}Hz, {} channels)", + track_id, + sample_rate, + channels + ); *pause_suspend_deadline = None; - if stream_opt.is_none() { - for attempt in 1..=MAX_INIT_RETRIES { + // Check if we need to recreate the stream + let needs_new_stream = stream_opt.is_none() + || *current_sample_rate != Some(sample_rate) + || *current_channels != Some(channels); + + if needs_new_stream { + if stream_opt.is_some() { log::info!( - "Audio device init on playback attempt {}/{}", - attempt, - MAX_INIT_RETRIES + "Sample rate changed from {:?}Hz to {}Hz - recreating OutputStream", + *current_sample_rate, + sample_rate ); - *stream_opt = init_device(current_device_name, &thread_state); - if stream_opt.is_some() { - thread_state.set_stream_error(false); - break; - } - if attempt < MAX_INIT_RETRIES { - log::warn!( - "Audio init failed, retrying in {}ms...", - RETRY_DELAY_MS - ); - std::thread::sleep(Duration::from_millis(RETRY_DELAY_MS)); - } + // Drop old stream + drop(stream_opt.take()); } - if stream_opt.is_none() { - log::error!( - "Failed to initialize audio after {} attempts.", - MAX_INIT_RETRIES - ); + + // Get audio settings (exclusive mode / DAC passthrough) + let dac_passthrough = thread_settings + .lock() + .ok() + .map(|s| s.dac_passthrough) + .unwrap_or(false); + + log::info!("DAC passthrough enabled: {}", dac_passthrough); + + // Get the audio device + let device = if let Some(ref name) = *current_device_name { + log::info!("Looking for audio device: {}", name); + let found = host.output_devices() + .ok() + .and_then(|mut devices| { + devices.find(|d| d.name().ok().as_ref() == Some(name)) + }); + + match found { + Some(d) if is_device_valid(&d) => { + log::info!("Found and validated device: {}", name); + Some(d) + } + Some(_) => { + log::warn!("Device '{}' found but has no valid output configs, using default", name); + host.default_output_device() + } + None => { + log::warn!("Device '{}' not found, using default", name); + host.default_output_device() + } + } + } else { + log::info!("Using default audio device"); + host.default_output_device() + }; + + let Some(device) = device else { + log::error!("No audio output device available"); + thread_state.set_current_device(None); thread_state.set_stream_error(true); return; + }; + + // Set current device name + if let Ok(name) = device.name() { + log::info!("Using audio device: {}", name); + thread_state.set_current_device(Some(name)); + } + + // Create OutputStream with custom sample rate + match create_output_stream_with_config( + &device, + sample_rate, + channels, + dac_passthrough, + ) { + Ok(stream) => { + *stream_opt = Some(stream); + *current_sample_rate = Some(sample_rate); + *current_channels = Some(channels); + thread_state.set_stream_error(false); + log::info!("✅ Audio stream ready at {}Hz", sample_rate); + } + Err(e) => { + log::error!("❌ Failed to create stream at {}Hz: {}", sample_rate, e); + log::warn!("Attempting fallback to default device config..."); + + // Try fallback to default config + match OutputStream::try_from_device(&device) { + Ok(stream) => { + log::warn!("Using default device config as fallback"); + *stream_opt = Some(stream); + *current_sample_rate = Some(sample_rate); + *current_channels = Some(channels); + thread_state.set_stream_error(false); + } + Err(e2) => { + log::error!("Fallback also failed: {}", e2); + thread_state.set_stream_error(true); + thread_state.set_current_device(None); + return; + } + } + } } } @@ -796,6 +979,8 @@ impl Player { &mut current_device_name, &mut consecutive_sink_failures, &mut pause_suspend_deadline, + &mut current_sample_rate, + &mut current_channels, ), Err(RecvTimeoutError::Timeout) => { let now = Instant::now(); @@ -844,6 +1029,8 @@ impl Player { &mut current_device_name, &mut consecutive_sink_failures, &mut pause_suspend_deadline, + &mut current_sample_rate, + &mut current_channels, ), Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => { @@ -865,6 +1052,8 @@ impl Player { &mut current_device_name, &mut consecutive_sink_failures, &mut pause_suspend_deadline, + &mut current_sample_rate, + &mut current_channels, ), Err(_) => { log::info!("Audio thread: channel closed, exiting"); @@ -875,7 +1064,7 @@ impl Player { } }); - Self { tx, state } + Self { tx, state, audio_settings: settings } } /// Play a track by ID (downloads audio) @@ -915,11 +1104,27 @@ impl Player { pub fn play_data(&self, data: Vec, track_id: u64) -> Result<(), String> { log::info!("Player: Playing {} bytes of audio data for track {}", data.len(), track_id); + // Extract audio metadata (sample rate and channels) + // We decode to get metadata, then the audio thread will decode again for playback + let audio_specs = decode_with_symphonia(&data) + .map_err(|e| format!("Failed to extract audio metadata: {}", e))?; + + let sample_rate = audio_specs.sample_rate; + let channels = audio_specs.channels; + + log::info!( + "Player: Detected audio format - {}Hz, {} channels", + sample_rate, + channels + ); + self.tx .send(AudioCommand::Play { data, track_id, duration_secs: 0, // Will be determined by decoder + sample_rate, + channels, }) .map_err(|e| { log::error!("Player: Failed to send to audio thread: {}", e);