diff --git a/src-tauri/src/audio/alsa_direct.rs b/src-tauri/src/audio/alsa_direct.rs index bdc730022..2fedfc770 100644 --- a/src-tauri/src/audio/alsa_direct.rs +++ b/src-tauri/src/audio/alsa_direct.rs @@ -271,6 +271,162 @@ impl AlsaDirectStream { } } + /// Write f32 audio samples to ALSA (converts to hardware format with full precision) + /// + /// f32 has 24 bits of significand, so 24-bit audio is preserved losslessly. + /// This is the primary write path for the f32 pipeline. + #[cfg(target_os = "linux")] + pub fn write_f32(&self, samples_f32: &[f32]) -> Result<(), String> { + let pcm = self.pcm.lock().unwrap(); + let frames = samples_f32.len() / self.channels as usize; + + match self.format { + Format::FloatLE => { + // Direct write - no conversion needed + let io = pcm.io_f32() + .map_err(|e| format!("Failed to get PCM I/O: {}", e))?; + + match io.writei(samples_f32) { + Ok(written) => { + if written != frames { + log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames); + } + Ok(()) + } + Err(e) => { + if let Err(recover_err) = pcm.recover(e.errno() as i32, false) { + Err(format!("Failed to recover from error: {}", recover_err)) + } else { + log::warn!("[ALSA Direct] Recovered from PCM error"); + Ok(()) + } + } + } + } + Format::S32LE => { + // f32 [-1.0, 1.0] -> i32 full range + let samples_i32: Vec = samples_f32 + .iter() + .map(|&s| (s * 2_147_483_647.0) as i32) + .collect(); + + let io = pcm.io_i32() + .map_err(|e| format!("Failed to get PCM I/O: {}", e))?; + + match io.writei(&samples_i32) { + Ok(written) => { + if written != frames { + log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames); + } + Ok(()) + } + Err(e) => { + if let Err(recover_err) = pcm.recover(e.errno() as i32, false) { + Err(format!("Failed to recover from error: {}", recover_err)) + } else { + log::warn!("[ALSA Direct] Recovered from PCM error"); + Ok(()) + } + } + } + } + Format::S24LE => { + // f32 -> 24-bit in 32-bit container + // Clamp to 24-bit range: [-8388608, 8388607] + let samples_i32: Vec = samples_f32 + .iter() + .map(|&s| { + let scaled = s * 8_388_607.0; + scaled.clamp(-8_388_608.0, 8_388_607.0) as i32 + }) + .collect(); + + let io = pcm.io_i32() + .map_err(|e| format!("Failed to get PCM I/O: {}", e))?; + + match io.writei(&samples_i32) { + Ok(written) => { + if written != frames { + log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames); + } + Ok(()) + } + Err(e) => { + if let Err(recover_err) = pcm.recover(e.errno() as i32, false) { + Err(format!("Failed to recover from error: {}", recover_err)) + } else { + log::warn!("[ALSA Direct] Recovered from PCM error"); + Ok(()) + } + } + } + } + Format::S243LE => { + // S24_3LE: 24-bit packed in 3 bytes, little-endian + // f32 -> 24-bit integer, packed into 3 bytes + let mut bytes: Vec = Vec::with_capacity(samples_f32.len() * 3); + + for &sample in samples_f32 { + let scaled = sample * 8_388_607.0; + let s24 = scaled.clamp(-8_388_608.0, 8_388_607.0) as i32; + // Pack as 3 bytes in little-endian order + bytes.push((s24 & 0xFF) as u8); // LSB + bytes.push(((s24 >> 8) & 0xFF) as u8); // Middle + bytes.push(((s24 >> 16) & 0xFF) as u8); // MSB (sign-extended) + } + + let io = pcm.io_bytes(); + + match io.writei(&bytes) { + Ok(written) => { + if written != frames { + log::warn!("[ALSA Direct] Partial write: {} / {} frames (S24_3LE)", written, frames); + } + Ok(()) + } + Err(e) => { + if let Err(recover_err) = pcm.recover(e.errno() as i32, false) { + Err(format!("Failed to recover from error: {}", recover_err)) + } else { + log::warn!("[ALSA Direct] Recovered from PCM error (S24_3LE)"); + Ok(()) + } + } + } + } + Format::S16LE => { + // f32 -> i16 + let samples_i16: Vec = samples_f32 + .iter() + .map(|&s| (s * 32_767.0) as i16) + .collect(); + + let io = pcm.io_i16() + .map_err(|e| format!("Failed to get PCM I/O: {}", e))?; + + match io.writei(&samples_i16) { + Ok(written) => { + if written != frames { + log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames); + } + Ok(()) + } + Err(e) => { + if let Err(recover_err) = pcm.recover(e.errno() as i32, false) { + Err(format!("Failed to recover from error: {}", recover_err)) + } else { + log::warn!("[ALSA Direct] Recovered from PCM error"); + Ok(()) + } + } + } + } + _ => { + Err(format!("Unsupported format: {:?}", self.format)) + } + } + } + /// Drain and stop playback #[cfg(target_os = "linux")] pub fn drain(&self) -> Result<(), String> { @@ -366,7 +522,11 @@ impl AlsaDirectStream { Err("ALSA Direct is only available on Linux".to_string()) } - pub fn write(&self, _samples: &[f32]) -> Result<(), String> { + pub fn write(&self, _samples: &[i16]) -> Result<(), String> { + Err("ALSA Direct is only available on Linux".to_string()) + } + + pub fn write_f32(&self, _samples: &[f32]) -> Result<(), String> { Err("ALSA Direct is only available on Linux".to_string()) } diff --git a/src-tauri/src/player/playback_engine.rs b/src-tauri/src/player/playback_engine.rs index b15c3b515..6f51af6d7 100644 --- a/src-tauri/src/player/playback_engine.rs +++ b/src-tauri/src/player/playback_engine.rs @@ -56,7 +56,7 @@ impl PlaybackEngine { /// Append audio source pub fn append(&mut self, source: S) -> Result<(), String> where - S: Source + Send + 'static, + S: Source + Send + 'static, { match self { Self::Rodio { sink } => { @@ -73,11 +73,10 @@ impl PlaybackEngine { hardware_volume: _, } => { // For ALSA Direct, we need to spawn a thread that: - // 1. Streams samples from source (no buffering entire file) - // 2. Converts i16 samples to f32 - // 3. Writes to ALSA PCM - // 4. Tracks position - // 5. Supports pause/resume without terminating + // 1. Streams f32 samples from source (no buffering entire file) + // 2. Writes to ALSA PCM (converts f32 to hardware format) + // 3. Tracks position + // 4. Supports pause/resume without terminating let stream_clone = stream.clone(); let is_playing_clone = is_playing.clone(); @@ -98,7 +97,7 @@ impl PlaybackEngine { const CHUNK_SIZE: usize = 8192; // frames per chunk let chunk_samples = CHUNK_SIZE * channels as usize; - let mut buffer_i16 = Vec::with_capacity(chunk_samples); + let mut buffer_f32 = Vec::with_capacity(chunk_samples); let mut total_frames: u64 = 0; let mut source_iter = source.into_iter(); @@ -123,15 +122,15 @@ impl PlaybackEngine { } // Fill buffer from source - buffer_i16.clear(); + buffer_f32.clear(); for _ in 0..chunk_samples { match source_iter.next() { - Some(sample) => buffer_i16.push(sample), + Some(sample) => buffer_f32.push(sample), None => break, // End of stream } } - if buffer_i16.is_empty() { + if buffer_f32.is_empty() { // End of stream log::info!("[ALSA Direct Engine] Stream ended (total frames: {})", total_frames); natural_end = true; @@ -140,13 +139,13 @@ impl PlaybackEngine { // Write to ALSA (auto-converts based on detected format) // This is bit-perfect: no resampling, no mixing, direct to hardware - if let Err(e) = stream_clone.write(&buffer_i16) { + if let Err(e) = stream_clone.write_f32(&buffer_f32) { log::error!("[ALSA Direct Engine] Write failed: {}", e); break 'playback; } // Update position - let frames_written = buffer_i16.len() / channels as usize; + let frames_written = buffer_f32.len() / channels as usize; total_frames += frames_written as u64; position_clone.store(total_frames, Ordering::SeqCst); duration_clone.store(total_frames, Ordering::SeqCst);