Skip to main content

open_stomp/
midi.rs

1//! MIDI message parsing, SysEx framing and stream reassembly (docs/protocol/midi-cc.md, docs/protocol/sysex.md).
2
3pub const MFR: [u8; 3] = [0x00, 0x21, 0x7A];
4pub const UID: u8 = 0x70;
5
6/// Pedal reports on channel 1, the host commands on channel 2.
7pub const PEDAL_CH: u8 = 0;
8pub const HOST_CH: u8 = 1;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum Cmd {
12    IrSlot = 0x09,
13    Preset = 0x0B,
14    EditBuffer = 0x0C,
15    Chain = 0x0D,
16    IrData = 0x10,
17    PresetName = 0x12,
18    System = 0x14,
19    CurState = 0x15,
20    Loop = 0x18,
21    Drum = 0x19,
22    UserAmp = 0x58,
23    Tuner = 0x6F,
24    Notify = 0x7E,
25}
26
27impl Cmd {
28    pub fn from_u8(b: u8) -> Option<Cmd> {
29        use Cmd::*;
30        Some(match b {
31            0x09 => IrSlot,
32            0x0B => Preset,
33            0x0C => EditBuffer,
34            0x0D => Chain,
35            0x10 => IrData,
36            0x12 => PresetName,
37            0x14 => System,
38            0x15 => CurState,
39            0x18 => Loop,
40            0x19 => Drum,
41            0x58 => UserAmp,
42            0x6F => Tuner,
43            0x7E => Notify,
44            _ => return None,
45        })
46    }
47
48    pub fn label(b: u8) -> &'static str {
49        match b {
50            0x09 => "user IR slot",
51            0x0B => "preset",
52            0x0C => "edit buffer",
53            0x0D => "chain order",
54            0x10 => "IR data",
55            0x12 => "preset name",
56            0x14 => "system settings",
57            0x15 => "current state",
58            0x16 => "delete IR",
59            0x18 => "looper",
60            0x19 => "drum",
61            0x1B => "bluetooth",
62            0x58 => "user amp (NAM)",
63            0x6F => "tuner",
64            0x7E => "notify",
65            _ => "unknown",
66        }
67    }
68}
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub enum Dir {
72    Read = 0,
73    Write = 1,
74    Reply = 2,
75    Ack = 3,
76}
77
78impl Dir {
79    pub fn label(b: u8) -> &'static str {
80        match b {
81            0 => "read",
82            1 => "write",
83            2 => "reply",
84            3 => "ack",
85            _ => "?",
86        }
87    }
88}
89
90/// Build a NEP frame `F0 00 21 7A 70 <cmd> <dir> <payload> F7`.
91pub fn frame(cmd: Cmd, dir: Dir, payload: &[u8]) -> Vec<u8> {
92    let mut v = Vec::with_capacity(payload.len() + 8);
93    v.push(0xF0);
94    v.extend_from_slice(&MFR);
95    v.push(UID);
96    v.push(cmd as u8);
97    v.push(dir as u8);
98    debug_assert!(payload.iter().all(|b| *b < 0x80));
99    v.extend_from_slice(payload);
100    v.push(0xF7);
101    v
102}
103
104/// Short identification request (`0x00` version, `0x60` product name).
105pub fn short_request(kind: u8) -> Vec<u8> {
106    vec![0xF0, MFR[0], MFR[1], MFR[2], kind, 0xF7]
107}
108
109/// Read requests used by the official app's handshake.
110pub mod req {
111    use super::*;
112    use crate::pack::pack;
113
114    pub fn version() -> Vec<u8> {
115        short_request(0x00)
116    }
117    pub fn product() -> Vec<u8> {
118        short_request(0x60)
119    }
120    pub fn settings() -> Vec<u8> {
121        frame(Cmd::System, Dir::Read, &[])
122    }
123    pub fn cur_state() -> Vec<u8> {
124        frame(Cmd::CurState, Dir::Read, &[])
125    }
126    pub fn drum() -> Vec<u8> {
127        frame(Cmd::Drum, Dir::Read, &[])
128    }
129    pub fn looper() -> Vec<u8> {
130        frame(Cmd::Loop, Dir::Read, &[])
131    }
132    pub fn tuner() -> Vec<u8> {
133        frame(Cmd::Tuner, Dir::Read, &[])
134    }
135    /// Padded with 14 zero bytes like the official app's request: the pedal takes request
136    /// parameters from those bytes, and a bare request makes it read whatever the previous message
137    /// left in its buffer (seen over BLE: empty or truncated replies).
138    pub fn edit_buffer() -> Vec<u8> {
139        frame(Cmd::EditBuffer, Dir::Read, &[0; 14])
140    }
141    /// The edit buffer's signal-chain order (reply: the 8 module indices, plain bytes).
142    pub fn chain() -> Vec<u8> {
143        frame(Cmd::Chain, Dir::Read, &[])
144    }
145    pub fn ir_slot(slot: u8) -> Vec<u8> {
146        frame(Cmd::IrSlot, Dir::Read, &[slot])
147    }
148    pub fn preset(index: u8) -> Vec<u8> {
149        let mut p = vec![0u8; 14];
150        p[0] = index & 0x7F;
151        frame(Cmd::Preset, Dir::Read, &p)
152    }
153    pub fn user_amp(slot: u8) -> Vec<u8> {
154        let mut hdr = [0u8; 12];
155        hdr[1] = slot;
156        hdr[2] = 4; // sub-command: read slot info
157        frame(Cmd::UserAmp, Dir::Read, &pack(&hdr))
158    }
159}
160
161/// Host → pedal commands (docs/protocol/midi-cc.md live control, docs/protocol/commands.md writes). Live changes are channel-2
162/// CCs/PCs; the pedal does not echo them, so apply them to the local model too.
163pub mod host {
164    use super::*;
165    use crate::catalog::Module;
166    use crate::records::{Preset, Settings, name_bytes};
167
168    pub fn cc(cc: u8, val: u8) -> Vec<u8> {
169        vec![0xB0 | HOST_CH, cc & 0x7F, val & 0x7F]
170    }
171
172    /// Select preset `index` (0-based, P01 = 0).
173    pub fn program(index: u8) -> Vec<u8> {
174        vec![0xC0 | HOST_CH, index & 0x7F]
175    }
176
177    /// Model + on/off of an effect module.
178    pub fn head(m: Module, model: u8, on: bool) -> Option<Vec<u8>> {
179        Some(cc(m.head_cc()?, (if on { 0 } else { 0x40 }) | (model & 0x3F)))
180    }
181
182    /// A module parameter by slot (app display order).
183    pub fn param(m: Module, slot: usize, val: u8) -> Option<Vec<u8>> {
184        let (first, n) = m.param_ccs()?;
185        (slot < n as usize).then(|| cc(first + slot as u8, val))
186    }
187
188    pub fn volume(v: u8) -> Vec<u8> {
189        cc(0x3A, v.min(100))
190    }
191
192    /// Make the pedal display jump to a module's page.
193    pub fn page(m: Module) -> Vec<u8> {
194        cc(0x3B, m as u8)
195    }
196
197    pub const LOOP_REC_PLAY_DUB: u8 = 0x01;
198    pub const LOOP_STOP: u8 = 0x02;
199    pub const LOOP_CLEAR: u8 = 0x04;
200    pub const LOOP_UNDO_REDO: u8 = 0x08;
201
202    pub fn looper_button(b: u8) -> Vec<u8> {
203        cc(0x44, b)
204    }
205
206    /// Switch the tuner on or off. Same payload the official app writes back after the pedal's
207    /// tuner notification; `0x0A` is the reference byte every read has returned.
208    pub fn tuner(on: bool) -> Vec<u8> {
209        frame(Cmd::Tuner, Dir::Write, &[on as u8, 0, 0x0A, 0, 0])
210    }
211
212    /// Set the edit buffer's name. The official app sends the slot being edited first
213    /// (the active preset, even when saving to another slot).
214    pub fn preset_name(source_slot: u8, name: &str) -> Vec<u8> {
215        let mut p = Vec::with_capacity(17);
216        p.push(source_slot & 0x7F);
217        p.extend(name_bytes(name).iter().map(|b| b & 0x7F));
218        frame(Cmd::PresetName, Dir::Write, &p)
219    }
220
221    /// Store a whole preset record in slot `preset.index`.
222    pub fn preset_write(preset: &Preset) -> Vec<u8> {
223        frame(Cmd::Preset, Dir::Write, &preset.to_packed())
224    }
225
226    /// The official app's save sequence: name, record, then select the saved slot.
227    pub fn save_preset(source_slot: u8, preset: &Preset) -> Vec<Vec<u8>> {
228        vec![preset_name(source_slot, &preset.name), preset_write(preset), program(preset.index)]
229    }
230
231    /// Reorder the edit buffer's signal chain: the eight effect modules (GATE included) as module
232    /// indices in signal order. A live edit like a CC; saving the preset stores it. The pedal answers
233    /// with a reply carrying the order it now uses (not an ack). `None` unless `order` is a
234    /// [`valid_chain`](crate::records::valid_chain).
235    pub fn chain(order: &[u8]) -> Option<Vec<u8>> {
236        crate::records::valid_chain(order).then(|| frame(Cmd::Chain, Dir::Write, order))
237    }
238
239    pub fn settings_write(s: &Settings) -> Vec<u8> {
240        frame(Cmd::System, Dir::Write, &s.to_packed())
241    }
242}
243
244/// One parsed MIDI message.
245#[derive(Clone, Debug, PartialEq, Eq)]
246pub enum Msg {
247    Cc { ch: u8, cc: u8, val: u8 },
248    Pc { ch: u8, prog: u8 },
249    /// `F0 00 21 7A 70 <cmd> <dir> <payload> F7`
250    Nep { cmd: u8, dir: u8, payload: Vec<u8> },
251    /// `F0 00 21 7A 70 7E 02 <what> 02 <payload> F7`
252    Notify { what: u8, payload: Vec<u8> },
253    /// `F0 00 21 7A <kind> <payload> F7` (`00`/`10` version, `60` product)
254    Short { kind: u8, payload: Vec<u8> },
255    /// Anything else (other manufacturers, realtime, note on/off...).
256    Other(Vec<u8>),
257}
258
259impl Msg {
260    pub fn parse(b: &[u8]) -> Msg {
261        let Some(&s) = b.first() else {
262            return Msg::Other(vec![]);
263        };
264        match s & 0xF0 {
265            0xB0 if b.len() >= 3 => return Msg::Cc { ch: s & 0x0F, cc: b[1], val: b[2] },
266            0xC0 if b.len() >= 2 => return Msg::Pc { ch: s & 0x0F, prog: b[1] },
267            _ => {}
268        }
269        if s != 0xF0 || b.len() < 6 || b[1..4] != MFR {
270            return Msg::Other(b.to_vec());
271        }
272        let end = if b.last() == Some(&0xF7) { b.len() - 1 } else { b.len() };
273        let body = &b[4..end];
274        if body[0] != UID || body.len() < 3 {
275            return Msg::Short { kind: body[0], payload: body[1..].to_vec() };
276        }
277        let (cmd, dir, payload) = (body[1], body[2], &body[3..]);
278        if cmd == Cmd::Notify as u8 && payload.len() >= 2 {
279            return Msg::Notify { what: payload[0], payload: payload[2..].to_vec() };
280        }
281        Msg::Nep { cmd, dir, payload: payload.to_vec() }
282    }
283}
284
285/// Reassembles a raw byte stream (possibly split SysEx) into whole messages.
286#[derive(Default)]
287pub struct Assembler {
288    buf: Vec<u8>,
289}
290
291impl Assembler {
292    pub fn push(&mut self, data: &[u8]) -> Vec<Vec<u8>> {
293        self.buf.extend_from_slice(data);
294        let mut out = vec![];
295        loop {
296            // drop stray data bytes in front of a status byte
297            let start = self.buf.iter().position(|b| *b >= 0x80).unwrap_or(self.buf.len());
298            self.buf.drain(..start);
299            let Some(&s) = self.buf.first() else { break };
300            let len = if s == 0xF0 {
301                match self.buf.iter().position(|b| *b == 0xF7) {
302                    Some(e) => e + 1,
303                    None => break,
304                }
305            } else if s >= 0xF8 {
306                1
307            } else {
308                let need = match s & 0xF0 {
309                    0xC0 | 0xD0 => 2,
310                    0xF0 => 1,
311                    _ => 3,
312                };
313                if self.buf.len() < need {
314                    break;
315                }
316                // a status byte inside the data means a truncated message
317                match self.buf[1..need].iter().position(|b| *b >= 0x80) {
318                    Some(p) => p + 1,
319                    None => need,
320                }
321            };
322            out.push(self.buf.drain(..len).collect());
323        }
324        out
325    }
326}
327
328pub fn hex(b: &[u8]) -> String {
329    let mut s = String::with_capacity(b.len() * 3);
330    for (i, x) in b.iter().enumerate() {
331        if i > 0 {
332            s.push(' ');
333        }
334        s.push_str(&format!("{x:02X}"));
335    }
336    s
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn parse_basic() {
345        assert_eq!(Msg::parse(&[0xB0, 0x12, 0x40]), Msg::Cc { ch: 0, cc: 0x12, val: 0x40 });
346        assert_eq!(Msg::parse(&[0xC1, 4]), Msg::Pc { ch: 1, prog: 4 });
347        assert_eq!(
348            Msg::parse(&[0xF0, 0, 0x21, 0x7A, 0x70, 0x7E, 0x02, 0x19, 0x02, 1, 2, 3, 0, 0, 0x78, 0xF7]),
349            Msg::Notify { what: 0x19, payload: vec![1, 2, 3, 0, 0, 0x78] }
350        );
351        assert_eq!(
352            Msg::parse(&req::settings()),
353            Msg::Nep { cmd: 0x14, dir: 0, payload: vec![] }
354        );
355    }
356
357    #[test]
358    fn tuner_write_matches_official_app() {
359        // From the capture: the app's write-back after the pedal's tuner notification.
360        assert_eq!(host::tuner(true), [0xF0, 0, 0x21, 0x7A, 0x70, 0x6F, 1, 1, 0, 0x0A, 0, 0, 0xF7]);
361        assert_eq!(host::tuner(false), [0xF0, 0, 0x21, 0x7A, 0x70, 0x6F, 1, 0, 0, 0x0A, 0, 0, 0xF7]);
362    }
363
364    #[test]
365    fn assembler_splits_and_joins() {
366        let mut a = Assembler::default();
367        assert!(a.push(&[0xF0, 0x00, 0x21]).is_empty());
368        let m = a.push(&[0x7A, 0x00, 0xF7, 0xB0, 0x01, 0x08, 0xC0]);
369        assert_eq!(m, vec![vec![0xF0, 0, 0x21, 0x7A, 0, 0xF7], vec![0xB0, 1, 8]]);
370        assert_eq!(a.push(&[0x05]), vec![vec![0xC0, 5]]);
371    }
372
373    #[test]
374    fn host_commands() {
375        use crate::catalog::Module;
376        assert_eq!(host::head(Module::Amp, 8, false), Some(vec![0xB1, 0x01, 0x48]));
377        assert_eq!(host::param(Module::OdFx, 1, 66), Some(vec![0xB1, 0x0D, 66]));
378        assert_eq!(host::param(Module::Gate, 2, 1), None);
379        assert_eq!(host::head(Module::Loop, 0, true), None);
380        assert_eq!(host::program(84), vec![0xC1, 0x54]);
381        assert_eq!(host::page(Module::Gate), vec![0xB1, 0x3B, 0x06]);
382        // captured rename (source slot P69 = 0x44, docs/protocol/commands.md)
383        assert_eq!(
384            hex(&host::preset_name(0x44, "4Ooz!")),
385            "F0 00 21 7A 70 12 01 44 34 4F 6F 7A 21 00 00 00 00 00 00 00 00 00 00 00 F7"
386        );
387    }
388
389    #[test]
390    fn chain_messages_match_pedal() {
391        // sent to the pedal and confirmed on its display (2026-12-03, v1.1.1, USB)
392        assert_eq!(hex(&req::chain()), "F0 00 21 7A 70 0D 00 F7");
393        assert_eq!(
394            hex(&host::chain(&[6, 0, 1, 2, 7, 4, 3, 5]).unwrap()),
395            "F0 00 21 7A 70 0D 01 06 00 01 02 07 04 03 05 F7"
396        );
397        assert_eq!(host::chain(&[6, 0, 1, 2, 7, 3, 4]), None);
398        assert_eq!(host::chain(&[6, 0, 1, 2, 7, 3, 4, 8]), None);
399    }
400
401    #[test]
402    fn user_amp_request_matches_capture() {
403        assert_eq!(
404            hex(&req::user_amp(1)),
405            "F0 00 21 7A 70 58 00 00 02 10 00 00 00 00 00 00 00 00 00 00 00 F7"
406        );
407    }
408}