Skip to main content

qualia_audio/midi/instrument/
preset.rs

1//! Unified [`InstrumentPreset`] view over the three instrument formats (SFZ / SF2 / DLS).
2//!
3//! A preset is the format-neutral description the rest of the engine and the UI work with:
4//! a human name, an optional MIDI bank/program address, the originating format, and *how* its
5//! samples are referenced. Qualia ships NO content — a preset only NAMES samples; the bytes are
6//! resolved later against the user's own asset store (see `resolver`).
7//!
8//! - SFZ presets reference samples by EXTERNAL relative paths (one per region) — these are what
9//!   the resolver joins against a base dir / asset lookup.
10//! - SF2 and DLS embed their sample audio INSIDE the file, so there are no external refs; the
11//!   preset records its bank/program address and the source file is the resolution target.
12
13use super::dls::DlsInstrument;
14use super::sf2::Sf2Preset;
15use super::sfz::SfzInstrument;
16
17/// Which on-disk format a preset came from.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum PresetFormat {
20    /// SFZ text instrument — external per-region sample files.
21    Sfz,
22    /// SoundFont2 — samples embedded in the `.sf2`.
23    Sf2,
24    /// Downloadable Sounds — samples embedded in the `.dls`.
25    Dls,
26}
27
28/// How a preset's sample content is located.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum SampleSource {
31    /// Samples are external files referenced by relative path (SFZ). Paths are de-duplicated,
32    /// in first-seen order.
33    ExternalRefs(Vec<String>),
34    /// Samples are embedded inside the source instrument file (SF2/DLS); the whole file is the
35    /// resolution target.
36    Embedded,
37}
38
39/// A format-neutral instrument preset.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct InstrumentPreset {
42    /// Display name.
43    pub name: String,
44    /// MIDI bank (0 for SFZ, which has no inherent bank/program).
45    pub bank: u16,
46    /// MIDI program (0 for SFZ).
47    pub program: u16,
48    /// Originating format.
49    pub format: PresetFormat,
50    /// How the samples are located.
51    pub samples: SampleSource,
52}
53
54impl InstrumentPreset {
55    /// Build a preset from a parsed SFZ instrument. `name` is caller-supplied (SFZ has no
56    /// embedded instrument name); the external sample refs are collected, de-duplicated, in
57    /// region order.
58    pub fn from_sfz(name: impl Into<String>, instr: &SfzInstrument<'_>) -> Self {
59        let mut refs: Vec<String> = Vec::new();
60        for r in instr.regions() {
61            if r.sample_ref.is_empty() {
62                continue;
63            }
64            if !refs.iter().any(|s| s == r.sample_ref) {
65                refs.push(r.sample_ref.to_string());
66            }
67        }
68        Self {
69            name: name.into(),
70            bank: 0,
71            program: 0,
72            format: PresetFormat::Sfz,
73            samples: SampleSource::ExternalRefs(refs),
74        }
75    }
76
77    /// Build a preset from an enumerated SoundFont2 preset (samples embedded).
78    pub fn from_sf2(p: &Sf2Preset) -> Self {
79        Self {
80            name: p.name.clone(),
81            bank: p.bank,
82            program: p.program,
83            format: PresetFormat::Sf2,
84            samples: SampleSource::Embedded,
85        }
86    }
87
88    /// Build a preset from an enumerated DLS instrument (samples embedded).
89    pub fn from_dls(i: &DlsInstrument) -> Self {
90        Self {
91            name: i.name.clone(),
92            bank: i.bank,
93            program: i.program as u16,
94            format: PresetFormat::Dls,
95            samples: SampleSource::Embedded,
96        }
97    }
98
99    /// The external sample references, if this preset has any (SFZ). Empty slice for embedded.
100    pub fn external_refs(&self) -> &[String] {
101        match &self.samples {
102            SampleSource::ExternalRefs(v) => v,
103            SampleSource::Embedded => &[],
104        }
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::super::sfz::parse_sfz;
111    use super::*;
112
113    #[test]
114    fn from_sfz_collects_unique_refs() {
115        let text = "\
116<region> sample=a.wav lokey=60 hikey=71
117<region> sample=b.wav lokey=72 hikey=83
118<region> sample=a.wav lokey=84 hikey=95";
119        let instr = parse_sfz(text).expect("parse");
120        let p = InstrumentPreset::from_sfz("Test Kit", &instr);
121        assert_eq!(p.name, "Test Kit");
122        assert_eq!(p.format, PresetFormat::Sfz);
123        assert_eq!(
124            p.external_refs(),
125            &["a.wav".to_string(), "b.wav".to_string()]
126        );
127    }
128
129    #[test]
130    fn from_sf2_is_embedded() {
131        let sp = Sf2Preset {
132            name: "Piano".into(),
133            bank: 0,
134            program: 1,
135        };
136        let p = InstrumentPreset::from_sf2(&sp);
137        assert_eq!(p.format, PresetFormat::Sf2);
138        assert_eq!(p.samples, SampleSource::Embedded);
139        assert_eq!(p.program, 1);
140        assert!(p.external_refs().is_empty());
141    }
142
143    #[test]
144    fn from_dls_is_embedded() {
145        let di = DlsInstrument {
146            name: "Pad".into(),
147            bank: 1,
148            program: 89,
149            is_drum: false,
150        };
151        let p = InstrumentPreset::from_dls(&di);
152        assert_eq!(p.format, PresetFormat::Dls);
153        assert_eq!(p.bank, 1);
154        assert_eq!(p.program, 89);
155    }
156}