Skip to main content

qualia_audio/features/mel/
mfcc.rs

1//! `mfcc` — Mel-Frequency Cepstral Coefficients: mel bank → log → DCT-II → first
2//! `n_coeffs`. This is the cepstral core reused by [`super::bfcc()`] and
3//! [`super::gfcc()`] with Bark / gammatone banks.
4
5use crate::features::mel::dct::dct2;
6use crate::types::AudioError;
7
8/// Log-energy floor so silent bands map to a large-negative (finite) log, never `-inf`.
9const LOG_FLOOR: f32 = 1e-10;
10
11/// Compute the first `n_coeffs` MFCCs of one power-spectrum frame, allocation-free.
12///
13/// Pipeline: apply the triangular `bank_weights` (`n_mel × n_fft_bins`, row-major),
14/// take `ln(energy + 1e-10)` per band, run an orthonormal DCT-II, and copy the
15/// leading `n_coeffs` cepstral coefficients into `out`. Coefficient 0 (`c0`) is the
16/// overall log-energy; higher coefficients describe spectral shape.
17///
18/// - `power_spectrum`: ≥ `n_fft_bins` (= `bank_weights.len()/n_mel`) values.
19/// - `bank_weights`: the precomputed bank.
20/// - `n_mel`: number of bank rows.
21/// - `n_coeffs`: how many leading coefficients to emit (`1..=n_mel`).
22/// - `out`: ≥ `n_coeffs` floats.
23/// - `scratch`: ≥ `2 * n_mel` floats (log-mel buffer + DCT output); clobbered.
24///
25/// Returns [`AudioError::InvalidParameter`] for degenerate sizes and
26/// [`AudioError::OutputBufferTooSmall`] if `out` or `scratch` are short.
27pub fn mfcc(
28    power_spectrum: &[f32],
29    bank_weights: &[f32],
30    n_mel: usize,
31    n_coeffs: usize,
32    out: &mut [f32],
33    scratch: &mut [f32],
34) -> Result<(), AudioError> {
35    if n_mel == 0
36        || n_coeffs == 0
37        || n_coeffs > n_mel
38        || bank_weights.is_empty()
39        || bank_weights.len() % n_mel != 0
40    {
41        return Err(AudioError::InvalidParameter);
42    }
43    let n_fft_bins = bank_weights.len() / n_mel;
44    if power_spectrum.len() < n_fft_bins {
45        return Err(AudioError::OutputBufferTooSmall);
46    }
47    if out.len() < n_coeffs || scratch.len() < 2 * n_mel {
48        return Err(AudioError::OutputBufferTooSmall);
49    }
50
51    let (log_mel, dct_out) = scratch.split_at_mut(n_mel);
52    let log_mel = &mut log_mel[..n_mel];
53    let dct_out = &mut dct_out[..n_mel];
54
55    for m in 0..n_mel {
56        let row = &bank_weights[m * n_fft_bins..(m + 1) * n_fft_bins];
57        let mut acc = 0.0f32;
58        for (w, p) in row.iter().zip(power_spectrum.iter()) {
59            acc += w * p;
60        }
61        log_mel[m] = (acc + LOG_FLOOR).ln();
62    }
63
64    dct2(log_mel, dct_out)?;
65    out[..n_coeffs].copy_from_slice(&dct_out[..n_coeffs]);
66    Ok(())
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72    use crate::features::mel::mel_bank::build_mel_bank;
73
74    #[test]
75    fn c0_dominates_for_single_tone() {
76        let n_bins = 257;
77        let n_mel = 26;
78        let n_coeffs = 13;
79        let sr = 16_000.0;
80        let mut bank = vec![0.0f32; n_mel * n_bins];
81        build_mel_bank(n_bins, n_mel, sr, 0.0, 8000.0, &mut bank).unwrap();
82
83        // Single-tone power spectrum: energy concentrated in one FFT bin (~2 kHz).
84        let mut power = vec![0.0f32; n_bins];
85        power[64] = 100.0;
86
87        let mut out = vec![0.0f32; n_coeffs];
88        let mut scratch = vec![0.0f32; 2 * n_mel];
89        mfcc(&power, &bank, n_mel, n_coeffs, &mut out, &mut scratch).unwrap();
90
91        // c0 (log-energy) must be the largest-magnitude coefficient.
92        let c0 = out[0].abs();
93        for (k, &c) in out.iter().enumerate().skip(1) {
94            assert!(
95                c0 > c.abs(),
96                "c0 ({c0}) does not dominate coeff {k} ({})",
97                c.abs()
98            );
99        }
100    }
101
102    #[test]
103    fn rejects_small_scratch() {
104        let n_bins = 5;
105        let n_mel = 4;
106        let bank = vec![0.1f32; n_mel * n_bins];
107        let power = vec![1.0f32; n_bins];
108        let mut out = vec![0.0f32; 2];
109        let mut scratch = vec![0.0f32; 3]; // needs 2*n_mel = 8
110        assert_eq!(
111            mfcc(&power, &bank, n_mel, 2, &mut out, &mut scratch),
112            Err(AudioError::OutputBufferTooSmall)
113        );
114    }
115}