Skip to main content

qualia_audio/features/contours/
contour_segmentation.rs

1//! Segment a pitch contour into note-like events (stable-pitch runs).
2//!
3//! A melody contour (a per-frame sequence of pitch positions, in salience bins)
4//! is carved into **notes**: maximal runs of frames that stay near a common
5//! pitch. A note ends when the pitch departs from the run's running mean by more
6//! than a tolerance, or when the contour goes unvoiced (a `0.0` sentinel). Very
7//! short runs (below `min_note_frames`) are discarded as transients/glides.
8//!
9//! EPISTEMIC NOTE: notes are *proposals* about how a continuous pitch track
10//! quantises into discrete events; the pitch value reported per note is the mean
11//! over its frames, not a snapped scale degree (no tuning system is assumed
12//! here).
13//!
14//! Zero-heap hot path: reads a caller-owned bin sequence and writes note events
15//! into caller-owned output slices; allocates nothing.
16
17use crate::types::AudioError;
18
19/// Segment `contour_bins[0..n_points]` into stable-pitch note events.
20///
21/// `contour_bins[i]` is the pitch of frame `i` on the salience grid (any
22/// monotonic pitch scale in units where `stable_tol_bins` is meaningful); a value
23/// of `0.0` marks an unvoiced frame that cannot belong to a note. A note is a run
24/// whose every frame lies within `stable_tol_bins` of the run's running mean; the
25/// run closes when a frame breaks that bound or is unvoiced. Runs of at least
26/// `min_note_frames` frames are emitted:
27///
28/// - `out_start[k]`: first frame index of note `k`.
29/// - `out_len[k]`: number of frames in note `k`.
30/// - `out_pitch[k]`: mean pitch (bins) over note `k`.
31///
32/// Returns the number of notes written.
33///
34/// # Errors
35/// - [`AudioError::InvalidParameter`] if `stable_tol_bins` is not a finite
36///   non-negative value, `min_note_frames == 0`, or `contour_bins.len() < n_points`.
37/// - [`AudioError::OutputBufferTooSmall`] if more notes are found than any of the
38///   output slices can hold.
39pub fn segment_contour(
40    contour_bins: &[f32],
41    n_points: usize,
42    stable_tol_bins: f32,
43    min_note_frames: usize,
44    out_start: &mut [usize],
45    out_len: &mut [usize],
46    out_pitch: &mut [f32],
47) -> Result<usize, AudioError> {
48    if !stable_tol_bins.is_finite()
49        || stable_tol_bins < 0.0
50        || min_note_frames == 0
51        || contour_bins.len() < n_points
52    {
53        return Err(AudioError::InvalidParameter);
54    }
55    let cap = out_start.len().min(out_len.len()).min(out_pitch.len());
56
57    let mut notes = 0usize;
58    let mut run_start = 0usize;
59    let mut run_len = 0usize;
60    let mut run_sum = 0.0f64; // running mean numerator (f64 for long runs)
61
62    // Emit the current run as a note if it is long enough.
63    // Returns Err on output overflow.
64    // (Inlined as a closure would borrow the out slices mutably twice; use a macro-free helper.)
65    let mut flush =
66        |start: usize, len: usize, sum: f64, notes: &mut usize| -> Result<(), AudioError> {
67            if len >= min_note_frames {
68                if *notes >= cap {
69                    return Err(AudioError::OutputBufferTooSmall);
70                }
71                out_start[*notes] = start;
72                out_len[*notes] = len;
73                out_pitch[*notes] = (sum / len as f64) as f32;
74                *notes += 1;
75            }
76            Ok(())
77        };
78
79    for i in 0..n_points {
80        let p = contour_bins[i];
81        let voiced = p > 0.0 && p.is_finite();
82
83        if run_len == 0 {
84            if voiced {
85                run_start = i;
86                run_len = 1;
87                run_sum = p as f64;
88            }
89            continue;
90        }
91
92        let mean = (run_sum / run_len as f64) as f32;
93        if voiced && (p - mean).abs() <= stable_tol_bins {
94            run_len += 1;
95            run_sum += p as f64;
96        } else {
97            // Close current run; start a fresh one at this frame if voiced.
98            flush(run_start, run_len, run_sum, &mut notes)?;
99            if voiced {
100                run_start = i;
101                run_len = 1;
102                run_sum = p as f64;
103            } else {
104                run_len = 0;
105                run_sum = 0.0;
106            }
107        }
108    }
109    // Close a trailing run.
110    if run_len > 0 {
111        flush(run_start, run_len, run_sum, &mut notes)?;
112    }
113    Ok(notes)
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    /// GOLDEN: a two-note contour — 6 frames near bin 100, then 6 frames near
121    /// bin 124 — splits into exactly two notes at frame 6, with correct means.
122    #[test]
123    fn splits_two_note_contour() {
124        let mut c = vec![0.0f32; 12];
125        for v in c.iter_mut().take(6) {
126            *v = 100.0;
127        }
128        for v in c.iter_mut().skip(6) {
129            *v = 124.0;
130        }
131        let mut start = [0usize; 4];
132        let mut len = [0usize; 4];
133        let mut pitch = [0.0f32; 4];
134        let n = segment_contour(&c, 12, 0.5, 2, &mut start, &mut len, &mut pitch).expect("segment");
135        assert_eq!(n, 2);
136        assert_eq!(start[0], 0);
137        assert_eq!(len[0], 6);
138        assert!((pitch[0] - 100.0).abs() < 1e-3);
139        assert_eq!(start[1], 6, "split at the pitch change");
140        assert_eq!(len[1], 6);
141        assert!((pitch[1] - 124.0).abs() < 1e-3);
142    }
143
144    /// An unvoiced gap breaks a note and short runs are discarded.
145    #[test]
146    fn gap_breaks_and_short_runs_dropped() {
147        // 4 frames at 100, one voiced blip at 200 (too short), gap, 4 at 100.
148        let c = [
149            100.0f32, 100.0, 100.0, 100.0, // note A (len 4)
150            200.0, // 1-frame blip → dropped
151            0.0, 0.0, // unvoiced gap
152            100.0, 100.0, 100.0, 100.0, // note B (len 4)
153        ];
154        let mut start = [0usize; 4];
155        let mut len = [0usize; 4];
156        let mut pitch = [0.0f32; 4];
157        let n = segment_contour(&c, c.len(), 0.5, 2, &mut start, &mut len, &mut pitch)
158            .expect("segment");
159        assert_eq!(n, 2, "two long notes; the 1-frame blip is dropped");
160        assert_eq!((start[0], len[0]), (0, 4));
161        assert_eq!((start[1], len[1]), (7, 4));
162    }
163
164    /// A slow glide (drift beyond tolerance) fragments rather than reading as one
165    /// note — the running-mean bound trips.
166    #[test]
167    fn drift_beyond_tolerance_fragments() {
168        // Steady climb 100,101,102,... with tol 0.5 → each step breaks the run.
169        let c: Vec<f32> = (0..8).map(|i| 100.0 + i as f32).collect();
170        let mut start = [0usize; 16];
171        let mut len = [0usize; 16];
172        let mut pitch = [0.0f32; 16];
173        let n = segment_contour(&c, 8, 0.5, 1, &mut start, &mut len, &mut pitch).expect("segment");
174        assert_eq!(n, 8, "each 1-cent-step frame is its own micro-note");
175    }
176
177    #[test]
178    fn rejects_bad_params() {
179        let c = [100.0f32; 4];
180        let mut s = [0usize; 4];
181        let mut l = [0usize; 4];
182        let mut p = [0.0f32; 4];
183        assert_eq!(
184            segment_contour(&c, 4, -1.0, 2, &mut s, &mut l, &mut p),
185            Err(AudioError::InvalidParameter)
186        );
187        assert_eq!(
188            segment_contour(&c, 4, 0.5, 0, &mut s, &mut l, &mut p),
189            Err(AudioError::InvalidParameter)
190        );
191    }
192
193    #[test]
194    fn output_overflow_errors() {
195        let c = [100.0f32, 100.0, 0.0, 200.0, 200.0, 0.0, 50.0, 50.0];
196        let mut s = [0usize; 1];
197        let mut l = [0usize; 1];
198        let mut p = [0.0f32; 1];
199        assert_eq!(
200            segment_contour(&c, c.len(), 0.5, 2, &mut s, &mut l, &mut p),
201            Err(AudioError::OutputBufferTooSmall)
202        );
203    }
204}