Skip to main content

qualia_audio/midi/instrument/
sfz.rs

1//! SFZ text-instrument parser (clean-room from the open SFZ format; no vendored sfizz).
2//!
3//! Qualia ships NO sample content. This parses a USER-supplied `.sfz` text file into a
4//! bounded set of key/velocity-mapped [`SfzRegion`]s. Each region only *references* a
5//! sample by relative path (`sample_ref`); the bytes live in the user's hypermedia library
6//! or a user/vendor content dir and are resolved later (see `resolver`).
7//!
8//! Supported subset (opcodes may appear at `<group>` scope and are inherited by the regions
9//! that follow, or at `<region>` scope):
10//!
11//! - Headers: `<group>`, `<region>` (and `<global>`, treated like a group-level default).
12//!   Any other header (`<control>`, `<curve>`, …) simply ends the current region.
13//! - Opcodes: `sample=`, `lokey`/`hikey`/`key`, `lovel`/`hivel`, `pitch_keycenter`,
14//!   `tune` (cents), `volume` (dB).
15//!
16//! Key values may be a MIDI number (`0..=127`) or a note name (`c4`, `F#3`, `bb2`, …) with the
17//! SFZ/MIDI convention `c-1 = 0` ⇒ middle `c4 = 60`.
18//!
19//! Parsing is a COLD path (transient `Vec` allocation is fine). The produced
20//! [`SfzInstrument`] borrows sample-path slices out of the input `text` (`sample_ref: &str`),
21//! and the note→region LOOKUP over its regions is allocation-free (see `sample_map`).
22
23use crate::types::AudioError;
24
25/// Upper bound on regions in one instrument. A larger file is rejected (bounded, DoS-safe).
26pub const MAX_REGIONS: usize = 4096;
27
28/// One key/velocity-mapped region: a rectangle in (note, velocity) space plus playback params.
29///
30/// `sample_ref` borrows the relative sample path out of the parsed `text`; it is NOT loaded
31/// here (Qualia ships no content). All ranges are inclusive.
32#[derive(Debug, Clone, Copy, PartialEq)]
33pub struct SfzRegion<'a> {
34    /// Lowest MIDI note this region responds to (inclusive).
35    pub lokey: u8,
36    /// Highest MIDI note this region responds to (inclusive).
37    pub hikey: u8,
38    /// Lowest velocity (inclusive).
39    pub lovel: u8,
40    /// Highest velocity (inclusive).
41    pub hivel: u8,
42    /// The unity/root key the sample was recorded at.
43    pub pitch_keycenter: u8,
44    /// Fine tune in cents (SFZ `tune`).
45    pub tune_cents: i32,
46    /// Gain in decibels (SFZ `volume`).
47    pub volume_db: f32,
48    /// Relative path to the sample file — a REFERENCE only, resolved by the caller.
49    pub sample_ref: &'a str,
50}
51
52impl<'a> SfzRegion<'a> {
53    /// Default region before any opcode is applied: full range, no sample.
54    #[inline]
55    const fn blank() -> Self {
56        Self {
57            lokey: 0,
58            hikey: 127,
59            lovel: 0,
60            hivel: 127,
61            pitch_keycenter: 60,
62            tune_cents: 0,
63            volume_db: 0.0,
64            sample_ref: "",
65        }
66    }
67
68    /// Does this region respond to `(note, velocity)`? (inclusive on all four bounds).
69    #[inline]
70    pub fn matches(&self, note: u8, velocity: u8) -> bool {
71        note >= self.lokey && note <= self.hikey && velocity >= self.lovel && velocity <= self.hivel
72    }
73}
74
75/// A parsed SFZ instrument: a bounded, ordered list of regions.
76///
77/// Regions borrow their `sample_ref` from the input text, so the instrument shares its
78/// lifetime. The order is preserved (SFZ layering is first-match by authoring order).
79#[derive(Debug, Clone)]
80pub struct SfzInstrument<'a> {
81    regions: Vec<SfzRegion<'a>>,
82}
83
84impl<'a> SfzInstrument<'a> {
85    /// Regions in authoring order.
86    #[inline]
87    pub fn regions(&self) -> &[SfzRegion<'a>] {
88        &self.regions
89    }
90
91    /// Number of regions.
92    #[inline]
93    pub fn len(&self) -> usize {
94        self.regions.len()
95    }
96
97    /// True when the instrument has no regions.
98    #[inline]
99    pub fn is_empty(&self) -> bool {
100        self.regions.is_empty()
101    }
102}
103
104/// Which header scope we are currently accumulating opcodes into.
105#[derive(Clone, Copy, PartialEq)]
106enum Scope {
107    /// `<global>`/`<group>`: opcodes become inherited defaults for following regions.
108    Group,
109    /// `<region>`: opcodes apply to the region under construction.
110    Region,
111    /// A header we don't model — swallow its opcodes.
112    Other,
113}
114
115/// Parse an SFZ text instrument into a bounded [`SfzInstrument`].
116///
117/// An empty file (or a file with no `<region>`) yields an empty instrument (`is_empty()`),
118/// NOT an error — an instrument with zero playable regions is a valid, well-formed result.
119/// Errors are returned only for genuinely malformed structure: a key/velocity value that is
120/// not a parseable MIDI number or note name, or exceeding [`MAX_REGIONS`].
121pub fn parse_sfz(text: &str) -> Result<SfzInstrument<'_>, AudioError> {
122    // Flatten to an ordered token stream, stripping `//` comments per line. Tokens keep their
123    // original `&str` so `sample=` values can borrow from `text`.
124    let mut tokens: Vec<&str> = Vec::new();
125    for line in text.lines() {
126        let content = match line.find("//") {
127            Some(i) => &line[..i],
128            None => line,
129        };
130        for tok in content.split_whitespace() {
131            tokens.push(tok);
132        }
133    }
134
135    let mut regions: Vec<SfzRegion<'_>> = Vec::new();
136    let mut group_default = SfzRegion::blank();
137    let mut cur = SfzRegion::blank();
138    let mut scope = Scope::Other;
139    let mut region_open = false;
140
141    let mut i = 0usize;
142    while i < tokens.len() {
143        let tok = tokens[i];
144
145        if is_header(tok) {
146            // A new header closes any region currently under construction.
147            if region_open {
148                regions.push(cur);
149                if regions.len() > MAX_REGIONS {
150                    return Err(AudioError::InvalidParameter);
151                }
152                region_open = false;
153            }
154            match header_name(tok) {
155                HeaderKind::GroupLike => {
156                    // A fresh group resets group-level defaults.
157                    group_default = SfzRegion::blank();
158                    scope = Scope::Group;
159                }
160                HeaderKind::Region => {
161                    cur = group_default; // inherit current group defaults
162                    region_open = true;
163                    scope = Scope::Region;
164                }
165                HeaderKind::Other => {
166                    scope = Scope::Other;
167                }
168            }
169            i += 1;
170            continue;
171        }
172
173        // Opcode `name=value`. `sample=` swallows following non-opcode tokens (paths may
174        // contain spaces) until the next header or `name=` opcode.
175        let Some(eq) = tok.find('=') else {
176            // Stray token (e.g. a bare path fragment with no opcode) — ignore, cold-path robust.
177            i += 1;
178            continue;
179        };
180        let name = &tok[..eq];
181        let first_val = &tok[eq + 1..];
182
183        // Choose the target region for this opcode based on scope.
184        let target: &mut SfzRegion<'_> = match scope {
185            Scope::Group => &mut group_default,
186            Scope::Region => &mut cur,
187            Scope::Other => {
188                i += 1;
189                continue;
190            }
191        };
192
193        if name == "sample" {
194            // Recover the full path: value token + following tokens up to the next opcode/header.
195            let start_byte = byte_offset_in(text, first_val);
196            let mut end_byte = start_byte + first_val.len();
197            let mut j = i + 1;
198            while j < tokens.len() {
199                let nt = tokens[j];
200                if is_header(nt) || nt.contains('=') {
201                    break;
202                }
203                end_byte = byte_offset_in(text, nt) + nt.len();
204                j += 1;
205            }
206            target.sample_ref = match text.get(start_byte..end_byte) {
207                Some(s) => s.trim(),
208                None => first_val, // fallback: single token (never expected)
209            };
210            i = j;
211            continue;
212        }
213
214        apply_opcode(target, name, first_val)?;
215        i += 1;
216    }
217
218    if region_open {
219        regions.push(cur);
220        if regions.len() > MAX_REGIONS {
221            return Err(AudioError::InvalidParameter);
222        }
223    }
224
225    Ok(SfzInstrument { regions })
226}
227
228enum HeaderKind {
229    GroupLike,
230    Region,
231    Other,
232}
233
234#[inline]
235fn is_header(tok: &str) -> bool {
236    tok.starts_with('<') && tok.ends_with('>') && tok.len() >= 2
237}
238
239fn header_name(tok: &str) -> HeaderKind {
240    let inner = &tok[1..tok.len() - 1];
241    if inner.eq_ignore_ascii_case("region") {
242        HeaderKind::Region
243    } else if inner.eq_ignore_ascii_case("group") || inner.eq_ignore_ascii_case("global") {
244        HeaderKind::GroupLike
245    } else {
246        HeaderKind::Other
247    }
248}
249
250/// Byte offset of a sub-slice within `parent` (both must come from the same allocation).
251#[inline]
252fn byte_offset_in(parent: &str, sub: &str) -> usize {
253    (sub.as_ptr() as usize).saturating_sub(parent.as_ptr() as usize)
254}
255
256fn apply_opcode(r: &mut SfzRegion<'_>, name: &str, val: &str) -> Result<(), AudioError> {
257    match name {
258        "lokey" => r.lokey = parse_key(val)?,
259        "hikey" => r.hikey = parse_key(val)?,
260        "key" => {
261            let k = parse_key(val)?;
262            r.lokey = k;
263            r.hikey = k;
264            r.pitch_keycenter = k;
265        }
266        "lovel" => r.lovel = parse_vel(val)?,
267        "hivel" => r.hivel = parse_vel(val)?,
268        "pitch_keycenter" => r.pitch_keycenter = parse_key(val)?,
269        "tune" | "pitch" => {
270            r.tune_cents = val
271                .parse::<i32>()
272                .map_err(|_| AudioError::InvalidParameter)?
273        }
274        "volume" => {
275            r.volume_db = val
276                .parse::<f32>()
277                .map_err(|_| AudioError::InvalidParameter)?
278        }
279        // Unknown opcode in the subset — ignore (forward-compatible with richer SFZ files).
280        _ => {}
281    }
282    Ok(())
283}
284
285/// Parse a velocity `0..=127`.
286fn parse_vel(val: &str) -> Result<u8, AudioError> {
287    let v: i32 = val.parse().map_err(|_| AudioError::InvalidParameter)?;
288    if (0..=127).contains(&v) {
289        Ok(v as u8)
290    } else {
291        Err(AudioError::InvalidParameter)
292    }
293}
294
295/// Parse a key as a MIDI number (`0..=127`) or a note name (`c4`, `F#3`, `bb2`).
296fn parse_key(val: &str) -> Result<u8, AudioError> {
297    if let Ok(n) = val.parse::<i32>() {
298        return if (0..=127).contains(&n) {
299            Ok(n as u8)
300        } else {
301            Err(AudioError::InvalidParameter)
302        };
303    }
304    parse_note_name(val)
305}
306
307/// Note name → MIDI number using `c-1 = 0` (so `c4 = 60`). Accepts `#`/`b` accidentals.
308fn parse_note_name(val: &str) -> Result<u8, AudioError> {
309    let bytes = val.as_bytes();
310    if bytes.is_empty() {
311        return Err(AudioError::InvalidParameter);
312    }
313    let mut idx = 0;
314    let base = match bytes[0].to_ascii_lowercase() {
315        b'c' => 0i32,
316        b'd' => 2,
317        b'e' => 4,
318        b'f' => 5,
319        b'g' => 7,
320        b'a' => 9,
321        b'b' => 11,
322        _ => return Err(AudioError::InvalidParameter),
323    };
324    idx += 1;
325    let mut accidental = 0i32;
326    while idx < bytes.len() {
327        match bytes[idx] {
328            b'#' => accidental += 1,
329            b'b' | b'B' => accidental -= 1,
330            _ => break,
331        }
332        idx += 1;
333    }
334    let octave: i32 = val[idx..]
335        .parse()
336        .map_err(|_| AudioError::InvalidParameter)?;
337    let midi = (octave + 1) * 12 + base + accidental;
338    if (0..=127).contains(&midi) {
339        Ok(midi as u8)
340    } else {
341        Err(AudioError::InvalidParameter)
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    #[test]
350    fn instrument_two_regions_ranges() {
351        let text = "\
352<region> sample=a.wav lokey=60 hikey=71 pitch_keycenter=60
353<region> sample=b.wav lokey=72 hikey=83 pitch_keycenter=72";
354        let instr = parse_sfz(text).expect("parse");
355        assert_eq!(instr.len(), 2);
356        let r0 = &instr.regions()[0];
357        assert_eq!(r0.lokey, 60);
358        assert_eq!(r0.hikey, 71);
359        assert_eq!(r0.pitch_keycenter, 60);
360        assert_eq!(r0.sample_ref, "a.wav");
361        let r1 = &instr.regions()[1];
362        assert_eq!(r1.lokey, 72);
363        assert_eq!(r1.hikey, 83);
364        assert_eq!(r1.sample_ref, "b.wav");
365    }
366
367    #[test]
368    fn empty_is_empty_not_error() {
369        let instr = parse_sfz("").expect("empty ok");
370        assert!(instr.is_empty());
371        let instr2 = parse_sfz("// only a comment\n\n").expect("comment ok");
372        assert!(instr2.is_empty());
373    }
374
375    #[test]
376    fn group_defaults_inherited() {
377        let text = "\
378<group> volume=-6 lovel=0 hivel=63
379<region> sample=soft.wav lokey=60 hikey=60
380<region> sample=soft2.wav lokey=61 hikey=61 hivel=127";
381        let instr = parse_sfz(text).expect("parse");
382        assert_eq!(instr.len(), 2);
383        assert_eq!(instr.regions()[0].volume_db, -6.0);
384        assert_eq!(instr.regions()[0].hivel, 63); // inherited
385        assert_eq!(instr.regions()[1].hivel, 127); // overridden
386    }
387
388    #[test]
389    fn key_opcode_sets_all_three() {
390        let instr = parse_sfz("<region> sample=x.wav key=64").expect("parse");
391        let r = &instr.regions()[0];
392        assert_eq!(r.lokey, 64);
393        assert_eq!(r.hikey, 64);
394        assert_eq!(r.pitch_keycenter, 64);
395    }
396
397    #[test]
398    fn note_name_keys() {
399        // c4 = 60 under c-1 = 0.
400        assert_eq!(parse_key("c4").unwrap(), 60);
401        assert_eq!(parse_key("a4").unwrap(), 69);
402        assert_eq!(parse_key("f#3").unwrap(), 54);
403        assert_eq!(parse_key("60").unwrap(), 60);
404        assert!(parse_key("h9").is_err());
405    }
406
407    #[test]
408    fn sample_path_with_spaces() {
409        let text = "<region> sample=Grand Piano/C4 v1.wav lokey=60 hikey=60";
410        let instr = parse_sfz(text).expect("parse");
411        assert_eq!(instr.regions()[0].sample_ref, "Grand Piano/C4 v1.wav");
412        assert_eq!(instr.regions()[0].lokey, 60);
413    }
414
415    #[test]
416    fn bad_key_is_error() {
417        assert_eq!(
418            parse_sfz("<region> sample=x.wav lokey=999").err(),
419            Some(AudioError::InvalidParameter)
420        );
421    }
422}