Skip to main content

open_stomp/
upload.rs

1//! User AMP (NAM, SysEx `0x58`) and user IR (SysEx `0x10` + `0x09`) uploads (docs/protocol/uploads.md).
2//!
3//! Both send a converted model as 2048 little-endian `f32`s (8192 bytes) in chunks of 136
4//! bytes, each a packed SysEx write acknowledged before the next. Every chunk starts with a
5//! 12-byte header:
6//!
7//! ```text
8//! [0] 0   [1] slot   [2] sub-command   [3] 0   [4..8] byte offset (u32 LE)   [8..12] total length (u32 LE)
9//! ```
10//!
11//! A user AMP upload is preceded by a 128-byte slot-info record (sub 3) carrying the name and a
12//! gain factor; a user IR upload is followed by a `0x09` name write. Converting a `.nam` or
13//! audio file into the 2048 floats is done by the `nam` and `ir` modules (docs/nam/index.md).
14
15use crate::midi::{Cmd, Dir, frame};
16use crate::pack::{pack, unpack};
17
18/// Bytes of payload per chunk (34 floats).
19pub const CHUNK_BYTES: usize = 136;
20/// Floats per upload, as the official app sends them.
21pub const UPLOAD_FLOATS: usize = 2048;
22/// Number of user AMP slots (amp models 30–39) and user IR slots (cab models 30–39).
23pub const USER_SLOTS: u8 = 10;
24/// Model number of user slot 0 (USER AMP 01 / USER IR 01).
25pub const USER_MODEL_BASE: u8 = 30;
26
27/// Why an upload was refused.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub enum UploadError {
30    /// Slots are 0–9.
31    Slot(u8),
32    /// The pedal takes exactly [`UPLOAD_FLOATS`] floats.
33    Length(usize),
34    /// NaN or infinite values.
35    NotFinite,
36}
37
38impl std::fmt::Display for UploadError {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            UploadError::Slot(s) => write!(f, "user slot {s} out of range (0-9)"),
42            UploadError::Length(n) => write!(f, "{n} floats, the pedal takes exactly {UPLOAD_FLOATS}"),
43            UploadError::NotFinite => write!(f, "model data contains NaN or infinite values"),
44        }
45    }
46}
47
48impl std::error::Error for UploadError {}
49
50/// Check a slot and model data before uploading.
51pub fn check(slot: u8, data: &[f32]) -> Result<(), UploadError> {
52    if slot >= USER_SLOTS {
53        return Err(UploadError::Slot(slot));
54    }
55    if data.len() != UPLOAD_FLOATS {
56        return Err(UploadError::Length(data.len()));
57    }
58    if !data.iter().all(|f| f.is_finite()) {
59        return Err(UploadError::NotFinite);
60    }
61    Ok(())
62}
63
64/// `0x58` sub-commands (unpacked header byte 2).
65pub mod amp_sub {
66    /// With `dir` 0 (read): one chunk of the slot's model data comes back (docs/protocol/uploads.md).
67    pub const READ_DATA: u8 = 0;
68    pub const DATA: u8 = 1;
69    pub const WRITE_INFO: u8 = 3;
70    pub const READ_INFO: u8 = 4;
71    pub const DELETE: u8 = 6;
72}
73
74/// `0x10` sub-command for IR data.
75pub const IR_DATA_SUB: u8 = 0;
76
77/// One upload chunk (or a header-only request/ack), unpacked.
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct Chunk {
80    /// Header byte 0: the user IR slot in IR data (`0x10`) chunks, 0 in NAM uploads.
81    pub ir_slot: u8,
82    /// Header byte 1: the user AMP slot in NAM (`0x58`) chunks, 0 in IR data.
83    pub slot: u8,
84    pub sub: u8,
85    /// Byte offset of `data` in the whole upload.
86    pub offset: u32,
87    /// Total upload length in bytes (8192 for model data, 128 for a slot-info record).
88    pub total: u32,
89    pub data: Vec<u8>,
90}
91
92impl Chunk {
93    /// Decode a packed `0x58`/`0x10` body (the bytes after `<dir>`).
94    pub fn parse(payload: &[u8]) -> Option<Chunk> {
95        let raw = unpack(payload);
96        let h = raw.get(..12)?;
97        Some(Chunk {
98            ir_slot: h[0],
99            slot: h[1],
100            sub: h[2],
101            offset: u32::from_le_bytes(h[4..8].try_into().ok()?),
102            total: u32::from_le_bytes(h[8..12].try_into().ok()?),
103            data: raw[12..].to_vec(),
104        })
105    }
106
107    fn header(ir_slot: u8, slot: u8, sub: u8, offset: u32, total: u32) -> [u8; 12] {
108        let mut h = [0u8; 12];
109        h[0] = ir_slot;
110        h[1] = slot;
111        h[2] = sub;
112        h[4..8].copy_from_slice(&offset.to_le_bytes());
113        h[8..12].copy_from_slice(&total.to_le_bytes());
114        h
115    }
116
117    /// The packed body: header + data.
118    pub fn to_packed(&self) -> Vec<u8> {
119        let mut raw = Self::header(self.ir_slot, self.slot, self.sub, self.offset, self.total).to_vec();
120        raw.extend_from_slice(&self.data);
121        pack(&raw)
122    }
123}
124
125/// Split `data` into `CHUNK_BYTES` write frames for `cmd` (`0x58` NAM data, `0x10` IR data). The
126/// slot goes where each command expects it: header byte 1 for NAM, byte 0 for IR data.
127pub fn data_frames(cmd: Cmd, slot: u8, sub: u8, data: &[u8]) -> Vec<Vec<u8>> {
128    let total = data.len() as u32;
129    let (ir_slot, slot) = if cmd == Cmd::IrData { (slot, 0) } else { (0, slot) };
130    data.chunks(CHUNK_BYTES)
131        .enumerate()
132        .map(|(i, part)| {
133            let c = Chunk { ir_slot, slot, sub, offset: (i * CHUNK_BYTES) as u32, total, data: part.to_vec() };
134            frame(cmd, Dir::Write, &c.to_packed())
135        })
136        .collect()
137}
138
139/// Model data as the little-endian bytes the pedal receives.
140pub fn floats_to_bytes(v: &[f32]) -> Vec<u8> {
141    v.iter().flat_map(|f| f.to_le_bytes()).collect()
142}
143
144pub fn bytes_to_floats(b: &[u8]) -> Vec<f32> {
145    b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()
146}
147
148/// Collects the data chunks of one upload (in any order) back into its floats.
149#[derive(Clone, Debug, Default)]
150pub struct Reassembler {
151    buf: Vec<u8>,
152    filled: usize,
153    slot: Option<u8>,
154}
155
156impl Reassembler {
157    /// Add a data chunk (NAM or IR). Returns the slot and floats once every byte has arrived.
158    pub fn push(&mut self, c: &Chunk) -> Option<(u8, Vec<f32>)> {
159        let (start, total) = (c.offset as usize, c.total as usize);
160        // the NAM slot or the IR slot, whichever header byte carries it
161        let slot = c.slot | c.ir_slot;
162        // a chunk at offset 0, or for another slot/size, starts a new upload
163        if start == 0 || self.slot != Some(slot) || self.buf.len() != total {
164            self.buf = vec![0; total];
165            self.filled = 0;
166            self.slot = Some(slot);
167        }
168        let end = (start + c.data.len()).min(total);
169        if start >= end {
170            return None;
171        }
172        self.buf[start..end].copy_from_slice(&c.data[..end - start]);
173        self.filled += end - start;
174        (self.filled >= total).then(|| {
175            self.filled = 0;
176            (slot, bytes_to_floats(&self.buf))
177        })
178    }
179}
180
181pub const AMP_INFO_LEN: usize = 128;
182const AMP_NAME_LEN: usize = 32;
183const AMP_FACTOR_AT: usize = 52;
184
185/// The 128-byte user AMP slot-info record (`0x58` sub 3 write, sub 4 reply), kept whole so
186/// unknown bytes survive.
187///
188/// Known: bytes 0–31 name (ASCII, zero-padded), 32–35 `u32` = 256 in every record seen,
189/// 52–55 `f32` factor (1.0 in both captured imports). An empty slot reads back as
190/// `"USER AMP NN"` with `1.0` in each of the eleven floats at 52–95.
191#[derive(Clone, Debug, PartialEq)]
192pub struct UserAmpInfo {
193    pub slot: u8,
194    pub name: String,
195    pub factor: f32,
196    pub raw: [u8; AMP_INFO_LEN],
197}
198
199impl UserAmpInfo {
200    /// The record the official app writes for a fresh import.
201    pub fn new(slot: u8, name: &str, factor: f32) -> Self {
202        let mut raw = [0u8; AMP_INFO_LEN];
203        raw[32..36].copy_from_slice(&256u32.to_le_bytes());
204        UserAmpInfo { slot, name: name.to_owned(), factor, raw }
205    }
206
207    /// Decode a sub 3 write or sub 4 reply body.
208    pub fn parse(payload: &[u8]) -> Option<Self> {
209        let c = Chunk::parse(payload)?;
210        if c.sub != amp_sub::WRITE_INFO && c.sub != amp_sub::READ_INFO {
211            return None;
212        }
213        let raw: [u8; AMP_INFO_LEN] = c.data.get(..AMP_INFO_LEN)?.try_into().ok()?;
214        Some(UserAmpInfo {
215            slot: c.slot,
216            name: crate::records::ascii(&raw[..AMP_NAME_LEN]),
217            factor: f32::from_le_bytes(raw[AMP_FACTOR_AT..AMP_FACTOR_AT + 4].try_into().ok()?),
218            raw,
219        })
220    }
221
222    pub fn to_raw(&self) -> [u8; AMP_INFO_LEN] {
223        let mut raw = self.raw;
224        raw[..AMP_NAME_LEN].copy_from_slice(&name_field::<AMP_NAME_LEN>(&self.name));
225        raw[AMP_FACTOR_AT..AMP_FACTOR_AT + 4].copy_from_slice(&self.factor.to_le_bytes());
226        raw
227    }
228
229    /// The sub 3 write frame.
230    pub fn write_frame(&self) -> Vec<u8> {
231        let c = Chunk {
232            ir_slot: 0,
233            slot: self.slot,
234            sub: amp_sub::WRITE_INFO,
235            offset: 0,
236            total: AMP_INFO_LEN as u32,
237            data: self.to_raw().to_vec(),
238        };
239        frame(Cmd::UserAmp, Dir::Write, &c.to_packed())
240    }
241}
242
243/// A name as an `N`-byte zero-padded ASCII field (non-ASCII becomes `?`, one byte kept for NUL).
244fn name_field<const N: usize>(name: &str) -> [u8; N] {
245    let mut b = [0u8; N];
246    for (d, c) in b.iter_mut().take(N - 1).zip(name.chars()) {
247        *d = if (' '..='~').contains(&c) { c as u8 } else { b'?' };
248    }
249    b
250}
251
252/// The official app's user AMP import: slot-info record, then the model data. The app selects
253/// the slot's amp model (`host::head(Module::Amp, 30 + slot, true)`) just before.
254pub fn user_amp_upload(info: &UserAmpInfo, data: &[f32]) -> Vec<Vec<u8>> {
255    let mut v = vec![info.write_frame()];
256    v.extend(data_frames(Cmd::UserAmp, info.slot, amp_sub::DATA, &floats_to_bytes(data)));
257    v
258}
259
260/// Header-only read requests for a slot's 8192 bytes of model data, one per 136-byte chunk.
261fn read_frames(cmd: Cmd, slot: u8, sub: u8) -> Vec<Vec<u8>> {
262    let total = (UPLOAD_FLOATS * 4) as u32;
263    let (ir_slot, slot) = if cmd == Cmd::IrData { (slot, 0) } else { (0, slot) };
264    (0..total)
265        .step_by(CHUNK_BYTES)
266        .map(|offset| {
267            let c = Chunk { ir_slot, slot, sub, offset, total, data: vec![] };
268            frame(cmd, Dir::Read, &c.to_packed())
269        })
270        .collect()
271}
272
273/// Read user AMP `slot`'s 2048 floats back from the pedal: 61 requests, each answered by a `dir` 2
274/// reply carrying that chunk (the upload's layout). Feed the replies to a [`Reassembler`]. Not
275/// used by the official app; found by probing (docs/protocol/uploads.md).
276pub fn user_amp_read(slot: u8) -> Vec<Vec<u8>> {
277    read_frames(Cmd::UserAmp, slot, amp_sub::READ_DATA)
278}
279
280/// Read user IR `slot`'s 2048 floats back, like [`user_amp_read`] (the slot in header byte 0).
281pub fn user_ir_read(slot: u8) -> Vec<Vec<u8>> {
282    read_frames(Cmd::IrData, slot, IR_DATA_SUB)
283}
284
285/// Delete a user AMP slot (the app re-reads its info afterwards).
286pub fn user_amp_delete(slot: u8) -> Vec<u8> {
287    let c = Chunk { ir_slot: 0, slot, sub: amp_sub::DELETE, offset: 0, total: 0, data: vec![] };
288    frame(Cmd::UserAmp, Dir::Write, &c.to_packed())
289}
290
291const IR_NAME_LEN: usize = 32;
292
293/// The `0x09` user IR name write: `<slot> <packed: 01 00 00 00, 32-byte name>`. The first field
294/// was `1` after an upload (meaning unknown, docs/protocol/open-questions.md).
295pub fn user_ir_name(slot: u8, name: &str) -> Vec<u8> {
296    let mut raw = vec![1, 0, 0, 0];
297    raw.extend_from_slice(&name_field::<IR_NAME_LEN>(name));
298    let mut p = vec![slot & 0x7F];
299    p.extend(pack(&raw));
300    frame(Cmd::IrSlot, Dir::Write, &p)
301}
302
303/// The official app's user IR import: the data (slot in header byte 0, unlike NAM's byte 1), then
304/// the name. Checked byte for byte against imports into all ten slots
305/// (`captures/logs/02-ir-tests.log`). The app selects the slot's cab model
306/// (`host::head(Module::Cab, 30 + slot, true)`) just before.
307pub fn user_ir_upload(slot: u8, name: &str, data: &[f32]) -> Vec<Vec<u8>> {
308    let mut v = data_frames(Cmd::IrData, slot, IR_DATA_SUB, &floats_to_bytes(data));
309    v.push(user_ir_name(slot, name));
310    v
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use crate::midi::{Msg, hex};
317
318    #[test]
319    fn read_requests() {
320        let amp = user_amp_read(9);
321        assert_eq!(amp.len(), 61);
322        // byte for byte what was sent to the pedal (2026-11-19) for the first chunk of USER AMP 10
323        assert_eq!(hex(&amp[0]), "F0 00 21 7A 70 58 00 00 12 00 00 00 00 00 00 00 00 00 01 00 00 F7");
324        let Msg::Nep { cmd: 0x58, dir: 0, payload } = Msg::parse(&amp[60]) else { panic!() };
325        let c = Chunk::parse(&payload).unwrap();
326        assert_eq!((c.slot, c.sub, c.offset, c.total, c.data.len()), (9, 0, 8160, 8192, 0));
327        let ir = user_ir_read(9);
328        assert_eq!(hex(&ir[0]), "F0 00 21 7A 70 10 00 09 00 00 00 00 00 00 00 00 00 00 01 00 00 F7");
329
330        // the replies carry the data at the requested offsets, like an upload
331        let data: Vec<f32> = (0..UPLOAD_FLOATS).map(|i| i as f32 * 0.25).collect();
332        let mut r = Reassembler::default();
333        let mut out = None;
334        for f in data_frames(Cmd::IrData, 9, IR_DATA_SUB, &floats_to_bytes(&data)) {
335            let Msg::Nep { payload, .. } = Msg::parse(&f) else { panic!() };
336            out = r.push(&Chunk::parse(&payload).unwrap());
337        }
338        assert_eq!(out, Some((9, data)));
339    }
340
341    #[test]
342    fn chunking() {
343        let data: Vec<f32> = (0..UPLOAD_FLOATS).map(|i| i as f32 * 0.5).collect();
344        let frames = data_frames(Cmd::UserAmp, 2, amp_sub::DATA, &floats_to_bytes(&data));
345        assert_eq!(frames.len(), 61);
346        let mut r = Reassembler::default();
347        let mut out = None;
348        for f in &frames {
349            let Msg::Nep { cmd: 0x58, dir: 1, payload } = Msg::parse(f) else { panic!() };
350            let c = Chunk::parse(&payload).unwrap();
351            assert_eq!((c.slot, c.sub, c.total), (2, 1, 8192));
352            out = r.push(&c);
353        }
354        assert_eq!(out, Some((2, data)));
355        // last chunk: offset 8160, 32 bytes
356        let Msg::Nep { payload, .. } = Msg::parse(frames.last().unwrap()) else { panic!() };
357        let c = Chunk::parse(&payload).unwrap();
358        assert_eq!((c.offset, c.data.len()), (8160, 32));
359    }
360
361    #[test]
362    fn info_round_trip() {
363        let i = UserAmpInfo::new(2, "Jcm800", 1.0);
364        let Msg::Nep { payload, .. } = Msg::parse(&i.write_frame()) else { panic!() };
365        let p = UserAmpInfo::parse(&payload).unwrap();
366        assert_eq!(p, UserAmpInfo { raw: i.to_raw(), ..i });
367        assert_eq!(hex(&user_amp_delete(0)), "F0 00 21 7A 70 58 01 00 00 18 00 00 00 00 00 00 00 00 00 00 00 F7");
368    }
369
370    /// A rename is the import's name record on its own: the AMP slot-info write that starts an
371    /// import, the IR name write that ends one (`Device::rename_user_amp` / `rename_user_ir`).
372    #[test]
373    fn rename_is_the_imports_name_record() {
374        let data = vec![0.25f32; UPLOAD_FLOATS];
375        let amp = user_amp_upload(&UserAmpInfo::new(4, "SVT G10 .5", 1.0), &data);
376        assert_eq!(UserAmpInfo::new(4, "SVT G10 .5", 1.0).write_frame(), amp[0]);
377        let ir = user_ir_upload(7, "SVT Neumann .5", &data);
378        assert_eq!(&user_ir_name(7, "SVT Neumann .5"), ir.last().unwrap());
379        // over-long and non-ASCII names: cut to 31 characters, '?' for anything else
380        let frame = UserAmpInfo::new(0, &"é".repeat(40), 1.0).write_frame();
381        let Msg::Nep { payload, .. } = Msg::parse(&frame) else { panic!() };
382        assert_eq!(UserAmpInfo::parse(&payload).unwrap().name, "?".repeat(31));
383    }
384
385}