From 63d3e8c0430f883fd78959673bd97847d345f1e4 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 19 Jan 2026 02:51:48 -0600 Subject: [PATCH] WIP: Add PlaybackEngine abstraction and StreamType enum - Create playback_engine.rs module wrapping Sink and AlsaDirectStream - Add StreamType enum (Rodio or AlsaDirect) - Modify try_init_stream_with_backend() to detect hw: devices - Update player thread types (stream_opt, current_engine) Next: Complete player.rs integration (extensive changes needed) Status: Does not compile yet - work in progress --- src-tauri/src/player/mod.rs | 45 ++++- src-tauri/src/player/playback_engine.rs | 252 ++++++++++++++++++++++++ 2 files changed, 290 insertions(+), 7 deletions(-) create mode 100644 src-tauri/src/player/playback_engine.rs diff --git a/src-tauri/src/player/mod.rs b/src-tauri/src/player/mod.rs index c63a55aa1..9c5886dac 100644 --- a/src-tauri/src/player/mod.rs +++ b/src-tauri/src/player/mod.rs @@ -8,6 +8,9 @@ //! - Real-time position tracking via events //! //! Uses a dedicated audio thread since rodio's OutputStream is not Send. +//! Supports both rodio (PipeWire/Pulse) and direct ALSA (hw: devices). + +mod playback_engine; use std::io::{BufReader, Cursor, Read, Seek, SeekFrom}; use std::panic::{self, AssertUnwindSafe}; @@ -33,6 +36,7 @@ use symphonia::default::{get_codecs, get_probe}; use crate::api::{client::QobuzClient, models::Quality}; use crate::audio::{AudioBackendType, BackendConfig, BackendManager}; use crate::config::audio_settings::AudioSettings; +use playback_engine::PlaybackEngine; /// Commands sent to the audio thread enum AudioCommand { @@ -355,13 +359,22 @@ fn create_output_stream_with_config( } } +/// Output stream type - either rodio or ALSA Direct +enum StreamType { + Rodio(OutputStream, rodio::OutputStreamHandle), + #[cfg(target_os = "linux")] + AlsaDirect(crate::audio::AlsaDirectStream), +} + /// Try to create output stream using the backend system (if configured) /// Returns None if backend system is not configured (backend_type = None) +/// +/// For ALSA backend with hw: devices, may return AlsaDirect instead of Rodio stream. fn try_init_stream_with_backend( audio_settings: &AudioSettings, sample_rate: u32, channels: u16, -) -> Option> { +) -> Option> { // Check if backend system is configured let backend_type = audio_settings.backend_type?; @@ -398,11 +411,29 @@ fn try_init_stream_with_backend( alsa_plugin: audio_settings.alsa_plugin, }; - // Create output stream via backend + // For ALSA backend with hw: devices, try direct ALSA first (Linux only) + #[cfg(target_os = "linux")] + if backend_type == AudioBackendType::Alsa { + // Check if device is hw: or plughw: + if let Some(ref device_id) = config.device_id { + if crate::audio::AlsaDirectStream::is_hw_device(device_id) { + log::info!("🎵 Detected hw: device, using ALSA Direct for bit-perfect playback"); + + // Downcast backend to AlsaBackend to access try_create_direct_stream + if let Some(alsa_backend) = backend.as_any().downcast_ref::() { + if let Some(result) = alsa_backend.try_create_direct_stream(&config) { + return Some(result.map(StreamType::AlsaDirect)); + } + } + } + } + } + + // Fallback to regular rodio stream (PipeWire, Pulse, ALSA via CPAL) match backend.create_output_stream(&config) { Ok(stream) => { log::info!("✅ Stream created via {:?} backend at {}Hz", backend_type, sample_rate); - Some(Ok(stream)) + Some(Ok(StreamType::Rodio(stream.0, stream.1))) } Err(e) => { log::error!("❌ Backend stream creation failed: {}", e); @@ -680,14 +711,14 @@ 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 stream_opt: Option = 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; - let mut current_sink: Option = None; + let mut current_engine: Option = None; // Store audio data for seeking (we need to re-decode from the beginning) let mut current_audio_data: Option> = None; // Track consecutive sink creation failures to detect broken streams @@ -701,9 +732,9 @@ impl Player { log::info!("Audio thread ready and waiting for commands"); let mut handle_command = |command: AudioCommand, - current_sink: &mut Option, + current_engine: &mut Option, current_audio_data: &mut Option>, - stream_opt: &mut Option<(OutputStream, rodio::OutputStreamHandle)>, + stream_opt: &mut Option, current_device_name: &mut Option, consecutive_sink_failures: &mut u32, pause_suspend_deadline: &mut Option, diff --git a/src-tauri/src/player/playback_engine.rs b/src-tauri/src/player/playback_engine.rs new file mode 100644 index 000000000..452406730 --- /dev/null +++ b/src-tauri/src/player/playback_engine.rs @@ -0,0 +1,252 @@ +//! Playback Engine Abstraction +//! +//! Unified interface for different playback backends: +//! - Rodio (PipeWire, Pulse, ALSA via CPAL) - uses rodio::Sink +//! - ALSA Direct (hw: devices) - bypasses rodio, writes directly to ALSA PCM +//! +//! This abstraction allows the player to work with both approaches transparently. + +use crate::audio::AlsaDirectStream; +use rodio::{OutputStream, OutputStreamHandle, Sink, Source}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Arc; +use std::thread; +use std::time::Duration; + +/// Unified playback engine +pub enum PlaybackEngine { + /// Rodio-based (PipeWire, Pulse, ALSA via CPAL) + Rodio { + sink: Sink, + }, + /// Direct ALSA (hw: devices, bit-perfect) + AlsaDirect { + stream: Arc, + is_playing: Arc, + position_frames: Arc, + duration_frames: Arc, + playback_thread: Option>, + }, +} + +impl PlaybackEngine { + /// Create Rodio engine + pub fn new_rodio(stream_handle: &OutputStreamHandle) -> Result { + let sink = Sink::try_new(stream_handle) + .map_err(|e| format!("Failed to create Sink: {}", e))?; + + Ok(Self::Rodio { sink }) + } + + /// Create ALSA Direct engine + pub fn new_alsa_direct(stream: AlsaDirectStream) -> Self { + Self::AlsaDirect { + stream: Arc::new(stream), + is_playing: Arc::new(AtomicBool::new(false)), + position_frames: Arc::new(AtomicU64::new(0)), + duration_frames: Arc::new(AtomicU64::new(0)), + playback_thread: None, + } + } + + /// Append audio source + pub fn append(&mut self, source: S) -> Result<(), String> + where + S: Source + Send + 'static, + { + match self { + Self::Rodio { sink } => { + sink.append(source); + Ok(()) + } + Self::AlsaDirect { + stream, + is_playing, + position_frames, + duration_frames, + playback_thread, + } => { + // For ALSA Direct, we need to spawn a thread that: + // 1. Converts i16 samples to f32 + // 2. Writes to ALSA PCM + // 3. Tracks position + + let stream_clone = stream.clone(); + let is_playing_clone = is_playing.clone(); + let position_clone = position_frames.clone(); + let duration_clone = duration_frames.clone(); + + let sample_rate = stream.sample_rate(); + let channels = stream.channels(); + + is_playing.store(true, Ordering::SeqCst); + position_clone.store(0, Ordering::SeqCst); + + let handle = thread::spawn(move || { + // Collect all samples from source + let samples_i16: Vec = source.collect(); + + // Convert i16 to f32 (normalize to -1.0..1.0) + let samples_f32: Vec = samples_i16 + .iter() + .map(|&s| s as f32 / 32768.0) + .collect(); + + // Store duration in frames + let total_frames = samples_f32.len() as u64 / channels as u64; + duration_clone.store(total_frames, Ordering::SeqCst); + + // Write in chunks to allow for control (pause/stop) + const CHUNK_SIZE: usize = 4096; // frames + let chunk_samples = CHUNK_SIZE * channels as usize; + + let mut offset = 0; + while offset < samples_f32.len() && is_playing_clone.load(Ordering::SeqCst) { + let end = (offset + chunk_samples).min(samples_f32.len()); + let chunk = &samples_f32[offset..end]; + + if let Err(e) = stream_clone.write(chunk) { + log::error!("[ALSA Direct Engine] Write failed: {}", e); + break; + } + + // Update position + let frames_written = (end - offset) / channels as usize; + position_clone.fetch_add(frames_written as u64, Ordering::SeqCst); + + offset = end; + } + + // Drain PCM buffer + if let Err(e) = stream_clone.drain() { + log::warn!("[ALSA Direct Engine] Drain failed: {}", e); + } + + is_playing_clone.store(false, Ordering::SeqCst); + log::info!("[ALSA Direct Engine] Playback thread finished"); + }); + + *playback_thread = Some(handle); + Ok(()) + } + } + } + + /// Play (unpause) + pub fn play(&self) { + match self { + Self::Rodio { sink } => sink.play(), + Self::AlsaDirect { is_playing, .. } => { + is_playing.store(true, Ordering::SeqCst); + } + } + } + + /// Pause + pub fn pause(&self) { + match self { + Self::Rodio { sink } => sink.pause(), + Self::AlsaDirect { is_playing, .. } => { + is_playing.store(false, Ordering::SeqCst); + } + } + } + + /// Stop + pub fn stop(self) { + match self { + Self::Rodio { sink } => { + sink.stop(); + } + Self::AlsaDirect { + stream, + is_playing, + playback_thread, + .. + } => { + is_playing.store(false, Ordering::SeqCst); + + // Wait for playback thread to finish + if let Some(handle) = playback_thread { + let _ = handle.join(); + } + + // Stop PCM + if let Err(e) = stream.stop() { + log::warn!("[ALSA Direct Engine] Stop failed: {}", e); + } + } + } + } + + /// Set volume (0.0 - 1.0) + pub fn set_volume(&self, volume: f32) { + match self { + Self::Rodio { sink } => sink.set_volume(volume), + Self::AlsaDirect { .. } => { + // TODO: Implement software volume or ALSA mixer control + // For now, ALSA Direct uses hardware volume + log::warn!("[ALSA Direct Engine] Software volume not yet implemented"); + } + } + } + + /// Check if playback queue is empty + pub fn empty(&self) -> bool { + match self { + Self::Rodio { sink } => sink.empty(), + Self::AlsaDirect { + is_playing, + position_frames, + duration_frames, + .. + } => { + if !is_playing.load(Ordering::SeqCst) { + let pos = position_frames.load(Ordering::SeqCst); + let dur = duration_frames.load(Ordering::SeqCst); + // Consider empty if stopped and reached the end + pos >= dur && dur > 0 + } else { + false + } + } + } + } + + /// Get current position in seconds (for ALSA Direct only) + pub fn position_secs(&self) -> Option { + match self { + Self::Rodio { .. } => None, // Rodio doesn't expose position directly + Self::AlsaDirect { + position_frames, + stream, + .. + } => { + let frames = position_frames.load(Ordering::SeqCst); + let sample_rate = stream.sample_rate() as u64; + Some(frames / sample_rate) + } + } + } + + /// Get duration in seconds (for ALSA Direct only) + pub fn duration_secs(&self) -> Option { + match self { + Self::Rodio { .. } => None, + Self::AlsaDirect { + duration_frames, + stream, + .. + } => { + let frames = duration_frames.load(Ordering::SeqCst); + let sample_rate = stream.sample_rate() as u64; + Some(frames / sample_rate) + } + } + } + + /// Check if using ALSA Direct engine + pub fn is_alsa_direct(&self) -> bool { + matches!(self, Self::AlsaDirect { .. }) + } +}