qualia_audio/midi/tuning/
mts.rs1use super::scala_kbm::KbmMapping;
16use super::scala_scl::SclScale;
17use crate::types::AudioError;
18
19#[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#[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; let period_cents = scale.degree_cents(octave_degree);
37 scale.degree_cents(residue) + (periods as f64) * period_cents
38}
39
40pub 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, };
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#[inline]
69pub fn note_frequency(table: &[f64; 128], note: u8) -> f64 {
70 table[(note & 0x7f) as usize]
71}
72
73const MTS_NOTE0_HZ: f64 = 8.175_798_915_643_71;
80
81pub const SNTC_LEN: usize = 12;
83
84pub 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 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 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#[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
140pub 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 assert!((note_frequency(&table, 69) - 440.0).abs() < 1e-3);
192 assert!((note_frequency(&table, 60) - 261.6255653).abs() < 1e-3);
194 assert!((note_frequency(&table, 81) - 880.0).abs() < 1e-3);
196 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 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 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 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 let kbm = KbmMapping::linear(12, 60, 60, 264.0);
230 let table = build_tuning_table(&scale, &kbm);
231 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 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 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 let f = 261.6255653 * 2.0_f64.powf(23.0 / 1200.0); 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; assert!(decode_single_note_tuning(&msg).is_err());
282 assert!(encode_single_note_tuning(0, 0, 69, -1.0).is_err());
283 }
284}