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 patch selector changes, sync all params from preset.
32                // The banks no longer agree on how many parameters an
33                // instrument has, so this collects rather than matching on a
34                // fixed-size array, and writes through a zip so a track
35                // carrying a shorter block than its instrument now has cannot
36                // index off the end of itself.
37                if idx == 0 {
38                    let new_params: Option<Vec<f32>> = match track.instrument_type {
39                        Some(InstrumentType::Jupiter8) => {
40                            Some(phosphor_dsp::jupiter::Jupiter8Synth::params_for_patch(new_val).to_vec())
41                        }
42                        Some(InstrumentType::Odyssey) => {
43                            Some(phosphor_dsp::odyssey::OdysseySynth::params_for_patch(new_val).to_vec())
44                        }
45                        Some(InstrumentType::Juno60) => {
46                            Some(phosphor_dsp::juno::Juno60Synth::params_for_patch(new_val).to_vec())
47                        }
48                        _ => None,
49                    };
50                    if let Some(preset_params) = new_params {
51                        for (slot, v) in track.synth_params.iter_mut().zip(preset_params) {
52                            *slot = v;
53                        }
54                    }
55                }
56
57                if let Some(mixer_id) = track.mixer_id {
58                    return Some((mixer_id, idx, new_val));
59                }
60            }
61        }
62        None
63    }
64
65
66    /// Show controls for the currently selected track and route MIDI to it.
67    /// For instrument tracks: opens clip view with Synth tab, activates MIDI input.
68    /// For bus tracks: no clip view, deactivates MIDI.
69    pub fn show_current_track_controls(&mut self) {
70        // Deactivate MIDI on ALL tracks first
71        for track in &self.tracks {
72            if let Some(ref h) = track.handle {
73                h.config.midi_active.store(false, std::sync::atomic::Ordering::Relaxed);
74            }
75        }
76
77        if let Some(track) = self.tracks.get(self.track_cursor) {
78            if track.is_live() {
79                if let Some(ref h) = track.handle {
80                    h.config.midi_active.store(true, std::sync::atomic::Ordering::Relaxed);
81                }
82                self.clip_view_visible = true;
83
84                // Use the currently selected clip element, or default to clip 0
85                let clip_idx = match self.track_element {
86                    super::TrackElement::Clip(i) if i < track.clips.len() => i,
87                    _ => 0,
88                };
89                self.clip_view_target = Some((self.track_cursor, clip_idx));
90
91                // If track has recorded clips, show piano roll. Otherwise show synth.
92                if !track.clips.is_empty() {
93                    self.clip_view.clip_tab = ClipTab::PianoRoll;
94                    self.clip_view.focus = ClipViewFocus::PianoRoll;
95                    self.clip_view.piano_roll.focus = PianoRollFocus::Navigation;
96                    self.clip_view.piano_roll.column = 0;
97                } else {
98                    self.clip_view.fx_panel_tab = FxPanelTab::Synth;
99                    self.clip_view.focus = ClipViewFocus::FxPanel;
100                    self.clip_view.synth_param_cursor = 0;
101                }
102            } else {
103                // Bus track — hide clip view
104                self.clip_view_visible = false;
105                self.clip_view_target = None;
106            }
107        }
108    }
109
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use phosphor_dsp::{drum_rack, dx7, juno, jupiter};
116
117    /// A nav state whose selected track is a DX7 at its default parameters.
118    fn dx7_track() -> NavState {
119        let mut nav = NavState::new(super::super::initial_tracks());
120        let mut track = TrackState::new("dx7", 0, true, TrackKind::Instrument, vec![]);
121        track.instrument_type = Some(InstrumentType::DX7);
122        track.synth_params = dx7::PARAM_DEFAULTS.to_vec();
123        nav.tracks.insert(0, track);
124        nav.track_cursor = 0;
125        nav
126    }
127
128    fn selected(nav: &NavState) -> (usize, usize) {
129        let p = &nav.tracks[0].synth_params;
130        (dx7::bank_index(p[dx7::P_BANK]), dx7::patch_index(p[dx7::P_PATCH]))
131    }
132
133    #[test]
134    fn dx7_selectors_move_one_step_per_keypress() {
135        // Both DX7 selectors are discrete: a keypress is one voice or one
136        // cartridge, not a fraction of the knob's travel. The patch knob alone
137        // would otherwise take 256 presses to cross the factory set.
138        let mut nav = dx7_track();
139        nav.clip_view.synth_param_cursor = dx7::P_PATCH;
140        let (bank, patch) = selected(&nav);
141        for step in 1..=5 {
142            nav.adjust_synth_param(0.05);
143            assert_eq!(selected(&nav), (bank, patch + step), "patch knob step {step}");
144        }
145        for step in (0..5).rev() {
146            nav.adjust_synth_param(-0.05);
147            assert_eq!(selected(&nav), (bank, patch + step), "patch knob back to {step}");
148        }
149
150        nav.clip_view.synth_param_cursor = dx7::P_BANK;
151        for step in 1..dx7::BANK_COUNT {
152            nav.adjust_synth_param(0.05);
153            assert_eq!(selected(&nav), (step, patch), "bank knob step {step}");
154        }
155        // ...and neither runs off its end.
156        for _ in 0..4 {
157            nav.adjust_synth_param(0.05);
158        }
159        assert_eq!(selected(&nav), (dx7::BANK_COUNT - 1, patch));
160    }
161
162    /// A nav state whose selected track is a Juno-60 at its default panel.
163    fn juno_track() -> NavState {
164        let mut nav = NavState::new(super::super::initial_tracks());
165        let mut track = TrackState::new("juno", 0, true, TrackKind::Instrument, vec![]);
166        track.instrument_type = Some(InstrumentType::Juno60);
167        track.synth_params = juno::PARAM_DEFAULTS.to_vec();
168        nav.tracks.insert(0, track);
169        nav.track_cursor = 0;
170        nav
171    }
172
173    fn juno_patch(nav: &NavState) -> usize {
174        juno::patch_index(nav.tracks[0].synth_params[juno::P_PATCH])
175    }
176
177    #[test]
178    fn juno_selectors_move_one_step_per_keypress() {
179        // 56 factory patches: a keypress is one patch, not a fraction of the
180        // knob's travel, and the whole bank has to be reachable from either
181        // end. The three-position PWM switch is here too, because a switch
182        // that gained a position is the one most likely to be stepped by a
183        // stale fraction.
184        let mut nav = juno_track();
185        nav.clip_view.synth_param_cursor = juno::P_PATCH;
186        for step in 1..juno::PATCH_COUNT {
187            nav.adjust_synth_param(0.05);
188            assert_eq!(juno_patch(&nav), step, "patch knob step {step}");
189        }
190        nav.adjust_synth_param(0.05);
191        assert_eq!(juno_patch(&nav), juno::PATCH_COUNT - 1, "patch knob ran off the top");
192        for step in (0..juno::PATCH_COUNT - 1).rev() {
193            nav.adjust_synth_param(-0.05);
194            assert_eq!(juno_patch(&nav), step, "patch knob back to {step}");
195        }
196
197        // Selecting a patch loads its panel: 78 SYNTHESIZER DRUM is the one
198        // with the filter at self-oscillation and no oscillator at all.
199        for _ in 0..juno::PATCH_COUNT {
200            nav.adjust_synth_param(0.05);
201        }
202        let panel = &nav.tracks[0].synth_params;
203        assert_eq!(juno_patch(&nav), juno::PATCH_COUNT - 1);
204        assert!((panel[juno::P_RESO] - 1.0).abs() < 1e-6, "res {}", panel[juno::P_RESO]);
205
206        // A fresh panel, because the switch has to start where 11 STRINGS 1
207        // leaves it rather than where the last patch of the sweep did.
208        let mut nav = juno_track();
209        nav.clip_view.synth_param_cursor = juno::P_PWM_MODE;
210        let label = |nav: &NavState| {
211            juno::discrete_label(juno::P_PWM_MODE, nav.tracks[0].synth_params[juno::P_PWM_MODE])
212        };
213        assert_eq!(label(&nav), Some("LFO"));
214        let mut seen = Vec::new();
215        for _ in 0..3 {
216            nav.adjust_synth_param(0.05);
217            seen.push(label(&nav));
218        }
219        assert_eq!(seen, [Some("MAN"), Some("ENV"), Some("ENV")]);
220    }
221
222    /// A nav state whose selected track is a Jupiter-8 at its default panel.
223    fn jupiter_track() -> NavState {
224        let mut nav = NavState::new(super::super::initial_tracks());
225        let mut track = TrackState::new("jupiter", 0, true, TrackKind::Instrument, vec![]);
226        track.instrument_type = Some(InstrumentType::Jupiter8);
227        track.synth_params = jupiter::PARAM_DEFAULTS.to_vec();
228        nav.tracks.insert(0, track);
229        nav.track_cursor = 0;
230        nav
231    }
232
233    #[test]
234    fn jupiter_selectors_move_one_step_per_keypress() {
235        // 64 patches and seven switches. The patch knob used to step by
236        // 1/(n - 0.01) of the travel, which is a fraction that does not
237        // divide the bank: the accumulated error lands on the wrong side of a
238        // boundary and the keypress reads as having done nothing.
239        let mut nav = jupiter_track();
240        nav.clip_view.synth_param_cursor = jupiter::P_PATCH;
241        let patch = |nav: &NavState| {
242            jupiter::patch_index(nav.tracks[0].synth_params[jupiter::P_PATCH])
243        };
244        for step in 1..jupiter::PATCH_COUNT {
245            nav.adjust_synth_param(0.05);
246            assert_eq!(patch(&nav), step, "patch knob step {step}");
247        }
248        nav.adjust_synth_param(0.05);
249        assert_eq!(patch(&nav), jupiter::PATCH_COUNT - 1, "patch knob ran off the top");
250        for step in (0..jupiter::PATCH_COUNT - 1).rev() {
251            nav.adjust_synth_param(-0.05);
252            assert_eq!(patch(&nav), step, "patch knob back to {step}");
253        }
254
255        // A fresh panel, because the waveform switch has to start where patch
256        // 0 leaves it rather than where the last patch of the sweep did.
257        let mut nav = jupiter_track();
258        nav.clip_view.synth_param_cursor = jupiter::P_VCO2_WAVE;
259        let label = |nav: &NavState| {
260            jupiter::discrete_label(
261                jupiter::P_VCO2_WAVE,
262                nav.tracks[0].synth_params[jupiter::P_VCO2_WAVE],
263            )
264        };
265        assert_eq!(label(&nav), Some("SAW"));
266        let mut seen = Vec::new();
267        for _ in 0..3 {
268            nav.adjust_synth_param(0.05);
269            seen.push(label(&nav));
270        }
271        assert_eq!(seen, [Some("PLS"), Some("NOISE"), Some("NOISE")]);
272    }
273
274    /// A nav state whose selected track is a drum rack at its default panel.
275    fn drum_track() -> NavState {
276        let mut nav = NavState::new(super::super::initial_tracks());
277        let mut track = TrackState::new("drums", 0, true, TrackKind::Instrument, vec![]);
278        track.instrument_type = Some(InstrumentType::DrumRack);
279        track.synth_params = drum_rack::PARAM_DEFAULTS.to_vec();
280        nav.tracks.insert(0, track);
281        nav.track_cursor = 0;
282        nav
283    }
284
285    #[test]
286    fn the_drum_kit_selector_moves_one_kit_per_keypress() {
287        // Fifteen kits, stepped by index. This used to add a fraction of the
288        // knob's travel per press, which does not divide the selector evenly:
289        // the accumulated error lands on the wrong side of a boundary and the
290        // keypress reads as having done nothing. The list is driven off
291        // `KIT_LABELS` so that adding a kit does not need this test edited.
292        let mut nav = drum_track();
293        nav.clip_view.synth_param_cursor = drum_rack::P_KIT;
294        let kit = |nav: &NavState| {
295            drum_rack::discrete_label(drum_rack::P_KIT, nav.tracks[0].synth_params[drum_rack::P_KIT])
296        };
297        let last = *drum_rack::KIT_LABELS.last().unwrap();
298        assert_eq!(kit(&nav), Some("808"));
299        for label in drum_rack::KIT_LABELS.iter().skip(1) {
300            nav.adjust_synth_param(0.05);
301            assert_eq!(kit(&nav), Some(*label));
302        }
303        nav.adjust_synth_param(0.05);
304        assert_eq!(kit(&nav), Some(last), "the kit knob ran off the top");
305        for label in drum_rack::KIT_LABELS.iter().rev().skip(1) {
306            nav.adjust_synth_param(-0.05);
307            assert_eq!(kit(&nav), Some(*label));
308        }
309
310        // The rest of the panel is continuous, and moving one control moves
311        // only that control.
312        nav.clip_view.synth_param_cursor = drum_rack::P_BD_DECAY;
313        let before = nav.tracks[0].synth_params.clone();
314        nav.adjust_synth_param(-0.05);
315        let after = &nav.tracks[0].synth_params;
316        assert!((after[drum_rack::P_BD_DECAY] - 0.45).abs() < 1e-6);
317        for i in 0..after.len() {
318            if i != drum_rack::P_BD_DECAY {
319                assert_eq!(before[i], after[i], "{} moved with the kick's decay", drum_rack::PARAM_NAMES[i]);
320            }
321        }
322    }
323
324    #[test]
325    fn the_dx7_bank_knob_is_the_last_parameter() {
326        // Sessions store `synth_params` positionally, so the bank selector was
327        // appended rather than filed next to the patch selector: inserting it
328        // would load every saved value of every existing session one slot out.
329        let nav = dx7_track();
330        assert_eq!(nav.tracks[0].synth_params.len(), dx7::PARAM_COUNT);
331        assert_eq!(dx7::P_BANK, dx7::PARAM_COUNT - 1);
332        assert_eq!(dx7::PARAM_NAMES[dx7::P_GAIN], "gain", "index 0-7 must not move");
333    }
334}