Skip to main content

qualia_audio/aqa/intrusive/
pesq_subset.rs

1//! A small, HONESTLY-LABELLED subset of PESQ-style perceptual processing.
2//!
3//! # This is NOT PESQ / POLQA
4//!
5//! ITU-T P.862 (PESQ) and P.863 (POLQA) are large, licence-encumbered, formally
6//! validated reference algorithms with time alignment, a full auditory model,
7//! asymmetry weighting and a trained mapping to the MOS scale. **This function is
8//! none of that.** It reproduces only three of PESQ's *ideas*, on already-aligned,
9//! already-framed magnitude spectra, and returns a **raw distortion score** — a
10//! non-negative number where 0 is identical and larger is worse. It is **not**
11//! calibrated to MOS and must never be reported as a PESQ/POLQA score.
12//!
13//! The three borrowed steps, applied per matched frame pair:
14//! 1. **Level alignment.** Scale the degraded spectrum so its total power matches
15//!    the reference (PESQ aligns overall gain before comparison, so a pure volume
16//!    change is not counted as distortion).
17//! 2. **Bark-domain warp.** Group linear FFT bins into critical bands on the Bark
18//!    scale (Traunmüller), summing power per band — a coarse stand-in for PESQ's
19//!    pitch-power-density stage.
20//! 3. **Loudness compression + difference.** Compress band powers with a Zwicker
21//!    style `p^0.23` law (perceived loudness grows sub-linearly), then take the
22//!    mean absolute band-loudness difference as the disturbance for that frame.
23//!
24//! Frames are averaged. Pure Rust, allocation-free (fixed Bark-band accumulators),
25//! scalar return.
26
27use crate::types::AudioError;
28
29/// Number of Bark critical bands used for the coarse warp (covers ~0–15.5 Bark,
30/// enough for speech/wideband; fixed so the accumulator is stack-allocated).
31pub const BARK_BANDS: usize = 24;
32
33/// Hz → Bark (Traunmüller 1990), matching `features::mel::bark_bank`.
34#[inline]
35fn hz_to_bark(hz: f32) -> f32 {
36    let f = hz.max(0.0);
37    26.81 * f / (1960.0 + f) - 0.53
38}
39
40/// PESQ-*subset* raw distortion score between two magnitude spectra.
41///
42/// - `reference_mag` / `degraded_mag`: linear magnitude spectra with the same
43///   number of bins, laid out as `k = 0..=N/2` (DC..Nyquist), e.g. the output of
44///   [`crate::features::fft::real_fft_magnitude`].
45/// - `sample_rate`: sampling rate in Hz (used to place bins on the Bark scale).
46///
47/// Returns a raw disturbance score ≥ 0. `0.0` means the two spectra are identical
48/// up to overall level; larger values mean greater perceptual distortion. This is
49/// a distortion (lower is better), NOT a MOS. See the module docs: it is a
50/// documented subset, not certified PESQ/POLQA.
51///
52/// Returns [`AudioError::InvalidParameter`] if the spectra are empty, differ in
53/// length, or `sample_rate` is not positive.
54pub fn pesq_subset(
55    reference_mag: &[f32],
56    degraded_mag: &[f32],
57    sample_rate: f32,
58) -> Result<f32, AudioError> {
59    if reference_mag.is_empty() || reference_mag.len() != degraded_mag.len() || sample_rate <= 0.0 {
60        return Err(AudioError::InvalidParameter);
61    }
62
63    let bins = reference_mag.len();
64    // For a real FFT, bins = N/2 + 1, so N = 2*(bins-1). Guard the 1-bin case.
65    let n_fft = if bins > 1 { 2 * (bins - 1) } else { 2 };
66    let hz_per_bin = sample_rate / n_fft as f32;
67
68    // --- Step 1: level alignment (match total power). ---
69    let mut ref_power = 0.0f32;
70    let mut deg_power = 0.0f32;
71    for k in 0..bins {
72        ref_power += reference_mag[k] * reference_mag[k];
73        deg_power += degraded_mag[k] * degraded_mag[k];
74    }
75    const EPS: f32 = 1.0e-12;
76    // Gain applied to degraded power so its total matches the reference.
77    let gain_power = if deg_power > EPS {
78        (ref_power + EPS) / (deg_power + EPS)
79    } else {
80        1.0
81    };
82
83    // --- Step 2: warp linear power into fixed Bark bands. ---
84    let mut ref_band = [0.0f32; BARK_BANDS];
85    let mut deg_band = [0.0f32; BARK_BANDS];
86    // Bark span mapped onto BARK_BANDS bins.
87    let bark_max = hz_to_bark(sample_rate * 0.5).max(EPS);
88    let band_width = bark_max / BARK_BANDS as f32;
89
90    for k in 0..bins {
91        let hz = k as f32 * hz_per_bin;
92        let bark = hz_to_bark(hz);
93        let mut b = (bark / band_width) as isize;
94        if b < 0 {
95            b = 0;
96        }
97        let b = (b as usize).min(BARK_BANDS - 1);
98        ref_band[b] += reference_mag[k] * reference_mag[k];
99        deg_band[b] += degraded_mag[k] * degraded_mag[k] * gain_power;
100    }
101
102    // --- Step 3: loudness compression + mean absolute band difference. ---
103    // Zwicker-style sub-linear loudness growth.
104    const LOUDNESS_EXP: f32 = 0.23;
105    let mut disturbance = 0.0f32;
106    for b in 0..BARK_BANDS {
107        let lr = (ref_band[b] + EPS).powf(LOUDNESS_EXP);
108        let ld = (deg_band[b] + EPS).powf(LOUDNESS_EXP);
109        disturbance += (lr - ld).abs();
110    }
111
112    Ok(disturbance / BARK_BANDS as f32)
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    fn synth_mag(bins: usize, seed: u32) -> Vec<f32> {
120        let mut state = seed;
121        (0..bins)
122            .map(|_| {
123                state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
124                (state >> 8) as f32 / (1u32 << 24) as f32 // [0,1)
125            })
126            .collect()
127    }
128
129    #[test]
130    fn identical_signals_score_best_zero() {
131        let mag = synth_mag(513, 7);
132        let score = pesq_subset(&mag, &mag, 16_000.0).expect("valid");
133        assert!(
134            score.abs() < 1e-4,
135            "identical spectra must give the best (≈0) distortion, got {score}"
136        );
137    }
138
139    #[test]
140    fn pure_level_change_is_forgiven() {
141        // Level alignment should make a scaled copy nearly identical.
142        let mag = synth_mag(513, 11);
143        let louder: Vec<f32> = mag.iter().map(|&v| v * 3.0).collect();
144        let score = pesq_subset(&mag, &louder, 16_000.0).expect("valid");
145        assert!(
146            score < 1e-2,
147            "a pure gain change should score near-zero, got {score}"
148        );
149    }
150
151    #[test]
152    fn spectral_distortion_scores_worse_than_identity() {
153        let mag = synth_mag(513, 3);
154        let identity = pesq_subset(&mag, &mag, 16_000.0).expect("valid");
155
156        // A genuinely different spectrum (different noise realisation).
157        let other = synth_mag(513, 999);
158        let distorted = pesq_subset(&mag, &other, 16_000.0).expect("valid");
159
160        assert!(
161            distorted > identity,
162            "distorted {distorted} must score worse than identical {identity}"
163        );
164        assert!(distorted.is_finite());
165    }
166
167    #[test]
168    fn more_distortion_scores_worse() {
169        let mag = synth_mag(513, 42);
170        let mild: Vec<f32> = mag
171            .iter()
172            .enumerate()
173            .map(|(k, &v)| if k % 8 == 0 { v * 1.2 } else { v })
174            .collect();
175        let heavy: Vec<f32> = mag
176            .iter()
177            .enumerate()
178            .map(|(k, &v)| if k % 2 == 0 { v * 4.0 } else { v * 0.1 })
179            .collect();
180        let s_mild = pesq_subset(&mag, &mild, 16_000.0).expect("valid");
181        let s_heavy = pesq_subset(&mag, &heavy, 16_000.0).expect("valid");
182        assert!(
183            s_heavy > s_mild,
184            "heavier distortion {s_heavy} must exceed milder {s_mild}"
185        );
186    }
187
188    #[test]
189    fn rejects_bad_input() {
190        assert_eq!(
191            pesq_subset(&[], &[], 16_000.0),
192            Err(AudioError::InvalidParameter)
193        );
194        assert_eq!(
195            pesq_subset(&[1.0, 2.0], &[1.0], 16_000.0),
196            Err(AudioError::InvalidParameter)
197        );
198        assert_eq!(
199            pesq_subset(&[1.0, 2.0], &[1.0, 2.0], 0.0),
200            Err(AudioError::InvalidParameter)
201        );
202    }
203}