phosphor-app 0.3.32

Shared business logic for Phosphor DAW frontends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! NavState methods: params.

use super::*;

impl NavState {

    /// Adjust the currently selected synth parameter by delta.
    /// Returns the (mixer_id, param_index, new_value) if changed, for sending to audio.
    pub fn adjust_synth_param(&mut self, delta: f32) -> Option<(usize, usize, f32)> {
        let idx = self.clip_view.synth_param_cursor;
        if let Some(track) = self.tracks.get_mut(self.track_cursor) {
            if idx < track.synth_params.len() {
                // A selector steps by *index* rather than by adding a fraction
                // of the knob's travel: 256 voices, or 56 patches and a
                // three-position range switch, or fifteen kits, are coarse
                // enough that an accumulated rounding error lands on the wrong
                // side of a step boundary, which reads as a keypress that did
                // nothing.
                //
                // Which controls those are is the instrument's own answer —
                // see `crate::discrete`, which is also what the session format
                // stores them through, so the two cannot drift apart.
                let instrument = track.instrument_type?;
                let new_val = if crate::discrete::is_discrete(instrument, idx) {
                    crate::discrete::step(instrument, idx, track.synth_params[idx], delta > 0.0)
                } else {
                    (track.synth_params[idx] + delta).clamp(0.0, 1.0)
                };
                track.synth_params[idx] = new_val;

                // When the preset selector changes, sync all params from the
                // preset. Index 0 for every instrument — except the Prophet-6,
                // whose preset is two selectors, a bank and a program, so
                // moving either one has to reload the panel.
                let is_program_selector = idx == 0
                    || (instrument == InstrumentType::Prophet6
                        && idx == phosphor_dsp::prophet6::P_BANK);
                // The banks no longer agree on how many parameters an
                // instrument has, so this collects rather than matching on a
                // fixed-size array, and writes through a zip so a track
                // carrying a shorter block than its instrument now has cannot
                // index off the end of itself.
                if is_program_selector {
                    let new_params: Option<Vec<f32>> = match track.instrument_type {
                        Some(InstrumentType::Synth | InstrumentType::Sampler) => {
                            Some(phosphor_dsp::synth::PhosphorSynth::params_for_patch(new_val).to_vec())
                        }
                        Some(InstrumentType::Jupiter8) => {
                            Some(phosphor_dsp::jupiter::Jupiter8Synth::params_for_patch(new_val).to_vec())
                        }
                        Some(InstrumentType::Odyssey) => {
                            Some(phosphor_dsp::odyssey::OdysseySynth::params_for_patch(new_val).to_vec())
                        }
                        Some(InstrumentType::Juno60) => {
                            Some(phosphor_dsp::juno::Juno60Synth::params_for_patch(new_val).to_vec())
                        }
                        Some(InstrumentType::Rhodes) => {
                            Some(phosphor_dsp::rhodes::RhodesPiano::params_for_patch(new_val).to_vec())
                        }
                        Some(InstrumentType::LittlePhatty) => {
                            Some(phosphor_dsp::phatty::LittlePhatty::params_for_patch(new_val).to_vec())
                        }
                        Some(InstrumentType::Prophet6) => Some(
                            phosphor_dsp::prophet6::params_for_program(
                                track.synth_params[phosphor_dsp::prophet6::P_BANK],
                                track.synth_params[phosphor_dsp::prophet6::P_PROGRAM],
                            )
                            .to_vec(),
                        ),
                        _ => None,
                    };
                    if let Some(preset_params) = new_params {
                        for (slot, v) in track.synth_params.iter_mut().zip(preset_params) {
                            *slot = v;
                        }
                    }
                }

                if let Some(mixer_id) = track.mixer_id {
                    return Some((mixer_id, idx, new_val));
                }
            }
        }
        None
    }


    /// Show controls for the currently selected track and route MIDI to it.
    /// For instrument tracks: opens clip view with Synth tab, activates MIDI input.
    /// For bus tracks: no clip view, deactivates MIDI.
    pub fn show_current_track_controls(&mut self) {
        // Deactivate MIDI on ALL tracks first
        for track in &self.tracks {
            if let Some(ref h) = track.handle {
                h.config.midi_active.store(false, std::sync::atomic::Ordering::Relaxed);
            }
        }

        if let Some(track) = self.tracks.get(self.track_cursor) {
            if track.is_live() {
                if let Some(ref h) = track.handle {
                    h.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
                }
                self.clip_view_visible = true;

                // Use the currently selected clip element, or default to clip 0
                let clip_idx = match self.track_element {
                    super::TrackElement::Clip(i) if i < track.clips.len() => i,
                    _ => 0,
                };
                self.clip_view_target = Some((self.track_cursor, clip_idx));

                // A sequencer track opens on its grid: the pattern is the
                // thing being worked on, and its clips — if it has any — are
                // bounces of it rather than what is playing.
                if track.sequencer.is_some() {
                    self.clip_view.clip_tab = ClipTab::Sequencer;
                    self.clip_view.focus = ClipViewFocus::PianoRoll;
                    self.clip_view.sequencer.focus_band(SeqBand::Grid);
                    // And the keyboard goes with it. The grid displaying in
                    // one pane while the keys land in another is a sequencer
                    // you can see but not touch — the tab and the inner focus
                    // above are only two thirds of "opened on its grid".
                    self.focused_pane = Pane::ClipView;
                } else if !track.clips.is_empty() {
                    self.clip_view.clip_tab = ClipTab::PianoRoll;
                    self.clip_view.focus = ClipViewFocus::PianoRoll;
                    self.clip_view.piano_roll.focus = PianoRollFocus::Navigation;
                    self.clip_view.piano_roll.column = 0;
                } else {
                    self.clip_view.fx_panel_tab = FxPanelTab::Synth;
                    self.clip_view.focus = ClipViewFocus::FxPanel;
                    self.clip_view.synth_param_cursor = 0;
                }
            } else {
                // Bus track — hide clip view
                self.clip_view_visible = false;
                self.clip_view_target = None;
            }
        }
    }

}

#[cfg(test)]
mod tests {
    use super::*;
    use phosphor_dsp::{drum_rack, dx7, juno, jupiter, rhodes};

    /// A nav state whose selected track is a DX7 at its default parameters.
    fn dx7_track() -> NavState {
        let mut nav = NavState::new(super::super::initial_tracks());
        let mut track = TrackState::new("dx7", 0, true, TrackKind::Instrument, vec![]);
        track.instrument_type = Some(InstrumentType::DX7);
        track.synth_params = dx7::PARAM_DEFAULTS.to_vec();
        nav.tracks.insert(0, track);
        nav.track_cursor = 0;
        nav
    }

    fn selected(nav: &NavState) -> (usize, usize) {
        let p = &nav.tracks[0].synth_params;
        (dx7::bank_index(p[dx7::P_BANK]), dx7::patch_index(p[dx7::P_PATCH]))
    }

    #[test]
    fn dx7_selectors_move_one_step_per_keypress() {
        // Both DX7 selectors are discrete: a keypress is one voice or one
        // cartridge, not a fraction of the knob's travel. The patch knob alone
        // would otherwise take 256 presses to cross the factory set.
        let mut nav = dx7_track();
        nav.clip_view.synth_param_cursor = dx7::P_PATCH;
        let (bank, patch) = selected(&nav);
        for step in 1..=5 {
            nav.adjust_synth_param(0.05);
            assert_eq!(selected(&nav), (bank, patch + step), "patch knob step {step}");
        }
        for step in (0..5).rev() {
            nav.adjust_synth_param(-0.05);
            assert_eq!(selected(&nav), (bank, patch + step), "patch knob back to {step}");
        }

        nav.clip_view.synth_param_cursor = dx7::P_BANK;
        for step in 1..dx7::BANK_COUNT {
            nav.adjust_synth_param(0.05);
            assert_eq!(selected(&nav), (step, patch), "bank knob step {step}");
        }
        // ...and neither runs off its end.
        for _ in 0..4 {
            nav.adjust_synth_param(0.05);
        }
        assert_eq!(selected(&nav), (dx7::BANK_COUNT - 1, patch));
    }

    /// A nav state whose selected track is a Juno-60 at its default panel.
    fn juno_track() -> NavState {
        let mut nav = NavState::new(super::super::initial_tracks());
        let mut track = TrackState::new("juno", 0, true, TrackKind::Instrument, vec![]);
        track.instrument_type = Some(InstrumentType::Juno60);
        track.synth_params = juno::PARAM_DEFAULTS.to_vec();
        nav.tracks.insert(0, track);
        nav.track_cursor = 0;
        nav
    }

    fn juno_patch(nav: &NavState) -> usize {
        juno::patch_index(nav.tracks[0].synth_params[juno::P_PATCH])
    }

    #[test]
    fn juno_selectors_move_one_step_per_keypress() {
        // 56 factory patches: a keypress is one patch, not a fraction of the
        // knob's travel, and the whole bank has to be reachable from either
        // end. The three-position PWM switch is here too, because a switch
        // that gained a position is the one most likely to be stepped by a
        // stale fraction.
        let mut nav = juno_track();
        nav.clip_view.synth_param_cursor = juno::P_PATCH;
        for step in 1..juno::PATCH_COUNT {
            nav.adjust_synth_param(0.05);
            assert_eq!(juno_patch(&nav), step, "patch knob step {step}");
        }
        nav.adjust_synth_param(0.05);
        assert_eq!(juno_patch(&nav), juno::PATCH_COUNT - 1, "patch knob ran off the top");
        for step in (0..juno::PATCH_COUNT - 1).rev() {
            nav.adjust_synth_param(-0.05);
            assert_eq!(juno_patch(&nav), step, "patch knob back to {step}");
        }

        // Selecting a patch loads its panel: 78 SYNTHESIZER DRUM is the one
        // with the filter at self-oscillation and no oscillator at all.
        for _ in 0..juno::PATCH_COUNT {
            nav.adjust_synth_param(0.05);
        }
        let panel = &nav.tracks[0].synth_params;
        assert_eq!(juno_patch(&nav), juno::PATCH_COUNT - 1);
        assert!((panel[juno::P_RESO] - 1.0).abs() < 1e-6, "res {}", panel[juno::P_RESO]);

        // A fresh panel, because the switch has to start where 11 STRINGS 1
        // leaves it rather than where the last patch of the sweep did.
        let mut nav = juno_track();
        nav.clip_view.synth_param_cursor = juno::P_PWM_MODE;
        let label = |nav: &NavState| {
            juno::discrete_label(juno::P_PWM_MODE, nav.tracks[0].synth_params[juno::P_PWM_MODE])
        };
        assert_eq!(label(&nav), Some("LFO"));
        let mut seen = Vec::new();
        for _ in 0..3 {
            nav.adjust_synth_param(0.05);
            seen.push(label(&nav));
        }
        assert_eq!(seen, [Some("MAN"), Some("ENV"), Some("ENV")]);
    }

    /// A nav state whose selected track is a Rhodes at its default panel.
    fn rhodes_track() -> NavState {
        let mut nav = NavState::new(super::super::initial_tracks());
        let mut track = TrackState::new("rhode", 0, true, TrackKind::Instrument, vec![]);
        track.instrument_type = Some(InstrumentType::Rhodes);
        track.synth_params = rhodes::PARAM_DEFAULTS.to_vec();
        nav.tracks.insert(0, track);
        nav.track_cursor = 0;
        nav
    }

    #[test]
    fn the_rhodes_patch_knob_moves_one_piano_per_keypress() {
        // Twenty-six patches, stepped by index, and selecting one loads its
        // panel. The Rhodes' panel is entirely continuous apart from this
        // knob, so it is the only control here that can stall on a boundary.
        let mut nav = rhodes_track();
        nav.clip_view.synth_param_cursor = rhodes::P_PATCH;
        let patch = |nav: &NavState| {
            rhodes::patch_index(nav.tracks[0].synth_params[rhodes::P_PATCH])
        };
        assert_eq!(rhodes::PATCH_NAMES[patch(&nav)], "MK1 Stage");
        for step in 1..rhodes::PATCH_COUNT {
            nav.adjust_synth_param(0.05);
            assert_eq!(patch(&nav), step, "patch knob step {step}");
        }
        nav.adjust_synth_param(0.05);
        assert_eq!(patch(&nav), rhodes::PATCH_COUNT - 1, "patch knob ran off the top");
        // ...and the panel that arrived with the last patch is that patch's.
        let panel = &nav.tracks[0].synth_params;
        let want = rhodes::RhodesPiano::params_for_patch(panel[rhodes::P_PATCH]);
        for i in 1..rhodes::PARAM_COUNT {
            assert!(
                (panel[i] - want[i]).abs() < 1e-6,
                "{} came back as {} where the patch says {}",
                rhodes::PARAM_NAMES[i], panel[i], want[i]
            );
        }
        for step in (0..rhodes::PATCH_COUNT - 1).rev() {
            nav.adjust_synth_param(-0.05);
            assert_eq!(patch(&nav), step, "patch knob back to {step}");
        }

        // Every other control is a fader, and moving one moves only it.
        let mut nav = rhodes_track();
        nav.clip_view.synth_param_cursor = rhodes::P_VOICING;
        let before = nav.tracks[0].synth_params.clone();
        nav.adjust_synth_param(0.05);
        let after = &nav.tracks[0].synth_params;
        assert!((after[rhodes::P_VOICING] - (before[rhodes::P_VOICING] + 0.05)).abs() < 1e-6);
        for i in 0..after.len() {
            if i != rhodes::P_VOICING {
                assert_eq!(before[i], after[i], "{} moved with the voicing", rhodes::PARAM_NAMES[i]);
            }
        }
    }

    /// A nav state whose selected track is a Jupiter-8 at its default panel.
    fn jupiter_track() -> NavState {
        let mut nav = NavState::new(super::super::initial_tracks());
        let mut track = TrackState::new("jupiter", 0, true, TrackKind::Instrument, vec![]);
        track.instrument_type = Some(InstrumentType::Jupiter8);
        track.synth_params = jupiter::PARAM_DEFAULTS.to_vec();
        nav.tracks.insert(0, track);
        nav.track_cursor = 0;
        nav
    }

    #[test]
    fn jupiter_selectors_move_one_step_per_keypress() {
        // 64 patches and seven switches. The patch knob used to step by
        // 1/(n - 0.01) of the travel, which is a fraction that does not
        // divide the bank: the accumulated error lands on the wrong side of a
        // boundary and the keypress reads as having done nothing.
        let mut nav = jupiter_track();
        nav.clip_view.synth_param_cursor = jupiter::P_PATCH;
        let patch = |nav: &NavState| {
            jupiter::patch_index(nav.tracks[0].synth_params[jupiter::P_PATCH])
        };
        for step in 1..jupiter::PATCH_COUNT {
            nav.adjust_synth_param(0.05);
            assert_eq!(patch(&nav), step, "patch knob step {step}");
        }
        nav.adjust_synth_param(0.05);
        assert_eq!(patch(&nav), jupiter::PATCH_COUNT - 1, "patch knob ran off the top");
        for step in (0..jupiter::PATCH_COUNT - 1).rev() {
            nav.adjust_synth_param(-0.05);
            assert_eq!(patch(&nav), step, "patch knob back to {step}");
        }

        // A fresh panel, because the waveform switch has to start where patch
        // 0 leaves it rather than where the last patch of the sweep did.
        let mut nav = jupiter_track();
        nav.clip_view.synth_param_cursor = jupiter::P_VCO2_WAVE;
        let label = |nav: &NavState| {
            jupiter::discrete_label(
                jupiter::P_VCO2_WAVE,
                nav.tracks[0].synth_params[jupiter::P_VCO2_WAVE],
            )
        };
        assert_eq!(label(&nav), Some("SAW"));
        let mut seen = Vec::new();
        for _ in 0..3 {
            nav.adjust_synth_param(0.05);
            seen.push(label(&nav));
        }
        assert_eq!(seen, [Some("PLS"), Some("NOISE"), Some("NOISE")]);
    }

    /// A nav state whose selected track is a Prophet-6 at its default panel.
    fn prophet6_track() -> NavState {
        let mut nav = NavState::new(super::super::initial_tracks());
        let mut track = TrackState::new("p6", 0, true, TrackKind::Instrument, vec![]);
        track.instrument_type = Some(InstrumentType::Prophet6);
        track.synth_params = phosphor_dsp::prophet6::param_defaults().to_vec();
        nav.tracks.insert(0, track);
        nav.track_cursor = 0;
        nav
    }

    /// Both of the Prophet-6's preset selectors reload the panel.
    ///
    /// It is the second instrument in the rack whose preset is two controls
    /// rather than one — the DX7 was the first — and the first whose *panel*
    /// is loaded from them, so the editor's "index 0 reloads the preset" rule
    /// is not enough on its own: stepping the bank has to reload as well, or
    /// four fifths of the factory set is unreachable from the panel.
    #[test]
    fn both_prophet_six_selectors_load_the_program() {
        use phosphor_dsp::prophet6;

        let mut nav = prophet6_track();
        let panel = |nav: &NavState| nav.tracks[0].synth_params.clone();
        assert_eq!(panel(&nav), prophet6::params_for_program(0.0, 0.0).to_vec());

        // Step the program knob: the whole panel follows it.
        nav.clip_view.synth_param_cursor = prophet6::P_PROGRAM;
        for step in 1..8 {
            nav.adjust_synth_param(0.05);
            let expected = prophet6::params_for_program(
                nav.tracks[0].synth_params[prophet6::P_BANK],
                nav.tracks[0].synth_params[prophet6::P_PROGRAM],
            );
            assert_eq!(panel(&nav), expected.to_vec(), "program knob step {step}");
            assert_eq!(
                prophet6::program_index(
                    nav.tracks[0].synth_params[prophet6::P_BANK],
                    nav.tracks[0].synth_params[prophet6::P_PROGRAM],
                ),
                step
            );
        }

        // Step the bank knob: same, a hundred programs further along each time.
        nav.clip_view.synth_param_cursor = prophet6::P_BANK;
        for bank in 1..prophet6::BANK_COUNT {
            nav.adjust_synth_param(0.05);
            let expected = prophet6::params_for_program(
                nav.tracks[0].synth_params[prophet6::P_BANK],
                nav.tracks[0].synth_params[prophet6::P_PROGRAM],
            );
            assert_eq!(panel(&nav), expected.to_vec(), "bank knob step {bank}");
            assert_eq!(
                prophet6::program_index(
                    nav.tracks[0].synth_params[prophet6::P_BANK],
                    nav.tracks[0].synth_params[prophet6::P_PROGRAM],
                ),
                bank * prophet6::PROGRAMS_PER_BANK + 7,
                "the bank knob lost the program knob's position"
            );
        }

        // And an ordinary knob does not reload anything.
        nav.clip_view.synth_param_cursor = prophet6::P_LP_CUTOFF;
        let before = panel(&nav);
        nav.adjust_synth_param(0.05);
        let after = panel(&nav);
        for (index, (a, b)) in before.iter().zip(&after).enumerate() {
            if index != prophet6::P_LP_CUTOFF {
                assert_eq!(a, b, "{} moved with the cutoff", prophet6::PARAM_NAMES[index]);
            }
        }
        assert!(after[prophet6::P_LP_CUTOFF] > before[prophet6::P_LP_CUTOFF]);
    }

    /// A nav state whose selected track is a drum rack at its default panel.
    fn drum_track() -> NavState {
        let mut nav = NavState::new(super::super::initial_tracks());
        let mut track = TrackState::new("drums", 0, true, TrackKind::Instrument, vec![]);
        track.instrument_type = Some(InstrumentType::DrumRack);
        track.synth_params = drum_rack::PARAM_DEFAULTS.to_vec();
        nav.tracks.insert(0, track);
        nav.track_cursor = 0;
        nav
    }

    #[test]
    fn the_drum_kit_selector_moves_one_kit_per_keypress() {
        // Fifteen kits, stepped by index. This used to add a fraction of the
        // knob's travel per press, which does not divide the selector evenly:
        // the accumulated error lands on the wrong side of a boundary and the
        // keypress reads as having done nothing. The list is driven off
        // `KIT_LABELS` so that adding a kit does not need this test edited.
        let mut nav = drum_track();
        nav.clip_view.synth_param_cursor = drum_rack::P_KIT;
        let kit = |nav: &NavState| {
            drum_rack::discrete_label(drum_rack::P_KIT, nav.tracks[0].synth_params[drum_rack::P_KIT])
        };
        let last = *drum_rack::KIT_LABELS.last().unwrap();
        assert_eq!(kit(&nav), Some("808"));
        for label in drum_rack::KIT_LABELS.iter().skip(1) {
            nav.adjust_synth_param(0.05);
            assert_eq!(kit(&nav), Some(*label));
        }
        nav.adjust_synth_param(0.05);
        assert_eq!(kit(&nav), Some(last), "the kit knob ran off the top");
        for label in drum_rack::KIT_LABELS.iter().rev().skip(1) {
            nav.adjust_synth_param(-0.05);
            assert_eq!(kit(&nav), Some(*label));
        }

        // The rest of the panel is continuous, and moving one control moves
        // only that control.
        nav.clip_view.synth_param_cursor = drum_rack::P_BD_DECAY;
        let before = nav.tracks[0].synth_params.clone();
        nav.adjust_synth_param(-0.05);
        let after = &nav.tracks[0].synth_params;
        assert!((after[drum_rack::P_BD_DECAY] - 0.45).abs() < 1e-6);
        for i in 0..after.len() {
            if i != drum_rack::P_BD_DECAY {
                assert_eq!(before[i], after[i], "{} moved with the kick's decay", drum_rack::PARAM_NAMES[i]);
            }
        }
    }

    #[test]
    fn the_dx7_bank_knob_is_the_last_parameter() {
        // Sessions store `synth_params` positionally, so the bank selector was
        // appended rather than filed next to the patch selector: inserting it
        // would load every saved value of every existing session one slot out.
        let nav = dx7_track();
        assert_eq!(nav.tracks[0].synth_params.len(), dx7::PARAM_COUNT);
        assert_eq!(dx7::P_BANK, dx7::PARAM_COUNT - 1);
        assert_eq!(dx7::PARAM_NAMES[dx7::P_GAIN], "gain", "index 0-7 must not move");
    }
}