diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 38eb1ff44..d787ee616 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -67,6 +67,9 @@ symphonia = { version = "0.5", features = ["all"] } # Audio visualization (FFT) spectrum-analyzer = "1.5" +# EBU R128 loudness measurement (real-time normalization) +ebur128 = "0.1" + # Media controls (MPRIS on Linux) souvlaki = "0.7" diff --git a/src-tauri/src/audio/analyzer_tap.rs b/src-tauri/src/audio/analyzer_tap.rs new file mode 100644 index 000000000..4c34819ba --- /dev/null +++ b/src-tauri/src/audio/analyzer_tap.rs @@ -0,0 +1,116 @@ +//! Analyzer tap — captures audio samples for loudness analysis. +//! +//! Sits in the audio pipeline as a transparent `Source` wrapper. +//! Batches samples and sends them to the loudness analyzer thread via a bounded +//! channel. Uses `try_send` so it never blocks the audio thread — if the channel +//! is full, the batch is silently dropped (graceful degradation). + +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::mpsc::SyncSender; +use std::sync::Arc; +use std::time::Duration; + +use rodio::Source; + +/// Messages sent from the audio pipeline to the loudness analyzer thread. +pub enum AnalyzerMessage { + /// A batch of interleaved f32 samples. + Samples(Vec), + /// A new track has started — reset analyzer state. + NewTrack { + track_id: u64, + sample_rate: u32, + channels: u16, + target_lufs: f32, + /// Shared gain atomic — analyzer writes, DynamicAmplify reads. + gain_atomic: Arc, + }, + /// Seek occurred — reset accumulated samples but keep current gain. + Reset, + /// Shut down the analyzer thread. + Shutdown, +} + +const BATCH_SIZE: usize = 4096; + +pub struct AnalyzerTap +where + S: Source, +{ + inner: S, + sender: SyncSender, + enabled: Arc, + buffer: Vec, +} + +impl AnalyzerTap +where + S: Source, +{ + pub fn new(source: S, sender: SyncSender, enabled: Arc) -> Self { + Self { + inner: source, + sender, + enabled, + buffer: Vec::with_capacity(BATCH_SIZE), + } + } + + #[inline] + fn flush_if_full(&mut self) { + if self.buffer.len() >= BATCH_SIZE { + let batch = std::mem::replace(&mut self.buffer, Vec::with_capacity(BATCH_SIZE)); + // Non-blocking send — drop batch if channel is full + let _ = self.sender.try_send(AnalyzerMessage::Samples(batch)); + } + } +} + +impl Iterator for AnalyzerTap +where + S: Source, +{ + type Item = f32; + + #[inline] + fn next(&mut self) -> Option { + let sample = self.inner.next()?; + + if self.enabled.load(Ordering::Relaxed) { + self.buffer.push(sample); + self.flush_if_full(); + } + + Some(sample) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +impl Source for AnalyzerTap +where + S: Source, +{ + #[inline] + fn current_frame_len(&self) -> Option { + self.inner.current_frame_len() + } + + #[inline] + fn channels(&self) -> u16 { + self.inner.channels() + } + + #[inline] + fn sample_rate(&self) -> u32 { + self.inner.sample_rate() + } + + #[inline] + fn total_duration(&self) -> Option { + self.inner.total_duration() + } +} diff --git a/src-tauri/src/audio/dynamic_amplify.rs b/src-tauri/src/audio/dynamic_amplify.rs new file mode 100644 index 000000000..a90345b50 --- /dev/null +++ b/src-tauri/src/audio/dynamic_amplify.rs @@ -0,0 +1,137 @@ +//! Dynamic gain wrapper for real-time volume normalization. +//! +//! Reads gain from a shared `Arc` (f32 stored as bits) and applies +//! it to each sample. When the gain value changes, a 50ms linear ramp smooths +//! the transition to prevent audible clicks. +//! +//! When the atomic holds 0.0 (gain not yet computed), the wrapper stays at +//! the `initial_gain` provided at construction. + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use rodio::Source; + +pub struct DynamicAmplify +where + S: Source, +{ + inner: S, + gain_atomic: Arc, + /// Current applied gain (smoothly ramped) + current_gain: f32, + /// Target gain we're ramping toward + target_gain: f32, + /// Gain increment per sample during ramp + ramp_step: f32, + /// Samples remaining in the current ramp + ramp_remaining: u32, + /// Number of samples in a 50ms ramp at the current sample rate + ramp_samples: u32, +} + +impl DynamicAmplify +where + S: Source, +{ + pub fn new(source: S, gain_atomic: Arc, initial_gain: f32) -> Self { + let sample_rate = source.sample_rate(); + let channels = source.channels() as u32; + // 50ms ramp in total samples (all channels) + let ramp_samples = (sample_rate * channels * 50) / 1000; + + Self { + inner: source, + gain_atomic, + current_gain: initial_gain, + target_gain: initial_gain, + ramp_step: 0.0, + ramp_remaining: 0, + ramp_samples, + } + } + + /// Check for a new gain value and start a ramp if it changed. + #[inline] + fn poll_gain(&mut self) { + let bits = self.gain_atomic.load(Ordering::Relaxed); + let new_gain = f32::from_bits(bits); + + // 0.0 means "not yet computed" — stay at current gain + if new_gain == 0.0 { + return; + } + + // Only start a ramp if the target actually changed + if (new_gain - self.target_gain).abs() > f32::EPSILON { + self.target_gain = new_gain; + if self.ramp_samples > 0 { + self.ramp_step = (self.target_gain - self.current_gain) / self.ramp_samples as f32; + self.ramp_remaining = self.ramp_samples; + } else { + self.current_gain = self.target_gain; + self.ramp_remaining = 0; + } + } + } +} + +impl Iterator for DynamicAmplify +where + S: Source, +{ + type Item = f32; + + #[inline] + fn next(&mut self) -> Option { + // Poll for new gain every 1024 samples to avoid atomic contention + // (ramp_remaining check is essentially free) + if self.ramp_remaining == 0 { + self.poll_gain(); + } + + let sample = self.inner.next()?; + + if self.ramp_remaining > 0 { + self.current_gain += self.ramp_step; + self.ramp_remaining -= 1; + if self.ramp_remaining == 0 { + // Snap to target at end of ramp to avoid float drift + self.current_gain = self.target_gain; + } + } + + Some(sample * self.current_gain) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +impl Source for DynamicAmplify +where + S: Source, +{ + #[inline] + fn current_frame_len(&self) -> Option { + self.inner.current_frame_len() + } + + #[inline] + fn channels(&self) -> u16 { + self.inner.channels() + } + + #[inline] + fn sample_rate(&self) -> u32 { + self.inner.sample_rate() + } + + #[inline] + fn total_duration(&self) -> Option { + self.inner.total_duration() + } +} diff --git a/src-tauri/src/audio/loudness_analyzer.rs b/src-tauri/src/audio/loudness_analyzer.rs new file mode 100644 index 000000000..bde4df507 --- /dev/null +++ b/src-tauri/src/audio/loudness_analyzer.rs @@ -0,0 +1,231 @@ +//! Background loudness analyzer thread. +//! +//! Long-lived thread that receives decoded audio samples from `AnalyzerTap`, +//! computes EBU R128 integrated LUFS, and updates a shared `Arc` +//! gain value that `DynamicAmplify` reads. +//! +//! - First measurement after ~10s of audio (EBU R128 needs sufficient data) +//! - Refinement every ~5s thereafter (gain converges by ~30-60s) +//! - Cached results are used immediately on cache hit + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::mpsc::Receiver; +use std::sync::Arc; +use std::thread; + +use ebur128::{EbuR128, Mode}; + +use super::analyzer_tap::AnalyzerMessage; +use super::loudness_cache::LoudnessCache; +use super::loudness::db_to_linear; + +/// Maximum gain boost in dB (conservative clipping prevention) +const MAX_GAIN_DB: f32 = 6.0; + + +pub struct LoudnessAnalyzer; + +impl LoudnessAnalyzer { + /// Spawn the analyzer thread. Returns the join handle. + /// + /// The thread blocks on `rx.recv()` when idle — zero CPU usage between tracks. + pub fn spawn( + rx: Receiver, + cache: Arc, + ) -> thread::JoinHandle<()> { + thread::Builder::new() + .name("loudness-analyzer".into()) + .spawn(move || { + log::info!("[LoudnessAnalyzer] Thread started"); + Self::run(rx, cache); + log::info!("[LoudnessAnalyzer] Thread exiting"); + }) + .expect("Failed to spawn loudness analyzer thread") + } + + fn run(rx: Receiver, cache: Arc) { + let mut state: Option = None; + + loop { + let msg = match rx.recv() { + Ok(msg) => msg, + Err(_) => { + log::info!("[LoudnessAnalyzer] Channel closed, shutting down"); + break; + } + }; + + match msg { + AnalyzerMessage::NewTrack { track_id, sample_rate, channels, target_lufs, gain_atomic } => { + log::info!( + "[LoudnessAnalyzer] New track {} ({}Hz, {}ch, target {:.1} LUFS)", + track_id, sample_rate, channels, target_lufs + ); + + // Check cache first + if let Some(cached) = cache.get(track_id) { + let gain = compute_gain_capped(cached.gain_db); + log::info!( + "[LoudnessAnalyzer] Cache hit for track {}: {:.2} dB (source: {}), gain {:.4}", + track_id, cached.gain_db, cached.source, gain + ); + + // Set gain immediately via the atomic + gain_atomic.store(gain.to_bits(), Ordering::Relaxed); + + // Create state marked as cached — still accept samples for refinement + let mut s = AnalyzerState::new(track_id, sample_rate, channels, target_lufs); + s.gain_atomic = Some(gain_atomic); + s.initial_done = true; + state = Some(s); + continue; + } + + // No cache — start fresh analysis + let mut s = AnalyzerState::new(track_id, sample_rate, channels, target_lufs); + s.gain_atomic = Some(gain_atomic); + state = Some(s); + } + AnalyzerMessage::Samples(samples) => { + if let Some(ref mut s) = state { + s.feed_samples(&samples, &cache); + } + } + AnalyzerMessage::Reset => { + if let Some(ref mut s) = state { + log::info!("[LoudnessAnalyzer] Reset (seek) — keeping current gain"); + s.reset_analyzer(); + } + } + AnalyzerMessage::Shutdown => { + log::info!("[LoudnessAnalyzer] Shutdown requested"); + break; + } + } + } + } +} + +struct AnalyzerState { + track_id: u64, + target_lufs: f32, + ebur128: EbuR128, + channels: u16, + sample_rate: u32, + /// Shared gain atomic — written by us, read by DynamicAmplify + gain_atomic: Option>, + /// Total samples fed since last reset + samples_fed: u64, + /// Total samples fed at last measurement + samples_at_last_measure: u64, + /// Whether initial measurement has been done + initial_done: bool, + /// Dynamic thresholds based on actual sample rate and channels + initial_threshold: u64, + refinement_interval: u64, +} + +impl AnalyzerState { + fn new(track_id: u64, sample_rate: u32, channels: u16, target_lufs: f32) -> Self { + let ebur128 = EbuR128::new(channels as u32, sample_rate, Mode::I) + .expect("Failed to create EbuR128 instance"); + + // Scale thresholds to actual sample rate and channel count + let samples_per_second = sample_rate as u64 * channels as u64; + let initial_threshold = samples_per_second * 10; // 10 seconds + let refinement_interval = samples_per_second * 5; // 5 seconds + + Self { + track_id, + target_lufs, + ebur128, + channels, + sample_rate, + gain_atomic: None, + samples_fed: 0, + samples_at_last_measure: 0, + initial_done: false, + initial_threshold, + refinement_interval, + } + } + + /// Reset the EBU R128 analyzer (e.g., after seek) but keep the gain atomic. + fn reset_analyzer(&mut self) { + self.ebur128 = EbuR128::new(self.channels as u32, self.sample_rate, Mode::I) + .expect("Failed to create EbuR128 instance"); + self.samples_fed = 0; + self.samples_at_last_measure = 0; + self.initial_done = false; + } + + /// Feed samples to the EBU R128 analyzer and possibly update gain. + fn feed_samples(&mut self, samples: &[f32], cache: &LoudnessCache) { + // Feed interleaved samples as frames + let frame_count = samples.len() / self.channels as usize; + if frame_count == 0 { + return; + } + + if let Err(e) = self.ebur128.add_frames_f32(samples) { + log::warn!("[LoudnessAnalyzer] Error feeding samples: {}", e); + return; + } + + self.samples_fed += samples.len() as u64; + + // Check if it's time to measure + let should_measure = if !self.initial_done { + self.samples_fed >= self.initial_threshold + } else { + self.samples_fed - self.samples_at_last_measure >= self.refinement_interval + }; + + if should_measure { + self.measure_and_update(cache); + } + } + + fn measure_and_update(&mut self, cache: &LoudnessCache) { + let loudness = match self.ebur128.loudness_global() { + Ok(l) => l, + Err(e) => { + log::warn!("[LoudnessAnalyzer] Failed to get loudness: {}", e); + return; + } + }; + + // -inf means silence — don't adjust + if loudness.is_infinite() || loudness.is_nan() { + log::debug!("[LoudnessAnalyzer] Track {}: loudness is {:?}, skipping", self.track_id, loudness); + return; + } + + let measured_lufs = loudness as f32; + let adjustment_db = self.target_lufs - measured_lufs; + let gain = compute_gain_capped(adjustment_db); + + let phase = if self.initial_done { "refine" } else { "initial" }; + log::info!( + "[LoudnessAnalyzer] Track {} ({}): measured {:.1} LUFS, target {:.1}, adjustment {:.2} dB, gain {:.4}", + self.track_id, phase, measured_lufs, self.target_lufs, adjustment_db, gain + ); + + // Update shared atomic + if let Some(ref atomic) = self.gain_atomic { + atomic.store(gain.to_bits(), Ordering::Relaxed); + } + + self.samples_at_last_measure = self.samples_fed; + self.initial_done = true; + + // Cache the result (store the adjustment in dB, not the linear gain) + cache.set(self.track_id, adjustment_db, 0.0, "ebur128"); + } +} + +/// Convert a dB adjustment to a capped linear gain factor. +fn compute_gain_capped(adjustment_db: f32) -> f32 { + let capped_db = adjustment_db.min(MAX_GAIN_DB); + db_to_linear(capped_db) +} diff --git a/src-tauri/src/audio/loudness_cache.rs b/src-tauri/src/audio/loudness_cache.rs new file mode 100644 index 000000000..68caedcea --- /dev/null +++ b/src-tauri/src/audio/loudness_cache.rs @@ -0,0 +1,80 @@ +//! Loudness cache — persists EBU R128 measurements in SQLite. +//! +//! Follows the `AudioSettingsStore` pattern: database lives in +//! `dirs::data_dir()/qbz/loudness_cache.db`. +//! +//! Thread-safe via `Mutex`. + +use rusqlite::{Connection, params}; +use std::sync::Mutex; + +#[derive(Debug, Clone)] +pub struct CachedLoudness { + pub gain_db: f32, + pub peak: f32, + /// Source of the measurement: "ebur128" or "replaygain" + pub source: String, +} + +pub struct LoudnessCache { + conn: Mutex, +} + +impl LoudnessCache { + pub fn new() -> Result { + let data_dir = dirs::data_dir() + .ok_or_else(|| "Could not determine data directory".to_string())? + .join("qbz"); + + std::fs::create_dir_all(&data_dir) + .map_err(|e| format!("Failed to create data directory: {}", e))?; + + let db_path = data_dir.join("loudness_cache.db"); + let conn = Connection::open(&db_path) + .map_err(|e| format!("Failed to open loudness cache database: {}", e))?; + + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS track_loudness ( + track_id INTEGER PRIMARY KEY, + gain_db REAL NOT NULL, + peak REAL NOT NULL DEFAULT 0.0, + source TEXT NOT NULL DEFAULT 'ebur128', + created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) + )" + ).map_err(|e| format!("Failed to create loudness table: {}", e))?; + + log::info!("[LoudnessCache] Opened at {}", db_path.display()); + + Ok(Self { conn: Mutex::new(conn) }) + } + + /// Look up cached loudness for a track. + pub fn get(&self, track_id: u64) -> Option { + let conn = self.conn.lock().ok()?; + conn.query_row( + "SELECT gain_db, peak, source FROM track_loudness WHERE track_id = ?1", + params![track_id as i64], + |row| { + Ok(CachedLoudness { + gain_db: row.get::<_, f64>(0)? as f32, + peak: row.get::<_, f64>(1)? as f32, + source: row.get(2)?, + }) + }, + ).ok() + } + + /// Store or update loudness data for a track. + pub fn set(&self, track_id: u64, gain_db: f32, peak: f32, source: &str) { + if let Ok(conn) = self.conn.lock() { + let result = conn.execute( + "INSERT OR REPLACE INTO track_loudness (track_id, gain_db, peak, source, created_at) + VALUES (?1, ?2, ?3, ?4, strftime('%s', 'now'))", + params![track_id as i64, gain_db as f64, peak as f64, source], + ); + if let Err(e) = result { + log::warn!("[LoudnessCache] Failed to store loudness for track {}: {}", track_id, e); + } + } + } +} diff --git a/src-tauri/src/audio/mod.rs b/src-tauri/src/audio/mod.rs index 5fdca9112..3d574fc96 100644 --- a/src-tauri/src/audio/mod.rs +++ b/src-tauri/src/audio/mod.rs @@ -10,6 +10,10 @@ pub mod pulse_backend; pub mod alsa_direct; pub mod diagnostic; pub mod loudness; +pub mod dynamic_amplify; +pub mod analyzer_tap; +pub mod loudness_cache; +pub mod loudness_analyzer; // Re-export commonly used types pub use backend::{ @@ -24,4 +28,8 @@ pub use backend::{ pub use alsa_direct::AlsaDirectStream; pub use alsa_backend::{normalize_device_id_to_stable, resolve_stable_to_current_hw}; pub use diagnostic::{AudioDiagnostic, DiagnosticSource, BitDepthResult}; -pub use loudness::{ReplayGainData, extract_replaygain, calculate_gain_factor}; +pub use loudness::{ReplayGainData, extract_replaygain, calculate_gain_factor, db_to_linear}; +pub use dynamic_amplify::DynamicAmplify; +pub use analyzer_tap::{AnalyzerTap, AnalyzerMessage}; +pub use loudness_cache::LoudnessCache; +pub use loudness_analyzer::LoudnessAnalyzer; diff --git a/src-tauri/src/player/mod.rs b/src-tauri/src/player/mod.rs index dbf9fb36e..2166e7088 100644 --- a/src-tauri/src/player/mod.rs +++ b/src-tauri/src/player/mod.rs @@ -18,7 +18,7 @@ pub use streaming_source::{BufferedMediaSource, BufferWriter, StreamingConfig, I use std::io::{BufReader, Cursor, Read, Seek, SeekFrom}; use std::panic::{self, AssertUnwindSafe}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; -use std::sync::mpsc::{self, Sender, RecvTimeoutError}; +use std::sync::mpsc::{self, Sender, SyncSender, RecvTimeoutError}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; @@ -37,7 +37,11 @@ use symphonia::core::probe::Hint; use symphonia::default::{get_codecs, get_probe}; use crate::api::{client::QobuzClient, models::Quality}; -use crate::audio::{AudioBackendType, AudioDiagnostic, BackendConfig, BackendManager, DiagnosticSource, extract_replaygain, calculate_gain_factor}; +use crate::audio::{ + AudioBackendType, AudioDiagnostic, BackendConfig, BackendManager, DiagnosticSource, + extract_replaygain, calculate_gain_factor, db_to_linear, + DynamicAmplify, AnalyzerTap, AnalyzerMessage, LoudnessCache, LoudnessAnalyzer, +}; use crate::config::audio_settings::AudioSettings; use crate::visualizer::{VisualizerTap, TappedSource}; use playback_engine::PlaybackEngine; @@ -702,17 +706,43 @@ impl Player { thread::spawn(move || { log::info!("Audio thread starting..."); + // Initialize loudness analysis system + let (analyzer_tx, analyzer_rx) = mpsc::sync_channel::(64); + let loudness_cache = match LoudnessCache::new() { + Ok(c) => Arc::new(c), + Err(e) => { + log::error!("Failed to create loudness cache: {}. Normalization will work without caching.", e); + // Create a fallback in-memory cache (will be lost on restart) + // For now, just panic — this should not fail in practice + panic!("LoudnessCache creation failed: {}", e); + } + }; + let _analyzer_handle = LoudnessAnalyzer::spawn(analyzer_rx, loudness_cache.clone()); + let analyzer_enabled = Arc::new(AtomicBool::new(false)); + // Helper to wrap source with visualizer tap, normalization, and diagnostic capture - // Pipeline order: Diagnostic (raw) → Amplify (normalization) → Visualizer - // When normalization_gain is None, no Amplify wrapper is inserted (bit-perfect) - let wrap_source = |source: Box + Send>, normalization_gain: Option| -> Box + Send> { + // Pipeline order (normalization ON): + // Diagnostic (raw) → AnalyzerTap → DynamicAmplify → Visualizer + // Pipeline order (normalization OFF — bit-perfect): + // Diagnostic (raw) → Visualizer + let wrap_source = |source: Box + Send>, + normalization_gain: Option, + gain_atomic: Option>, + analyzer_tx: &SyncSender, + analyzer_enabled: &Arc| -> Box + Send> { // Diagnostic tap (innermost — captures raw decoded samples) let source: Box + Send> = Box::new(DiagnosticSource::new(source, thread_diagnostic.clone())); - // Normalization gain (only when enabled — no wrapper at all when OFF) - let source: Box + Send> = if let Some(gain) = normalization_gain { - log::info!("Audio thread: applying normalization gain factor {:.4}", gain); + // Normalization: dynamic (Phase 2) > static (Phase 1 fallback) > none (bit-perfect) + let source: Box + Send> = if let Some(gain_atomic) = gain_atomic { + let initial_gain = normalization_gain.unwrap_or(1.0); + log::info!("Audio thread: dynamic normalization enabled (initial gain {:.4})", initial_gain); + analyzer_enabled.store(true, Ordering::SeqCst); + let source: Box + Send> = Box::new(AnalyzerTap::new(source, analyzer_tx.clone(), analyzer_enabled.clone())); + Box::new(DynamicAmplify::new(source, gain_atomic, initial_gain)) + } else if let Some(gain) = normalization_gain { + log::info!("Audio thread: applying static normalization gain factor {:.4}", gain); Box::new(source.amplify(gain)) } else { source @@ -854,6 +884,8 @@ impl Player { let mut last_empty_check = Instant::now(); // Current track's normalization gain factor (stored for reuse on resume/seek) let mut current_normalization_gain: Option = None; + // Current track's dynamic gain atomic (shared with DynamicAmplify + LoudnessAnalyzer) + let mut current_gain_atomic: Option> = None; log::info!("Audio thread ready and waiting for commands"); @@ -867,7 +899,8 @@ impl Player { pause_suspend_deadline: &mut Option, current_sample_rate: &mut Option, current_channels: &mut Option, - current_normalization_gain: &mut Option| { + current_normalization_gain: &mut Option, + current_gain_atomic: &mut Option>| { match command { AudioCommand::Play { data, track_id, duration_secs, sample_rate, channels } => { log::info!( @@ -1163,19 +1196,48 @@ impl Player { thread_state.duration.store(actual_duration, Ordering::SeqCst); // Calculate normalization gain if enabled - let normalization = thread_settings + let norm_settings = thread_settings .lock() .ok() .filter(|s| s.normalization_enabled) - .and_then(|s| { - let target = s.normalization_target_lufs; - extract_replaygain(&data).map(|rg| calculate_gain_factor(&rg, target)) + .map(|s| s.normalization_target_lufs); + + let (normalization, gain_atomic) = if let Some(target_lufs) = norm_settings { + // Check for ReplayGain metadata first (initial gain hint) + let rg_gain = extract_replaygain(&data).map(|rg| calculate_gain_factor(&rg, target_lufs)); + + // Create shared atomic for dynamic normalization + let atomic = Arc::new(AtomicU32::new( + rg_gain.unwrap_or(1.0).to_bits() + )); + + // Check loudness cache for pre-computed EBU R128 gain + if let Some(cached) = loudness_cache.get(track_id) { + let cached_gain = db_to_linear(cached.gain_db.min(6.0)); + atomic.store(cached_gain.to_bits(), Ordering::Relaxed); + log::info!("Normalization: cache hit for track {}, gain {:.4}", track_id, cached_gain); + } + + // Notify analyzer of new track + let _ = analyzer_tx.try_send(AnalyzerMessage::NewTrack { + track_id, + sample_rate, + channels, + target_lufs, + gain_atomic: atomic.clone(), }); + + (rg_gain, Some(atomic)) + } else { + (None, None) + }; + *current_normalization_gain = normalization; + *current_gain_atomic = gain_atomic.clone(); thread_state.set_normalization_gain(normalization); // Wrap source with diagnostic, normalization, and visualizer - let source = wrap_source(source, normalization); + let source = wrap_source(source, normalization, gain_atomic, &analyzer_tx, &analyzer_enabled); if let Err(e) = engine.append(source) { log::error!("Failed to append source to engine: {}", e); return; @@ -1399,25 +1461,54 @@ impl Player { // This allows the seekbar to show progress even during streaming thread_state.duration.store(duration_secs, Ordering::SeqCst); - // Normalization for streaming: try to extract from buffered data - // If not enough data is buffered yet, skip (bit-perfect for this play) - let normalization = thread_settings + // Normalization for streaming: try ReplayGain from buffered data, + // then fall back to real-time EBU R128 analysis + let norm_settings = thread_settings .lock() .ok() .filter(|s| s.normalization_enabled) - .and_then(|s| { - let target = s.normalization_target_lufs; - source.get_buffered_data().and_then(|data| { - extract_replaygain(&data).map(|rg| calculate_gain_factor(&rg, target)) - }) + .map(|s| s.normalization_target_lufs); + + let (normalization, gain_atomic) = if let Some(target_lufs) = norm_settings { + // Try ReplayGain metadata from buffered data + let rg_gain = source.get_buffered_data().and_then(|data| { + extract_replaygain(&data).map(|rg| calculate_gain_factor(&rg, target_lufs)) }); + + // Create shared atomic for dynamic normalization + let atomic = Arc::new(AtomicU32::new( + rg_gain.unwrap_or(1.0).to_bits() + )); + + // Check loudness cache + if let Some(cached) = loudness_cache.get(track_id) { + let cached_gain = db_to_linear(cached.gain_db.min(6.0)); + atomic.store(cached_gain.to_bits(), Ordering::Relaxed); + log::info!("Streaming normalization: cache hit for track {}, gain {:.4}", track_id, cached_gain); + } + + // Notify analyzer of new track + let _ = analyzer_tx.try_send(AnalyzerMessage::NewTrack { + track_id, + sample_rate, + channels, + target_lufs, + gain_atomic: atomic.clone(), + }); + + (rg_gain, Some(atomic)) + } else { + (None, None) + }; + *current_normalization_gain = normalization; + *current_gain_atomic = gain_atomic.clone(); thread_state.set_normalization_gain(normalization); // Box the incremental source to match the expected type let source_to_play: Box + Send> = Box::new(incremental_source); // Wrap source with diagnostic, normalization, and visualizer - let source_to_play = wrap_source(source_to_play, normalization); + let source_to_play = wrap_source(source_to_play, normalization, gain_atomic, &analyzer_tx, &analyzer_enabled); if let Err(e) = engine.append(source_to_play) { log::error!("Failed to append streaming source to engine: {}", e); return; @@ -1531,8 +1622,8 @@ impl Player { }; // Wrap source with diagnostic, normalization, and visualizer - // Reuse the gain from the original Play (stored in current_normalization_gain) - let skipped_source = wrap_source(skipped_source, *current_normalization_gain); + // Reuse the gain + atomic from the original Play + let skipped_source = wrap_source(skipped_source, *current_normalization_gain, current_gain_atomic.clone(), &analyzer_tx, &analyzer_enabled); if let Err(e) = engine.append(skipped_source) { log::error!("Failed to append source for resume: {}", e); return; @@ -1560,6 +1651,8 @@ impl Player { *current_audio_data = None; *current_streaming_source = None; *current_normalization_gain = None; + *current_gain_atomic = None; + analyzer_enabled.store(false, Ordering::SeqCst); thread_state.set_normalization_gain(None); thread_state.is_playing.store(false, Ordering::SeqCst); thread_state.position.store(0, Ordering::SeqCst); @@ -1632,9 +1725,12 @@ impl Player { let skip_duration = Duration::from_secs(position_secs); let skipped_source: Box + Send> = Box::new(source.skip_duration(skip_duration)); + // Send Reset to analyzer (seek invalidates accumulated samples) + let _ = analyzer_tx.try_send(AnalyzerMessage::Reset); + // Wrap source with diagnostic, normalization, and visualizer - // Reuse the gain from the current track - let skipped_source = wrap_source(skipped_source, *current_normalization_gain); + // Reuse the gain + atomic from the current track + let skipped_source = wrap_source(skipped_source, *current_normalization_gain, current_gain_atomic.clone(), &analyzer_tx, &analyzer_enabled); if let Err(e) = engine.append(skipped_source) { log::error!("Failed to append source for seek: {}", e); return; @@ -1713,6 +1809,7 @@ impl Player { &mut current_sample_rate, &mut current_channels, &mut current_normalization_gain, + &mut current_gain_atomic, ), Err(RecvTimeoutError::Timeout) => { let now = Instant::now(); @@ -1765,6 +1862,7 @@ impl Player { &mut current_sample_rate, &mut current_channels, &mut current_normalization_gain, + &mut current_gain_atomic, ), Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => { @@ -1790,6 +1888,7 @@ impl Player { &mut current_sample_rate, &mut current_channels, &mut current_normalization_gain, + &mut current_gain_atomic, ), Err(_) => { log::info!("Audio thread: channel closed, exiting"); diff --git a/src/lib/components/NowPlayingBar.svelte b/src/lib/components/NowPlayingBar.svelte index a99045fcd..634d3c598 100644 --- a/src/lib/components/NowPlayingBar.svelte +++ b/src/lib/components/NowPlayingBar.svelte @@ -69,10 +69,9 @@ onTrackClick?: () => void; onContextClick?: () => void; queueOpen?: boolean; - // Normalization UI hidden until Phase 2 (EBU R128 analysis) - // normalizationEnabled?: boolean; - // normalizationGain?: number | null; - // onToggleNormalization?: () => void; + normalizationEnabled?: boolean; + normalizationGain?: number | null; + onToggleNormalization?: () => void; } let { @@ -114,7 +113,10 @@ onAlbumClick, onTrackClick, onContextClick, - queueOpen = false + queueOpen = false, + normalizationEnabled = false, + normalizationGain = null, + onToggleNormalization }: Props = $props(); let progressRef: HTMLDivElement; @@ -386,7 +388,6 @@ -
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index ba8a54d21..54aeab454 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -3373,6 +3373,9 @@ }} onContextClick={handleContextNavigation} queueOpen={isQueueOpen} + {normalizationEnabled} + {normalizationGain} + onToggleNormalization={toggleNormalization} onTrackClick={() => { if (currentTrack && !currentTrack.isLocal) { trackInfoTrackId = currentTrack.id;