qualia_audio/midi/tuning/
scala_scl.rs1use crate::types::AudioError;
23
24pub const MAX_SCALE_NOTES: usize = 512;
26
27#[derive(Debug, Clone, Copy, PartialEq)]
30pub enum SclEntry {
31 Ratio { num: u64, den: u64 },
33 Cents(f64),
35}
36
37impl SclEntry {
38 #[inline]
40 pub fn ratio(self) -> f64 {
41 match self {
42 SclEntry::Ratio { num, den } => num as f64 / den as f64,
43 SclEntry::Cents(c) => 2.0_f64.powf(c / 1200.0),
44 }
45 }
46
47 #[inline]
49 pub fn cents(self) -> f64 {
50 match self {
51 SclEntry::Ratio { num, den } => 1200.0 * (num as f64 / den as f64).log2(),
52 SclEntry::Cents(c) => c,
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy)]
60pub struct SclScale {
61 entries: [SclEntry; MAX_SCALE_NOTES],
62 count: usize,
63}
64
65impl SclScale {
66 #[inline]
69 pub fn count(&self) -> usize {
70 self.count
71 }
72
73 #[inline]
76 pub fn entry(&self, degree: usize) -> Option<SclEntry> {
77 if degree == 0 || degree > self.count {
78 None
79 } else {
80 Some(self.entries[degree - 1])
81 }
82 }
83
84 #[inline]
88 pub fn degree_cents(&self, degree: usize) -> f64 {
89 if degree == 0 {
90 0.0
91 } else if degree <= self.count {
92 self.entries[degree - 1].cents()
93 } else {
94 self.entries[self.count - 1].cents()
95 }
96 }
97
98 pub fn twelve_tet() -> SclScale {
102 let mut entries = [SclEntry::Cents(0.0); MAX_SCALE_NOTES];
103 for (i, e) in entries.iter_mut().enumerate().take(12) {
104 e_set(e, i);
105 }
106 SclScale { entries, count: 12 }
107 }
108}
109
110#[inline]
111fn e_set(e: &mut SclEntry, i: usize) {
112 *e = SclEntry::Cents(((i + 1) as f64) * 100.0);
114}
115
116pub fn parse_scl(text: &str) -> Result<SclScale, AudioError> {
122 let mut data = text.lines().filter(|l| {
124 let t = l.trim_start();
125 !t.starts_with('!')
126 });
127
128 let _description = data.next().ok_or(AudioError::InvalidParameter)?;
130
131 let count_line = data.next().ok_or(AudioError::InvalidParameter)?;
133 let count: usize = count_line
134 .split_whitespace()
135 .next()
136 .ok_or(AudioError::InvalidParameter)?
137 .parse()
138 .map_err(|_| AudioError::InvalidParameter)?;
139 if count == 0 || count > MAX_SCALE_NOTES {
140 return Err(AudioError::InvalidParameter);
141 }
142
143 let mut entries = [SclEntry::Cents(0.0); MAX_SCALE_NOTES];
144 for slot in entries.iter_mut().take(count) {
145 let line = data.next().ok_or(AudioError::InvalidParameter)?;
146 *slot = parse_pitch(line)?;
147 }
148
149 Ok(SclScale { entries, count })
150}
151
152fn parse_pitch(line: &str) -> Result<SclEntry, AudioError> {
155 let tok = line
156 .split_whitespace()
157 .next()
158 .ok_or(AudioError::InvalidParameter)?;
159
160 if tok.contains('.') {
161 let c: f64 = tok.parse().map_err(|_| AudioError::InvalidParameter)?;
163 if !c.is_finite() {
164 return Err(AudioError::InvalidParameter);
165 }
166 Ok(SclEntry::Cents(c))
167 } else if let Some((n, d)) = tok.split_once('/') {
168 let num: u64 = n.parse().map_err(|_| AudioError::InvalidParameter)?;
169 let den: u64 = d.parse().map_err(|_| AudioError::InvalidParameter)?;
170 if num == 0 || den == 0 {
171 return Err(AudioError::InvalidParameter);
172 }
173 Ok(SclEntry::Ratio { num, den })
174 } else {
175 let num: u64 = tok.parse().map_err(|_| AudioError::InvalidParameter)?;
177 if num == 0 {
178 return Err(AudioError::InvalidParameter);
179 }
180 Ok(SclEntry::Ratio { num, den: 1 })
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 #[test]
189 fn tuning_twelve_tet_constructor_is_equal_tempered() {
190 let s = SclScale::twelve_tet();
191 assert_eq!(s.count(), 12);
192 for d in 1..=12 {
194 assert!((s.degree_cents(d) - (d as f64) * 100.0).abs() < 1e-9);
195 }
196 assert!((s.entry(12).unwrap().ratio() - 2.0).abs() < 1e-12);
198 }
199
200 #[test]
201 fn tuning_parse_12tet_scl_reproduces_equal_temperament() {
202 let text = "\
203! 12tet.scl
20412 equal steps
205 12
206 100.0
207 200.0
208 300.0
209 400.0
210 500.0
211 600.0
212 700.0
213 800.0
214 900.0
215 1000.0
216 1100.0
217 1200.0
218";
219 let s = parse_scl(text).expect("parse 12-TET .scl");
220 assert_eq!(s.count(), 12);
221 let step = 2.0_f64.powf(1.0 / 12.0);
222 for d in 1..=12 {
223 assert!((s.degree_cents(d) - (d as f64) * 100.0).abs() < 1e-6);
225 assert!((s.entry(d).unwrap().ratio() - step.powi(d as i32)).abs() < 1e-9);
226 }
227 }
228
229 #[test]
230 fn tuning_parse_pythagorean_ratio_fifth_is_exactly_three_halves() {
231 let text = "\
233! just.scl
234Just intonation snippet
235 3
236 9/8
237 3/2
238 2/1
239";
240 let s = parse_scl(text).expect("parse just .scl");
241 assert_eq!(s.count(), 3);
242 let fifth = s.entry(2).unwrap();
244 assert_eq!(fifth, SclEntry::Ratio { num: 3, den: 2 });
245 assert!((fifth.ratio() - 1.5).abs() < 1e-12);
246 assert!((fifth.cents() - 701.955).abs() < 1e-3);
247 assert!((s.entry(3).unwrap().ratio() - 2.0).abs() < 1e-12);
249 }
250
251 #[test]
252 fn tuning_parse_comments_and_blank_description_are_handled() {
253 let text = "\
254! leading comment
255\t
256! another comment
257 2
258! mid comment
259 100.0
260 2/1
261";
262 let s = parse_scl(text).expect("blank description + comments");
263 assert_eq!(s.count(), 2);
264 assert!((s.degree_cents(1) - 100.0).abs() < 1e-9);
265 }
266
267 #[test]
268 fn tuning_parse_rejects_bad_count_and_short_files() {
269 assert!(parse_scl("desc\nnotanumber\n").is_err());
270 assert!(parse_scl("desc\n3\n100.0\n").is_err()); assert!(parse_scl("desc\n0\n").is_err()); }
273}