Skip to main content

qualia_audio/midi/instrument/
sample_map.rs

1//! Allocation-free note→region lookup over a parsed [`SfzInstrument`].
2//!
3//! This is the HOT path used when a note-on must pick the sample region to play. It performs
4//! a linear scan of the instrument's fixed region slice and returns the FIRST matching region
5//! (SFZ layering is by authoring order). No allocation, no sorting — the region list was
6//! built once during the cold `parse_sfz` pass.
7
8use super::sfz::{SfzInstrument, SfzRegion};
9
10/// Return the first region matching `(note, velocity)`, or `None` if the instrument has no
11/// region covering that key/velocity rectangle.
12///
13/// Allocation-free: borrows straight out of `instr`'s region slice.
14#[inline]
15pub fn region_for<'a>(
16    instr: &'a SfzInstrument<'a>,
17    note: u8,
18    velocity: u8,
19) -> Option<&'a SfzRegion<'a>> {
20    instr.regions().iter().find(|r| r.matches(note, velocity))
21}
22
23#[cfg(test)]
24mod tests {
25    use super::super::sfz::parse_sfz;
26    use super::*;
27
28    fn two_region_instr() -> String {
29        "\
30<region> sample=a.wav lokey=60 hikey=71 pitch_keycenter=60
31<region> sample=b.wav lokey=72 hikey=83 pitch_keycenter=72"
32            .to_string()
33    }
34
35    #[test]
36    fn golden_first_region() {
37        let text = two_region_instr();
38        let instr = parse_sfz(&text).expect("parse");
39        let r = region_for(&instr, 65, 100).expect("match");
40        assert_eq!(r.sample_ref, "a.wav");
41        assert_eq!(r.lokey, 60);
42    }
43
44    #[test]
45    fn golden_second_region() {
46        let text = two_region_instr();
47        let instr = parse_sfz(&text).expect("parse");
48        let r = region_for(&instr, 75, 100).expect("match");
49        assert_eq!(r.sample_ref, "b.wav");
50        assert_eq!(r.hikey, 83);
51    }
52
53    #[test]
54    fn out_of_range_none() {
55        let text = two_region_instr();
56        let instr = parse_sfz(&text).expect("parse");
57        assert!(region_for(&instr, 40, 100).is_none());
58        assert!(region_for(&instr, 90, 100).is_none());
59    }
60
61    #[test]
62    fn velocity_filters() {
63        let text = "\
64<region> sample=soft.wav lokey=60 hikey=60 lovel=0 hivel=63
65<region> sample=loud.wav lokey=60 hikey=60 lovel=64 hivel=127";
66        let instr = parse_sfz(text).expect("parse");
67        assert_eq!(region_for(&instr, 60, 20).unwrap().sample_ref, "soft.wav");
68        assert_eq!(region_for(&instr, 60, 100).unwrap().sample_ref, "loud.wav");
69    }
70
71    #[test]
72    fn empty_instrument_none() {
73        let instr = parse_sfz("").expect("parse");
74        assert!(region_for(&instr, 60, 100).is_none());
75    }
76}