qualia_audio/features/tonal/
key.rs1use crate::types::AudioError;
17
18const KS_MAJOR: [f32; 12] = [
20 6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88,
21];
22const KS_MINOR: [f32; 12] = [
24 6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17,
25];
26
27#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct KeyEstimate {
31 pub tonic_pc: u8,
32 pub is_major: bool,
33 pub correlation: f32,
34}
35
36fn pearson(a: &[f32], b: &[f32]) -> f32 {
39 let n = a.len();
40 if n == 0 || b.len() != n {
41 return 0.0;
42 }
43 let inv = 1.0 / n as f32;
44 let ma = a.iter().sum::<f32>() * inv;
45 let mb = b.iter().sum::<f32>() * inv;
46 let (mut num, mut da, mut db) = (0.0f32, 0.0f32, 0.0f32);
47 for i in 0..n {
48 let x = a[i] - ma;
49 let y = b[i] - mb;
50 num += x * y;
51 da += x * x;
52 db += y * y;
53 }
54 let den = (da * db).sqrt();
55 if den <= 0.0 || !den.is_finite() {
56 return 0.0;
57 }
58 num / den
59}
60
61pub fn estimate_key(
74 hpcp: &[f32],
75 assumes_12tet: bool,
76 min_correlation: f32,
77) -> Result<Option<KeyEstimate>, AudioError> {
78 if hpcp.is_empty() {
79 return Err(AudioError::InvalidParameter);
80 }
81 if !assumes_12tet || hpcp.len() < 12 {
83 return Ok(None);
84 }
85 let frame = &hpcp[..12];
86
87 let mut best = KeyEstimate {
88 tonic_pc: 0,
89 is_major: true,
90 correlation: f32::MIN,
91 };
92 for tonic in 0usize..12 {
93 for (profile, is_major) in [(&KS_MAJOR, true), (&KS_MINOR, false)] {
94 let mut rot = [0.0f32; 12];
96 for (pc, slot) in rot.iter_mut().enumerate() {
97 *slot = profile[(pc + 12 - tonic) % 12];
98 }
99 let c = pearson(frame, &rot);
100 if c > best.correlation {
101 best = KeyEstimate {
102 tonic_pc: tonic as u8,
103 is_major,
104 correlation: c,
105 };
106 }
107 }
108 }
109
110 if best.correlation < min_correlation {
111 Ok(None) } else {
113 Ok(Some(best))
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120
121 #[test]
124 fn c_major_profile_returns_c_major() {
125 let est = estimate_key(&KS_MAJOR, true, 0.5)
126 .expect("key")
127 .expect("some key");
128 assert_eq!(est.tonic_pc, 0, "tonic should be C");
129 assert!(est.is_major, "should be major");
130 assert!(est.correlation > 0.9, "corr = {}", est.correlation);
131 }
132
133 #[test]
136 fn c_major_triad_returns_c_major() {
137 let mut hpcp = [0.0f32; 12];
138 hpcp[0] = 1.0; hpcp[4] = 1.0; hpcp[7] = 1.0; let est = estimate_key(&hpcp, true, 0.3)
142 .expect("key")
143 .expect("some key");
144 assert_eq!(est.tonic_pc, 0);
145 assert!(est.is_major);
146 assert!(est.correlation > 0.0, "corr = {}", est.correlation);
147 }
148
149 #[test]
151 fn a_minor_triad_returns_a_minor() {
152 let mut hpcp = [0.0f32; 12];
153 hpcp[9] = 1.0; hpcp[0] = 1.0; hpcp[4] = 1.0; let est = estimate_key(&hpcp, true, 0.3)
157 .expect("key")
158 .expect("some key");
159 assert_eq!(est.tonic_pc, 9, "tonic should be A");
160 assert!(!est.is_major, "should be minor");
161 }
162
163 #[test]
165 fn flat_hpcp_abstains() {
166 let hpcp = [1.0f32; 12];
167 assert!(estimate_key(&hpcp, true, 0.5).expect("key").is_none());
168 }
169
170 #[test]
172 fn abstains_without_12tet() {
173 assert!(estimate_key(&KS_MAJOR, false, 0.1).expect("key").is_none());
174 }
175
176 #[test]
177 fn rejects_empty() {
178 assert_eq!(
179 estimate_key(&[], true, 0.5),
180 Err(AudioError::InvalidParameter)
181 );
182 }
183}