qualia_audio/features/loudness/replay_gain.rs
1//! ReplayGain 2.0 track/album gain from integrated loudness.
2//!
3//! ReplayGain 2.0 normalises to a reference of **−18 LUFS**. Given a program's
4//! measured integrated loudness (LUFS, e.g. from
5//! [`integrated_lufs`](crate::features::loudness::r128::integrated_lufs)), the
6//! recommended gain is `target − measured` dB. Pure scalar arithmetic, zero-heap.
7
8/// ReplayGain 2.0 reference loudness (LUFS).
9pub const REPLAY_GAIN_2_TARGET_LUFS: f32 = -18.0;
10
11/// ReplayGain adjustment in dB for a given integrated loudness (LUFS).
12///
13/// `gain_dB = target − integrated`. Positive → the track is quieter than the
14/// reference and should be turned up; negative → it should be turned down.
15pub fn replay_gain_db(integrated_lufs: f32) -> f32 {
16 REPLAY_GAIN_2_TARGET_LUFS - integrated_lufs
17}
18
19/// The same adjustment as a linear amplitude scale factor (`10^(gain/20)`).
20///
21/// Multiply sample values by this to reach the reference level.
22pub fn replay_gain_scale(integrated_lufs: f32) -> f32 {
23 10f32.powf(replay_gain_db(integrated_lufs) / 20.0)
24}
25
26#[cfg(test)]
27mod tests {
28 use super::*;
29
30 #[test]
31 fn at_reference_gain_is_zero() {
32 assert!((replay_gain_db(-18.0) - 0.0).abs() < 1e-6);
33 assert!((replay_gain_scale(-18.0) - 1.0).abs() < 1e-6);
34 }
35
36 #[test]
37 fn quiet_track_gets_positive_gain() {
38 // −23 LUFS is 5 LU below reference → +5 dB.
39 assert!((replay_gain_db(-23.0) - 5.0).abs() < 1e-6);
40 }
41
42 #[test]
43 fn loud_track_gets_negative_gain() {
44 // −9 LUFS is 9 LU above reference → −9 dB.
45 assert!((replay_gain_db(-9.0) - (-9.0)).abs() < 1e-6);
46 }
47
48 #[test]
49 fn six_db_gain_doubles_amplitude() {
50 // −24 LUFS → +6 dB → scale ≈ 2.0.
51 assert!((replay_gain_scale(-24.0) - 1.9952624).abs() < 1e-4);
52 }
53}