Skip to main content

qualia_audio/features/spectral/
flux.rs

1//! True per-bin spectral flux between two consecutive magnitude frames.
2
3use crate::types::AudioError;
4
5/// Half-wave-rectified spectral flux between a previous and current magnitude
6/// spectrum.
7///
8/// Flux is the sum over bins of the positive part of the bin-to-bin change,
9/// `Σ_k max(cur[k] - prev[k], 0)`. Only rising energy contributes, so the
10/// value is an onset-sensitive novelty: `0` for identical frames and strictly
11/// positive when spectral energy increases in any bin. This is the true
12/// per-bin flux (contrast with the frame-energy novelty used by `music.rs`).
13///
14/// `prev` and `cur` must be the same non-zero length (both one-sided magnitude
15/// spectra of the same FFT size).
16///
17/// Zero-heap: single pass, scalar result.
18///
19/// # Errors
20/// - [`AudioError::InvalidParameter`] if the slices are empty or differ in length.
21pub fn spectral_flux(prev: &[f32], cur: &[f32]) -> Result<f32, AudioError> {
22    if prev.is_empty() || prev.len() != cur.len() {
23        return Err(AudioError::InvalidParameter);
24    }
25    let mut acc = 0.0f64;
26    for (p, c) in prev.iter().zip(cur.iter()) {
27        let d = (*c - *p) as f64;
28        if d > 0.0 {
29            acc += d;
30        }
31    }
32    Ok(acc as f32)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn identical_frames_zero_flux() {
41        let frame = [1.0f32, 2.0, 3.0, 0.5];
42        let f = spectral_flux(&frame, &frame).expect("flux");
43        assert!(f.abs() < 1e-6, "flux={f}");
44    }
45
46    #[test]
47    fn rising_energy_positive_flux() {
48        let prev = [1.0f32, 1.0, 1.0, 1.0];
49        let cur = [1.5f32, 2.0, 1.0, 3.0]; // +0.5 +1.0 +0 +2.0 = 3.5
50        let f = spectral_flux(&prev, &cur).expect("flux");
51        assert!((f - 3.5).abs() < 1e-5, "flux={f}");
52    }
53
54    #[test]
55    fn falling_energy_is_rectified_away() {
56        // Only rising bins count; a purely decaying frame yields zero flux.
57        let prev = [3.0f32, 3.0, 3.0];
58        let cur = [1.0f32, 2.0, 0.0];
59        let f = spectral_flux(&prev, &cur).expect("flux");
60        assert!(f.abs() < 1e-6, "flux={f}");
61    }
62
63    #[test]
64    fn mixed_counts_only_positive() {
65        let prev = [2.0f32, 2.0, 2.0];
66        let cur = [0.0f32, 5.0, 2.0]; // -2 -> 0, +3, 0  => 3.0
67        let f = spectral_flux(&prev, &cur).expect("flux");
68        assert!((f - 3.0).abs() < 1e-5, "flux={f}");
69    }
70
71    #[test]
72    fn rejects_mismatched_lengths() {
73        assert_eq!(
74            spectral_flux(&[1.0, 2.0], &[1.0]),
75            Err(AudioError::InvalidParameter)
76        );
77        assert_eq!(spectral_flux(&[], &[]), Err(AudioError::InvalidParameter));
78    }
79}