oscyl_driver/contract.rs
1//! What a driver tells Oscyl about one synth model.
2//!
3//! Programs are opaque bytes in the driver's own native layout; generic
4//! code reads and writes them only through the driver. Field indices are
5//! positions in [`Driver::fields`].
6
7use std::borrow::Cow;
8use std::collections::BTreeMap;
9use std::time::Instant;
10
11use crate::curation::*;
12
13/// A driver-specific failure, as text the apps can show.
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15#[error("{0}")]
16pub struct DriverError(pub String);
17
18/// Which synth a driver serves.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct Info {
21 /// Stable id: `<vendor>-<model>`, lowercase, dash-separated.
22 pub id: &'static str,
23 /// The maker, as people write it ("KORG").
24 pub vendor: &'static str,
25 /// The model, as the maker writes it ("minilogue xd").
26 pub model: &'static str,
27}
28
29/// A run of program slots, numbered from `first`.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct Bank {
32 /// The bank's name, as the synth shows it ("U1").
33 pub name: &'static str,
34 /// The number of the bank's first slot.
35 pub first: u16,
36 /// How many slots the bank has.
37 pub len: u16,
38 /// False for factory/ROM banks Oscyl must never write.
39 pub writable: bool,
40}
41
42/// One kind of user unit (custom oscillator, effect, …) and its slot count.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct UnitKind {
45 /// The kind's short name ("osc", "modfx").
46 pub name: &'static str,
47 /// How many slots of this kind the synth has.
48 pub slots: u8,
49}
50
51/// What the synth can do. Apps show only what is listed here.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct Capabilities {
54 /// The program banks, in slot order.
55 pub banks: &'static [Bank],
56 /// Programs can be loaded into an edit buffer without storing them.
57 pub edit_buffer: bool,
58 /// Parameters can change while notes sound (CC/NRPN).
59 pub live_changes: bool,
60 /// The kinds of user unit the synth holds; empty when it holds none.
61 pub units: &'static [UnitKind],
62}
63
64/// One program parameter: raw stored values `min..=max`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct FieldInfo {
67 /// The parameter's name ("Cutoff").
68 pub name: &'static str,
69 /// The group it belongs to ("Filter"). [`curation_by_group`] makes one
70 /// page for each group.
71 pub group: &'static str,
72 /// The smallest raw value.
73 pub min: u16,
74 /// The largest raw value.
75 pub max: u16,
76}
77
78/// Program-name limits.
79#[derive(Debug, Clone, Copy)]
80pub struct NameRules {
81 /// The longest name, in characters.
82 pub max_len: usize,
83 /// Whether a character can be part of a name.
84 pub allowed: fn(char) -> bool,
85}
86
87/// One program in a library, with its author metadata.
88#[derive(Debug, Clone, Default, PartialEq, Eq)]
89pub struct LibProgram {
90 /// The driver's native program bytes.
91 pub data: Vec<u8>,
92 /// Who made the program; empty when nobody says.
93 pub author: String,
94 /// A note on the program; empty when there is none.
95 pub comment: String,
96}
97
98/// A library's contents, independent of any file format.
99#[derive(Debug, Clone, Default, PartialEq, Eq)]
100pub struct LibraryData {
101 /// The programs, in library order.
102 pub programs: Vec<LibProgram>,
103 /// Driver-owned members (vendor entries Oscyl does not edit), kept
104 /// verbatim so an export loses nothing. Names are the driver's.
105 pub extras: BTreeMap<String, Vec<u8>>,
106}
107
108/// A vendor file format a driver reads and writes.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct FileFormat {
111 /// File extension, without the dot.
112 pub ext: &'static str,
113 /// The format's name, for file pickers ("minilogue xd library").
114 pub name: &'static str,
115 /// Whether the format stores each program's author and comment. When
116 /// false, import gives them empty.
117 pub keeps_metadata: bool,
118}
119
120/// Decodes the Control Changes a synth's panel sends: one per synth, as it
121/// keeps state between messages (a 10-bit value's lower bits, an NRPN
122/// selection).
123pub trait PanelListener: Send {
124 /// One Control Change on the synth's channel: the field it sets in
125 /// `program` (the program the synth plays) and the value, once complete.
126 fn control(&mut self, cc: u8, value: u8, program: &[u8]) -> Option<(usize, u16)>;
127}
128
129/// One synth model: everything the apps know about it. Object-safe, so
130/// apps can hold several at once, as `&dyn Driver`. A driver crate exposes
131/// one as `pub static DRIVER`.
132///
133/// Methods without a default are required. The others have a default that
134/// suits a driver which does not use them.
135pub trait Driver: Send + Sync {
136 /// Which synth this driver serves.
137 fn info(&self) -> &'static Info;
138 /// What the synth can do. Apps show only what this lists.
139 fn capabilities(&self) -> &'static Capabilities;
140 /// The program's parameters. A field's index in this slice is the
141 /// `field` argument of the other methods.
142 fn fields(&self) -> &'static [FieldInfo];
143 /// The limits of a program's name.
144 fn name_rules(&self) -> NameRules;
145 /// A new program, valid, with a name that [`Driver::name_rules`] allow.
146 fn init_program(&self) -> Vec<u8>;
147 /// Refuses bytes that are not a whole, valid program.
148 fn check_program(&self, program: &[u8]) -> Result<(), DriverError>;
149 /// The raw value of `field` in `program`. An error for a bad program
150 /// or field index.
151 fn get(&self, program: &[u8], field: usize) -> Result<u16, DriverError>;
152 /// Sets `field` in `program` to `value`, and changes no other field. An
153 /// error for a bad program, a bad field index, or a value outside
154 /// `min..=max`.
155 fn set(&self, program: &mut [u8], field: usize, value: u16) -> Result<(), DriverError>;
156 /// The program's name, without padding.
157 fn name(&self, program: &[u8]) -> Result<String, DriverError>;
158 /// Sets the program's name. An error for a name that
159 /// [`Driver::name_rules`] refuse.
160 fn set_name(&self, program: &mut [u8], name: &str) -> Result<(), DriverError>;
161 /// The synth's own file formats that the driver reads and writes,
162 /// the usual one first. Can be empty.
163 fn file_formats(&self) -> &'static [FileFormat];
164 /// Read a vendor file of format `ext`.
165 fn import(&self, ext: &str, bytes: &[u8]) -> Result<LibraryData, DriverError>;
166 /// Write a vendor file of format `ext`; `import` of the result gives
167 /// back `lib`.
168 fn export(&self, ext: &str, lib: &LibraryData) -> Result<Vec<u8>, DriverError>;
169
170 // Curation: data the apps render. Everything but `curation` has a
171 // default that suits a driver with no curation of its own.
172
173 /// Pages and sections of the editor. Required: a simple driver may
174 /// return [`curation_by_group`]`(self.fields())`, but says so on
175 /// purpose.
176 fn curation(&self) -> Curation;
177 /// The widget for `field`. It may depend on other fields of `program`
178 /// (a depth that names chords in one mode and is a dial in another), so
179 /// apps query it again after an edit and rebuild the control when it
180 /// changes.
181 fn control(&self, _program: &[u8], field: usize) -> Control {
182 match self.fields().get(field) {
183 Some(f) if f.max - f.min == 1 => Control::Toggle,
184 _ => Control::Continuous,
185 }
186 }
187 /// A compact label for use inside a titled section.
188 fn short_label(&self, field: usize) -> &'static str {
189 self.fields().get(field).map_or("", |f| f.name)
190 }
191 /// The label for `field` under `program`'s settings, when its job
192 /// changes with another field (a depth that is a chord in one mode and
193 /// a detune in another). Defaults to [`Driver::short_label`].
194 fn label_in(&self, _program: &[u8], field: usize) -> Cow<'static, str> {
195 Cow::Borrowed(self.short_label(field))
196 }
197 /// Whether `field` is one of its section's main controls, which apps
198 /// draw larger.
199 fn emphasized(&self, _field: usize) -> bool {
200 false
201 }
202 /// `field`'s value in `program`, for people, read in the context of
203 /// the program's other fields. Empty when unreadable.
204 fn format_value(&self, program: &[u8], field: usize) -> String {
205 self.get(program, field)
206 .map(|v| self.format_raw(field, v))
207 .unwrap_or_default()
208 }
209 /// `raw` for `field` without a program (range tooltips, before/after
210 /// text). Values whose meaning depends on other fields show plainly.
211 fn format_raw(&self, field: usize, raw: u16) -> String {
212 self.fields()
213 .get(field)
214 .map(|f| format_raw_default(f, raw))
215 .unwrap_or_default()
216 }
217 /// A one-line description of `page`'s state in `program`, or empty.
218 fn page_summary(&self, _program: &[u8], _page: usize) -> String {
219 String::new()
220 }
221 /// Pictures of `page` in `program`; curves use about `points` points.
222 fn graphs(&self, _program: &[u8], _page: usize, _points: usize) -> Vec<Graph> {
223 vec![]
224 }
225 /// Draggable points on `page`'s first graph.
226 fn handles(&self, _program: &[u8], _page: usize) -> Vec<Handle> {
227 vec![]
228 }
229 /// The field values that put handle `handle` of `page` at `at` (graph
230 /// coordinates), only those that change.
231 fn drag(
232 &self,
233 _program: &[u8],
234 _page: usize,
235 _handle: usize,
236 _at: (f32, f32),
237 ) -> Vec<(usize, u16)> {
238 vec![]
239 }
240 /// Whether `field` does anything under `program`'s other settings;
241 /// editors hide fields that do not.
242 fn relevant(&self, _program: &[u8], _field: usize) -> bool {
243 true
244 }
245 /// What `field` does to the sound, for the editor's help. Empty by
246 /// default.
247 fn help(&self, _field: usize) -> Help {
248 Help::default()
249 }
250 /// What kind of sound `program` is (for example "Bass"), if the driver
251 /// can tell.
252 fn category(&self, _program: &[u8]) -> Option<&'static str> {
253 None
254 }
255 /// Every value [`Driver::category`] can return, in display order, for
256 /// filters.
257 fn categories(&self) -> &'static [&'static str] {
258 &[]
259 }
260
261 // Generation. A driver with no characters does not generate.
262
263 /// What generation may do to `field`. By default
264 /// [`Mutability::Restricted`]: generation keeps it.
265 fn mutability(&self, _field: usize) -> Mutability {
266 Mutability::Restricted
267 }
268 /// The kinds of sound that Generate makes for this synth. Empty by
269 /// default: the driver does not generate.
270 fn characters(&self) -> &'static [Character] {
271 &[]
272 }
273 /// Titles and help for the four [`Macros`], in their order.
274 fn macro_info(&self) -> [MacroInfo; 4] {
275 MACROS
276 }
277 /// A name for a generated program of `character`, from `seed`.
278 fn generated_name(&self, character: usize, seed: u64) -> String {
279 let title = self
280 .characters()
281 .get(character)
282 .map_or("Sound", |c| c.title);
283 format!("{title} {}", seed % 1000)
284 }
285 /// A new program from `recipe`. Same recipe and base, same bytes.
286 ///
287 /// Without a base, non-free fields are the init program's. With
288 /// `Some(base)`, every non-free ([`Mutability::Restricted`] or
289 /// [`Mutability::Fixed`]) field is the base's, and every field on the
290 /// pages in `recipe.keep` comes back byte for byte from the base, even
291 /// a value out of range; only free fields on other pages are
292 /// generated.
293 fn generate(&self, _recipe: &Recipe, _base: Option<&[u8]>) -> Result<Vec<u8>, DriverError> {
294 Err(no_generation())
295 }
296 /// A mutation of `program` by `amount` (`0.0..=1.0`). Only free fields
297 /// change; restricted and fixed fields stay as they are.
298 fn vary(&self, _program: &[u8], _amount: f32, _seed: u64) -> Result<Vec<u8>, DriverError> {
299 Err(no_generation())
300 }
301 /// A child of `a` and `b`; `mix` 0 is `a`, 1 is `b`. Free fields mix;
302 /// restricted and fixed fields are `a`'s, as they are. Out-of-range
303 /// parent values are clamped where they mix.
304 fn breed(&self, _a: &[u8], _b: &[u8], _mix: f32, _seed: u64) -> Result<Vec<u8>, DriverError> {
305 Err(no_generation())
306 }
307 /// The user unit slots `program` relies on (a user oscillator its
308 /// mixer lets through, a user effect that is on), by kind. `vary`,
309 /// `breed` and `morph` never make a program select a slot none of its
310 /// parents selected.
311 fn needs(&self, _program: &[u8]) -> Vec<(UnitKind, u8)> {
312 vec![]
313 }
314 /// When `field` is, under `program`'s settings, a parameter of a user
315 /// unit: the unit's kind and slot, and which of its parameters (from
316 /// 0). Apps that know the unit show its own name and range there.
317 fn unit_param(&self, _program: &[u8], _field: usize) -> Option<(UnitKind, u8, usize)> {
318 None
319 }
320 /// Step `t` (`0.0..=1.0`) of the way from `a` to `b`: 0 is `a`, 1 is
321 /// `b`'s sound, and steps in between never turn back, so a row of them
322 /// goes smoothly from one to the other. Same inputs, same bytes; `seed`
323 /// decides where along the way each group of selectors switches.
324 /// Restricted and fixed fields are `a`'s. By default
325 /// [`morph_fields`]; a driver with coherence rules applies them on top.
326 fn morph(&self, a: &[u8], b: &[u8], t: f32, seed: u64) -> Result<Vec<u8>, DriverError> {
327 if self.characters().is_empty() {
328 return Err(no_generation());
329 }
330 morph_fields(self, a, b, t, seed)
331 }
332
333 /// The MIDI messages that set `field` to its value in `program` on the
334 /// sounding voices, in order, one complete message per inner `Vec`: a
335 /// transport sends each one separately, since some backends send only
336 /// the first event of a buffer. Callers pass `channel` 0-15. `None`
337 /// when only a whole-program audition can make the change. Only with
338 /// [`Capabilities::live_changes`].
339 fn live_messages(&self, _program: &[u8], _field: usize, _channel: u8) -> Option<Vec<Vec<u8>>> {
340 None
341 }
342
343 // Sessions.
344
345 /// A new session with one synth that listens on MIDI channel
346 /// `channel` (0-15). A driver whose SysEx has no channel ignores it.
347 fn session(&self, channel: u8) -> Box<dyn DriverSession>;
348 /// A new simulated synth, for the conformance suite and the tests.
349 fn simulator(&self) -> Box<dyn Simulator>;
350 /// Substrings of the MIDI port names this synth shows up as.
351 fn port_hint(&self) -> &'static [&'static str];
352 /// Whether `identity_reply`, an answer to
353 /// [`crate::sysex::DEVICE_INQUIRY`], comes from this synth.
354 fn recognize(&self, identity_reply: &[u8]) -> bool;
355
356 // What apps show around the editor. All optional.
357
358 /// A library to explore without a synth. By default one generated
359 /// program per character (none without characters).
360 fn demo_library(&self) -> LibraryData {
361 let programs = (0..self.characters().len())
362 .filter_map(|character| {
363 let recipe = Recipe {
364 character,
365 seed: character as u64,
366 ..Recipe::default()
367 };
368 self.generate(&recipe, None).ok()
369 })
370 .map(|data| LibProgram {
371 data,
372 ..LibProgram::default()
373 })
374 .collect();
375 LibraryData {
376 programs,
377 extras: BTreeMap::new(),
378 }
379 }
380 /// The simulator demo mode connects to, holding whatever makes a demo
381 /// worth exploring. By default [`Driver::simulator`].
382 fn demo_simulator(&self) -> Box<dyn Simulator> {
383 self.simulator()
384 }
385 /// A [`Control::Choice`] field program lists can filter by (a voice
386 /// mode), if any.
387 fn list_facet(&self) -> Option<usize> {
388 None
389 }
390 /// The firmware version an identity reply names, for people.
391 fn firmware(&self, _identity_reply: &[u8]) -> Option<String> {
392 None
393 }
394 /// The program slot the synth's panel picked, from the Bank Select
395 /// it sent last (CC 0 and CC 32) and a Program Change: apps follow it.
396 /// `None` when out of range or the driver does not say.
397 fn program_slot(&self, _bank_msb: u8, _bank_lsb: u8, _program: u8) -> Option<u16> {
398 None
399 }
400 /// A decoder for what the synth's panel sends as its knobs turn: apps
401 /// follow it. `None` when the driver does not say.
402 fn panel_listener(&self) -> Option<Box<dyn PanelListener>> {
403 None
404 }
405 /// What to check on the synth when it does not answer the device
406 /// inquiry (a setting that routes SysEx elsewhere), or empty.
407 fn setup_hint(&self) -> &'static str {
408 ""
409 }
410 /// The driver's support tier (GOVERNANCE.md): 1 hardware-validated,
411 /// 2 conformance-proven, 3 community. By default 3.
412 fn tier(&self) -> u8 {
413 3
414 }
415 /// The polyphony of the models it covers, fewest first (`[8, 16]` for a
416 /// synth sold in 8- and 16-voice versions), or empty when unknown.
417 fn voices(&self) -> &'static [u8] {
418 &[]
419 }
420 /// [`Driver::page_summary`] for an app: `compact` asks for the shortest
421 /// form that still reads (narrow columns), and `tr` translates the
422 /// driver's own phrases (templates with `{name}` placeholders, filled
423 /// after translating) and value names. By default, `page_summary` as
424 /// it is.
425 fn page_summary_in(
426 &self,
427 program: &[u8],
428 page: usize,
429 _compact: bool,
430 _tr: &dyn Fn(&str) -> String,
431 ) -> String {
432 self.page_summary(program, page)
433 }
434}
435
436/// A generic operation on a connected synth.
437#[derive(Debug, Clone, PartialEq, Eq)]
438pub enum SessionOp {
439 /// Read the edit buffer: the program the synth plays now.
440 ReadCurrent,
441 /// Read these slots, in this order.
442 ReadPrograms(Vec<u16>),
443 /// Store programs; the driver plans the exact sequence that leaves the
444 /// synth committed and safe to read.
445 WritePrograms(Vec<(u16, Vec<u8>)>),
446 /// Load a program into the edit buffer without storing it.
447 Audition(Vec<u8>),
448}
449
450/// Results of [`SessionOp`]s, in order.
451#[derive(Debug, Clone, PartialEq, Eq)]
452pub enum SessionEvent {
453 /// The edit buffer's program, for [`SessionOp::ReadCurrent`].
454 Current(Vec<u8>),
455 /// A slot's program, for [`SessionOp::ReadPrograms`].
456 Program(u16, Vec<u8>),
457 /// Steps of the op that are done, out of all its steps.
458 Progress {
459 /// Steps done.
460 done: usize,
461 /// All the op's steps.
462 total: usize,
463 },
464 /// The op ended, and every step succeeded.
465 Done,
466 /// The op ended at a failed step; the steps after it did not run.
467 Failed(crate::engine::OpError),
468}
469
470/// A sans-IO session with one connected synth.
471pub trait DriverSession: Send {
472 /// Plans the op. Errors before anything is queued: a bad slot, a
473 /// write to a factory slot, or a bad program sends nothing.
474 fn submit(&mut self, op: SessionOp) -> Result<(), DriverError>;
475 /// True when nothing is queued or in flight.
476 fn is_idle(&self) -> bool;
477 /// The next bytes to send to the synth, if the session sends now.
478 fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>>;
479 /// When the caller must call [`DriverSession::handle_timeout`], if a
480 /// request waits for its reply.
481 fn next_deadline(&self) -> Option<Instant>;
482 /// Time passed: a request whose reply did not come by now fails.
483 fn handle_timeout(&mut self, now: Instant);
484 /// Bytes that the synth sent, in fragments of any size.
485 fn handle_input(&mut self, bytes: &[u8]);
486 /// The next result of the submitted ops, in order.
487 fn poll_event(&mut self) -> Option<SessionEvent>;
488}
489
490/// A sans-IO simulated synth, for tests and demo mode.
491pub trait Simulator: Send {
492 /// One complete SysEx message in, the replies out.
493 fn handle(&mut self, msg: &[u8]) -> Vec<Vec<u8>>;
494 /// One firmware main-loop pass with no MIDI traffic.
495 fn idle_tick(&mut self);
496 /// The program in `slot`, or `None` for a slot the synth does not have.
497 fn program(&self, slot: u16) -> Option<Vec<u8>>;
498 /// The edit buffer's program.
499 fn edit_buffer(&self) -> Vec<u8>;
500 /// No pending save and no corrupted reply state.
501 fn is_settled(&self) -> bool;
502 /// Failures seen on hardware that [`Simulator::inject`] can switch on.
503 fn faults(&self) -> &'static [&'static str];
504 /// Switches on `fault`, one of [`Simulator::faults`], until the
505 /// simulator is dropped.
506 fn inject(&mut self, fault: &str);
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512
513 #[test]
514 fn curation_by_group_keeps_schema_order() {
515 let f = |name, group| FieldInfo {
516 name,
517 group,
518 min: 0,
519 max: 1,
520 };
521 let c = curation_by_group(&[f("a", "X"), f("b", "Y"), f("c", "X")]);
522 let titles: Vec<_> = c.pages.iter().map(|p| p.title).collect();
523 assert_eq!(titles, ["X", "Y"]);
524 assert_eq!(c.pages[0].sections.len(), 1);
525 assert_eq!(c.pages[0].sections[0].title, "X");
526 assert_eq!(c.pages[0].sections[0].fields, [0, 2]);
527 assert_eq!(c.pages[1].sections[0].fields, [1]);
528 assert!(c.excluded.is_empty());
529 }
530
531 #[test]
532 fn default_format_matches_the_default_control() {
533 let f = |min, max| FieldInfo {
534 name: "f",
535 group: "G",
536 min,
537 max,
538 };
539 assert_eq!(format_raw_default(&f(0, 1), 0), "Off");
540 assert_eq!(format_raw_default(&f(0, 1), 1), "On");
541 assert_eq!(format_raw_default(&f(3, 4), 4), "On");
542 assert_eq!(format_raw_default(&f(0, 9), 1), "1");
543 }
544}