qualia_audio/features/salience/salience_peaks.rs
1//! Salient pitch candidates: the peaks of a pitch-salience curve for one frame.
2//!
3//! Reuses [`crate::features::peaks::detect_peaks`] to pick local maxima of the
4//! salience function produced by
5//! [`crate::features::salience::pitch_salience`], keeping only peaks above a
6//! fraction of the frame's strongest salience. These are the per-frame pitch
7//! candidates that contour tracking later streams across time.
8//!
9//! EPISTEMIC NOTE: the returned candidates are *proposals* — a polyphonic frame
10//! legitimately yields several. No monophonic collapse happens here.
11//!
12//! Zero-heap hot path: the caller owns the output buffers; the reused
13//! `detect_peaks` is itself allocation-free.
14
15use crate::features::peaks::detect_peaks;
16use crate::types::AudioError;
17
18/// Pick the salient pitch candidates (salience-curve peaks) of one frame.
19///
20/// A candidate is a local maximum of `salience[0..n_bins]` whose value is at
21/// least `threshold_ratio * max(salience)`; candidates closer than
22/// `min_distance_bins` bins are resolved in favour of the stronger (via the
23/// reused peak picker). Output is written **bin-ascending**: `out_bins[k]` the
24/// sub-bin candidate position and `out_salience[k]` its salience.
25///
26/// Returns the number of candidates written.
27///
28/// - `salience`: the frame's salience curve; only `[0, n_bins)` is read.
29/// - `threshold_ratio`: relative floor in `[0, 1]` (e.g. `0.1`).
30/// - `min_distance_bins`: minimum spacing between accepted candidates.
31///
32/// # Errors
33/// - [`AudioError::InvalidParameter`] if `threshold_ratio` is not a finite value
34/// in `[0, 1]`, or `salience.len() < n_bins`.
35/// - [`AudioError::OutputBufferTooSmall`] propagated from the peak picker if more
36/// candidates are found than the output buffers can hold.
37pub fn salient_pitch_peaks(
38 salience: &[f32],
39 n_bins: usize,
40 threshold_ratio: f32,
41 min_distance_bins: usize,
42 out_bins: &mut [f32],
43 out_salience: &mut [f32],
44) -> Result<usize, AudioError> {
45 if !threshold_ratio.is_finite()
46 || !(0.0..=1.0).contains(&threshold_ratio)
47 || salience.len() < n_bins
48 {
49 return Err(AudioError::InvalidParameter);
50 }
51 if n_bins < 3 {
52 return Ok(0);
53 }
54 let view = &salience[..n_bins];
55
56 // Absolute threshold from the frame's own strongest salience.
57 let mut max_s = 0.0f32;
58 for &v in view {
59 if v > max_s {
60 max_s = v;
61 }
62 }
63 if max_s <= 0.0 {
64 return Ok(0); // silent / unpitched frame → no candidates
65 }
66 let threshold = threshold_ratio * max_s;
67
68 detect_peaks(view, threshold, min_distance_bins, out_bins, out_salience)
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 /// Two salience ridges → two candidates, weak noise ridge rejected by the
76 /// relative threshold.
77 #[test]
78 fn picks_two_ridges() {
79 let mut s = vec![0.0f32; 64];
80 // Ridge A at bin 10 (tall), ridge B at bin 40 (medium), noise at bin 25.
81 for (c, h) in [(10usize, 4.0f32), (40, 3.0), (25, 0.2)] {
82 s[c - 1] = 0.5 * h;
83 s[c] = h;
84 s[c + 1] = 0.5 * h;
85 }
86 let mut bins = [0.0f32; 8];
87 let mut sal = [0.0f32; 8];
88 let n = salient_pitch_peaks(&s, 64, 0.1, 3, &mut bins, &mut sal).expect("peaks");
89 assert_eq!(n, 2, "noise ridge (0.2 < 0.1*4=0.4) rejected");
90 // Bin-ascending output.
91 assert!((bins[0] - 10.0).abs() < 1e-3, "b0={}", bins[0]);
92 assert!((bins[1] - 40.0).abs() < 1e-3, "b1={}", bins[1]);
93 assert_eq!(sal[0], 4.0);
94 assert_eq!(sal[1], 3.0);
95 }
96
97 #[test]
98 fn silent_frame_no_candidates() {
99 let s = vec![0.0f32; 32];
100 let mut bins = [0.0f32; 4];
101 let mut sal = [0.0f32; 4];
102 let n = salient_pitch_peaks(&s, 32, 0.1, 1, &mut bins, &mut sal).expect("ok");
103 assert_eq!(n, 0);
104 }
105
106 #[test]
107 fn rejects_bad_ratio() {
108 let s = vec![1.0f32; 8];
109 let mut bins = [0.0f32; 4];
110 let mut sal = [0.0f32; 4];
111 assert_eq!(
112 salient_pitch_peaks(&s, 8, 1.5, 1, &mut bins, &mut sal),
113 Err(AudioError::InvalidParameter)
114 );
115 }
116}