rosa 0.1.0

Audio feature extraction library matching librosa output
Documentation
//! Spectral flatness matching `librosa.feature.spectral_flatness`.

use crate::matrix::Matrix;

/// Compute spectral flatness from a magnitude spectrogram.
///
/// Matches `librosa.feature.spectral_flatness(S=S, amin=amin, power=power)`.
///
/// Spectral flatness is the ratio of geometric mean to arithmetic mean
/// of the (power-raised, thresholded) spectrum per frame.
/// Values near 1.0 indicate noise-like signal, near 0.0 indicate tonal signal.
///
/// - `s`: magnitude spectrogram (rows = frequency bins, cols = frames).
///   Note: librosa internally computes magnitude (power=1.0) spectrogram,
///   so pass magnitude (not power) spectrogram.
/// - `amin`: minimum threshold for numerical stability (default: 1e-10)
/// - `power`: exponent applied to the magnitude spectrogram (default: 2.0)
pub fn spectral_flatness(s: &Matrix, amin: f64, power: f64) -> Vec<f64> {
    let n_frames = s.cols();
    let n_bins = s.rows();
    let mut result = Vec::with_capacity(n_frames);

    for t in 0..n_frames {
        let mut log_sum = 0.0;
        let mut arith_sum = 0.0;

        for k in 0..n_bins {
            let val = s.get(k, t).powf(power).max(amin);
            log_sum += val.ln();
            arith_sum += val;
        }

        let gmean = (log_sum / n_bins as f64).exp();
        let amean = arith_sum / n_bins as f64;
        result.push(gmean / amean);
    }

    result
}