Skip to main content

open_stomp/
records.rs

1//! Data records carried in SysEx (docs/protocol/preset.md, docs/protocol/records.md).
2
3use crate::catalog::Module;
4use crate::pack::{pack, unpack};
5
6pub const PRESET_LEN: usize = 110;
7pub const PRESET_COUNT: usize = 99;
8
9/// One effect module's state.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub struct ModuleState {
12    pub on: bool,
13    pub model: u8,
14    pub params: [u8; 12],
15}
16
17impl ModuleState {
18    pub fn set_head(&mut self, head: u8) {
19        self.on = head & 0x40 == 0;
20        self.model = head & 0x3F;
21    }
22
23    pub fn head(&self) -> u8 {
24        (if self.on { 0 } else { 0x40 }) | (self.model & 0x3F)
25    }
26}
27
28/// A preset (SysEx `0x0B` / `0x0C`), kept with its raw record so unknown bytes survive a round trip.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct Preset {
31    pub index: u8,
32    /// Indexed by `Module as usize` for the eight effect modules.
33    pub modules: [ModuleState; 8],
34    pub volume: u8,
35    /// Signal-chain order of the eight effect modules, GATE included (module indices, see
36    /// [`valid_chain`]). LOOPER and DRUM always follow the chain.
37    pub chain: [u8; CHAIN_LEN],
38    pub name: String,
39    pub raw: [u8; PRESET_LEN],
40}
41
42/// (count offset, first param offset) per effect module, indexed by module.
43const PARAM_LAYOUT: [(usize, usize); 8] = [
44    (25, 26), // OD/FX
45    (32, 33), // AMP
46    (41, 42), // CAB
47    (61, 62), // MOD
48    (66, 67), // DELAY
49    (73, 74), // REVERB
50    (20, 21), // GATE
51    (48, 49), // EQ
52];
53
54impl Default for Preset {
55    fn default() -> Self {
56        Preset {
57            index: 0,
58            modules: Default::default(),
59            volume: 80,
60            chain: DEFAULT_CHAIN,
61            name: String::new(),
62            raw: [0; PRESET_LEN],
63        }
64    }
65}
66
67pub const CHAIN_LEN: usize = 8;
68
69/// GATE > OD/FX > AMP > CAB > EQ > MOD > DELAY > REVERB, the order of most factory presets.
70pub const DEFAULT_CHAIN: [u8; CHAIN_LEN] = [6, 0, 1, 2, 7, 3, 4, 5];
71
72/// Whether `chain` orders the eight effect modules (indices 0–7), each exactly once.
73pub fn valid_chain(chain: &[u8]) -> bool {
74    chain.len() == CHAIN_LEN && (0..CHAIN_LEN as u8).all(|m| chain.contains(&m))
75}
76
77impl Preset {
78    /// From the packed SysEx body (after `<dir>`).
79    pub fn from_packed(midi: &[u8]) -> Option<Preset> {
80        Preset::from_raw(&unpack(midi))
81    }
82
83    pub fn from_raw(b: &[u8]) -> Option<Preset> {
84        let raw: [u8; PRESET_LEN] = b.get(..PRESET_LEN)?.try_into().ok()?;
85        let mut p = Preset { index: raw[0], raw, ..Default::default() };
86        for m in Module::EFFECTS {
87            let i = m.index();
88            let st = &mut p.modules[i];
89            st.set_head(raw[12 + i]);
90            let (_, first) = PARAM_LAYOUT[i];
91            let n = m.param_ccs().map(|x| x.1 as usize).unwrap_or(0);
92            st.params[..n].copy_from_slice(&raw[first..first + n]);
93        }
94        p.volume = raw[78];
95        if valid_chain(&raw[82..90]) {
96            p.chain.copy_from_slice(&raw[82..90]);
97        }
98        p.name = ascii(&raw[94..110]);
99        Some(p)
100    }
101
102    /// The 110-byte record: the original raw bytes with every decoded field written back.
103    /// Param-count bytes are only recomputed for modules whose model changed.
104    pub fn to_raw(&self) -> [u8; PRESET_LEN] {
105        let mut raw = self.raw;
106        raw[0] = self.index;
107        for m in Module::EFFECTS {
108            let i = m.index();
109            let st = &self.modules[i];
110            if raw[12 + i] & 0x3F != st.model {
111                raw[PARAM_LAYOUT[i].0] = param_count(m, st.model);
112            }
113            raw[12 + i] = st.head();
114            let (_, first) = PARAM_LAYOUT[i];
115            let n = m.param_ccs().map(|x| x.1 as usize).unwrap_or(0);
116            raw[first..first + n].copy_from_slice(&st.params[..n]);
117        }
118        raw[78] = self.volume;
119        raw[82..90].copy_from_slice(&self.chain);
120        raw[94..110].copy_from_slice(&name_bytes(&self.name));
121        raw
122    }
123
124    /// Packed SysEx body for a `0x0B` write.
125    pub fn to_packed(&self) -> Vec<u8> {
126        pack(&self.to_raw())
127    }
128
129    pub fn module(&self, m: Module) -> Option<&ModuleState> {
130        self.modules.get(m.index())
131    }
132
133    pub fn module_mut(&mut self, m: Module) -> Option<&mut ModuleState> {
134        self.modules.get_mut(m.index())
135    }
136
137    /// Whether the decoded sound (modules, volume, chain) is the same, ignoring unused params.
138    pub fn same_sound(&self, other: &Preset) -> bool {
139        self.volume == other.volume
140            && self.chain == other.chain
141            && Module::EFFECTS.into_iter().all(|m| {
142                let (a, b) = (&self.modules[m.index()], &other.modules[m.index()]);
143                a.on == b.on
144                    && a.model == b.model
145                    && m.params(a.model)
146                        .iter()
147                        .all(|p| a.params[p.slot as usize] == b.params[p.slot as usize])
148            })
149    }
150}
151
152pub const SETTINGS_LEN: usize = 17;
153
154/// Value of a module's param-count byte for a model (the number of params the model uses).
155/// CAB always carries all five: user IRs only hide MIC/POSITION in the UI.
156pub fn param_count(m: Module, model: u8) -> u8 {
157    match m {
158        Module::Cab => 5,
159        _ => m.params(model).len() as u8,
160    }
161}
162
163/// A preset name as the 16-byte zero-padded ASCII field (non-ASCII becomes `?`).
164pub fn name_bytes(name: &str) -> [u8; 16] {
165    let mut b = [0u8; 16];
166    for (d, c) in b.iter_mut().zip(name.chars()) {
167        *d = if (' '..='~').contains(&c) { c as u8 } else { b'?' };
168    }
169    b
170}
171
172/// Global system settings (SysEx `0x14`), 17 bytes.
173#[derive(Clone, Debug, Default, PartialEq, Eq)]
174pub struct Settings {
175    /// 0–20 → −10…+10 dB.
176    pub input_trim: u8,
177    pub eq_bass: u8,
178    pub eq_mid: u8,
179    pub eq_treble: u8,
180    pub wireless: bool,
181    pub loopback: bool,
182    pub raw: Vec<u8>,
183}
184
185impl Settings {
186    pub fn from_packed(midi: &[u8]) -> Option<Settings> {
187        let raw = unpack(midi);
188        if raw.len() < 11 {
189            return None;
190        }
191        Some(Settings {
192            input_trim: raw[1],
193            eq_bass: raw[4],
194            eq_mid: raw[5],
195            eq_treble: raw[6],
196            wireless: raw[9] != 0,
197            loopback: raw[10] != 0,
198            raw,
199        })
200    }
201
202    /// The record with the decoded fields written back over the original bytes.
203    pub fn to_raw(&self) -> Vec<u8> {
204        let mut raw = self.raw.clone();
205        if raw.len() < SETTINGS_LEN {
206            raw.resize(SETTINGS_LEN, 0);
207        }
208        raw[1] = self.input_trim.min(20);
209        raw[4] = self.eq_bass.min(100);
210        raw[5] = self.eq_mid.min(100);
211        raw[6] = self.eq_treble.min(100);
212        raw[9] = self.wireless as u8;
213        raw[10] = self.loopback as u8;
214        raw
215    }
216
217    pub fn to_packed(&self) -> Vec<u8> {
218        pack(&self.to_raw())
219    }
220
221    pub fn input_trim_db(&self) -> i16 {
222        self.input_trim as i16 - 10
223    }
224}
225
226/// User IR slot reply payload (`<slot> <packed: 4 B field, name>`).
227pub fn parse_ir_slot(payload: &[u8]) -> Option<(u8, String)> {
228    let (&slot, rest) = payload.split_first()?;
229    let raw = unpack(rest);
230    Some((slot, ascii(raw.get(4..)?)))
231}
232
233/// User AMP (NAM) slot info reply payload: slot and name. See [`crate::upload::UserAmpInfo`] for
234/// the whole record.
235pub fn parse_user_amp(payload: &[u8]) -> Option<(u8, String)> {
236    let i = crate::upload::UserAmpInfo::parse(payload)?;
237    (crate::upload::Chunk::parse(payload)?.sub == crate::upload::amp_sub::READ_INFO).then_some((i.slot, i.name))
238}
239
240/// Plain 7-bit 14-bit value, high 7 bits first.
241pub fn u14(hi: u8, lo: u8) -> u16 {
242    ((hi as u16 & 0x7F) << 7) | (lo as u16 & 0x7F)
243}
244
245/// Zero-terminated, zero-padded ASCII.
246pub fn ascii(b: &[u8]) -> String {
247    b.iter()
248        .take_while(|c| **c != 0)
249        .map(|&c| if (0x20..0x7F).contains(&c) { c as char } else { '?' })
250        .collect::<String>()
251        .trim_end()
252        .to_owned()
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::pack::pack;
259
260    #[test]
261    fn preset_decode() {
262        let mut raw = [0u8; PRESET_LEN];
263        raw[0] = 4;
264        raw[13] = 0x48; // AMP off, model 8
265        raw[33] = 64; // AMP gain
266        raw[78] = 80;
267        raw[82..90].copy_from_slice(&DEFAULT_CHAIN);
268        raw[94..99].copy_from_slice(b"Hello");
269        let p = Preset::from_packed(&pack(&raw)).unwrap();
270        assert_eq!(p.index, 4);
271        assert!(!p.modules[1].on);
272        assert_eq!(p.modules[1].model, 8);
273        assert_eq!(p.modules[1].params[0], 64);
274        assert_eq!(p.name, "Hello");
275    }
276
277    #[test]
278    fn settings_factory() {
279        let raw = [0x00, 0x0A, 0x1E, 0x0A, 0x32, 0x32, 0x32, 0x32, 0x32, 1, 1, 0x3C, 0xB4, 0, 0, 0, 0];
280        let s = Settings::from_packed(&pack(&raw)).unwrap();
281        assert_eq!(s.input_trim_db(), 0);
282        assert_eq!(s.eq_mid, 50);
283        assert!(s.wireless && s.loopback);
284        assert_eq!(s.to_raw(), raw);
285        let mut s2 = s.clone();
286        s2.input_trim = 13;
287        s2.loopback = false;
288        let r = Settings::from_packed(&s2.to_packed()).unwrap();
289        assert_eq!((r.input_trim, r.loopback, r.raw[12]), (13, false, 0xB4));
290    }
291
292    #[test]
293    fn preset_encode_patches_fields() {
294        let mut raw = [0u8; PRESET_LEN];
295        raw[8] = 0x62;
296        raw[12] = 0x05; // OD/FX DS1 (3 params)
297        raw[25] = 3;
298        raw[82..90].copy_from_slice(&DEFAULT_CHAIN);
299        let mut p = Preset::from_raw(&raw).unwrap();
300        assert_eq!(p.to_raw(), raw);
301        p.index = 9;
302        p.modules[0].model = 3; // Boost RC (4 params)
303        p.modules[0].on = false;
304        p.modules[0].params[3] = 77;
305        p.name = "Lead ünicode name too long".into();
306        let r = p.to_raw();
307        assert_eq!((r[0], r[8], r[12], r[25], r[29]), (9, 0x62, 0x43, 4, 77));
308        assert_eq!(&r[94..110], b"Lead ?nicode nam");
309        assert_eq!(Preset::from_packed(&p.to_packed()).unwrap().to_raw(), r);
310    }
311
312    #[test]
313    fn chain_includes_gate() {
314        let mut raw = [0u8; PRESET_LEN];
315        // read from the pedal after moving GATE behind OD/FX (2026-12-03)
316        raw[82..90].copy_from_slice(&[0, 6, 1, 2, 7, 4, 3, 5]);
317        let p = Preset::from_raw(&raw).unwrap();
318        assert_eq!(p.chain, [0, 6, 1, 2, 7, 4, 3, 5]);
319        assert_eq!(p.to_raw(), raw);
320        raw[82..90].copy_from_slice(&[6, 0, 1, 2, 7, 3, 4, 4]);
321        assert_eq!(Preset::from_raw(&raw).unwrap().chain, DEFAULT_CHAIN);
322        assert!(valid_chain(&DEFAULT_CHAIN) && !valid_chain(&DEFAULT_CHAIN[1..]));
323    }
324}