pub fn onset_detection(
mags: &[f32],
n_frames: usize,
n_bins: usize,
out_onsets: &mut [u32],
) -> Result<usize, AudioError>Expand description
Detect note/percussion onsets in a magnitude spectrogram.
mags is a row-major spectrogram of n_frames consecutive one-sided
magnitude spectra, each n_bins long (frame f occupies
mags[f*n_bins .. (f+1)*n_bins]), exactly the layout produced by
crate::features::stft_stream::magnitude_stft_chunk. Between every
adjacent pair of frames the true per-bin spectral flux
(Σ_k max(cur[k]-prev[k], 0), via spectral_flux) forms an onset novelty
curve; the flux value for the transition f-1 → f is attributed to frame
f.
A frame is emitted as an onset when its flux is a local maximum
(flux[f] > flux[f-1] && flux[f] >= flux[f+1]), exceeds the adaptive
threshold LAMBDA · mean(previous THRESH_WINDOW flux values), exceeds
NOISE_FLOOR_FRAC · running_max_flux, and is at least MIN_ONSET_GAP frames
after the previous accepted onset. Onset frame indices are written to
out_onsets in ascending order.
The novelty curve is consumed with a three-tap sliding delay, so no
per-frame heap buffer is needed; the only state is a fixed
THRESH_WINDOW-element stack ring. This replaces the frame-energy novelty
placeholder in music.rs::detect_onsets with real per-bin flux.
Returns the number of onsets written.
§Errors
AudioError::InvalidParameterifn_bins == 0, orn_frames*n_binsexceedsmags.len().AudioError::OutputBufferTooSmallif more onsets are found thanout_onsetscan hold.