Skip to main content

qualia_audio/midi/tuning/
mts.rs

1//! MIDI Tuning Standard (MTS) — clean-room from the open MMA spec.
2//!
3//! Two concerns, both native and heap-free on the hot path:
4//!
5//! 1. **Tuning table.** [`build_tuning_table`] combines a Scala [`SclScale`] and [`KbmMapping`]
6//!    into a fixed `[f64; 128]` of key→frequency. [`note_frequency`] is an allocation-free,
7//!    panic-free lookup into that table. Tuning is fully PARAMETERISED — the table is a function
8//!    of the supplied scale + mapping; 12-TET is just one possible input, never hardcoded.
9//!
10//! 2. **Single Note Tuning Change** SysEx (MTS sub-ID 0x02) — [`encode_single_note_tuning`] /
11//!    [`decode_single_note_tuning`]. Frequency is carried as the MTS 3-byte value: a nearest
12//!    equal-tempered semitone (MIDI note, `8.175799 Hz = note 0`) plus a 14-bit fraction of
13//!    100 cents.
14
15use super::scala_kbm::KbmMapping;
16use super::scala_scl::SclScale;
17use crate::types::AudioError;
18
19/// Floor of `a / b` for a positive divisor `b` (Rust `/` truncates toward zero).
20#[inline]
21fn floor_div(a: i32, b: i32) -> i32 {
22    let mut q = a / b;
23    if a % b != 0 && (a < 0) != (b < 0) {
24        q -= 1;
25    }
26    q
27}
28
29/// Cumulative cents (relative to the mapping's `middle_note` = `1/1`) of an ABSOLUTE scale
30/// degree `d`, wrapping every `octave_degree` degrees by the scale's period.
31#[inline]
32fn absolute_degree_cents(scale: &SclScale, octave_degree: usize, d: i32) -> f64 {
33    let oct = octave_degree as i32;
34    let periods = floor_div(d, oct);
35    let residue = (d - periods * oct) as usize; // 0..octave_degree
36    let period_cents = scale.degree_cents(octave_degree);
37    scale.degree_cents(residue) + (periods as f64) * period_cents
38}
39
40/// Build the 128-key frequency table from a scale + keyboard mapping, per MTS.
41///
42/// Keys the mapping does not cover (unmapped `x`, or outside `[first_midi, last_midi]`) are set
43/// to `0.0` (a "no note" sentinel). Anchoring is exact: `reference_note` receives `reference_freq`,
44/// and every other key is `reference_freq · 2^((cents(key) − cents(reference))/1200)`.
45///
46/// If the reference key itself is not mapped the table cannot be anchored and an all-zero table
47/// is returned (build never panics).
48pub fn build_tuning_table(scale: &SclScale, kbm: &KbmMapping) -> [f64; 128] {
49    let mut table = [0.0_f64; 128];
50
51    let ref_degree = match kbm.absolute_degree(kbm.reference_note) {
52        Some(d) => d,
53        None => return table, // cannot anchor
54    };
55    let ref_cents = absolute_degree_cents(scale, kbm.octave_degree, ref_degree);
56
57    for (note, slot) in table.iter_mut().enumerate() {
58        if let Some(d) = kbm.absolute_degree(note as u8) {
59            let c = absolute_degree_cents(scale, kbm.octave_degree, d);
60            *slot = kbm.reference_freq * 2.0_f64.powf((c - ref_cents) / 1200.0);
61        }
62    }
63    table
64}
65
66/// Allocation-free, panic-free key→frequency lookup. `note` is masked into `0..128`, so any
67/// `u8` is valid; an unmapped key returns `0.0`.
68#[inline]
69pub fn note_frequency(table: &[f64; 128], note: u8) -> f64 {
70    table[(note & 0x7f) as usize]
71}
72
73// ---------------------------------------------------------------------------
74// MTS Single Note Tuning Change (real-time SysEx, sub-ID#1 = 0x08, sub-ID#2 = 0x02)
75// ---------------------------------------------------------------------------
76
77/// Reference frequency of MIDI note 0 under MTS's equal-tempered frequency encoding
78/// (`8.175799 Hz`, i.e. A4 = 440 Hz ⇒ note 69).
79const MTS_NOTE0_HZ: f64 = 8.175_798_915_643_71;
80
81/// Byte length of a one-change Single Note Tuning Change SysEx.
82pub const SNTC_LEN: usize = 12;
83
84/// Encode a single-note tuning change as a 12-byte real-time SysEx:
85/// `F0 7F <dev> 08 02 <program> 01 <note> <xx yy zz> F7`.
86///
87/// The 3 frequency bytes are `xx` = nearest ET semitone (0..127), then a 14-bit fraction of one
88/// semitone as `yy` (high 7 bits) and `zz` (low 7 bits).
89///
90/// # Errors
91/// [`AudioError::InvalidParameter`] if `device_id`, `program`, or `note` exceed 7 bits, or `freq`
92/// is not a positive, in-range frequency.
93pub fn encode_single_note_tuning(
94    device_id: u8,
95    program: u8,
96    note: u8,
97    freq: f64,
98) -> Result<[u8; SNTC_LEN], AudioError> {
99    if device_id > 0x7f || program > 0x7f || note > 0x7f {
100        return Err(AudioError::InvalidParameter);
101    }
102    if !(freq.is_finite() && freq > 0.0) {
103        return Err(AudioError::InvalidParameter);
104    }
105
106    // Fractional MIDI semitone number for this frequency.
107    let semis = 12.0 * (freq / MTS_NOTE0_HZ).log2();
108    if !(semis.is_finite() && semis >= 0.0 && semis < 128.0) {
109        return Err(AudioError::InvalidParameter);
110    }
111    let xx = semis.floor() as i64;
112    // 14-bit fraction of a semitone.
113    let frac = semis - xx as f64;
114    let mut f14 = (frac * 16384.0).round() as i64;
115    let mut xx = xx;
116    if f14 >= 16384 {
117        f14 -= 16384;
118        xx += 1;
119    }
120    if !(0..=127).contains(&xx) {
121        return Err(AudioError::InvalidParameter);
122    }
123    let yy = ((f14 >> 7) & 0x7f) as u8;
124    let zz = (f14 & 0x7f) as u8;
125
126    Ok([
127        0xF0, 0x7F, device_id, 0x08, 0x02, program, 0x01, note, xx as u8, yy, zz, 0xF7,
128    ])
129}
130
131/// A decoded single-note tuning change.
132#[derive(Debug, Clone, Copy, PartialEq)]
133pub struct SingleNoteTuning {
134    pub device_id: u8,
135    pub program: u8,
136    pub note: u8,
137    pub freq: f64,
138}
139
140/// Decode a one-change Single Note Tuning Change SysEx produced by [`encode_single_note_tuning`].
141///
142/// # Errors
143/// [`AudioError::InvalidParameter`] if the framing/header is wrong, the change count is not 1,
144/// or the message length is unexpected.
145pub fn decode_single_note_tuning(msg: &[u8]) -> Result<SingleNoteTuning, AudioError> {
146    if msg.len() != SNTC_LEN {
147        return Err(AudioError::InvalidParameter);
148    }
149    if msg[0] != 0xF0
150        || msg[1] != 0x7F
151        || msg[3] != 0x08
152        || msg[4] != 0x02
153        || msg[6] != 0x01
154        || msg[11] != 0xF7
155    {
156        return Err(AudioError::InvalidParameter);
157    }
158    let device_id = msg[2];
159    let program = msg[5];
160    let note = msg[7];
161    let xx = msg[8];
162    let yy = msg[9];
163    let zz = msg[10];
164    if device_id > 0x7f || program > 0x7f || note > 0x7f || xx > 0x7f || yy > 0x7f || zz > 0x7f {
165        return Err(AudioError::InvalidParameter);
166    }
167    let f14 = ((yy as i64) << 7) | (zz as i64);
168    let semis = xx as f64 + (f14 as f64) / 16384.0;
169    let freq = MTS_NOTE0_HZ * 2.0_f64.powf(semis / 12.0);
170    Ok(SingleNoteTuning {
171        device_id,
172        program,
173        note,
174        freq,
175    })
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use crate::midi::tuning::scala_kbm::{parse_kbm, KbmMapping};
182    use crate::midi::tuning::scala_scl::{parse_scl, SclScale};
183
184    #[test]
185    fn tuning_twelve_tet_reference_a440() {
186        let scale = SclScale::twelve_tet();
187        let kbm = KbmMapping::linear_12(440.0);
188        let table = build_tuning_table(&scale, &kbm);
189
190        // Note 69 (A4) is the reference — exactly 440.
191        assert!((note_frequency(&table, 69) - 440.0).abs() < 1e-3);
192        // Middle C (note 60) ≈ 261.626 Hz.
193        assert!((note_frequency(&table, 60) - 261.6255653).abs() < 1e-3);
194        // One octave above A4 (note 81) == 880.
195        assert!((note_frequency(&table, 81) - 880.0).abs() < 1e-3);
196        // One octave below (note 57) == 220.
197        assert!((note_frequency(&table, 57) - 220.0).abs() < 1e-3);
198    }
199
200    #[test]
201    fn tuning_detuned_reference_a432() {
202        let scale = SclScale::twelve_tet();
203        let kbm = KbmMapping::linear_12(432.0);
204        let table = build_tuning_table(&scale, &kbm);
205        assert!((note_frequency(&table, 69) - 432.0).abs() < 1e-3);
206        // The whole grid scales by 432/440.
207        assert!((note_frequency(&table, 81) - 864.0).abs() < 1e-3);
208    }
209
210    #[test]
211    fn tuning_scl_plus_kbm_end_to_end_equals_equal_temperament() {
212        // Parsed from text (not the constructor) to prove the parse path drives the table.
213        let scl = "12tet\n12\n100.\n200.\n300.\n400.\n500.\n600.\n700.\n800.\n900.\n1000.\n1100.\n1200.\n";
214        let kbm_txt = "12\n0\n127\n60\n69\n440.0\n12\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n";
215        let scale = parse_scl(scl).unwrap();
216        let kbm = parse_kbm(kbm_txt).unwrap();
217        let table = build_tuning_table(&scale, &kbm);
218        assert!((note_frequency(&table, 69) - 440.0).abs() < 1e-3);
219        assert!((note_frequency(&table, 60) - 261.6255653).abs() < 1e-3);
220    }
221
222    #[test]
223    fn tuning_non_12tet_just_scale_perfect_fifth() {
224        // A tuning where degree 7's fifth is a JUST 3/2 rather than 12-TET's 2^(7/12).
225        // Full 12-note just-ish scale; degree 7 (key 67, G) is 3/2 above middle C's 1/1.
226        let scl = "just\n12\n16/15\n9/8\n6/5\n5/4\n4/3\n45/32\n3/2\n8/5\n5/3\n9/5\n15/8\n2/1\n";
227        let scale = parse_scl(scl).unwrap();
228        // Anchor 1/1 at middle_note = 60 (C), reference the same C at 264 Hz for a clean check.
229        let kbm = KbmMapping::linear(12, 60, 60, 264.0);
230        let table = build_tuning_table(&scale, &kbm);
231        // Key 67 = degree 7 = 3/2 above the 1/1 at key 60.
232        let c = note_frequency(&table, 60);
233        let g = note_frequency(&table, 67);
234        assert!((c - 264.0).abs() < 1e-3);
235        assert!(
236            (g / c - 1.5).abs() < 1e-9,
237            "just fifth must be exactly 3/2, got {}",
238            g / c
239        );
240        // And it differs from 12-TET's tempered fifth.
241        let tempered = 2.0_f64.powf(7.0 / 12.0);
242        assert!((g / c - tempered).abs() > 1e-3);
243    }
244
245    #[test]
246    fn tuning_note_frequency_lookup_is_masked_and_total() {
247        let table = build_tuning_table(&SclScale::twelve_tet(), &KbmMapping::linear_12(440.0));
248        // note & 0x7f keeps any u8 in range; 197 & 0x7f == 69.
249        assert_eq!(note_frequency(&table, 197), note_frequency(&table, 69));
250    }
251
252    #[test]
253    fn tuning_mts_single_note_roundtrip() {
254        let msg = encode_single_note_tuning(0, 0, 69, 440.0).unwrap();
255        assert_eq!(msg.len(), SNTC_LEN);
256        assert_eq!(msg[0], 0xF0);
257        assert_eq!(msg[11], 0xF7);
258        let d = decode_single_note_tuning(&msg).unwrap();
259        assert_eq!(d.note, 69);
260        assert!((d.freq - 440.0).abs() < 0.05, "decoded {}", d.freq);
261
262        // A detuned pitch survives the 14-bit-fraction round trip within one MTS step (~0.006 c).
263        let f = 261.6255653 * 2.0_f64.powf(23.0 / 1200.0); // +23 cents
264        let m = encode_single_note_tuning(3, 5, 60, f).unwrap();
265        let back = decode_single_note_tuning(&m).unwrap();
266        assert_eq!(back.device_id, 3);
267        assert_eq!(back.program, 5);
268        assert!(
269            (back.freq - f).abs() < 0.02,
270            "roundtrip {} vs {}",
271            back.freq,
272            f
273        );
274    }
275
276    #[test]
277    fn tuning_mts_rejects_bad_frames() {
278        assert!(decode_single_note_tuning(&[0u8; 4]).is_err());
279        let mut msg = encode_single_note_tuning(0, 0, 69, 440.0).unwrap();
280        msg[4] = 0x01; // wrong sub-ID#2
281        assert!(decode_single_note_tuning(&msg).is_err());
282        assert!(encode_single_note_tuning(0, 0, 69, -1.0).is_err());
283    }
284}