qualia_audio/features/tonal/hpcp.rs
1//! Harmonic Pitch Class Profile (HPCP) from spectral peaks.
2//!
3//! This replaces the fake `bin % 12` "chroma" that used to live in `music.rs`.
4//! Each spectral peak `(freq_hz, magnitude)` is mapped to a **real** pitch class
5//! via `log2(f / ref_freq)` — an equal division of the octave into `n_pc` bins —
6//! and its magnitude is accumulated into the nearest pitch-class bin.
7//!
8//! # Tuning is a declared parameter, not a universal truth
9//! - `ref_freq_hz` is the **tuning reference** (the frequency of concert A, A4);
10//! it defaults to 440 Hz by convention only — the caller passes whatever the
11//! material actually uses (see [`super::tuning`] to estimate it). Nothing here
12//! hardcodes 440.
13//! - `n_pc` is the number of pitch classes per octave. 12 is the 12-TET case, but
14//! any `n_pc ≥ 1` (e.g. 24 for quarter-tones, or a non-12 microtonal system) is
15//! accepted. Qualia is modality-first and does not privilege 12-TET.
16//!
17//! # Pitch-class origin
18//! Bin 0 is the **C-equivalent** origin: with the chromatic convention, A sits
19//! `0.75` of an octave (9 of 12 semitones) above C, so the reference A maps to bin
20//! `0.75 * n_pc` and bin 0 corresponds to `ref_freq * 2^(-0.75)`. This origin is a
21//! labelling convention for the 12-TET chromatic layout; the frequency→bin
22//! mapping itself is fully general for any `n_pc`.
23//!
24//! Zero-heap: the profile is written into caller-owned `out`; no allocation.
25
26use crate::types::AudioError;
27
28/// A (concert A) lies this fraction of an octave above the C-origin bin 0
29/// (9 semitones / 12 = 0.75). Used to place the tuning reference correctly.
30const A_ABOVE_C_OCTAVES: f32 = 0.75;
31
32/// Accumulate spectral peaks into a Harmonic Pitch Class Profile.
33///
34/// - `peak_freqs` / `peak_mags`: parallel arrays of peak frequency (Hz) and
35/// magnitude, e.g. from [`crate::features::peaks::spectral_peaks()`].
36/// - `n_peaks`: how many leading entries of those arrays to use (clamped to the
37/// shorter of the two).
38/// - `ref_freq_hz`: tuning reference frequency (frequency of A4); **parameterised**,
39/// default-by-convention 440 Hz — never assume it.
40/// - `n_pc`: pitch classes per octave (12 for 12-TET; any `≥ 1` accepted).
41/// - `out`: destination profile; the first `n_pc` entries are overwritten with the
42/// accumulated magnitudes (raw, not normalised).
43///
44/// # Errors
45/// - [`AudioError::InvalidParameter`] if `ref_freq_hz` is not positive-finite, or
46/// `n_pc == 0`.
47/// - [`AudioError::OutputBufferTooSmall`] if `out.len() < n_pc`.
48pub fn hpcp(
49 peak_freqs: &[f32],
50 peak_mags: &[f32],
51 n_peaks: usize,
52 ref_freq_hz: f32,
53 n_pc: usize,
54 out: &mut [f32],
55) -> Result<(), AudioError> {
56 if !(ref_freq_hz > 0.0) || !ref_freq_hz.is_finite() || n_pc == 0 {
57 return Err(AudioError::InvalidParameter);
58 }
59 if out.len() < n_pc {
60 return Err(AudioError::OutputBufferTooSmall);
61 }
62 for slot in out.iter_mut().take(n_pc) {
63 *slot = 0.0;
64 }
65
66 let np = n_peaks.min(peak_freqs.len()).min(peak_mags.len());
67 let bins = n_pc as f32;
68 // Where the reference A lands, in bins above the C-origin.
69 let a_offset = A_ABOVE_C_OCTAVES * bins;
70
71 for k in 0..np {
72 let f = peak_freqs[k];
73 let m = peak_mags[k];
74 if !(f > 0.0) || !f.is_finite() || !(m > 0.0) || !m.is_finite() {
75 continue;
76 }
77 // Bins above the reference A, then shift to the C origin.
78 let rel = bins * (f / ref_freq_hz).log2();
79 let mut b = (rel + a_offset) % bins;
80 if b < 0.0 {
81 b += bins;
82 }
83 // Nearest pitch-class bin (round may reach `n_pc`; fold with `% n_pc`).
84 let idx = (b.round() as usize) % n_pc;
85 out[idx] += m;
86 }
87 Ok(())
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 /// Equal-tempered note frequency `n` semitones from the A4 reference.
95 fn semis(a4: f32, n: i32) -> f32 {
96 a4 * 2f32.powf(n as f32 / 12.0)
97 }
98
99 /// GOLDEN: a C-major triad (C4, E4, G4) at the standard 440 Hz reference lands
100 /// exactly on pitch classes C=0, E=4, G=7 — and those three bins dominate.
101 #[test]
102 fn golden_c_major_triad_peaks_at_c_e_g() {
103 let a4 = 440.0f32;
104 // C4 = -9, E4 = -5, G4 = -2 semitones from A4.
105 let freqs = [semis(a4, -9), semis(a4, -5), semis(a4, -2)];
106 let mags = [1.0f32, 0.9, 0.8];
107 let mut out = [0.0f32; 12];
108 hpcp(&freqs, &mags, 3, a4, 12, &mut out).expect("hpcp");
109
110 // The chord tones carry all the energy.
111 assert!(out[0] > 0.99 && out[0] < 1.01, "C bin = {}", out[0]);
112 assert!(out[4] > 0.89 && out[4] < 0.91, "E bin = {}", out[4]);
113 assert!(out[7] > 0.79 && out[7] < 0.81, "G bin = {}", out[7]);
114 // Every non-chord pitch class is strictly smaller than each chord tone.
115 for (pc, &v) in out.iter().enumerate() {
116 if pc != 0 && pc != 4 && pc != 7 {
117 assert!(v < out[7], "pc {pc} = {v} not below G bin {}", out[7]);
118 }
119 }
120 }
121
122 /// Non-440 tuning: the same triad synthesised at A4 = 432 Hz still maps to
123 /// C/E/G when `ref_freq_hz` is told the real tuning — tuning is parameterised.
124 #[test]
125 fn respects_non_440_reference() {
126 let a4 = 432.0f32;
127 let freqs = [semis(a4, -9), semis(a4, -5), semis(a4, -2)];
128 let mags = [1.0f32, 1.0, 1.0];
129 let mut out = [0.0f32; 12];
130 hpcp(&freqs, &mags, 3, a4, 12, &mut out).expect("hpcp");
131 assert!(out[0] > 0.99 && out[4] > 0.99 && out[7] > 0.99);
132 }
133
134 /// `n_pc` is a real parameter: a 24-bin (quarter-tone) profile places A at
135 /// bin 18 (= 0.75 * 24) and is not tied to 12.
136 #[test]
137 fn n_pc_is_parameterised() {
138 let a4 = 440.0f32;
139 let freqs = [a4];
140 let mags = [1.0f32];
141 let mut out = [0.0f32; 24];
142 hpcp(&freqs, &mags, 1, a4, 24, &mut out).expect("hpcp");
143 assert!(out[18] > 0.99, "A should be at bin 18 in a 24-bin profile");
144 }
145
146 #[test]
147 fn rejects_bad_params() {
148 let mut out = [0.0f32; 12];
149 assert_eq!(
150 hpcp(&[440.0], &[1.0], 1, 0.0, 12, &mut out),
151 Err(AudioError::InvalidParameter)
152 );
153 assert_eq!(
154 hpcp(&[440.0], &[1.0], 1, 440.0, 0, &mut out),
155 Err(AudioError::InvalidParameter)
156 );
157 let mut tiny = [0.0f32; 4];
158 assert_eq!(
159 hpcp(&[440.0], &[1.0], 1, 440.0, 12, &mut tiny),
160 Err(AudioError::OutputBufferTooSmall)
161 );
162 }
163
164 /// Non-positive / non-finite peaks are skipped, not accumulated.
165 #[test]
166 fn skips_invalid_peaks() {
167 let freqs = [0.0f32, -10.0, f32::NAN, 440.0];
168 let mags = [1.0f32, 1.0, 1.0, 1.0];
169 let mut out = [0.0f32; 12];
170 hpcp(&freqs, &mags, 4, 440.0, 12, &mut out).expect("hpcp");
171 let total: f32 = out.iter().sum();
172 assert!(
173 (total - 1.0).abs() < 1e-6,
174 "only the 440 peak counts, total={total}"
175 );
176 }
177}