Skip to main content

qualia_audio/io/eqloud/
eqloud_loader.rs

1//! Decode + equal-loudness convenience: a single "perceptual load" scalar.
2//!
3//! This is a **cold-path convenience** (not the zero-heap hot path): it takes a
4//! complete WAV byte buffer and returns one number summarising how *loud the
5//! content is to a human ear*, combining three existing primitives:
6//!
7//! 1. [`decode_wav`] → PCM, then [`to_mono_f32`] → mono samples.
8//! 2. Non-overlapping [`BLOCK`]-length FFT magnitude spectra
9//!    ([`real_fft_magnitude`]).
10//! 3. [`apply_equal_loudness`] A-weighting per block.
11//!
12//! The returned value is the root-mean-square of the A-weighted magnitude
13//! spectrum, averaged over all analysis blocks — an equal-loudness-weighted
14//! spectral energy proxy. Two recordings of equal physical amplitude but
15//! different spectral content (e.g. a 1 kHz tone vs. a 50 Hz rumble) yield
16//! different perceptual loads, with mid-band content weighted higher.
17
18use crate::convert::to_mono_f32;
19use crate::features::fft::real_fft::real_fft_magnitude;
20use crate::io::eqloud::equal_loudness::apply_equal_loudness;
21use crate::types::AudioError;
22use crate::wav::decode_wav;
23
24/// FFT analysis block size (power of two) used for the perceptual-load spectrum.
25pub const BLOCK: usize = 1024;
26
27/// Compute the equal-loudness-weighted "perceptual load" of a WAV byte buffer.
28///
29/// Returns a single non-negative scalar (A-weighted spectral RMS averaged over
30/// blocks). Propagates [`AudioError`] from decode / conversion / FFT.
31pub fn perceptual_load_from_wav(bytes: &[u8]) -> Result<f32, AudioError> {
32    let decoded = decode_wav(bytes)?;
33    let view = decoded.view();
34    let sample_rate = view.sample_rate;
35    let frames = view.frames as usize;
36
37    // Cold path: allocate a mono working buffer once.
38    let mut mono = vec![0.0f32; frames];
39    let got = to_mono_f32(view, &mut mono)?;
40    mono.truncate(got);
41
42    let bins = BLOCK / 2 + 1;
43    let mut block = [0.0f32; BLOCK];
44    let mut scratch = vec![0.0f32; 2 * BLOCK];
45    let mut mags = vec![0.0f32; bins];
46    let mut weighted = vec![0.0f32; bins];
47
48    let mut acc = 0.0f64;
49    let mut nblocks = 0usize;
50    let total = mono.len();
51    let mut start = 0usize;
52    loop {
53        // Fill one block, zero-padding the tail past the signal end.
54        for (i, slot) in block.iter_mut().enumerate() {
55            *slot = mono.get(start + i).copied().unwrap_or(0.0);
56        }
57        real_fft_magnitude(&block, &mut scratch, &mut mags)?;
58        apply_equal_loudness(&mags, sample_rate, &mut weighted)?;
59        for &w in weighted.iter() {
60            acc += (w as f64) * (w as f64);
61        }
62        nblocks += 1;
63        start += BLOCK;
64        if start >= total {
65            break;
66        }
67    }
68
69    let denom = (nblocks * bins).max(1) as f64;
70    Ok((acc / denom).sqrt() as f32)
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use crate::wav::encode_wav_i16_mono;
77    use core::f32::consts::TAU;
78
79    /// Encode a mono sine WAV of `n` samples at `freq` Hz, amplitude `amp`.
80    fn sine_wav(freq: f32, amp: f32, n: usize, fs: u32) -> Vec<u8> {
81        let samples: Vec<i16> = (0..n)
82            .map(|i| {
83                let s = amp * (TAU * freq * i as f32 / fs as f32).sin();
84                (s.clamp(-1.0, 1.0) * 32767.0) as i16
85            })
86            .collect();
87        let mut buf = vec![0u8; 44 + samples.len() * 2];
88        let n = encode_wav_i16_mono(&samples, fs, &mut buf).unwrap();
89        buf.truncate(n);
90        buf
91    }
92
93    #[test]
94    fn midband_tone_has_higher_perceptual_load_than_low_rumble() {
95        let fs = 8000;
96        let n = 4096;
97        let amp = 0.5;
98        let mid = sine_wav(1000.0, amp, n, fs); // near unity A-weight
99        let low = sine_wav(100.0, amp, n, fs); // ~ -19 dB A-weight
100
101        let load_mid = perceptual_load_from_wav(&mid).unwrap();
102        let load_low = perceptual_load_from_wav(&low).unwrap();
103
104        assert!(load_mid.is_finite() && load_low.is_finite());
105        assert!(load_mid > 0.0);
106        // Equal physical amplitude, but the mid-band tone is perceptually louder.
107        assert!(
108            load_mid > 2.0 * load_low,
109            "expected mid ({load_mid}) ≫ low ({load_low})"
110        );
111    }
112}