Skip to main content

qualia_audio/features/mel/
dct.rs

1//! `dct2` — orthonormal Discrete Cosine Transform, type II (the cepstral kernel),
2//! delegated to [`etalon_signal::loudness::dct_ii_into`].
3
4use crate::types::AudioError;
5
6/// Orthonormal DCT-II of `input` into `out` (same length `N`).
7pub fn dct2(input: &[f32], out: &mut [f32]) -> Result<(), AudioError> {
8    let n = input.len();
9    if n == 0 {
10        return Err(AudioError::InvalidParameter);
11    }
12    if out.len() < n {
13        return Err(AudioError::OutputBufferTooSmall);
14    }
15    etalon_signal::loudness::dct_ii_into(input, out);
16    Ok(())
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22
23    #[test]
24    fn dct2_matches_closed_form_reference() {
25        let input = [1.0f32, 2.0, 3.0, 4.0];
26        let mut out = [0.0f32; 4];
27        dct2(&input, &mut out).unwrap();
28        let expected = [5.0f32, -2.23044, 0.0, -0.15851];
29        for (i, (&g, &e)) in out.iter().zip(expected.iter()).enumerate() {
30            assert!((g - e).abs() < 1e-3, "coeff {i}: got {g}, want {e}");
31        }
32    }
33
34    #[test]
35    fn dct2_of_constant_is_pure_dc() {
36        let input = [3.0f32; 8];
37        let mut out = [0.0f32; 8];
38        dct2(&input, &mut out).unwrap();
39        assert!((out[0] - (8.0f32).sqrt() * 3.0).abs() < 1e-3);
40        for &c in &out[1..] {
41            assert!(c.abs() < 1e-4, "AC term nonzero: {c}");
42        }
43    }
44
45    #[test]
46    fn dct2_preserves_energy() {
47        let input = [0.5f32, -1.0, 2.0, 0.25, -0.75, 1.5];
48        let mut out = [0.0f32; 6];
49        dct2(&input, &mut out).unwrap();
50        let e_in: f32 = input.iter().map(|v| v * v).sum();
51        let e_out: f32 = out.iter().map(|v| v * v).sum();
52        assert!((e_in - e_out).abs() < 1e-3, "energy {e_in} vs {e_out}");
53    }
54
55    #[test]
56    fn rejects_short_out() {
57        let input = [1.0f32, 2.0, 3.0];
58        let mut out = [0.0f32; 2];
59        assert_eq!(
60            dct2(&input, &mut out),
61            Err(AudioError::OutputBufferTooSmall)
62        );
63    }
64}