Skip to main content

qualia_audio/midi/tuning/
scala_scl.rs

1//! Scala scale file (`.scl`) parsing — clean-room from the open Scala format spec.
2//!
3//! A `.scl` file describes ONE octave/period of a scale as an ordered list of pitches
4//! above the implicit `1/1` (0 cents). Grammar (comment lines begin with `!`):
5//!
6//! ```text
7//! ! name.scl
8//! <description text, may be blank>   ← first non-comment line
9//! <count>                            ← number of note lines that follow
10//! <pitch 1>                          ← a ratio `p/q` (or `p`) OR a cents value `x.y`
11//! ...
12//! <pitch count>                      ← the last pitch is the formal octave (e.g. 2/1 or 1200.0)
13//! ```
14//!
15//! A pitch TOKEN is a ratio when it has no `.` (either `p/q` or a bare integer `p` ⇒ `p/1`),
16//! and cents when it contains a `.`. Anything after the value on a line is a description and
17//! is ignored. Degree 0 (`1/1`) is implicit and never listed.
18//!
19//! Parsing is a COLD path and may allocate transiently; the produced [`SclScale`] is a
20//! fixed-size, `Copy`, heap-free value so the hot note→frequency build/lookup never allocates.
21
22use crate::types::AudioError;
23
24/// Upper bound on scale degrees. A `.scl` beyond this is rejected (bounded, DoS-safe).
25pub const MAX_SCALE_NOTES: usize = 512;
26
27/// One pitch entry of a Scala scale, kept in its ORIGINAL exact form so that a
28/// just-intonation ratio (e.g. `3/2`) stays exact and a cents value stays a float.
29#[derive(Debug, Clone, Copy, PartialEq)]
30pub enum SclEntry {
31    /// A rational interval `num/den` above `1/1` (`den` is never 0).
32    Ratio { num: u64, den: u64 },
33    /// An interval given directly in cents (1200 cents = one octave). May be negative.
34    Cents(f64),
35}
36
37impl SclEntry {
38    /// Linear frequency ratio of this interval relative to `1/1`.
39    #[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    /// Size of this interval in cents relative to `1/1`.
48    #[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/// A parsed Scala scale: `count` pitch entries describing one period above the implicit `1/1`.
58/// Fixed-size and `Copy` — no heap, safe to embed in the tuning-table build path.
59#[derive(Debug, Clone, Copy)]
60pub struct SclScale {
61    entries: [SclEntry; MAX_SCALE_NOTES],
62    count: usize,
63}
64
65impl SclScale {
66    /// Number of pitch degrees (the value on the `.scl` count line). Degree 0 (`1/1`) is implicit,
67    /// so the scale spans degrees `0..=count`, with degree `count` being the formal octave/period.
68    #[inline]
69    pub fn count(&self) -> usize {
70        self.count
71    }
72
73    /// Entry for scale degree `degree` in `1..=count` (degree 1 is the first listed pitch).
74    /// Returns `None` for degree 0 (which is always `1/1`) or out of range.
75    #[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    /// Cumulative cents of scale degree `degree` relative to `1/1`.
85    /// Degree 0 ⇒ 0.0; degree `d` in `1..=count` ⇒ the `d`-th listed pitch's cents.
86    /// Degrees above `count` are clamped to the period (callers handle octave wrapping).
87    #[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    /// 12-tone equal temperament: twelve equal 100-cent steps to the `2/1` octave.
99    /// Parameterised like every other scale — the engine hardcodes NOTHING; this is merely a
100    /// convenience constructor for the ubiquitous default.
101    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    // Degree i+1 ⇒ (i+1)*100 cents; degree 12 ⇒ 1200.0 (exact octave).
113    *e = SclEntry::Cents(((i + 1) as f64) * 100.0);
114}
115
116/// Parse Scala `.scl` text into a fixed-size [`SclScale`].
117///
118/// # Errors
119/// [`AudioError::InvalidParameter`] if the count line is missing/unparseable, the declared count
120/// exceeds [`MAX_SCALE_NOTES`], a pitch line is malformed, or fewer pitch lines are present than declared.
121pub fn parse_scl(text: &str) -> Result<SclScale, AudioError> {
122    // Data lines are all lines whose first non-whitespace char is not '!'.
123    let mut data = text.lines().filter(|l| {
124        let t = l.trim_start();
125        !t.starts_with('!')
126    });
127
128    // Line 1: description (may be blank) — consumed and ignored.
129    let _description = data.next().ok_or(AudioError::InvalidParameter)?;
130
131    // Line 2: note count.
132    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
152/// Parse a single `.scl` pitch line into an [`SclEntry`]. The value is the first
153/// whitespace-delimited token; any trailing text is an ignored description.
154fn 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        // Cents value (may be negative, e.g. a descending step).
162        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        // Bare integer ⇒ p/1.
176        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        // Each degree is a whole number of 100-cent steps.
193        for d in 1..=12 {
194            assert!((s.degree_cents(d) - (d as f64) * 100.0).abs() < 1e-9);
195        }
196        // Formal octave is an exact 2/1.
197        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            // Each semitone == 100 cents, and its ratio == 2^(d/12).
224            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        // A just / Pythagorean snippet with a ratio line for the perfect fifth.
232        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        // Degree 2 is the perfect fifth 3/2 — EXACT, proving non-12-TET support.
243        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        // Octave exact.
248        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()); // fewer pitches than declared
271        assert!(parse_scl("desc\n0\n").is_err()); // zero notes
272    }
273}