oscyl_driver/curation.rs
1//! Curation and generation data a driver gives the apps: editor pages,
2//! controls, help, generation recipes. Platform-neutral; apps render it.
3
4use crate::contract::{DriverError, FieldInfo, UnitKind};
5
6/// A titled group of fields on a [`Page`].
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Section {
9 /// The section's title ("VCO 1").
10 pub title: &'static str,
11 /// Field indices, in display order.
12 pub fields: Vec<usize>,
13}
14
15/// A top-level editor page (a stage of the signal path, a layer, …).
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Page {
18 /// The page's title ("Filter").
19 pub title: &'static str,
20 /// Symbolic icon name the apps ship, if any. For now these are the GTK
21 /// app's symbolic icon ids (`oscyl-filter-symbolic`, …); other apps map
22 /// them to their own icons.
23 pub icon: Option<&'static str>,
24 /// An introduction shown under the page heading, or empty.
25 pub help: &'static str,
26 /// The page's sections, in display order.
27 pub sections: Vec<Section>,
28}
29
30/// How the editor lays out a driver's fields. Every field is in exactly
31/// one section or in `excluded` (fields the editor does not show, such as
32/// sequencer data that needs its own view).
33#[derive(Debug, Clone, PartialEq, Eq, Default)]
34pub struct Curation {
35 /// The editor's pages, in display order.
36 pub pages: Vec<Page>,
37 /// The indices of the fields that the editor does not show.
38 pub excluded: Vec<usize>,
39}
40
41/// `raw` for `f` with no curation: "Off"/"On" for a two-value field (the
42/// default control is then a toggle), else the number.
43pub fn format_raw_default(f: &FieldInfo, raw: u16) -> String {
44 match (f.max - f.min == 1, raw == f.min) {
45 (true, true) => "Off".into(),
46 (true, false) => "On".into(),
47 _ => raw.to_string(),
48 }
49}
50
51/// One page per schema group, in the order the groups first appear, each
52/// with one section of the same name. A starting point for a simple
53/// driver's [`Driver::curation`](crate::Driver::curation).
54pub fn curation_by_group(fields: &[FieldInfo]) -> Curation {
55 let mut pages: Vec<Page> = vec![];
56 for (i, f) in fields.iter().enumerate() {
57 match pages.iter_mut().find(|p| p.title == f.group) {
58 Some(p) => p.sections[0].fields.push(i),
59 None => pages.push(Page {
60 title: f.group,
61 icon: None,
62 help: "",
63 sections: vec![Section {
64 title: f.group,
65 fields: vec![i],
66 }],
67 }),
68 }
69 }
70 Curation {
71 pages,
72 excluded: vec![],
73 }
74}
75
76/// The widget a field wants.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum Control {
79 /// A numeric range: a dial or slider.
80 Continuous,
81 /// Off / On, for a two-value field.
82 Toggle,
83 /// Named values: `names[raw - min]`. Raw values past the end show as
84 /// [`Driver::format_value`](crate::Driver::format_value) formats them.
85 Choice(&'static [&'static str]),
86 /// Named bands of raw values: name `i` covers raw `i * width` up to
87 /// the next band; the last band extends to the field's max. To pick
88 /// band `i`, set `i * width + width / 2`.
89 Bands {
90 /// The bands' names, from the lowest raw values.
91 names: &'static [&'static str],
92 /// How many raw values each band covers.
93 width: u16,
94 },
95}
96
97/// Help text for one field.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
99pub struct Help {
100 /// One line: what the control does to the sound, or empty.
101 pub summary: &'static str,
102 /// A non-obvious tip, or empty.
103 pub detail: &'static str,
104}
105
106/// What generation may do to a field.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum Mutability {
109 /// Generation, vary and breed may set it.
110 Free,
111 /// Generation keeps it: the base program's value (init's without a
112 /// base); vary leaves it; breed takes parent `a`'s. Tuning, MIDI and
113 /// performance settings.
114 Restricted,
115 /// Never changed by generate (with a base), vary or breed: metadata
116 /// set by the synth or the user, such as a loaded user unit's
117 /// parameter types.
118 Fixed,
119}
120
121/// What a [`Character`] is for; apps group characters by it.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123pub enum Family {
124 /// Keys, organs, bells and plucks.
125 Keys,
126 /// Basses.
127 Bass,
128 /// Leads.
129 Lead,
130 /// Pads, strings and drones.
131 Pad,
132 /// Drums and rhythmic pulses.
133 Rhythm,
134 /// Sound effects: risers, sirens, impacts.
135 Effect,
136}
137
138impl Family {
139 /// Every family, in the order apps show them.
140 pub const ALL: [Family; 6] = [
141 Family::Keys,
142 Family::Bass,
143 Family::Lead,
144 Family::Pad,
145 Family::Rhythm,
146 Family::Effect,
147 ];
148
149 /// Stable and lowercase, for bindings and command lines.
150 pub fn id(self) -> &'static str {
151 match self {
152 Family::Keys => "keys",
153 Family::Bass => "bass",
154 Family::Lead => "lead",
155 Family::Pad => "pad",
156 Family::Rhythm => "rhythm",
157 Family::Effect => "effect",
158 }
159 }
160
161 /// For people.
162 pub fn title(self) -> &'static str {
163 match self {
164 Family::Keys => "Keys",
165 Family::Bass => "Bass",
166 Family::Lead => "Lead",
167 Family::Pad => "Pad",
168 Family::Rhythm => "Rhythm",
169 Family::Effect => "Effect",
170 }
171 }
172}
173
174/// A kind of sound a driver can generate.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub struct Character {
177 /// Stable, lowercase, dash-separated.
178 pub id: &'static str,
179 /// The character's name, for people ("Fuzz bass").
180 pub title: &'static str,
181 /// One line on what it sounds like.
182 pub hint: &'static str,
183 /// The family that apps group it in.
184 pub family: Family,
185 /// The page whose graphs say most about this character, as an index
186 /// into [`Curation::pages`].
187 pub signature_page: Option<usize>,
188}
189
190/// How a driver names and explains one of the four [`Macros`].
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub struct MacroInfo {
193 /// The macro's name on this synth ("Bright").
194 pub title: &'static str,
195 /// What the macro changes on this synth.
196 pub help: &'static str,
197}
198
199/// Generic macro titles and help, for a driver that says nothing better.
200/// In [`Macros`] order: bright, movement, grit, space.
201pub const MACROS: [MacroInfo; 4] = [
202 MacroInfo {
203 title: "Bright",
204 help: "Filter openness and resonance",
205 },
206 MacroInfo {
207 title: "Movement",
208 help: "Modulation amount and speed",
209 },
210 MacroInfo {
211 title: "Grit",
212 help: "Drive, noise and other dirt",
213 },
214 MacroInfo {
215 title: "Ambience",
216 help: "Delay, reverb and other effects",
217 },
218];
219
220/// A note on a piano roll, for [`Graph::Voices`]. Times and pitch 0..1.
221#[derive(Debug, Clone, Copy, PartialEq)]
222pub struct Note {
223 /// The voice that plays the note, from 0.
224 pub voice: u8,
225 /// When the note starts.
226 pub start: f32,
227 /// When the note ends.
228 pub end: f32,
229 /// How high the note is.
230 pub pitch: f32,
231}
232
233/// An illustrative picture of part of a program, as plain numbers the apps
234/// draw. Coordinates are 0..1 unless noted; none of it claims to match the
235/// synth's audio.
236#[derive(Debug, Clone, PartialEq)]
237pub enum Graph {
238 /// Samples of a waveform, −1..1.
239 Wave(Vec<f32>),
240 /// A filter response: `(x, y)` points, the cutoff's x, and the y of
241 /// unity gain.
242 Response {
243 /// The curve, as `(frequency, gain)` points.
244 points: Vec<(f32, f32)>,
245 /// The cutoff's x.
246 cutoff: f32,
247 /// The y of unity gain.
248 unity: f32,
249 },
250 /// Envelope corners as `(time, level)`: start, attack peak, decay end,
251 /// sustain end, release end.
252 Envelope([(f32, f32); 5]),
253 /// Source levels.
254 Levels(Vec<f32>),
255 /// Echo taps `(time, level)`, a reverb tail `(length, level)` and a
256 /// modulation sweep `(cycles, depth)`, each when on.
257 Effects {
258 /// The echo taps, as `(time, level)`.
259 taps: Vec<(f32, f32)>,
260 /// The reverb tail, as `(length, level)`, when the reverb is on.
261 tail: Option<(f32, f32)>,
262 /// The modulation sweep, as `(cycles, depth)`, when it is on.
263 sweep: Option<(f32, f32)>,
264 },
265 /// What each voice plays.
266 Voices(Vec<Note>),
267}
268
269/// A draggable point on a page's first graph; dragging it sets the fields
270/// on its axes through [`Driver::drag`](crate::Driver::drag).
271#[derive(Debug, Clone, Copy, PartialEq)]
272pub struct Handle {
273 /// What it moves, for people ("Cutoff and resonance").
274 pub name: &'static str,
275 /// Where it is, in graph coordinates.
276 pub at: (f32, f32),
277 /// The field the horizontal axis sets, if any.
278 pub x: Option<usize>,
279 /// The field the vertical axis sets, if any.
280 pub y: Option<usize>,
281}
282
283/// Four generic ways to shape a generated sound, each `0.0..=1.0`. Each
284/// driver maps them onto its own fields.
285#[derive(Debug, Clone, Copy, PartialEq)]
286pub struct Macros {
287 /// Filter openness and resonance.
288 pub bright: f32,
289 /// Modulation amount and speed.
290 pub movement: f32,
291 /// Drive, noise and other dirt.
292 pub grit: f32,
293 /// Delay, reverb and other ambience.
294 pub space: f32,
295}
296
297impl Default for Macros {
298 fn default() -> Self {
299 Macros {
300 bright: 0.5,
301 movement: 0.5,
302 grit: 0.5,
303 space: 0.5,
304 }
305 }
306}
307
308/// How a user unit's parameter reads.
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub enum UnitParamKind {
311 /// A percentage.
312 Percent,
313 /// A percentage either side of zero.
314 Bipolar,
315 /// A plain number: one of a list of choices.
316 Choice,
317}
318
319/// A parameter a user unit declares, in its own values.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct UnitParam {
322 /// The parameter's name, as the unit declares it.
323 pub name: String,
324 /// The smallest value.
325 pub min: i16,
326 /// The largest value.
327 pub max: i16,
328 /// How the value reads.
329 pub kind: UnitParamKind,
330}
331
332/// A user unit (a loaded oscillator or effect) a synth holds, as a source
333/// generation may use.
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub struct PaletteUnit {
336 /// Which of [`Capabilities::units`](crate::Capabilities::units) it is.
337 pub kind: UnitKind,
338 /// Its slot, from 0.
339 pub slot: u8,
340 /// The unit's name, as it declares it.
341 pub name: String,
342 /// Its parameters, in order; `None` when they are not known (then
343 /// generation leaves them alone).
344 pub params: Option<Vec<UnitParam>>,
345}
346
347/// The extra sources a synth holds right now, beyond its built-in engines.
348#[derive(Debug, Clone, PartialEq, Eq, Default)]
349pub struct Palette {
350 /// The units, in slot order.
351 pub units: Vec<PaletteUnit>,
352}
353
354/// What to generate.
355#[derive(Debug, Clone, PartialEq, Default)]
356pub struct Recipe {
357 /// Index into [`Driver::characters`](crate::Driver::characters).
358 pub character: usize,
359 /// The four dials.
360 pub macros: Macros,
361 /// The seed: the same recipe and seed make the same bytes.
362 pub seed: u64,
363 /// Indices into [`Curation::pages`] whose fields are copied from the
364 /// base program as they are.
365 pub keep: Vec<usize>,
366 /// User units the program may select. Empty: none is used. Not empty:
367 /// the driver uses one (or an oscillator and an effect) wherever the
368 /// character can take it, with each parameter inside its declared
369 /// range, so a caller decides which sounds of a hand get units by
370 /// which recipes carry a palette. A program never selects a unit the
371 /// palette lacks.
372 pub palette: Palette,
373}
374
375/// SplitMix64's output step.
376fn mix64(mut z: u64) -> u64 {
377 z = z.wrapping_add(0x9E37_79B9_7F4A_7C15);
378 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
379 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
380 z ^ (z >> 31)
381}
382
383/// Step `t` (`0.0..=1.0`) of the way from `a` to `b`, over the free fields
384/// ([`Driver::morph`](crate::Driver::morph)'s default): a dial ([`Control::Continuous`] in `a`)
385/// interpolates; every other free field is `a`'s until `t` reaches its
386/// group's threshold (from `seed`, within 0.15..0.85), then `b`'s. So 0 is
387/// `a`, 1 is `b`'s sound, and a field never turns back on the way.
388/// Non-free fields and the name are `a`'s. Parent values out of range are
389/// clamped; a value the program refuses stays `a`'s.
390pub fn morph_fields<D: crate::Driver + ?Sized>(
391 d: &D,
392 a: &[u8],
393 b: &[u8],
394 t: f32,
395 seed: u64,
396) -> Result<Vec<u8>, DriverError> {
397 morph_fields_by(d, a, b, t, seed, |i| d.control(a, i) == Control::Continuous)
398}
399
400/// [`morph_fields`] for a driver that knows better than its controls
401/// which fields are dials (`dial`, by field index): a number that names
402/// something (a destination) must switch, not slide.
403pub fn morph_fields_by<D: crate::Driver + ?Sized>(
404 d: &D,
405 a: &[u8],
406 b: &[u8],
407 t: f32,
408 seed: u64,
409 dial: impl Fn(usize) -> bool,
410) -> Result<Vec<u8>, DriverError> {
411 let t = t.clamp(0.0, 1.0);
412 let mut out = a.to_vec();
413 for (i, f) in d.fields().iter().enumerate() {
414 if d.mutability(i) != Mutability::Free {
415 continue;
416 }
417 let (x, y) = (d.get(a, i)?, d.get(b, i)?);
418 let v = if dial(i) {
419 (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u16
420 } else {
421 // FNV-1a of the group's name: one threshold per group.
422 let h = f.group.bytes().fold(0xCBF2_9CE4_8422_2325u64, |h, c| {
423 (h ^ u64::from(c)).wrapping_mul(0x0100_0000_01B3)
424 });
425 let u = (mix64(seed ^ h) >> 40) as f32 / (1u64 << 24) as f32;
426 if t >= 0.15 + 0.7 * u { y } else { x }
427 };
428 let _ = d.set(&mut out, i, v.clamp(f.min, f.max));
429 }
430 Ok(out)
431}
432
433pub(crate) fn no_generation() -> DriverError {
434 DriverError("this driver does not generate programs".into())
435}