Skip to main content

qualia_audio/features/tonal/
key.rs

1//! Key estimation by Krumhansl–Schmuckler profile correlation over an HPCP.
2//!
3//! The Krumhansl–Kessler major/minor tonal-hierarchy profiles are correlated
4//! against the (12-bin) HPCP at all 12 rotations; the best-correlating
5//! (tonic, mode) is the proposed key.
6//!
7//! # Proposal, with abstention (hard epistemic rule)
8//! The K–S profiles are **12-TET-specific**. This function therefore takes an
9//! explicit `assumes_12tet` flag and **abstains** (`Ok(None)`) when 12-TET is not
10//! asserted, when the HPCP is not 12-bin, or when the best correlation falls below
11//! `min_correlation` (flat / ambiguous / atonal material). It never forces a key
12//! label onto content that does not support one.
13//!
14//! Zero-heap: rotation happens in a stack `[f32; 12]`; no allocation.
15
16use crate::types::AudioError;
17
18/// Krumhansl–Kessler major-key tonal-hierarchy profile (tonic at index 0).
19const 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];
22/// Krumhansl–Kessler minor-key tonal-hierarchy profile (tonic at index 0).
23const 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/// A proposed key: tonic pitch class (0 = C … 11 = B), mode, and the correlation
28/// that supports it.
29#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct KeyEstimate {
31    pub tonic_pc: u8,
32    pub is_major: bool,
33    pub correlation: f32,
34}
35
36/// Pearson correlation of two equal-length slices; `0.0` if either has no
37/// variance (e.g. a flat HPCP), which drives abstention rather than a spurious key.
38fn 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
61/// Estimate the musical key of a 12-bin HPCP frame/profile.
62///
63/// - `hpcp`: pitch-class profile; must be at least 12 bins (bin 0 = C).
64/// - `assumes_12tet`: caller-declared assumption. If `false`, abstains.
65/// - `min_correlation`: acceptance threshold; below it the result is `Ok(None)`
66///   (abstain). A value around `0.6`–`0.7` is typical for confident keys.
67///
68/// Returns `Ok(Some(KeyEstimate))` when a key is proposed, `Ok(None)` when the
69/// function abstains.
70///
71/// # Errors
72/// - [`AudioError::InvalidParameter`] if `hpcp` is empty.
73pub 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    // Abstain unless the 12-TET assumption holds and the profile is chromatic.
82    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            // Rotate the profile so its tonic aligns with `tonic` (stack buffer).
95            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) // abstain — no key confident enough.
112    } else {
113        Ok(Some(best))
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    /// GOLDEN: an HPCP equal to the C-major profile itself yields tonic C, major,
122    /// with a strongly positive correlation.
123    #[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    /// A C-major *triad* HPCP (energy only at C, E, G) still proposes C major with
134    /// positive correlation.
135    #[test]
136    fn c_major_triad_returns_c_major() {
137        let mut hpcp = [0.0f32; 12];
138        hpcp[0] = 1.0; // C
139        hpcp[4] = 1.0; // E
140        hpcp[7] = 1.0; // G
141        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    /// An A-minor triad (A, C, E) proposes A minor (tonic 9, minor).
150    #[test]
151    fn a_minor_triad_returns_a_minor() {
152        let mut hpcp = [0.0f32; 12];
153        hpcp[9] = 1.0; // A
154        hpcp[0] = 1.0; // C
155        hpcp[4] = 1.0; // E
156        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    /// ABSTAIN: a flat HPCP has no key.
164    #[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    /// ABSTAIN: without the 12-TET assumption the function refuses to guess.
171    #[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}