Skip to main content

qualia_audio/features/structure/
segmentation.rs

1//! Segment boundaries from novelty-curve peaks (emitted as PROPOSALS).
2//!
3//! Peaks of the Foote novelty curve are candidate structural boundaries. This
4//! layer picks them with the shared [`crate::features::peaks::detect_peaks`]
5//! local-maximum picker and rounds each sub-sample peak position to a frame
6//! index. The results are epistemic **proposals** — "a section change is
7//! plausible near frame N" — not ground-truth cuts; downstream governance
8//! decides what to do with them.
9
10use crate::features::peaks::detect_peaks;
11use crate::types::AudioError;
12
13/// Propose segment boundaries as novelty-curve peak frame indices.
14///
15/// `novelty` is a per-frame novelty curve (as produced by
16/// [`super::novelty::novelty_curve`]); only its first `n_frames` values are
17/// examined. A frame is a boundary candidate when the novelty curve has a local
18/// maximum there of at least `threshold`, with peaks closer than `min_distance`
19/// frames resolved in favour of the taller one (see `detect_peaks`). Ascending
20/// boundary frame indices are written to `out_boundaries`; the count is
21/// returned.
22///
23/// # Caller-buffer contract (zero-heap)
24/// `pos_scratch` and `mag_scratch` are caller-owned working buffers handed
25/// straight to `detect_peaks` (each must hold at least as many entries as the
26/// number of peaks you expect to accept). The rounded frame indices are then
27/// written into `out_boundaries`. No heap allocation is performed.
28///
29/// # Errors
30/// - [`AudioError::InvalidParameter`] if `n_frames == 0`, `n_frames` exceeds
31///   `novelty.len()`, or `threshold` is not finite.
32/// - [`AudioError::OutputBufferTooSmall`] if `out_boundaries` cannot hold every
33///   accepted peak (propagated from `detect_peaks` for the scratch buffers).
34pub fn segment_boundaries(
35    novelty: &[f32],
36    n_frames: usize,
37    threshold: f32,
38    min_distance: usize,
39    pos_scratch: &mut [f32],
40    mag_scratch: &mut [f32],
41    out_boundaries: &mut [usize],
42) -> Result<usize, AudioError> {
43    if n_frames == 0 || n_frames > novelty.len() || !threshold.is_finite() {
44        return Err(AudioError::InvalidParameter);
45    }
46
47    let count = detect_peaks(
48        &novelty[..n_frames],
49        threshold,
50        min_distance,
51        pos_scratch,
52        mag_scratch,
53    )?;
54
55    if out_boundaries.len() < count {
56        return Err(AudioError::OutputBufferTooSmall);
57    }
58    for k in 0..count {
59        // detect_peaks returns parabolically-interpolated positions; a boundary
60        // is a whole frame, so round to the nearest index. round() ties away
61        // from zero, and positions are always in [1, n_frames-2].
62        out_boundaries[k] = pos_scratch[k].round() as usize;
63    }
64    Ok(count)
65}
66
67#[cfg(test)]
68mod tests {
69    use super::super::novelty::novelty_curve;
70    use super::super::ssm::self_similarity;
71    use super::*;
72
73    fn two_section_ssm(n_frames: usize, half: usize) -> Vec<f32> {
74        let dims = 2;
75        let mut f = vec![0.0f32; n_frames * dims];
76        for frame in 0..n_frames {
77            if frame < half {
78                f[frame * dims] = 1.0;
79            } else {
80                f[frame * dims + 1] = 1.0;
81            }
82        }
83        let mut ssm = vec![0.0f32; n_frames * n_frames];
84        self_similarity(&f, n_frames, dims, &mut ssm).expect("ssm");
85        ssm
86    }
87
88    /// Golden end-to-end: features -> SSM -> novelty -> boundary at the true
89    /// midpoint (frame 4 of an 8-frame, two-section signal).
90    #[test]
91    fn golden_boundary_at_midpoint() {
92        let n = 8;
93        let ssm = two_section_ssm(n, 4);
94        let mut nov = vec![0.0f32; n];
95        novelty_curve(&ssm, n, 4, &mut nov).expect("novelty");
96
97        let mut pos = [0.0f32; 8];
98        let mut mag = [0.0f32; 8];
99        let mut boundaries = [0usize; 8];
100        // Threshold 4.0 admits the boundary peak (8.0) and rejects the flanks.
101        let k = segment_boundaries(&nov, n, 4.0, 1, &mut pos, &mut mag, &mut boundaries)
102            .expect("segment");
103        assert_eq!(k, 1, "one boundary; curve={nov:?}");
104        assert_eq!(boundaries[0], 4, "boundary frame");
105    }
106
107    /// A 16-frame signal split at frame 8 yields a boundary at frame 8.
108    #[test]
109    fn boundary_tracks_true_split() {
110        let n = 16;
111        let ssm = two_section_ssm(n, 8);
112        let mut nov = vec![0.0f32; n];
113        novelty_curve(&ssm, n, 4, &mut nov).expect("novelty");
114        let mut pos = [0.0f32; 16];
115        let mut mag = [0.0f32; 16];
116        let mut boundaries = [0usize; 16];
117        let k =
118            segment_boundaries(&nov, n, 4.0, 2, &mut pos, &mut mag, &mut boundaries).expect("seg");
119        assert_eq!(k, 1, "curve={nov:?}");
120        assert_eq!(boundaries[0], 8);
121    }
122
123    /// A high threshold suppresses all peaks -> no proposed boundaries.
124    #[test]
125    fn high_threshold_yields_no_boundaries() {
126        let n = 8;
127        let ssm = two_section_ssm(n, 4);
128        let mut nov = vec![0.0f32; n];
129        novelty_curve(&ssm, n, 4, &mut nov).expect("novelty");
130        let mut pos = [0.0f32; 8];
131        let mut mag = [0.0f32; 8];
132        let mut boundaries = [0usize; 8];
133        let k = segment_boundaries(&nov, n, 100.0, 1, &mut pos, &mut mag, &mut boundaries)
134            .expect("seg");
135        assert_eq!(k, 0);
136    }
137
138    #[test]
139    fn rejects_bad_params() {
140        let nov = [0.0f32; 4];
141        let mut pos = [0.0f32; 4];
142        let mut mag = [0.0f32; 4];
143        let mut out = [0usize; 4];
144        assert_eq!(
145            segment_boundaries(&nov, 0, 1.0, 1, &mut pos, &mut mag, &mut out),
146            Err(AudioError::InvalidParameter)
147        );
148        // n_frames beyond the slice.
149        assert_eq!(
150            segment_boundaries(&nov, 5, 1.0, 1, &mut pos, &mut mag, &mut out),
151            Err(AudioError::InvalidParameter)
152        );
153        // non-finite threshold.
154        assert_eq!(
155            segment_boundaries(&nov, 4, f32::NAN, 1, &mut pos, &mut mag, &mut out),
156            Err(AudioError::InvalidParameter)
157        );
158    }
159}