qualia_audio/midi/instrument/resolver.rs
1//! Sample resolution + LICENCE PROVENANCE for a loaded instrument.
2//!
3//! # Qualia ships NO sample content
4//! Every instrument's audio is USER-supplied — from the user's hypermedia library or a user /
5//! vendor content directory. The loaders in this module only READ references and metadata; this
6//! resolver binds those references to concrete asset locations AND stamps the instrument with a
7//! [`LicenceTag`] recording the terms under which the content was supplied.
8//!
9//! The licence tag is carried on the [`ResolvedInstrument`] so that a downstream export/share
10//! step can **fail closed**: content marked non-commercial, no-redistribution, or unknown must
11//! not be baked into a shared/exported artifact without the principal's explicit decision. That
12//! policy is exposed here as [`ResolvedInstrument::redistribution_allowed`] — the resolver never
13//! *decides* to share, it only records enough provenance for the export gate to refuse safely.
14
15use super::preset::{InstrumentPreset, PresetFormat, SampleSource};
16
17/// Licence provenance for user-supplied instrument content.
18///
19/// This is a coarse, export-safety classification — not a full SPDX licence identifier. The
20/// resolver treats [`LicenceTag::Unknown`] as the safe default (fail closed on redistribution).
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum LicenceTag {
23 /// Public-domain-equivalent (CC0). Freely redistributable.
24 Cc0,
25 /// A permissive licence allowing commercial use and redistribution (e.g. CC-BY, MIT-like).
26 Permissive,
27 /// Non-commercial only (e.g. CC-BY-NC). Must not be redistributed in a commercial artifact.
28 NonCommercial,
29 /// Redistribution prohibited (personal-use / evaluation licences).
30 NoRedistribution,
31 /// Provenance unknown — treated as the most restrictive case.
32 Unknown,
33}
34
35impl LicenceTag {
36 /// May content under this tag be redistributed / baked into an exported, shared artifact?
37 /// Fails closed: only explicitly-free tags return `true`.
38 #[inline]
39 pub fn allows_redistribution(self) -> bool {
40 matches!(self, LicenceTag::Cc0 | LicenceTag::Permissive)
41 }
42}
43
44/// One resolved sample reference: the original relative reference plus, where a base/lookup was
45/// supplied, the concrete location it maps to.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct ResolvedSample {
48 /// The reference as it appeared in the instrument (relative path, or an embedded marker).
49 pub reference: String,
50 /// The resolved location (base-joined path or asset key), if resolution was performed.
51 pub resolved: Option<String>,
52}
53
54/// A preset bound to its content location(s) and stamped with licence provenance.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct ResolvedInstrument {
57 /// Display name (carried from the preset).
58 pub name: String,
59 /// Originating format.
60 pub format: PresetFormat,
61 /// Resolved sample references. For embedded (SF2/DLS) formats this is a single entry marking
62 /// the source file as the resolution target.
63 pub samples: Vec<ResolvedSample>,
64 /// Licence provenance — PRESERVED so a later export/share can fail closed.
65 pub licence: LicenceTag,
66}
67
68impl ResolvedInstrument {
69 /// May this instrument's content be redistributed in a shared/exported artifact?
70 /// Delegates to the recorded [`LicenceTag`], failing closed on `Unknown`/restricted tags.
71 #[inline]
72 pub fn redistribution_allowed(&self) -> bool {
73 self.licence.allows_redistribution()
74 }
75}
76
77/// Resolve an instrument preset and attach its licence provenance.
78///
79/// This is the mandated entry point: it records each sample reference WITHOUT joining against a
80/// base directory (`resolved` is left `None`) and stamps the supplied `licence`. Use
81/// [`resolve_instrument_with`] to also bind references to concrete locations against a caller-
82/// supplied base path or asset lookup.
83///
84/// Qualia ships no content: `preset` came from a USER-supplied instrument file, and `licence`
85/// is the provenance the caller recorded when importing that content.
86pub fn resolve_instrument(preset: &InstrumentPreset, licence: LicenceTag) -> ResolvedInstrument {
87 resolve_with_opt(preset, licence, None::<&dyn Fn(&str) -> Option<String>>)
88}
89
90/// Resolve an instrument preset, binding each external sample reference against a caller-supplied
91/// `lookup` (e.g. "join base dir" or "hypermedia asset by key"), and attach `licence`.
92///
93/// `lookup` maps a reference to its concrete location (path/asset key), or `None` if the asset is
94/// missing. Embedded (SF2/DLS) content is passed through `lookup` too, keyed by the preset name,
95/// so an embedded source file can be located the same way.
96pub fn resolve_instrument_with<F>(
97 preset: &InstrumentPreset,
98 licence: LicenceTag,
99 lookup: F,
100) -> ResolvedInstrument
101where
102 F: Fn(&str) -> Option<String>,
103{
104 resolve_with_opt(preset, licence, Some(&lookup))
105}
106
107fn resolve_with_opt(
108 preset: &InstrumentPreset,
109 licence: LicenceTag,
110 lookup: Option<&dyn Fn(&str) -> Option<String>>,
111) -> ResolvedInstrument {
112 let mut samples = Vec::new();
113 match &preset.samples {
114 SampleSource::ExternalRefs(refs) => {
115 for r in refs {
116 let resolved = lookup.and_then(|f| f(r));
117 samples.push(ResolvedSample {
118 reference: r.clone(),
119 resolved,
120 });
121 }
122 }
123 SampleSource::Embedded => {
124 // The whole source file is the resolution target; key it by the preset name.
125 let resolved = lookup.and_then(|f| f(&preset.name));
126 samples.push(ResolvedSample {
127 reference: format!("<embedded:{}>", preset.name),
128 resolved,
129 });
130 }
131 }
132 ResolvedInstrument {
133 name: preset.name.clone(),
134 format: preset.format,
135 samples,
136 licence,
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::super::sfz::parse_sfz;
143 use super::*;
144
145 fn sfz_preset() -> InstrumentPreset {
146 let text = "\
147<region> sample=a.wav lokey=60 hikey=71
148<region> sample=b.wav lokey=72 hikey=83";
149 let instr = parse_sfz(text).expect("parse");
150 InstrumentPreset::from_sfz("Test", &instr)
151 }
152
153 #[test]
154 fn licence_tag_preserved_noncommercial() {
155 let preset = sfz_preset();
156 let resolved = resolve_instrument(&preset, LicenceTag::NonCommercial);
157 // The tag is preserved so a later export can refuse.
158 assert_eq!(resolved.licence, LicenceTag::NonCommercial);
159 assert!(!resolved.redistribution_allowed());
160 }
161
162 #[test]
163 fn no_redistribution_and_unknown_fail_closed() {
164 let preset = sfz_preset();
165 assert!(!resolve_instrument(&preset, LicenceTag::NoRedistribution).redistribution_allowed());
166 assert!(!resolve_instrument(&preset, LicenceTag::Unknown).redistribution_allowed());
167 }
168
169 #[test]
170 fn permissive_and_cc0_allow_export() {
171 let preset = sfz_preset();
172 assert!(resolve_instrument(&preset, LicenceTag::Cc0).redistribution_allowed());
173 assert!(resolve_instrument(&preset, LicenceTag::Permissive).redistribution_allowed());
174 }
175
176 #[test]
177 fn resolve_records_refs_without_base() {
178 let preset = sfz_preset();
179 let resolved = resolve_instrument(&preset, LicenceTag::Cc0);
180 assert_eq!(resolved.samples.len(), 2);
181 assert_eq!(resolved.samples[0].reference, "a.wav");
182 assert!(resolved.samples[0].resolved.is_none());
183 }
184
185 #[test]
186 fn resolve_with_lookup_binds_base() {
187 let preset = sfz_preset();
188 let resolved = resolve_instrument_with(&preset, LicenceTag::Permissive, |r| {
189 Some(format!("/content/piano/{r}"))
190 });
191 assert_eq!(
192 resolved.samples[0].resolved.as_deref(),
193 Some("/content/piano/a.wav")
194 );
195 }
196}