Skip to main content

qualia_audio/features/tonal/
chord.rs

1//! Simple triad chord proposal from a single HPCP frame (major/minor/dim).
2//!
3//! For each root (0..12) and each triad template — major {0,4,7}, minor {0,3,7},
4//! diminished {0,3,6} — we score the fraction of HPCP energy captured by the three
5//! chord tones, and take the best. The result is a **proposal**.
6//!
7//! # Abstention (hard epistemic rule)
8//! Triad templates are 12-TET-specific, so an explicit `assumes_12tet` flag is
9//! required. The function returns `Ok(None)` (abstain) when 12-TET is not asserted,
10//! when the HPCP is not 12-bin, when the frame is flat/empty, or when the best
11//! triad captures less than `min_score` of the energy. It never forces a chord.
12//!
13//! Zero-heap: fixed templates and scalar accumulation; no allocation.
14
15use crate::types::AudioError;
16
17/// Triad quality.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ChordQuality {
20    Major,
21    Minor,
22    Diminished,
23}
24
25/// A proposed triad: root pitch class, quality, and the energy-coverage score.
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct ChordEstimate {
28    /// Root pitch class (0 = C … 11 = B).
29    pub root_pc: u8,
30    pub quality: ChordQuality,
31    /// Fraction `[0,1]` of HPCP energy captured by the three chord tones.
32    pub score: f32,
33}
34
35/// (quality, third-interval, fifth-interval) in semitones above the root.
36const TEMPLATES: [(ChordQuality, usize, usize); 3] = [
37    (ChordQuality::Major, 4, 7),
38    (ChordQuality::Minor, 3, 7),
39    (ChordQuality::Diminished, 3, 6),
40];
41
42/// Propose a triad for a 12-bin HPCP frame.
43///
44/// - `hpcp`: pitch-class profile (≥ 12 bins; bin 0 = C).
45/// - `assumes_12tet`: caller-declared assumption; `false` ⇒ abstain (`Ok(None)`).
46/// - `min_score`: coverage acceptance threshold (e.g. `0.8`). Below it, abstain.
47///
48/// # Errors
49/// - [`AudioError::InvalidParameter`] if `hpcp` is empty.
50pub fn estimate_chord(
51    hpcp: &[f32],
52    assumes_12tet: bool,
53    min_score: f32,
54) -> Result<Option<ChordEstimate>, AudioError> {
55    if hpcp.is_empty() {
56        return Err(AudioError::InvalidParameter);
57    }
58    if !assumes_12tet || hpcp.len() < 12 {
59        return Ok(None);
60    }
61    let frame = &hpcp[..12];
62
63    let total: f32 = frame.iter().map(|v| v.max(0.0)).sum();
64    if total <= 0.0 {
65        return Ok(None);
66    }
67
68    let mut best = ChordEstimate {
69        root_pc: 0,
70        quality: ChordQuality::Major,
71        score: 0.0,
72    };
73    for root in 0usize..12 {
74        for (quality, third, fifth) in TEMPLATES {
75            let e = frame[root].max(0.0)
76                + frame[(root + third) % 12].max(0.0)
77                + frame[(root + fifth) % 12].max(0.0);
78            let score = e / total;
79            if score > best.score {
80                best = ChordEstimate {
81                    root_pc: root as u8,
82                    quality,
83                    score,
84                };
85            }
86        }
87    }
88
89    if best.score < min_score {
90        Ok(None) // abstain — no triad captures enough energy.
91    } else {
92        Ok(Some(best))
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    /// GOLDEN: a C-E-G HPCP is proposed as a C major triad.
101    #[test]
102    fn c_e_g_is_c_major() {
103        let mut hpcp = [0.0f32; 12];
104        hpcp[0] = 1.0; // C
105        hpcp[4] = 1.0; // E
106        hpcp[7] = 1.0; // G
107        let est = estimate_chord(&hpcp, true, 0.8)
108            .expect("chord")
109            .expect("some chord");
110        assert_eq!(est.root_pc, 0);
111        assert_eq!(est.quality, ChordQuality::Major);
112        assert!(est.score > 0.99, "score = {}", est.score);
113    }
114
115    /// A-C-E is proposed as an A minor triad.
116    #[test]
117    fn a_c_e_is_a_minor() {
118        let mut hpcp = [0.0f32; 12];
119        hpcp[9] = 1.0; // A
120        hpcp[0] = 1.0; // C
121        hpcp[4] = 1.0; // E
122        let est = estimate_chord(&hpcp, true, 0.8)
123            .expect("chord")
124            .expect("some chord");
125        assert_eq!(est.root_pc, 9);
126        assert_eq!(est.quality, ChordQuality::Minor);
127    }
128
129    /// B-D-F is proposed as a B diminished triad.
130    #[test]
131    fn b_d_f_is_b_diminished() {
132        let mut hpcp = [0.0f32; 12];
133        hpcp[11] = 1.0; // B
134        hpcp[2] = 1.0; // D
135        hpcp[5] = 1.0; // F
136        let est = estimate_chord(&hpcp, true, 0.8)
137            .expect("chord")
138            .expect("some chord");
139        assert_eq!(est.root_pc, 11);
140        assert_eq!(est.quality, ChordQuality::Diminished);
141    }
142
143    /// ABSTAIN: a flat HPCP → no chord.
144    #[test]
145    fn flat_abstains() {
146        let hpcp = [1.0f32; 12];
147        assert!(estimate_chord(&hpcp, true, 0.8).expect("chord").is_none());
148    }
149
150    /// ABSTAIN: without 12-TET → no chord.
151    #[test]
152    fn non_12tet_abstains() {
153        let mut hpcp = [0.0f32; 12];
154        hpcp[0] = 1.0;
155        hpcp[4] = 1.0;
156        hpcp[7] = 1.0;
157        assert!(estimate_chord(&hpcp, false, 0.8).expect("chord").is_none());
158    }
159
160    #[test]
161    fn rejects_empty() {
162        assert_eq!(
163            estimate_chord(&[], true, 0.8),
164            Err(AudioError::InvalidParameter)
165        );
166    }
167}