adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
Documentation
//! Whisper log-mel spectrogram on the MLX device.

use mlx_rs::ops::indexing::TryIndexOp;
use mlx_rs::{Array, ops};

use super::{mlx_err, stt_error};
use crate::error::AudioResult;
use crate::mlx::filters::{HOP_LENGTH, N_FFT, N_FREQS, hann_periodic, mel_filterbank};

/// 30 s window at 16 kHz.
pub(crate) const N_SAMPLES: usize = 480_000;
/// Mel frames per 30 s window.
pub(crate) const N_FRAMES: usize = 3_000;
/// Centred STFT frames over the reflect-padded window (`N_FRAMES + 1`).
const N_STFT_FRAMES: usize = N_FRAMES + 1;

/// Device-resident Whisper front end: Hann window and transposed mel filters.
pub(crate) struct MelFrontend {
    /// `[N_FFT]` periodic Hann window.
    window: Array,
    /// `[N_FREQS, n_mels]` (filterbank transposed for `power @ filters`).
    filters: Array,
    /// Gather indices for the left reflect pad: `x[PAD], .., x[1]`.
    reflect_left: Array,
    /// Gather indices for the right reflect pad: `x[N-2], .., x[N-1-PAD]`.
    reflect_right: Array,
}

/// `torch.stft(center=True)` reflect padding on each side.
const PAD: usize = N_FFT / 2;

impl MelFrontend {
    /// Uploads the window, mel filterbank and reflect-pad indices for
    /// `n_mels` ∈ {80, 128}.
    pub fn new(n_mels: usize) -> AudioResult<Self> {
        if !matches!(n_mels, 80 | 128) {
            return Err(stt_error(format!("MelFrontend::new: unsupported n_mels {n_mels}")));
        }
        let window = Array::from_slice(&hann_periodic(N_FFT), &[N_FFT as i32]);
        let filters = Array::from_slice(&mel_filterbank(n_mels), &[n_mels as i32, N_FREQS as i32])
            .transpose()
            .map_err(mlx_err("transpose mel filters"))?;

        let left: Vec<i32> = (1..=PAD as i32).rev().collect();
        let last = N_SAMPLES as i32 - 1;
        let right: Vec<i32> = (1..=PAD as i32).map(|i| last - i).collect();
        let reflect_left = Array::from_slice(&left, &[PAD as i32]);
        let reflect_right = Array::from_slice(&right, &[PAD as i32]);

        // Materialise everything on the device once, not on the first call.
        mlx_rs::transforms::eval([&window, &filters, &reflect_left, &reflect_right])
            .map_err(mlx_err("upload mel front end"))?;
        Ok(Self { window, filters, reflect_left, reflect_right })
    }

    /// Log-mel spectrogram of one 30 s window `[480000]` f32 → `[1, 3000, n_mels]`.
    ///
    /// Mirrors openai/whisper `log_mel_spectrogram`: centred reflect-padded STFT
    /// (`n_fft = 400`, `hop = 160`, periodic Hann), power spectrum, mel
    /// projection, `log10(max(x, 1e-10))`, dynamic range clamp to `max - 8`,
    /// `(x + 4) / 4`. The result is lazy; the caller evaluates it.
    ///
    /// Like Whisper, frames all 3001 centred STFT windows and drops the last
    /// one before the mel projection (so it never affects the `max - 8` clamp).
    pub fn log_mel(&self, window_pcm: &Array) -> AudioResult<Array> {
        if window_pcm.shape() != [N_SAMPLES as i32] {
            return Err(stt_error(format!(
                "log_mel: expected PCM shape [{N_SAMPLES}], got {:?}",
                window_pcm.shape()
            )));
        }

        let left = window_pcm.take(&self.reflect_left).map_err(mlx_err("reflect pad"))?;
        let right = window_pcm.take(&self.reflect_right).map_err(mlx_err("reflect pad"))?;
        let padded =
            ops::concatenate(&[&left, window_pcm, &right], 0).map_err(mlx_err("reflect pad"))?;

        let frames = padded
            .as_strided(&[N_STFT_FRAMES as i32, N_FFT as i32][..], &[HOP_LENGTH as i64, 1][..], 0)
            .map_err(mlx_err("frame"))?
            .multiply(&self.window)
            .map_err(mlx_err("window"))?;
        let power = mlx_rs::fft::rfft(&frames, N_FFT as i32, -1)
            .and_then(|spec| spec.abs())
            .and_then(|mag| mag.square())
            .and_then(|pow| pow.try_index(0..N_FRAMES as i32))
            .map_err(mlx_err("stft"))?;

        let log_spec = power
            .matmul(&self.filters)
            .and_then(|mel| ops::maximum(&mel, Array::from_f32(1e-10)))
            .and_then(|mel| mel.log10())
            .map_err(mlx_err("log mel"))?;
        let floor = log_spec
            .max(None)
            .and_then(|m| m.subtract(Array::from_f32(8.0)))
            .map_err(mlx_err("dynamic range"))?;
        let n_mels = self.filters.shape()[1];
        ops::maximum(&log_spec, &floor)
            .and_then(|x| x.add(Array::from_f32(4.0)))
            .and_then(|x| x.divide(Array::from_f32(4.0)))
            .and_then(|x| x.reshape(&[1, N_FRAMES as i32, n_mels]))
            .map_err(mlx_err("normalise"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mlx::filters::tests::{f32_values, reference_case, reference_fixture};

    fn sine_window() -> Array {
        let mut pcm = vec![0.0f32; N_SAMPLES];
        for (i, s) in pcm.iter_mut().take(16_000).enumerate() {
            let t = i as f64 / 16_000.0;
            *s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()) as f32;
        }
        Array::from_slice(&pcm, &[N_SAMPLES as i32])
    }

    fn assert_log_mel_matches(n_mels: usize) {
        let fixture = reference_fixture();
        let case = reference_case(&fixture, n_mels);
        let frontend = MelFrontend::new(n_mels).expect("frontend");
        let mel = frontend.log_mel(&sine_window()).expect("log_mel");
        mel.eval().expect("eval");
        assert_eq!(mel.shape(), &[1, N_FRAMES as i32, n_mels as i32]);
        let data: &[f32] = mel.as_slice();

        let mut checked = 0;
        for block in case["frames"].as_array().expect("frames") {
            let start = block["start"].as_u64().expect("start") as usize;
            // Frames 98..102 straddle the tone -> silence edge, where high mel
            // bands hold only spectral leakage ~8 decades below the peak. The
            // Metal rfft (n = 400) is ~10x less precise than MLX's CPU FFT there
            // (measured max |diff|: GPU 1.1e-4 / 1.5e-4, CPU 7e-6 / 1.5e-5 for
            // 80 / 128 mels), so this block gets a looser bound.
            let tol = if start == 98 { 2.5e-4 } else { 1e-4 };
            for (i, frame) in block["values"].as_array().expect("values").iter().enumerate() {
                let expected = f32_values(frame);
                let row = (start + i) * n_mels;
                let actual = &data[row..row + n_mels];
                for (m, (a, e)) in actual.iter().zip(&expected).enumerate() {
                    assert!(
                        (a - e).abs() <= tol,
                        "n_mels={n_mels} frame={} mel={m}: {a} vs {e}",
                        start + i
                    );
                }
                checked += 1;
            }
        }
        // Blocks at frames 0, 48, 98, 1000 and 2996, four frames each.
        assert_eq!(checked, 20);
    }

    #[test]
    fn log_mel_matches_reference_80() {
        assert_log_mel_matches(80);
    }

    #[test]
    fn log_mel_matches_reference_128() {
        assert_log_mel_matches(128);
    }

    #[test]
    fn log_mel_shape_is_nlc() {
        let frontend = MelFrontend::new(80).expect("frontend");
        let pcm = Array::from_slice(&vec![0.0f32; N_SAMPLES], &[N_SAMPLES as i32]);
        let mel = frontend.log_mel(&pcm).expect("log_mel");
        assert_eq!(mel.shape(), &[1, N_FRAMES as i32, 80]);
    }
}