Skip to main content

phosphor_app/state/
params.rs

1//! NavState methods: params.
2
3use super::*;
4
5impl NavState {
6
7    /// Adjust the currently selected synth parameter by delta.
8    /// Returns the (mixer_id, param_index, new_value) if changed, for sending to audio.
9    pub fn adjust_synth_param(&mut self, delta: f32) -> Option<(usize, usize, f32)> {
10        let idx = self.clip_view.synth_param_cursor;
11        if let Some(track) = self.tracks.get_mut(self.track_cursor) {
12            if idx < track.synth_params.len() {
13                // A selector steps by *index* rather than by adding a fraction
14                // of the knob's travel: 256 voices, or 56 patches and a
15                // three-position range switch, or fifteen kits, are coarse
16                // enough that an accumulated rounding error lands on the wrong
17                // side of a step boundary, which reads as a keypress that did
18                // nothing.
19                //
20                // Which controls those are is the instrument's own answer —
21                // see `crate::discrete`, which is also what the session format
22                // stores them through, so the two cannot drift apart.
23                let instrument = track.instrument_type?;
24                let new_val = if crate::discrete::is_discrete(instrument, idx) {
25                    crate::discrete::step(instrument, idx, track.synth_params[idx], delta > 0.0)
26                } else {
27                    (track.synth_params[idx] + delta).clamp(0.0, 1.0)
28                };
29                track.synth_params[idx] = new_val;
30
31                // When the preset selector changes, sync all params from the
32                // preset. Index 0 for every instrument — except the Prophet-6,
33                // whose preset is two selectors, a bank and a program, so
34                // moving either one has to reload the panel.
35                let is_program_selector = idx == 0
36                    || (instrument == InstrumentType::Prophet6
37                        && idx == phosphor_dsp::prophet6::P_BANK);
38                // The banks no longer agree on how many parameters an
39                // instrument has, so this collects rather than matching on a
40                // fixed-size array, and writes through a zip so a track
41                // carrying a shorter block than its instrument now has cannot
42                // index off the end of itself.
43                if is_program_selector {
44                    let new_params: Option<Vec<f32>> = match track.instrument_type {
45                        Some(InstrumentType::Synth | InstrumentType::Sampler) => {
46                            Some(phosphor_dsp::synth::PhosphorSynth::params_for_patch(new_val).to_vec())
47                        }
48                        Some(InstrumentType::Jupiter8) => {
49                            Some(phosphor_dsp::jupiter::Jupiter8Synth::params_for_patch(new_val).to_vec())
50                        }
51                        Some(InstrumentType::Odyssey) => {
52                            Some(phosphor_dsp::odyssey::OdysseySynth::params_for_patch(new_val).to_vec())
53                        }
54                        Some(InstrumentType::Juno60) => {
55                            Some(phosphor_dsp::juno::Juno60Synth::params_for_patch(new_val).to_vec())
56                        }
57                        Some(InstrumentType::Rhodes) => {
58                            Some(phosphor_dsp::rhodes::RhodesPiano::params_for_patch(new_val).to_vec())
59                        }
60                        Some(InstrumentType::LittlePhatty) => {
61                            Some(phosphor_dsp::phatty::LittlePhatty::params_for_patch(new_val).to_vec())
62                        }
63                        Some(InstrumentType::Prophet6) => Some(
64                            phosphor_dsp::prophet6::params_for_program(
65                                track.synth_params[phosphor_dsp::prophet6::P_BANK],
66                                track.synth_params[phosphor_dsp::prophet6::P_PROGRAM],
67                            )
68                            .to_vec(),
69                        ),
70                        _ => None,
71                    };
72                    if let Some(preset_params) = new_params {
73                        for (slot, v) in track.synth_params.iter_mut().zip(preset_params) {
74                            *slot = v;
75                        }
76                    }
77                }
78
79                if let Some(mixer_id) = track.mixer_id {
80                    return Some((mixer_id, idx, new_val));
81                }
82            }
83        }
84        None
85    }
86
87
88    /// Show controls for the currently selected track and route MIDI to it.
89    /// For instrument tracks: opens clip view with Synth tab, activates MIDI input.
90    /// For bus tracks: no clip view, deactivates MIDI.
91    pub fn show_current_track_controls(&mut self) {
92        // Deactivate MIDI on ALL tracks first
93        for track in &self.tracks {
94            if let Some(ref h) = track.handle {
95                h.config.midi_active.store(false, std::sync::atomic::Ordering::Relaxed);
96            }
97        }
98
99        if let Some(track) = self.tracks.get(self.track_cursor) {
100            if track.is_live() {
101                if let Some(ref h) = track.handle {
102                    h.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
103                }
104                self.clip_view_visible = true;
105
106                // Use the currently selected clip element, or default to clip 0
107                let clip_idx = match self.track_element {
108                    super::TrackElement::Clip(i) if i < track.clips.len() => i,
109                    _ => 0,
110                };
111                self.clip_view_target = Some((self.track_cursor, clip_idx));
112
113                // If track has recorded clips, show piano roll. Otherwise show synth.
114                if !track.clips.is_empty() {
115                    self.clip_view.clip_tab = ClipTab::PianoRoll;
116                    self.clip_view.focus = ClipViewFocus::PianoRoll;
117                    self.clip_view.piano_roll.focus = PianoRollFocus::Navigation;
118                    self.clip_view.piano_roll.column = 0;
119                } else {
120                    self.clip_view.fx_panel_tab = FxPanelTab::Synth;
121                    self.clip_view.focus = ClipViewFocus::FxPanel;
122                    self.clip_view.synth_param_cursor = 0;
123                }
124            } else {
125                // Bus track — hide clip view
126                self.clip_view_visible = false;
127                self.clip_view_target = None;
128            }
129        }
130    }
131
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use phosphor_dsp::{drum_rack, dx7, juno, jupiter, rhodes};
138
139    /// A nav state whose selected track is a DX7 at its default parameters.
140    fn dx7_track() -> NavState {
141        let mut nav = NavState::new(super::super::initial_tracks());
142        let mut track = TrackState::new("dx7", 0, true, TrackKind::Instrument, vec![]);
143        track.instrument_type = Some(InstrumentType::DX7);
144        track.synth_params = dx7::PARAM_DEFAULTS.to_vec();
145        nav.tracks.insert(0, track);
146        nav.track_cursor = 0;
147        nav
148    }
149
150    fn selected(nav: &NavState) -> (usize, usize) {
151        let p = &nav.tracks[0].synth_params;
152        (dx7::bank_index(p[dx7::P_BANK]), dx7::patch_index(p[dx7::P_PATCH]))
153    }
154
155    #[test]
156    fn dx7_selectors_move_one_step_per_keypress() {
157        // Both DX7 selectors are discrete: a keypress is one voice or one
158        // cartridge, not a fraction of the knob's travel. The patch knob alone
159        // would otherwise take 256 presses to cross the factory set.
160        let mut nav = dx7_track();
161        nav.clip_view.synth_param_cursor = dx7::P_PATCH;
162        let (bank, patch) = selected(&nav);
163        for step in 1..=5 {
164            nav.adjust_synth_param(0.05);
165            assert_eq!(selected(&nav), (bank, patch + step), "patch knob step {step}");
166        }
167        for step in (0..5).rev() {
168            nav.adjust_synth_param(-0.05);
169            assert_eq!(selected(&nav), (bank, patch + step), "patch knob back to {step}");
170        }
171
172        nav.clip_view.synth_param_cursor = dx7::P_BANK;
173        for step in 1..dx7::BANK_COUNT {
174            nav.adjust_synth_param(0.05);
175            assert_eq!(selected(&nav), (step, patch), "bank knob step {step}");
176        }
177        // ...and neither runs off its end.
178        for _ in 0..4 {
179            nav.adjust_synth_param(0.05);
180        }
181        assert_eq!(selected(&nav), (dx7::BANK_COUNT - 1, patch));
182    }
183
184    /// A nav state whose selected track is a Juno-60 at its default panel.
185    fn juno_track() -> NavState {
186        let mut nav = NavState::new(super::super::initial_tracks());
187        let mut track = TrackState::new("juno", 0, true, TrackKind::Instrument, vec![]);
188        track.instrument_type = Some(InstrumentType::Juno60);
189        track.synth_params = juno::PARAM_DEFAULTS.to_vec();
190        nav.tracks.insert(0, track);
191        nav.track_cursor = 0;
192        nav
193    }
194
195    fn juno_patch(nav: &NavState) -> usize {
196        juno::patch_index(nav.tracks[0].synth_params[juno::P_PATCH])
197    }
198
199    #[test]
200    fn juno_selectors_move_one_step_per_keypress() {
201        // 56 factory patches: a keypress is one patch, not a fraction of the
202        // knob's travel, and the whole bank has to be reachable from either
203        // end. The three-position PWM switch is here too, because a switch
204        // that gained a position is the one most likely to be stepped by a
205        // stale fraction.
206        let mut nav = juno_track();
207        nav.clip_view.synth_param_cursor = juno::P_PATCH;
208        for step in 1..juno::PATCH_COUNT {
209            nav.adjust_synth_param(0.05);
210            assert_eq!(juno_patch(&nav), step, "patch knob step {step}");
211        }
212        nav.adjust_synth_param(0.05);
213        assert_eq!(juno_patch(&nav), juno::PATCH_COUNT - 1, "patch knob ran off the top");
214        for step in (0..juno::PATCH_COUNT - 1).rev() {
215            nav.adjust_synth_param(-0.05);
216            assert_eq!(juno_patch(&nav), step, "patch knob back to {step}");
217        }
218
219        // Selecting a patch loads its panel: 78 SYNTHESIZER DRUM is the one
220        // with the filter at self-oscillation and no oscillator at all.
221        for _ in 0..juno::PATCH_COUNT {
222            nav.adjust_synth_param(0.05);
223        }
224        let panel = &nav.tracks[0].synth_params;
225        assert_eq!(juno_patch(&nav), juno::PATCH_COUNT - 1);
226        assert!((panel[juno::P_RESO] - 1.0).abs() < 1e-6, "res {}", panel[juno::P_RESO]);
227
228        // A fresh panel, because the switch has to start where 11 STRINGS 1
229        // leaves it rather than where the last patch of the sweep did.
230        let mut nav = juno_track();
231        nav.clip_view.synth_param_cursor = juno::P_PWM_MODE;
232        let label = |nav: &NavState| {
233            juno::discrete_label(juno::P_PWM_MODE, nav.tracks[0].synth_params[juno::P_PWM_MODE])
234        };
235        assert_eq!(label(&nav), Some("LFO"));
236        let mut seen = Vec::new();
237        for _ in 0..3 {
238            nav.adjust_synth_param(0.05);
239            seen.push(label(&nav));
240        }
241        assert_eq!(seen, [Some("MAN"), Some("ENV"), Some("ENV")]);
242    }
243
244    /// A nav state whose selected track is a Rhodes at its default panel.
245    fn rhodes_track() -> NavState {
246        let mut nav = NavState::new(super::super::initial_tracks());
247        let mut track = TrackState::new("rhode", 0, true, TrackKind::Instrument, vec![]);
248        track.instrument_type = Some(InstrumentType::Rhodes);
249        track.synth_params = rhodes::PARAM_DEFAULTS.to_vec();
250        nav.tracks.insert(0, track);
251        nav.track_cursor = 0;
252        nav
253    }
254
255    #[test]
256    fn the_rhodes_patch_knob_moves_one_piano_per_keypress() {
257        // Twenty-six patches, stepped by index, and selecting one loads its
258        // panel. The Rhodes' panel is entirely continuous apart from this
259        // knob, so it is the only control here that can stall on a boundary.
260        let mut nav = rhodes_track();
261        nav.clip_view.synth_param_cursor = rhodes::P_PATCH;
262        let patch = |nav: &NavState| {
263            rhodes::patch_index(nav.tracks[0].synth_params[rhodes::P_PATCH])
264        };
265        assert_eq!(rhodes::PATCH_NAMES[patch(&nav)], "MK1 Stage");
266        for step in 1..rhodes::PATCH_COUNT {
267            nav.adjust_synth_param(0.05);
268            assert_eq!(patch(&nav), step, "patch knob step {step}");
269        }
270        nav.adjust_synth_param(0.05);
271        assert_eq!(patch(&nav), rhodes::PATCH_COUNT - 1, "patch knob ran off the top");
272        // ...and the panel that arrived with the last patch is that patch's.
273        let panel = &nav.tracks[0].synth_params;
274        let want = rhodes::RhodesPiano::params_for_patch(panel[rhodes::P_PATCH]);
275        for i in 1..rhodes::PARAM_COUNT {
276            assert!(
277                (panel[i] - want[i]).abs() < 1e-6,
278                "{} came back as {} where the patch says {}",
279                rhodes::PARAM_NAMES[i], panel[i], want[i]
280            );
281        }
282        for step in (0..rhodes::PATCH_COUNT - 1).rev() {
283            nav.adjust_synth_param(-0.05);
284            assert_eq!(patch(&nav), step, "patch knob back to {step}");
285        }
286
287        // Every other control is a fader, and moving one moves only it.
288        let mut nav = rhodes_track();
289        nav.clip_view.synth_param_cursor = rhodes::P_VOICING;
290        let before = nav.tracks[0].synth_params.clone();
291        nav.adjust_synth_param(0.05);
292        let after = &nav.tracks[0].synth_params;
293        assert!((after[rhodes::P_VOICING] - (before[rhodes::P_VOICING] + 0.05)).abs() < 1e-6);
294        for i in 0..after.len() {
295            if i != rhodes::P_VOICING {
296                assert_eq!(before[i], after[i], "{} moved with the voicing", rhodes::PARAM_NAMES[i]);
297            }
298        }
299    }
300
301    /// A nav state whose selected track is a Jupiter-8 at its default panel.
302    fn jupiter_track() -> NavState {
303        let mut nav = NavState::new(super::super::initial_tracks());
304        let mut track = TrackState::new("jupiter", 0, true, TrackKind::Instrument, vec![]);
305        track.instrument_type = Some(InstrumentType::Jupiter8);
306        track.synth_params = jupiter::PARAM_DEFAULTS.to_vec();
307        nav.tracks.insert(0, track);
308        nav.track_cursor = 0;
309        nav
310    }
311
312    #[test]
313    fn jupiter_selectors_move_one_step_per_keypress() {
314        // 64 patches and seven switches. The patch knob used to step by
315        // 1/(n - 0.01) of the travel, which is a fraction that does not
316        // divide the bank: the accumulated error lands on the wrong side of a
317        // boundary and the keypress reads as having done nothing.
318        let mut nav = jupiter_track();
319        nav.clip_view.synth_param_cursor = jupiter::P_PATCH;
320        let patch = |nav: &NavState| {
321            jupiter::patch_index(nav.tracks[0].synth_params[jupiter::P_PATCH])
322        };
323        for step in 1..jupiter::PATCH_COUNT {
324            nav.adjust_synth_param(0.05);
325            assert_eq!(patch(&nav), step, "patch knob step {step}");
326        }
327        nav.adjust_synth_param(0.05);
328        assert_eq!(patch(&nav), jupiter::PATCH_COUNT - 1, "patch knob ran off the top");
329        for step in (0..jupiter::PATCH_COUNT - 1).rev() {
330            nav.adjust_synth_param(-0.05);
331            assert_eq!(patch(&nav), step, "patch knob back to {step}");
332        }
333
334        // A fresh panel, because the waveform switch has to start where patch
335        // 0 leaves it rather than where the last patch of the sweep did.
336        let mut nav = jupiter_track();
337        nav.clip_view.synth_param_cursor = jupiter::P_VCO2_WAVE;
338        let label = |nav: &NavState| {
339            jupiter::discrete_label(
340                jupiter::P_VCO2_WAVE,
341                nav.tracks[0].synth_params[jupiter::P_VCO2_WAVE],
342            )
343        };
344        assert_eq!(label(&nav), Some("SAW"));
345        let mut seen = Vec::new();
346        for _ in 0..3 {
347            nav.adjust_synth_param(0.05);
348            seen.push(label(&nav));
349        }
350        assert_eq!(seen, [Some("PLS"), Some("NOISE"), Some("NOISE")]);
351    }
352
353    /// A nav state whose selected track is a Prophet-6 at its default panel.
354    fn prophet6_track() -> NavState {
355        let mut nav = NavState::new(super::super::initial_tracks());
356        let mut track = TrackState::new("p6", 0, true, TrackKind::Instrument, vec![]);
357        track.instrument_type = Some(InstrumentType::Prophet6);
358        track.synth_params = phosphor_dsp::prophet6::param_defaults().to_vec();
359        nav.tracks.insert(0, track);
360        nav.track_cursor = 0;
361        nav
362    }
363
364    /// Both of the Prophet-6's preset selectors reload the panel.
365    ///
366    /// It is the second instrument in the rack whose preset is two controls
367    /// rather than one — the DX7 was the first — and the first whose *panel*
368    /// is loaded from them, so the editor's "index 0 reloads the preset" rule
369    /// is not enough on its own: stepping the bank has to reload as well, or
370    /// four fifths of the factory set is unreachable from the panel.
371    #[test]
372    fn both_prophet_six_selectors_load_the_program() {
373        use phosphor_dsp::prophet6;
374
375        let mut nav = prophet6_track();
376        let panel = |nav: &NavState| nav.tracks[0].synth_params.clone();
377        assert_eq!(panel(&nav), prophet6::params_for_program(0.0, 0.0).to_vec());
378
379        // Step the program knob: the whole panel follows it.
380        nav.clip_view.synth_param_cursor = prophet6::P_PROGRAM;
381        for step in 1..8 {
382            nav.adjust_synth_param(0.05);
383            let expected = prophet6::params_for_program(
384                nav.tracks[0].synth_params[prophet6::P_BANK],
385                nav.tracks[0].synth_params[prophet6::P_PROGRAM],
386            );
387            assert_eq!(panel(&nav), expected.to_vec(), "program knob step {step}");
388            assert_eq!(
389                prophet6::program_index(
390                    nav.tracks[0].synth_params[prophet6::P_BANK],
391                    nav.tracks[0].synth_params[prophet6::P_PROGRAM],
392                ),
393                step
394            );
395        }
396
397        // Step the bank knob: same, a hundred programs further along each time.
398        nav.clip_view.synth_param_cursor = prophet6::P_BANK;
399        for bank in 1..prophet6::BANK_COUNT {
400            nav.adjust_synth_param(0.05);
401            let expected = prophet6::params_for_program(
402                nav.tracks[0].synth_params[prophet6::P_BANK],
403                nav.tracks[0].synth_params[prophet6::P_PROGRAM],
404            );
405            assert_eq!(panel(&nav), expected.to_vec(), "bank knob step {bank}");
406            assert_eq!(
407                prophet6::program_index(
408                    nav.tracks[0].synth_params[prophet6::P_BANK],
409                    nav.tracks[0].synth_params[prophet6::P_PROGRAM],
410                ),
411                bank * prophet6::PROGRAMS_PER_BANK + 7,
412                "the bank knob lost the program knob's position"
413            );
414        }
415
416        // And an ordinary knob does not reload anything.
417        nav.clip_view.synth_param_cursor = prophet6::P_LP_CUTOFF;
418        let before = panel(&nav);
419        nav.adjust_synth_param(0.05);
420        let after = panel(&nav);
421        for (index, (a, b)) in before.iter().zip(&after).enumerate() {
422            if index != prophet6::P_LP_CUTOFF {
423                assert_eq!(a, b, "{} moved with the cutoff", prophet6::PARAM_NAMES[index]);
424            }
425        }
426        assert!(after[prophet6::P_LP_CUTOFF] > before[prophet6::P_LP_CUTOFF]);
427    }
428
429    /// A nav state whose selected track is a drum rack at its default panel.
430    fn drum_track() -> NavState {
431        let mut nav = NavState::new(super::super::initial_tracks());
432        let mut track = TrackState::new("drums", 0, true, TrackKind::Instrument, vec![]);
433        track.instrument_type = Some(InstrumentType::DrumRack);
434        track.synth_params = drum_rack::PARAM_DEFAULTS.to_vec();
435        nav.tracks.insert(0, track);
436        nav.track_cursor = 0;
437        nav
438    }
439
440    #[test]
441    fn the_drum_kit_selector_moves_one_kit_per_keypress() {
442        // Fifteen kits, stepped by index. This used to add a fraction of the
443        // knob's travel per press, which does not divide the selector evenly:
444        // the accumulated error lands on the wrong side of a boundary and the
445        // keypress reads as having done nothing. The list is driven off
446        // `KIT_LABELS` so that adding a kit does not need this test edited.
447        let mut nav = drum_track();
448        nav.clip_view.synth_param_cursor = drum_rack::P_KIT;
449        let kit = |nav: &NavState| {
450            drum_rack::discrete_label(drum_rack::P_KIT, nav.tracks[0].synth_params[drum_rack::P_KIT])
451        };
452        let last = *drum_rack::KIT_LABELS.last().unwrap();
453        assert_eq!(kit(&nav), Some("808"));
454        for label in drum_rack::KIT_LABELS.iter().skip(1) {
455            nav.adjust_synth_param(0.05);
456            assert_eq!(kit(&nav), Some(*label));
457        }
458        nav.adjust_synth_param(0.05);
459        assert_eq!(kit(&nav), Some(last), "the kit knob ran off the top");
460        for label in drum_rack::KIT_LABELS.iter().rev().skip(1) {
461            nav.adjust_synth_param(-0.05);
462            assert_eq!(kit(&nav), Some(*label));
463        }
464
465        // The rest of the panel is continuous, and moving one control moves
466        // only that control.
467        nav.clip_view.synth_param_cursor = drum_rack::P_BD_DECAY;
468        let before = nav.tracks[0].synth_params.clone();
469        nav.adjust_synth_param(-0.05);
470        let after = &nav.tracks[0].synth_params;
471        assert!((after[drum_rack::P_BD_DECAY] - 0.45).abs() < 1e-6);
472        for i in 0..after.len() {
473            if i != drum_rack::P_BD_DECAY {
474                assert_eq!(before[i], after[i], "{} moved with the kick's decay", drum_rack::PARAM_NAMES[i]);
475            }
476        }
477    }
478
479    #[test]
480    fn the_dx7_bank_knob_is_the_last_parameter() {
481        // Sessions store `synth_params` positionally, so the bank selector was
482        // appended rather than filed next to the patch selector: inserting it
483        // would load every saved value of every existing session one slot out.
484        let nav = dx7_track();
485        assert_eq!(nav.tracks[0].synth_params.len(), dx7::PARAM_COUNT);
486        assert_eq!(dx7::P_BANK, dx7::PARAM_COUNT - 1);
487        assert_eq!(dx7::PARAM_NAMES[dx7::P_GAIN], "gain", "index 0-7 must not move");
488    }
489}