feat(audio): add volume normalization (Phase 1 — ReplayGain metadata)
Add ReplayGain-based volume normalization to the audio pipeline. When enabled, extracts ReplayGain track gain/peak tags from audio file metadata (Vorbis comments, ID3v2 TXXX) and applies a gain factor via rodio's Amplify wrapper. Pipeline order: Diagnostic (raw) -> Amplify (normalization) -> Visualizer When normalization is OFF (default), no Amplify wrapper is inserted and the pipeline remains 100% bit-perfect. - New module: audio/loudness.rs (extraction + gain calculation) - New settings: normalization_enabled, normalization_target_lufs - New Tauri commands: set_audio_normalization_enabled/target - Supports -14 LUFS (default), -18 LUFS, -23 LUFS targets - Clipping prevention using peak metadata - Gain preserved across resume/seek operations cc
This commit is contained in:
1 parent
a237be3a83
commit
6edd2a3cda
6 files changed
+471
-15
No files matched your search
@@ -0,0 +1,335 @@
|
||||
//! Loudness normalization support
|
||||
//!
|
||||
//! Extracts ReplayGain metadata from audio files and calculates gain factors
|
||||
//! for volume normalization. When normalization is disabled, this module is
|
||||
//! not invoked and the audio pipeline remains bit-perfect.
|
||||
|
||||
use symphonia::core::formats::FormatReader;
|
||||
use symphonia::core::meta::{MetadataOptions, StandardTagKey, Tag, Value};
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::io::{MediaSource, MediaSourceStream};
|
||||
use symphonia::core::probe::Hint;
|
||||
use symphonia::default::get_probe;
|
||||
use std::io::{Cursor, Read, Seek, SeekFrom};
|
||||
|
||||
/// Extracted loudness data for a track
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReplayGainData {
|
||||
/// Gain adjustment in dB (negative = reduce volume, positive = increase)
|
||||
pub gain_db: f32,
|
||||
/// Peak sample value (0.0-1.0+), used for clipping prevention
|
||||
pub peak: Option<f32>,
|
||||
}
|
||||
|
||||
/// Wrapper to make Cursor<Vec<u8>> implement MediaSource
|
||||
struct CursorMediaSource {
|
||||
inner: Cursor<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl CursorMediaSource {
|
||||
fn new(data: Vec<u8>) -> Self {
|
||||
Self { inner: Cursor::new(data) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for CursorMediaSource {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.inner.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for CursorMediaSource {
|
||||
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
|
||||
self.inner.seek(pos)
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaSource for CursorMediaSource {
|
||||
fn is_seekable(&self) -> bool { true }
|
||||
fn byte_len(&self) -> Option<u64> {
|
||||
Some(self.inner.get_ref().len() as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract ReplayGain metadata from raw audio file bytes.
|
||||
///
|
||||
/// Searches for ReplayGain track gain and peak values in:
|
||||
/// - Vorbis comments (FLAC, Ogg): `REPLAYGAIN_TRACK_GAIN`, `REPLAYGAIN_TRACK_PEAK`
|
||||
/// - ID3v2 TXXX frames: `replaygain_track_gain`
|
||||
/// - Standard tag keys mapped by Symphonia
|
||||
///
|
||||
/// Returns `None` if no ReplayGain metadata is found.
|
||||
pub fn extract_replaygain(data: &[u8]) -> Option<ReplayGainData> {
|
||||
let source = Box::new(CursorMediaSource::new(data.to_vec())) as Box<dyn MediaSource>;
|
||||
let mss = MediaSourceStream::new(source, Default::default());
|
||||
|
||||
let mut hint = Hint::new();
|
||||
// Help Symphonia detect isomp4/m4a
|
||||
if data.len() >= 12 && &data[4..8] == b"ftyp" {
|
||||
hint.with_extension("m4a");
|
||||
}
|
||||
|
||||
let format_opts = FormatOptions {
|
||||
enable_gapless: true,
|
||||
..Default::default()
|
||||
};
|
||||
let metadata_opts: MetadataOptions = Default::default();
|
||||
|
||||
let mut probed = match get_probe().format(&hint, mss, &format_opts, &metadata_opts) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
log::debug!("Loudness: probe failed for ReplayGain extraction: {}", e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
// Collect all tags from both the probe metadata and the format reader metadata
|
||||
let mut gain_db: Option<f32> = None;
|
||||
let mut peak: Option<f32> = None;
|
||||
|
||||
// Check probe-level metadata (container-level tags)
|
||||
if let Some(metadata) = probed.metadata.get() {
|
||||
if let Some(rev) = metadata.current() {
|
||||
extract_from_tags(rev.tags(), &mut gain_db, &mut peak);
|
||||
}
|
||||
}
|
||||
|
||||
// Check format-level metadata (in-stream tags, e.g., Vorbis comments in FLAC)
|
||||
if gain_db.is_none() {
|
||||
let fmt_metadata = probed.format.metadata();
|
||||
if let Some(rev) = fmt_metadata.current() {
|
||||
extract_from_tags(rev.tags(), &mut gain_db, &mut peak);
|
||||
}
|
||||
}
|
||||
|
||||
gain_db.map(|db| {
|
||||
log::info!("Loudness: found ReplayGain: {:.2} dB, peak: {:?}", db, peak);
|
||||
ReplayGainData { gain_db: db, peak }
|
||||
})
|
||||
}
|
||||
|
||||
/// Extract ReplayGain data from a Symphonia FormatReader (for streaming sources).
|
||||
///
|
||||
/// This is used when we already have a probed format reader and don't want
|
||||
/// to re-probe the data.
|
||||
pub fn extract_replaygain_from_reader(format: &mut dyn FormatReader) -> Option<ReplayGainData> {
|
||||
let mut gain_db: Option<f32> = None;
|
||||
let mut peak: Option<f32> = None;
|
||||
|
||||
let metadata = format.metadata();
|
||||
if let Some(rev) = metadata.current() {
|
||||
extract_from_tags(rev.tags(), &mut gain_db, &mut peak);
|
||||
}
|
||||
|
||||
gain_db.map(|db| {
|
||||
log::info!("Loudness: found ReplayGain (streaming): {:.2} dB, peak: {:?}", db, peak);
|
||||
ReplayGainData { gain_db: db, peak }
|
||||
})
|
||||
}
|
||||
|
||||
/// Search tags for ReplayGain values.
|
||||
fn extract_from_tags(tags: &[Tag], gain_db: &mut Option<f32>, peak: &mut Option<f32>) {
|
||||
for tag in tags {
|
||||
// Check Symphonia's standard tag key mapping first
|
||||
if let Some(std_key) = tag.std_key {
|
||||
match std_key {
|
||||
StandardTagKey::ReplayGainTrackGain => {
|
||||
if let Some(g) = parse_gain_value(&tag.value) {
|
||||
*gain_db = Some(g);
|
||||
}
|
||||
}
|
||||
StandardTagKey::ReplayGainTrackPeak => {
|
||||
if let Some(p) = parse_peak_value(&tag.value) {
|
||||
*peak = Some(p);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Also check raw tag keys (case-insensitive) for formats where
|
||||
// Symphonia might not map to StandardTagKey
|
||||
let key_lower = tag.key.to_lowercase();
|
||||
match key_lower.as_str() {
|
||||
"replaygain_track_gain" => {
|
||||
if gain_db.is_none() {
|
||||
if let Some(g) = parse_gain_value(&tag.value) {
|
||||
*gain_db = Some(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
"replaygain_track_peak" => {
|
||||
if peak.is_none() {
|
||||
if let Some(p) = parse_peak_value(&tag.value) {
|
||||
*peak = Some(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a ReplayGain gain value like "-6.54 dB" or "-6.54"
|
||||
fn parse_gain_value(value: &Value) -> Option<f32> {
|
||||
let s = value_to_string(value)?;
|
||||
// Strip " dB" suffix if present, then parse
|
||||
let trimmed = s.trim().trim_end_matches(" dB").trim_end_matches(" db").trim_end_matches("dB");
|
||||
trimmed.parse::<f32>().ok()
|
||||
}
|
||||
|
||||
/// Parse a ReplayGain peak value like "0.988553" or "1.0"
|
||||
fn parse_peak_value(value: &Value) -> Option<f32> {
|
||||
let s = value_to_string(value)?;
|
||||
s.trim().parse::<f32>().ok()
|
||||
}
|
||||
|
||||
/// Convert a Symphonia Value to a string representation
|
||||
fn value_to_string(value: &Value) -> Option<String> {
|
||||
match value {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Float(f) => Some(f.to_string()),
|
||||
Value::SignedInt(i) => Some(i.to_string()),
|
||||
Value::UnsignedInt(u) => Some(u.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a gain in dB to a linear amplitude factor.
|
||||
///
|
||||
/// gain_db = 0.0 → factor = 1.0 (no change)
|
||||
/// gain_db = -6.0 → factor ≈ 0.501 (half amplitude)
|
||||
/// gain_db = +6.0 → factor ≈ 1.995 (double amplitude)
|
||||
#[inline]
|
||||
pub fn db_to_linear(db: f32) -> f32 {
|
||||
10_f32.powf(db / 20.0)
|
||||
}
|
||||
|
||||
/// Calculate the normalization gain factor for a track.
|
||||
///
|
||||
/// Takes ReplayGain metadata and a target LUFS level, returns the linear
|
||||
/// gain factor to apply to samples. Includes clipping prevention using
|
||||
/// peak data when available.
|
||||
///
|
||||
/// The ReplayGain standard targets -18 LUFS (83 dB SPL). If the user's
|
||||
/// target differs, we adjust accordingly.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `rg` - ReplayGain metadata extracted from the track
|
||||
/// * `target_lufs` - User's target loudness (e.g., -14.0, -18.0, -23.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Linear gain factor to multiply samples by
|
||||
pub fn calculate_gain_factor(rg: &ReplayGainData, target_lufs: f32) -> f32 {
|
||||
// ReplayGain reference level is -18 LUFS (EBU R128 / ReplayGain 2.0)
|
||||
const REPLAYGAIN_REFERENCE_LUFS: f32 = -18.0;
|
||||
|
||||
// Adjust gain for the user's target level
|
||||
// If target is -14 LUFS (louder than reference), we need to add +4 dB
|
||||
// If target is -23 LUFS (quieter), we need to subtract -5 dB
|
||||
let target_adjustment = target_lufs - REPLAYGAIN_REFERENCE_LUFS;
|
||||
let adjusted_gain_db = rg.gain_db + target_adjustment;
|
||||
|
||||
let mut gain = db_to_linear(adjusted_gain_db);
|
||||
|
||||
// Clipping prevention: if we have peak data, cap the gain so
|
||||
// the loudest sample doesn't exceed 1.0
|
||||
if let Some(peak) = rg.peak {
|
||||
if peak > 0.0 {
|
||||
let max_safe_gain = 1.0 / peak;
|
||||
if gain > max_safe_gain {
|
||||
log::debug!(
|
||||
"Loudness: capping gain from {:.3} to {:.3} (peak: {:.4})",
|
||||
gain, max_safe_gain, peak
|
||||
);
|
||||
gain = max_safe_gain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without peak data, cap at +6 dB maximum (conservative)
|
||||
if rg.peak.is_none() {
|
||||
let max_gain = db_to_linear(6.0);
|
||||
if gain > max_gain {
|
||||
log::debug!("Loudness: capping gain to +6 dB (no peak data)");
|
||||
gain = max_gain;
|
||||
}
|
||||
}
|
||||
|
||||
log::debug!(
|
||||
"Loudness: gain_db={:.2}, target={:.1} LUFS, adjusted={:.2} dB, factor={:.4}",
|
||||
rg.gain_db, target_lufs, adjusted_gain_db, gain
|
||||
);
|
||||
|
||||
gain
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_db_to_linear() {
|
||||
// 0 dB = factor 1.0
|
||||
assert!((db_to_linear(0.0) - 1.0).abs() < 0.001);
|
||||
// -6 dB ≈ 0.501
|
||||
assert!((db_to_linear(-6.0) - 0.501).abs() < 0.01);
|
||||
// +6 dB ≈ 1.995
|
||||
assert!((db_to_linear(6.0) - 1.995).abs() < 0.01);
|
||||
// -20 dB = 0.1
|
||||
assert!((db_to_linear(-20.0) - 0.1).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calculate_gain_factor_at_reference() {
|
||||
// At -18 LUFS target (ReplayGain reference), gain_db should pass through directly
|
||||
let rg = ReplayGainData { gain_db: -3.0, peak: Some(0.9) };
|
||||
let factor = calculate_gain_factor(&rg, -18.0);
|
||||
// -3 dB → ~0.708
|
||||
assert!((factor - 0.708).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calculate_gain_factor_with_target_adjustment() {
|
||||
// At -14 LUFS target, we add +4 dB to the RG gain
|
||||
let rg = ReplayGainData { gain_db: -3.0, peak: Some(0.5) };
|
||||
let factor = calculate_gain_factor(&rg, -14.0);
|
||||
// -3 + 4 = +1 dB → ~1.122
|
||||
assert!((factor - 1.122).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clipping_prevention_with_peak() {
|
||||
// High positive gain but peak close to 1.0 — should be capped
|
||||
let rg = ReplayGainData { gain_db: 10.0, peak: Some(0.95) };
|
||||
let factor = calculate_gain_factor(&rg, -18.0);
|
||||
// max_safe_gain = 1/0.95 ≈ 1.053, which is less than db_to_linear(10) ≈ 3.162
|
||||
assert!((factor - (1.0 / 0.95)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clipping_prevention_without_peak() {
|
||||
// High gain without peak data — capped at +6 dB
|
||||
let rg = ReplayGainData { gain_db: 12.0, peak: None };
|
||||
let factor = calculate_gain_factor(&rg, -18.0);
|
||||
assert!((factor - db_to_linear(6.0)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_gain_value_formats() {
|
||||
// Standard format: "-6.54 dB"
|
||||
assert!((parse_gain_value(&Value::String("-6.54 dB".to_string())).unwrap() - (-6.54)).abs() < 0.001);
|
||||
// Without dB suffix
|
||||
assert!((parse_gain_value(&Value::String("-6.54".to_string())).unwrap() - (-6.54)).abs() < 0.001);
|
||||
// Positive
|
||||
assert!((parse_gain_value(&Value::String("+3.21 dB".to_string())).unwrap() - 3.21).abs() < 0.001);
|
||||
// Float value
|
||||
assert!((parse_gain_value(&Value::Float(-6.54)).unwrap() - (-6.54)).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_peak_value() {
|
||||
assert!((parse_peak_value(&Value::String("0.988553".to_string())).unwrap() - 0.988553).abs() < 0.0001);
|
||||
assert!((parse_peak_value(&Value::Float(0.95)).unwrap() - 0.95).abs() < 0.001);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod alsa_backend;
|
||||
pub mod pulse_backend;
|
||||
pub mod alsa_direct;
|
||||
pub mod diagnostic;
|
||||
pub mod loudness;
|
||||
|
||||
// Re-export commonly used types
|
||||
pub use backend::{
|
||||
@@ -23,3 +24,4 @@ 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};
|
||||
@@ -30,6 +30,12 @@ pub struct AudioSettings {
|
||||
/// Cached max sample rate of the selected device (set when device is selected)
|
||||
/// Used when limit_quality_to_device is true
|
||||
pub device_max_sample_rate: Option<u32>,
|
||||
/// When true, apply volume normalization using ReplayGain metadata.
|
||||
/// When false (default), the audio pipeline is 100% bit-perfect — no sample modification.
|
||||
pub normalization_enabled: bool,
|
||||
/// Target loudness in LUFS for normalization.
|
||||
/// Common values: -14.0 (Spotify/YouTube), -18.0 (audiophile), -23.0 (EBU broadcast)
|
||||
pub normalization_target_lufs: f32,
|
||||
}
|
||||
|
||||
impl Default for AudioSettings {
|
||||
@@ -47,6 +53,8 @@ impl Default for AudioSettings {
|
||||
streaming_only: false, // Disabled by default (cache tracks for instant replay)
|
||||
limit_quality_to_device: false, // Disabled in 1.1.9 — detection logic unreliable (#45)
|
||||
device_max_sample_rate: None, // Set when device is selected
|
||||
normalization_enabled: false, // Off by default — preserves bit-perfect pipeline
|
||||
normalization_target_lufs: -14.0, // Spotify/YouTube standard
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,6 +98,8 @@ impl AudioSettingsStore {
|
||||
let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN streaming_only INTEGER DEFAULT 0", []);
|
||||
let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN limit_quality_to_device INTEGER DEFAULT 0", []);
|
||||
let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN device_max_sample_rate INTEGER", []);
|
||||
let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN normalization_enabled INTEGER DEFAULT 0", []);
|
||||
let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN normalization_target_lufs REAL DEFAULT -14.0", []);
|
||||
|
||||
Ok(Self { conn })
|
||||
}
|
||||
@@ -108,7 +118,7 @@ impl AudioSettingsStore {
|
||||
pub fn get_settings(&self) -> Result<AudioSettings, String> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate FROM audio_settings WHERE id = 1",
|
||||
"SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs FROM audio_settings WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
// Parse backend_type from JSON string
|
||||
@@ -134,6 +144,8 @@ impl AudioSettingsStore {
|
||||
streaming_only: row.get::<_, Option<i64>>(9)?.unwrap_or(0) != 0,
|
||||
limit_quality_to_device: row.get::<_, Option<i64>>(10)?.unwrap_or(1) != 0,
|
||||
device_max_sample_rate: row.get::<_, Option<i64>>(11)?.map(|r| r as u32),
|
||||
normalization_enabled: row.get::<_, Option<i64>>(12)?.unwrap_or(0) != 0,
|
||||
normalization_target_lufs: row.get::<_, Option<f64>>(13)?.unwrap_or(-14.0) as f32,
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -271,6 +283,26 @@ impl AudioSettingsStore {
|
||||
.map_err(|e| format!("Failed to set device max sample rate: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_normalization_enabled(&self, enabled: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE audio_settings SET normalization_enabled = ?1 WHERE id = 1",
|
||||
params![enabled as i64],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set normalization enabled: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_normalization_target_lufs(&self, target: f32) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE audio_settings SET normalization_target_lufs = ?1 WHERE id = 1",
|
||||
params![target as f64],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set normalization target LUFS: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Thread-safe wrapper
|
||||
@@ -448,3 +480,25 @@ pub fn set_audio_device_max_sample_rate(
|
||||
let store = guard.as_ref().ok_or("No active session - please log in")?;
|
||||
store.set_device_max_sample_rate(rate)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_audio_normalization_enabled(
|
||||
state: tauri::State<'_, AudioSettingsState>,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: set_audio_normalization_enabled {}", enabled);
|
||||
let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?;
|
||||
let store = guard.as_ref().ok_or("No active session - please log in")?;
|
||||
store.set_normalization_enabled(enabled)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_audio_normalization_target(
|
||||
state: tauri::State<'_, AudioSettingsState>,
|
||||
target_lufs: f32,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: set_audio_normalization_target {} LUFS", target_lufs);
|
||||
let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?;
|
||||
let store = guard.as_ref().ok_or("No active session - please log in")?;
|
||||
store.set_normalization_target_lufs(target_lufs)
|
||||
}
|
||||
@@ -733,6 +733,8 @@ pub fn run() {
|
||||
config::audio_settings::set_audio_streaming_only,
|
||||
config::audio_settings::set_audio_limit_quality_to_device,
|
||||
config::audio_settings::set_audio_device_max_sample_rate,
|
||||
config::audio_settings::set_audio_normalization_enabled,
|
||||
config::audio_settings::set_audio_normalization_target,
|
||||
// Audio backend commands
|
||||
commands::get_available_backends,
|
||||
commands::get_devices_for_backend,
|
||||
|
||||
+59
-14
@@ -37,7 +37,7 @@ 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};
|
||||
use crate::audio::{AudioBackendType, AudioDiagnostic, BackendConfig, BackendManager, DiagnosticSource, extract_replaygain, calculate_gain_factor};
|
||||
use crate::config::audio_settings::AudioSettings;
|
||||
use crate::visualizer::{VisualizerTap, TappedSource};
|
||||
use playback_engine::PlaybackEngine;
|
||||
@@ -682,12 +682,22 @@ impl Player {
|
||||
thread::spawn(move || {
|
||||
log::info!("Audio thread starting...");
|
||||
|
||||
// Helper to wrap source with visualizer tap and diagnostic capture
|
||||
let wrap_source = |source: Box<dyn Source<Item = f32> + Send>| -> Box<dyn Source<Item = f32> + Send> {
|
||||
// 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<dyn Source<Item = f32> + Send>, normalization_gain: Option<f32>| -> Box<dyn Source<Item = f32> + Send> {
|
||||
// Diagnostic tap (innermost — captures raw decoded samples)
|
||||
let source: Box<dyn Source<Item = f32> + Send> =
|
||||
Box::new(DiagnosticSource::new(source, thread_diagnostic.clone()));
|
||||
|
||||
// Normalization gain (only when enabled — no wrapper at all when OFF)
|
||||
let source: Box<dyn Source<Item = f32> + Send> = if let Some(gain) = normalization_gain {
|
||||
log::info!("Audio thread: applying normalization gain factor {:.4}", gain);
|
||||
Box::new(source.amplify(gain))
|
||||
} else {
|
||||
source
|
||||
};
|
||||
|
||||
// Visualizer tap (outermost)
|
||||
if let Some(ref tap) = thread_viz_tap {
|
||||
Box::new(TappedSource::new(source, tap.ring_buffer.clone(), tap.enabled.clone()))
|
||||
@@ -822,6 +832,8 @@ impl Player {
|
||||
const PAUSE_SUSPEND_DELAY_MS: u64 = 2000;
|
||||
let mut pause_suspend_deadline: Option<Instant> = None;
|
||||
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<f32> = None;
|
||||
|
||||
log::info!("Audio thread ready and waiting for commands");
|
||||
|
||||
@@ -834,7 +846,8 @@ impl Player {
|
||||
consecutive_sink_failures: &mut u32,
|
||||
pause_suspend_deadline: &mut Option<Instant>,
|
||||
current_sample_rate: &mut Option<u32>,
|
||||
current_channels: &mut Option<u16>| {
|
||||
current_channels: &mut Option<u16>,
|
||||
current_normalization_gain: &mut Option<f32>| {
|
||||
match command {
|
||||
AudioCommand::Play { data, track_id, duration_secs, sample_rate, channels } => {
|
||||
log::info!(
|
||||
@@ -1129,8 +1142,19 @@ impl Player {
|
||||
.unwrap_or(duration_secs);
|
||||
thread_state.duration.store(actual_duration, Ordering::SeqCst);
|
||||
|
||||
// Wrap source for visualization (if enabled)
|
||||
let source = wrap_source(source);
|
||||
// Calculate normalization gain if enabled
|
||||
let normalization = 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))
|
||||
});
|
||||
*current_normalization_gain = normalization;
|
||||
|
||||
// Wrap source with diagnostic, normalization, and visualizer
|
||||
let source = wrap_source(source, normalization);
|
||||
if let Err(e) = engine.append(source) {
|
||||
log::error!("Failed to append source to engine: {}", e);
|
||||
return;
|
||||
@@ -1143,8 +1167,9 @@ impl Player {
|
||||
|
||||
*current_engine = Some(engine);
|
||||
log::info!(
|
||||
"Audio thread: playback started, duration: {}s",
|
||||
actual_duration
|
||||
"Audio thread: playback started, duration: {}s, normalization: {}",
|
||||
actual_duration,
|
||||
normalization.map(|g| format!("{:.4}x", g)).unwrap_or_else(|| "off".to_string())
|
||||
);
|
||||
}
|
||||
AudioCommand::PlayStreaming { source, track_id, sample_rate, channels, duration_secs } => {
|
||||
@@ -1353,10 +1378,24 @@ 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
|
||||
.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))
|
||||
})
|
||||
});
|
||||
*current_normalization_gain = normalization;
|
||||
|
||||
// Box the incremental source to match the expected type
|
||||
let source_to_play: Box<dyn Source<Item = f32> + Send> = Box::new(incremental_source);
|
||||
// Wrap source for visualization (if enabled)
|
||||
let source_to_play = wrap_source(source_to_play);
|
||||
// Wrap source with diagnostic, normalization, and visualizer
|
||||
let source_to_play = wrap_source(source_to_play, normalization);
|
||||
if let Err(e) = engine.append(source_to_play) {
|
||||
log::error!("Failed to append streaming source to engine: {}", e);
|
||||
return;
|
||||
@@ -1469,8 +1508,9 @@ impl Player {
|
||||
source
|
||||
};
|
||||
|
||||
// Wrap source for visualization (if enabled)
|
||||
let skipped_source = wrap_source(skipped_source);
|
||||
// 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);
|
||||
if let Err(e) = engine.append(skipped_source) {
|
||||
log::error!("Failed to append source for resume: {}", e);
|
||||
return;
|
||||
@@ -1497,6 +1537,7 @@ impl Player {
|
||||
}
|
||||
*current_audio_data = None;
|
||||
*current_streaming_source = None;
|
||||
*current_normalization_gain = None;
|
||||
thread_state.is_playing.store(false, Ordering::SeqCst);
|
||||
thread_state.position.store(0, Ordering::SeqCst);
|
||||
thread_state.playback_start_millis.store(0, Ordering::SeqCst);
|
||||
@@ -1568,8 +1609,9 @@ impl Player {
|
||||
let skip_duration = Duration::from_secs(position_secs);
|
||||
let skipped_source: Box<dyn Source<Item = f32> + Send> = Box::new(source.skip_duration(skip_duration));
|
||||
|
||||
// Wrap source for visualization (if enabled)
|
||||
let skipped_source = wrap_source(skipped_source);
|
||||
// Wrap source with diagnostic, normalization, and visualizer
|
||||
// Reuse the gain from the current track
|
||||
let skipped_source = wrap_source(skipped_source, *current_normalization_gain);
|
||||
if let Err(e) = engine.append(skipped_source) {
|
||||
log::error!("Failed to append source for seek: {}", e);
|
||||
return;
|
||||
@@ -1647,6 +1689,7 @@ impl Player {
|
||||
&mut pause_suspend_deadline,
|
||||
&mut current_sample_rate,
|
||||
&mut current_channels,
|
||||
&mut current_normalization_gain,
|
||||
),
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
let now = Instant::now();
|
||||
@@ -1698,6 +1741,7 @@ impl Player {
|
||||
&mut pause_suspend_deadline,
|
||||
&mut current_sample_rate,
|
||||
&mut current_channels,
|
||||
&mut current_normalization_gain,
|
||||
),
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
@@ -1722,6 +1766,7 @@ impl Player {
|
||||
&mut pause_suspend_deadline,
|
||||
&mut current_sample_rate,
|
||||
&mut current_channels,
|
||||
&mut current_normalization_gain,
|
||||
),
|
||||
Err(_) => {
|
||||
log::info!("Audio thread: channel closed, exiting");
|
||||
|
||||
@@ -242,6 +242,24 @@ impl BufferedMediaSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a copy of the currently buffered data (for metadata extraction).
|
||||
///
|
||||
/// Returns whatever data has been downloaded so far, even if incomplete.
|
||||
/// Useful for extracting file-level metadata (e.g., ReplayGain tags)
|
||||
/// which are typically in the first few KB of the file.
|
||||
pub fn get_buffered_data(&self) -> Option<Vec<u8>> {
|
||||
let (lock, _) = &*self.state;
|
||||
if let Ok(state) = lock.lock() {
|
||||
if state.data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(state.data.clone())
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get download progress as a fraction (0.0 to 1.0)
|
||||
///
|
||||
/// Returns None if total size is unknown
|
||||
|
||||
Reference in new issue
Block a user