Skip to main content

deepmind_midi/program/
mod.rs

1//! A program: the 242 bytes that are one sound, and the types that read them.
2//!
3//! A [`Program`] holds a dump exactly as the synthesizer sent it and lends every
4//! byte a name. The parameter layer says what each byte means; this layer is
5//! where the bytes live.
6//!
7//! ```
8//! use deepmind_midi::ids::ProtocolVersion;
9//! use deepmind_midi::param::ParamId;
10//! use deepmind_midi::program::{LfoShape, Program, ProgramName};
11//!
12//! let mut program = Program::new(ProtocolVersion::V6);
13//! program.set_name(ProgramName::new("Bass Sweep")?);
14//! program.set_lfo1_shape(LfoShape::Triangle);
15//! program.set_vcf_frequency(200);
16//!
17//! assert_eq!(program.name().as_str(), "Bass Sweep");
18//! assert_eq!(program.lfo1_shape(), Some(LfoShape::Triangle));
19//! assert_eq!(program.get(ParamId::VcfFrequency), 200);
20//! # Ok::<(), deepmind_midi::Error>(())
21//! ```
22//!
23//! # The bytes are what is stored
24//!
25//! A program is its dump, not a decoded copy of one. Reading is a lookup and
26//! writing is a byte, so a dump that goes in comes out unchanged. That includes
27//! the reserved bytes a comms protocol version 7 dump carries, and any value no
28//! table lists, which hardware may send and a library must not lose.
29//!
30//! It is also why the typed accessors answer `Option` for a parameter with a
31//! value table. `None` means the byte is not one the table names; the byte is
32//! still there, and [`Program::get`] returns it.
33//!
34//! # Firmware
35//!
36//! Three value tables were renumbered by firmware 1.1, and nothing in a stored
37//! program says which firmware wrote it. The generated accessors assume
38//! [`DEFAULT_FIRMWARE`]. Where the host knows better,
39//! [`ModSource::from_raw_for`] and its neighbours take the version a device
40//! inquiry reported, and [`Program::get`] hands them the byte.
41//!
42//! # Getting one on and off the wire
43//!
44//! [`Program::from_dump`] takes the two messages that carry a program.
45//! [`Program::pack_into`] is the way back, into a buffer a [`Message`] can
46//! borrow:
47//!
48//! ```
49//! use deepmind_midi::ids::{DeviceId, ProtocolVersion};
50//! use deepmind_midi::program::Program;
51//! use deepmind_midi::sysex::{Frame, Message};
52//!
53//! let program = Program::new(ProtocolVersion::V6);
54//!
55//! let mut packed = [0; Program::PACKED_MAX_LEN];
56//! let len = program.pack_into(&mut packed)?;
57//! let frame = Frame::new(
58//!     DeviceId::Unit(0),
59//!     Message::EditBufferDumpResponse {
60//!         version: program.version(),
61//!         packed: packed.get(..len).unwrap_or_default(),
62//!     },
63//! );
64//!
65//! let mut bytes = [0; 320];
66//! let len = frame.encode_into(&mut bytes)?;
67//! assert_eq!(bytes.get(..2), Some(&[0xF0, 0x00][..]));
68//! # Ok::<(), deepmind_midi::Error>(())
69//! ```
70//!
71//! # Serde
72//!
73//! Under the `serde` feature a [`Program`] is two fields: `version`, the comms
74//! protocol version, and `data`, the unpacked dump as a byte string.
75//! [`ProgramName`] is a string, and the value types are their variant names.
76//! Reading a program back goes through [`Program::from_bytes`], so the length
77//! rule holds for one that came out of a file. A host that would rather embed the
78//! raw dump has [`Program::as_bytes`] and [`Program::from_bytes`] directly.
79
80mod generated;
81mod name;
82#[cfg(feature = "serde")]
83mod serde;
84
85// The generated module is this module's other half: it holds a type per value
86// table and a pair of accessors per parameter, both of which are this module's
87// public surface. Naming its twenty-two value types here would be a list to keep
88// in step by hand, and a table added to `spec/` would go missing from the API
89// rather than fail to build.
90pub use generated::*;
91pub use name::ProgramName;
92
93use core::fmt;
94
95use crate::effect::{Algorithm, Engine};
96use crate::error::{Error, Result};
97use crate::ids::{PROGRAMS_PER_BANK, ProgramNumber, ProtocolVersion};
98use crate::param::{DEFAULT_FIRMWARE, PARAMETER_COUNT, ParamId};
99use crate::sysex::inquiry::Version;
100use crate::sysex::{Command, Message, PROGRAM_NAME_LEN, packed};
101
102/// One program: a sound, as the synthesizer stores and sends it.
103///
104/// See the [module documentation](self) for what it is and how it travels.
105#[derive(Clone, PartialEq, Eq, Hash)]
106pub struct Program {
107    version: ProtocolVersion,
108    data: [u8; Program::MAX_LEN],
109}
110
111impl Program {
112    /// Bytes the longest documented program carries.
113    ///
114    /// A comms protocol version 7 program; a version 6 program is three bytes
115    /// shorter and those three bytes are the reserved ones.
116    pub const MAX_LEN: usize = ProtocolVersion::V7.program_data_len();
117
118    /// Bytes [`Program::pack_into`] needs at most.
119    pub const PACKED_MAX_LEN: usize = packed::packed_len(Self::MAX_LEN);
120
121    /// Builds a program with every parameter at the lowest value it accepts.
122    ///
123    /// Not the initialised program the synthesizer's INIT button loads, which is
124    /// a factory sound this specification does not record. It is a program that
125    /// every parameter accepts, which is what building one from nothing needs.
126    ///
127    #[must_use]
128    pub fn new(version: ProtocolVersion) -> Self {
129        let mut program = Self {
130            version,
131            data: [0; Self::MAX_LEN],
132        };
133        for parameter in ParamId::ALL.iter().copied() {
134            let min = u8::try_from(parameter.min()).unwrap_or(0);
135            program.set_clamped(parameter, min);
136        }
137        program
138    }
139
140    /// Reads a program from the bytes of an unpacked dump.
141    ///
142    /// Nothing is checked beyond the length. A value outside what its parameter
143    /// accepts is kept and reported by [`Program::invalid`], since the
144    /// synthesizer is the authority on what it holds.
145    ///
146    /// # Errors
147    ///
148    /// Returns [`Error::ProgramLength`] when `bytes` is not as long as that
149    /// version's program.
150    pub fn from_bytes(version: ProtocolVersion, bytes: &[u8]) -> Result<Self> {
151        let expected = version.program_data_len();
152        if bytes.len() != expected {
153            return Err(Error::ProgramLength {
154                expected,
155                found: bytes.len(),
156            });
157        }
158        let mut data = [0; Self::MAX_LEN];
159        for (slot, byte) in data.iter_mut().zip(bytes) {
160            *slot = *byte;
161        }
162        Ok(Self { version, data })
163    }
164
165    /// Reads a program from the packed payload of a dump.
166    ///
167    /// A packed run is padded to a multiple of eight bytes, so it can carry up
168    /// to six bytes more than the program needs; the version says how much of
169    /// it is the program and the rest is dropped. That is the same rule
170    /// [`Frame::parse`](crate::sysex::Frame::parse) applies to a program dump,
171    /// so a frame that parses is a program that decodes.
172    ///
173    /// # Errors
174    ///
175    /// Returns [`Error::PackedRunLength`] for a run that cannot be unpacked and
176    /// [`Error::ProgramLength`] for one that unpacks to fewer bytes than this
177    /// version's program, or to a whole group more.
178    pub fn from_packed(version: ProtocolVersion, packed: &[u8]) -> Result<Self> {
179        let expected = version.program_data_len();
180        let found = packed::unpacked_len(packed.len())?;
181        if found < expected || found >= expected + packed::RAW_GROUP {
182            return Err(Error::ProgramLength { expected, found });
183        }
184        // Room for the padding of a last group, which is dropped.
185        let mut scratch = [0; Self::MAX_LEN + packed::RAW_GROUP - 1];
186        packed::unpack_into(packed, &mut scratch)?;
187        let mut data = [0; Self::MAX_LEN];
188        for (slot, byte) in data.iter_mut().zip(scratch).take(expected) {
189            *slot = byte;
190        }
191        Ok(Self { version, data })
192    }
193
194    /// Reads a program from the message that carried it.
195    ///
196    /// Both dumps that carry a program are accepted: one stored in a bank, and
197    /// the edit buffer.
198    ///
199    /// # Errors
200    ///
201    /// Returns [`Error::NotAProgramDump`] for any other message, and whatever
202    /// [`Program::from_packed`] returns for the payload.
203    pub fn from_dump(message: &Message<'_>) -> Result<Self> {
204        match *message {
205            Message::ProgramDumpResponse {
206                version, packed, ..
207            }
208            | Message::EditBufferDumpResponse { version, packed } => {
209                Self::from_packed(version, packed)
210            }
211            other => Err(Error::NotAProgramDump(other.command().to_byte())),
212        }
213    }
214
215    /// Returns the comms protocol version this program is stored in.
216    #[must_use]
217    pub const fn version(&self) -> ProtocolVersion {
218        self.version
219    }
220
221    /// Returns the program as an unpacked dump.
222    #[must_use]
223    pub fn as_bytes(&self) -> &[u8] {
224        self.data.get(..self.data_len()).unwrap_or(&self.data)
225    }
226
227    /// Returns the bytes past the last parameter.
228    ///
229    /// Empty under comms protocol version 6. Version 7 adds three reserved
230    /// bytes, which are zero in every factory program examined and are carried
231    /// through rather than decoded.
232    #[must_use]
233    pub fn reserved(&self) -> &[u8] {
234        self.as_bytes().get(PARAMETER_COUNT..).unwrap_or_default()
235    }
236
237    /// Returns the number of bytes [`Program::pack_into`] writes.
238    #[must_use]
239    pub fn packed_len(&self) -> usize {
240        packed::packed_len(self.data_len())
241    }
242
243    /// Packs the program into `out`, ready for a dump message to borrow.
244    ///
245    /// # Errors
246    ///
247    /// Returns [`Error::BufferTooSmall`] when `out` is shorter than
248    /// [`Program::packed_len`].
249    pub fn pack_into(&self, out: &mut [u8]) -> Result<usize> {
250        packed::pack_into(self.as_bytes(), out)
251    }
252
253    /// Returns the raw value of one parameter.
254    #[must_use]
255    pub fn get(&self, parameter: ParamId) -> u8 {
256        self.data
257            .get(usize::from(parameter.offset()))
258            .copied()
259            .unwrap_or(0)
260    }
261
262    /// Returns the algorithm an effect engine is running, on
263    /// [`DEFAULT_FIRMWARE`].
264    ///
265    /// The join between the twelve raw bytes the engine holds and what they
266    /// mean: [`Algorithm::slots`] says what each of them is, and
267    /// [`Engine::slot_parameter`] which byte to read.
268    ///
269    /// `None` when the stored byte names no algorithm, which a program written
270    /// on a firmware this one does not describe can do.
271    ///
272    /// ```
273    /// use deepmind_midi::effect::Engine;
274    /// use deepmind_midi::ids::ProtocolVersion;
275    /// use deepmind_midi::param::ParamId;
276    /// use deepmind_midi::program::Program;
277    ///
278    /// let mut program = Program::new(ProtocolVersion::V7);
279    /// program.set(ParamId::Fx1Type, 2)?;                 // a Room Reverb
280    ///
281    /// let room = program.algorithm(Engine::One).expect("byte 2 names one");
282    /// assert_eq!(room.full_name, "Room Reverb");
283    /// assert_eq!(room.slot(3).map(|slot| slot.title), Some("Size"));
284    /// # Ok::<(), deepmind_midi::Error>(())
285    /// ```
286    #[must_use]
287    pub fn algorithm(&self, engine: Engine) -> Option<&'static Algorithm> {
288        self.algorithm_for(engine, DEFAULT_FIRMWARE)
289    }
290
291    /// Returns the algorithm an effect engine is running, on the firmware a
292    /// device inquiry reported.
293    ///
294    /// Use this wherever [`ParamId::label_for`] applies: firmware 1.1 inserted an
295    /// algorithm rather than appending one, so byte 33 is Rotary Speaker on 1.0
296    /// and Vintage Pitch on 1.1, and every slot of the panel follows from which
297    /// of the two it is.
298    #[must_use]
299    pub fn algorithm_for(&self, engine: Engine, firmware: Version) -> Option<&'static Algorithm> {
300        Algorithm::for_value(self.get(engine.algorithm_parameter()), firmware)
301    }
302
303    /// Sets one parameter, refusing a value it does not accept.
304    ///
305    /// # Errors
306    ///
307    /// Returns [`Error::ValueOutOfRange`] when the parameter does not accept the
308    /// value. [`Program::set_clamped`] is there for callers that would rather
309    /// bend the value than refuse it.
310    pub fn set(&mut self, parameter: ParamId, value: u8) -> Result<()> {
311        if !parameter.accepts(u16::from(value)) {
312            return Err(Error::ValueOutOfRange {
313                parameter: parameter.offset(),
314                value: u16::from(value),
315                max: parameter.max(),
316            });
317        }
318        self.write(parameter, value);
319        Ok(())
320    }
321
322    /// Sets one parameter, bringing the value inside its range first.
323    ///
324    /// Returns what was stored. This is what the generated accessors use, since
325    /// a `u8` reaches values a parameter does not.
326    pub fn set_clamped(&mut self, parameter: ParamId, value: u8) -> u8 {
327        // Every parameter's range fits in the byte it occupies in a dump, so the
328        // clamped value is always a byte.
329        let clamped = u8::try_from(parameter.clamp(u16::from(value))).unwrap_or(value);
330        self.write(parameter, clamped);
331        clamped
332    }
333
334    /// Returns every parameter and the value it holds, in offset order.
335    pub fn values(&self) -> impl Iterator<Item = (ParamId, u8)> + '_ {
336        ParamId::ALL
337            .iter()
338            .copied()
339            .map(move |parameter| (parameter, self.get(parameter)))
340    }
341
342    /// Returns the parameters whose values differ, and what `target` holds.
343    ///
344    /// The list of edits that turn this program into `target`.
345    /// [`ParamId::edit`] turns one into the NRPN message that sends it.
346    ///
347    /// ```
348    /// use deepmind_midi::ids::ProtocolVersion;
349    /// use deepmind_midi::param::ParamId;
350    /// use deepmind_midi::program::Program;
351    ///
352    /// let before = Program::new(ProtocolVersion::V6);
353    /// let mut after = before.clone();
354    /// after.set_lfo1_rate(64);
355    ///
356    /// let changed: Vec<_> = before.changes(&after).collect();
357    /// assert_eq!(changed, [(ParamId::Lfo1Rate, 64)]);
358    /// # Ok::<(), deepmind_midi::Error>(())
359    /// ```
360    pub fn changes<'a>(&'a self, target: &'a Self) -> impl Iterator<Item = (ParamId, u8)> + 'a {
361        ParamId::ALL.iter().copied().filter_map(move |parameter| {
362            let value = target.get(parameter);
363            (self.get(parameter) != value).then_some((parameter, value))
364        })
365    }
366
367    /// Returns the parameters holding a value they do not accept.
368    ///
369    /// Empty for anything the synthesizer sent, on the evidence so far. A dump
370    /// read from a file is another matter.
371    pub fn invalid(&self) -> impl Iterator<Item = (ParamId, u8)> + '_ {
372        self.values()
373            .filter(|(parameter, value)| !parameter.accepts(u16::from(*value)))
374    }
375
376    /// Returns whether every parameter holds a value it accepts.
377    ///
378    /// # Errors
379    ///
380    /// Returns [`Error::ValueOutOfRange`] for the first parameter that does not,
381    /// in offset order. [`Program::invalid`] lists them all.
382    pub fn validate(&self) -> Result<()> {
383        match self.invalid().next() {
384            None => Ok(()),
385            Some((parameter, value)) => Err(Error::ValueOutOfRange {
386                parameter: parameter.offset(),
387                value: u16::from(value),
388                max: parameter.max(),
389            }),
390        }
391    }
392
393    /// Returns the program's name.
394    #[must_use]
395    pub fn name(&self) -> ProgramName {
396        let start = usize::from(NAME_OFFSET);
397        ProgramName::from_field(
398            self.data
399                .get(start..start.saturating_add(NAME_LEN))
400                .unwrap_or_default(),
401        )
402    }
403
404    /// Sets the program's name.
405    ///
406    /// [`ProgramName::new`] is where a string becomes one of these, and where a
407    /// string that cannot be a program name is refused.
408    pub fn set_name(&mut self, name: ProgramName) {
409        let start = usize::from(NAME_OFFSET);
410        let field = self
411            .data
412            .get_mut(start..start.saturating_add(NAME_LEN))
413            .unwrap_or_default();
414        for (slot, byte) in field
415            .iter_mut()
416            .zip(name.as_bytes().iter().copied().chain(core::iter::repeat(0)))
417        {
418            *slot = byte;
419        }
420    }
421
422    /// Returns the program's transposition in semitones, -48 to 48.
423    ///
424    /// The one parameter that does not start at zero: the manual gives it as 80
425    /// to 176 for -48 to +48, so the value it carries is its distance from the
426    /// middle of that range. A byte outside 80 to 176, which
427    /// [`invalid`](Program::invalid) reports, is clamped to the nearer end.
428    #[must_use]
429    pub fn transpose(&self) -> i8 {
430        let raw = i16::from(self.get(ParamId::ProgramTranspose));
431        i8::try_from((raw - i16::from(transpose_centre())).clamp(-48, 48)).unwrap_or(0)
432    }
433
434    /// Sets the program's transposition in semitones.
435    ///
436    /// # Errors
437    ///
438    /// Returns [`Error::ValueOutOfRange`] outside -48 to 48.
439    pub fn set_transpose(&mut self, semitones: i8) -> Result<()> {
440        let raw = i16::from(transpose_centre()) + i16::from(semitones);
441        let raw = u8::try_from(raw).unwrap_or(0);
442        self.set(ParamId::ProgramTranspose, raw)
443    }
444
445    /// Returns the length of this program's dump.
446    fn data_len(&self) -> usize {
447        self.version.program_data_len()
448    }
449
450    /// Writes one byte, at an offset the parameter table guarantees is inside
451    /// the program.
452    fn write(&mut self, parameter: ParamId, value: u8) {
453        if let Some(slot) = self.data.get_mut(usize::from(parameter.offset())) {
454            *slot = value;
455        }
456    }
457}
458
459/// Returns the raw value that transposes by nothing, which is the middle of the
460/// parameter's range.
461fn transpose_centre() -> u8 {
462    let parameter = ParamId::ProgramTranspose;
463    u8::try_from(parameter.min().midpoint(parameter.max())).unwrap_or(0)
464}
465
466impl fmt::Debug for Program {
467    /// Names the program rather than listing 242 bytes.
468    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469        f.debug_struct("Program")
470            .field("version", &self.version)
471            .field("name", &self.name())
472            .finish_non_exhaustive()
473    }
474}
475
476impl fmt::Display for Program {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        fmt::Display::fmt(&self.name(), f)
479    }
480}
481
482/// The names of the 128 programs in one bank, as the bank names dump carries
483/// them.
484///
485/// Sixteen bytes each, borrowed where they lie. The dump answers a whole bank at
486/// once, which is how a host fills a program list without asking for 128
487/// programs.
488///
489/// ```
490/// use deepmind_midi::ids::ProgramNumber;
491/// use deepmind_midi::program::BankNames;
492///
493/// let mut unpacked = [0; BankNames::LEN];
494/// unpacked.get_mut(..4).unwrap_or_default().copy_from_slice(b"Bass");
495///
496/// let names = BankNames::new(&unpacked)?;
497/// assert_eq!(names.get(ProgramNumber::new(0)?).as_str(), "Bass");
498/// assert_eq!(names.iter().count(), BankNames::COUNT);
499/// # Ok::<(), deepmind_midi::Error>(())
500/// ```
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
502pub struct BankNames<'a> {
503    unpacked: &'a [u8],
504}
505
506impl<'a> BankNames<'a> {
507    /// Names one dump carries, which is every program in a bank.
508    pub const COUNT: usize = PROGRAMS_PER_BANK as usize;
509
510    /// Bytes the unpacked dump holds.
511    pub const LEN: usize = PROGRAM_NAME_LEN * Self::COUNT;
512
513    /// Reads the names out of an unpacked bank names dump.
514    ///
515    /// # Errors
516    ///
517    /// Returns [`Error::PayloadLength`] when `unpacked` is not [`BankNames::LEN`]
518    /// bytes, naming the bank program names dump as the command.
519    pub fn new(unpacked: &'a [u8]) -> Result<Self> {
520        if unpacked.len() != Self::LEN {
521            return Err(Error::PayloadLength {
522                command: Command::BankProgramNamesDumpResponse.to_byte(),
523                expected: Self::LEN,
524                found: unpacked.len(),
525            });
526        }
527        Ok(Self { unpacked })
528    }
529
530    /// Returns one program's name.
531    #[must_use]
532    pub fn get(&self, program: ProgramNumber) -> ProgramName {
533        let start = usize::from(program.get()) * PROGRAM_NAME_LEN;
534        ProgramName::from_field(
535            self.unpacked
536                .get(start..start.saturating_add(PROGRAM_NAME_LEN))
537                .unwrap_or_default(),
538        )
539    }
540
541    /// Returns every name, in program order.
542    pub fn iter(&self) -> impl Iterator<Item = ProgramName> + '_ {
543        self.unpacked
544            .chunks_exact(PROGRAM_NAME_LEN)
545            .map(ProgramName::from_field)
546    }
547}
548
549#[cfg(test)]
550#[expect(
551    clippy::expect_used,
552    reason = "a failed expectation is the test failure"
553)]
554mod tests {
555    use super::*;
556    use crate::ids::Bank;
557    use crate::param::Group;
558    use crate::sysex::inquiry::Version;
559
560    /// Firmware 1.0, which numbers three value tables differently.
561    const FIRMWARE_1_0: Version = Version { major: 1, minor: 0 };
562
563    fn program() -> Program {
564        Program::new(ProtocolVersion::V6)
565    }
566
567    /// Seventeen parameters holding a character each are one word to whoever
568    /// is reading them, and a host has to know which seventeen.
569    #[test]
570    fn the_name_is_the_parameters_at_the_offsets_the_field_occupies() {
571        assert_eq!(NAME_PARAMETERS.len(), NAME_LEN);
572        assert_eq!(
573            NAME_PARAMETERS.first().map(|parameter| parameter.offset()),
574            Some(NAME_OFFSET)
575        );
576        for (index, parameter) in NAME_PARAMETERS.iter().enumerate() {
577            let offset = NAME_OFFSET + u8::try_from(index).expect("seventeen fit in a byte");
578            assert_eq!(parameter.offset(), offset);
579            assert_eq!(parameter.group(), Group::Program);
580        }
581
582        // The seventeenth byte is the terminator and belongs to the field
583        // rather than to the name.
584        assert_eq!(NAME_PARAMETERS.len(), ProgramName::MAX_CHARS + 1);
585    }
586
587    /// A keystroke costs one message to the one character it moved, which is
588    /// what makes drawing the seventeen as one field free.
589    #[test]
590    fn naming_a_program_moves_only_the_characters_that_changed() {
591        let mut program = program();
592        program.set_name(ProgramName::new("Bass").expect("a name the display can write"));
593
594        let mut renamed = program.clone();
595        renamed.set_name(ProgramName::new("Bassy").expect("a name the display can write"));
596
597        assert!(
598            program
599                .changes(&renamed)
600                .eq([(ParamId::ProgramNameChar5, b'y')]),
601            "one character moved"
602        );
603        assert!(
604            program
605                .changes(&renamed)
606                .all(|(parameter, _)| NAME_PARAMETERS.contains(&parameter))
607        );
608    }
609
610    #[test]
611    fn a_dump_survives_the_round_trip_byte_for_byte() {
612        let mut bytes = [0; PARAMETER_COUNT];
613        for (offset, byte) in bytes.iter_mut().enumerate() {
614            // Every byte pattern, including values no parameter accepts.
615            *byte = u8::try_from(offset).unwrap_or(0).wrapping_mul(7);
616        }
617        let program = Program::from_bytes(ProtocolVersion::V6, &bytes).expect("a v6 program");
618        assert_eq!(program.as_bytes(), bytes);
619
620        let mut packed = [0; Program::PACKED_MAX_LEN];
621        let len = program.pack_into(&mut packed).expect("room to pack");
622        let read = Program::from_packed(ProtocolVersion::V6, packed.get(..len).expect("packed"))
623            .expect("a v6 program");
624        assert_eq!(read, program);
625    }
626
627    /// A packed run is padded to a multiple of eight, so 242 bytes travel as
628    /// 280 and the last three are not the program's.
629    #[test]
630    fn padding_on_the_wire_is_not_part_of_the_program() {
631        let program = program();
632        assert_eq!(program.as_bytes().len(), 242);
633        assert_eq!(program.packed_len(), 280);
634
635        let mut packed = [0xFF; Program::PACKED_MAX_LEN];
636        let len = program.pack_into(&mut packed).expect("room to pack");
637        assert_eq!(len, 280);
638        let read = Program::from_packed(ProtocolVersion::V6, packed.get(..len).expect("packed"))
639            .expect("a v6 program");
640        assert_eq!(read, program);
641    }
642
643    #[test]
644    fn version_seven_keeps_its_reserved_bytes() {
645        let mut bytes = [0; 245];
646        for (index, byte) in bytes.iter_mut().enumerate().skip(PARAMETER_COUNT) {
647            *byte = u8::try_from(index).unwrap_or(0);
648        }
649        let seven = Program::from_bytes(ProtocolVersion::V7, &bytes).expect("a v7 program");
650        assert_eq!(seven.reserved(), &[242, 243, 244]);
651        assert_eq!(seven.as_bytes(), bytes);
652        assert!(program().reserved().is_empty());
653    }
654
655    /// Every parameter's range fits in the byte it occupies, over every byte a
656    /// caller can offer. The clamp relies on it, and 242 rows are too many to
657    /// take on trust.
658    #[test]
659    fn clamping_lands_inside_every_parameters_range() {
660        let mut program = program();
661        for parameter in ParamId::ALL.iter().copied() {
662            for value in 0..=u8::MAX {
663                let stored = program.set_clamped(parameter, value);
664                assert_eq!(program.get(parameter), stored);
665                assert!(
666                    parameter.accepts(u16::from(stored)),
667                    "{parameter} clamped {value} to {stored}"
668                );
669            }
670        }
671    }
672
673    #[test]
674    fn a_dump_of_the_wrong_length_is_refused() {
675        assert_eq!(
676            Program::from_bytes(ProtocolVersion::V6, &[0; 240]),
677            Err(Error::ProgramLength {
678                expected: 242,
679                found: 240,
680            })
681        );
682    }
683
684    /// A run that unpacks to more than the program is the padding of a last
685    /// group, up to six bytes; a whole group more is not a program.
686    #[test]
687    fn a_packed_run_may_carry_the_padding_of_its_last_group_and_no_more() {
688        let program = program();
689        let mut packed = [0; Program::PACKED_MAX_LEN + packed::PACKED_GROUP];
690        let len = program.pack_into(&mut packed).expect("room to pack");
691        // 242 bytes pack to 280, which unpack to 245: three bytes of padding.
692        assert_eq!(len, 280);
693        assert_eq!(
694            Program::from_packed(ProtocolVersion::V6, packed.get(..len).expect("in range")),
695            Ok(program.clone())
696        );
697        // One more group, unpacking to 252, is more than the padding.
698        assert_eq!(
699            Program::from_packed(
700                ProtocolVersion::V6,
701                packed.get(..len + packed::PACKED_GROUP).expect("in range")
702            ),
703            Err(Error::ProgramLength {
704                expected: 242,
705                found: 252,
706            })
707        );
708        // Two bytes short of a group is still short of the program.
709        assert_eq!(
710            Program::from_packed(
711                ProtocolVersion::V6,
712                packed.get(..len - packed::PACKED_GROUP).expect("in range")
713            ),
714            Err(Error::ProgramLength {
715                expected: 242,
716                found: 238,
717            })
718        );
719    }
720
721    #[test]
722    fn transpose_is_clamped_to_the_range_the_manual_gives() {
723        let mut program = program();
724        program.set_clamped(ParamId::ProgramTranspose, 0);
725        assert_eq!(program.transpose(), -48);
726        program.set_clamped(ParamId::ProgramTranspose, 255);
727        assert_eq!(program.transpose(), 48);
728    }
729
730    #[test]
731    fn a_new_program_holds_what_every_parameter_accepts() {
732        let program = program();
733        assert_eq!(program.validate(), Ok(()));
734        assert_eq!(program.invalid().count(), 0);
735        // The one parameter that does not start at zero.
736        assert_eq!(program.program_transpose(), 80);
737        assert_eq!(program.transpose(), -48);
738    }
739
740    #[test]
741    fn a_value_outside_the_range_is_kept_but_reported() {
742        let mut bytes = [0; PARAMETER_COUNT];
743        // Offset 2 is LFO 1 Shape, which stops at 6.
744        *bytes.get_mut(2).expect("offset 2") = 9;
745        let program = Program::from_bytes(ProtocolVersion::V6, &bytes).expect("a v6 program");
746
747        assert_eq!(program.get(ParamId::Lfo1Shape), 9);
748        assert_eq!(program.lfo1_shape(), None);
749        assert!(
750            program
751                .invalid()
752                .eq([(ParamId::Lfo1Shape, 9), (ParamId::ProgramTranspose, 0)]),
753            "both out-of-range bytes are reported, in offset order"
754        );
755    }
756
757    #[test]
758    fn setting_refuses_what_clamping_bends() {
759        let mut program = program();
760        assert_eq!(
761            program.set(ParamId::Lfo1Shape, 9),
762            Err(Error::ValueOutOfRange {
763                parameter: 2,
764                value: 9,
765                max: 6,
766            })
767        );
768        assert_eq!(program.set_clamped(ParamId::Lfo1Shape, 9), 6);
769        assert_eq!(program.lfo1_shape(), Some(LfoShape::SampleAndGlide));
770    }
771
772    #[test]
773    fn the_typed_accessors_are_the_bytes_under_another_name() {
774        let mut program = program();
775        program.set_lfo1_shape(LfoShape::Square);
776        program.set_lfo1_key_sync(true);
777        program.set_vcf_frequency(128);
778
779        assert_eq!(program.get(ParamId::Lfo1Shape), 2);
780        assert_eq!(program.get(ParamId::Lfo1KeySync), 1);
781        assert_eq!(program.get(ParamId::VcfFrequency), 128);
782        assert!(program.lfo1_key_sync());
783        assert_eq!(program.vcf_frequency(), 128);
784    }
785
786    /// Firmware 1.1 renumbered the modulation sources, so the same byte is a
787    /// different source depending on which firmware wrote the program.
788    #[test]
789    fn a_renumbered_table_reads_by_firmware() {
790        let mut program = program();
791        program.set_mod1_source(ModSource::Expression);
792        let raw = program.get(ParamId::Mod1Source);
793
794        assert_eq!(raw, 6);
795        assert_eq!(program.mod1_source(), Some(ModSource::Expression));
796        assert_eq!(
797            ModSource::from_raw_for(raw, FIRMWARE_1_0),
798            Some(ModSource::Lfo1)
799        );
800        assert_eq!(ModSource::Expression.raw_for(FIRMWARE_1_0), None);
801        assert_eq!(ModSource::Lfo1.raw_for(FIRMWARE_1_0), Some(6));
802        assert_eq!(ModSource::Expression.name(), "Expression");
803        assert_eq!(ModSource::Expression.name_for(FIRMWARE_1_0), None);
804    }
805
806    #[test]
807    fn every_value_of_every_table_survives_the_round_trip() {
808        for source in ModSource::ALL.iter().copied() {
809            assert_eq!(ModSource::from_raw(source.raw()), Some(source));
810        }
811        for destination in ModDestination::ALL.iter().copied() {
812            assert_eq!(
813                ModDestination::from_raw(destination.raw()),
814                Some(destination)
815            );
816        }
817        for effect in FxType::ALL.iter().copied() {
818            assert_eq!(FxType::from_raw(effect.raw()), Some(effect));
819        }
820        for shape in LfoShape::ALL.iter().copied() {
821            assert_eq!(LfoShape::from_raw(shape.raw()), Some(shape));
822            assert_eq!(
823                Some(shape.name()),
824                shape.name_for(crate::param::DEFAULT_FIRMWARE)
825            );
826        }
827    }
828
829    #[test]
830    fn a_name_is_written_and_read_back() {
831        let mut program = program();
832        program.set_name(ProgramName::new("Bass Sweep").expect("a valid name"));
833
834        assert_eq!(program.name().as_str(), "Bass Sweep");
835        assert_eq!(program.get(ParamId::ProgramNameChar1), b'B');
836        // The terminator, and everything after it, is cleared.
837        assert_eq!(program.get(ParamId::ProgramNameChar11), 0);
838        assert_eq!(program.get(ParamId::ProgramNameChar17), 0);
839
840        program.set_name(ProgramName::new("A").expect("a valid name"));
841        assert_eq!(program.name().as_str(), "A");
842        assert_eq!(program.get(ParamId::ProgramNameChar2), 0);
843    }
844
845    #[test]
846    fn transposition_counts_from_the_middle_of_its_range() {
847        let mut program = program();
848        program.set_transpose(0).expect("no transposition");
849        assert_eq!(program.program_transpose(), 128);
850        assert_eq!(program.transpose(), 0);
851
852        program.set_transpose(48).expect("four octaves up");
853        assert_eq!(program.program_transpose(), 176);
854        assert_eq!(program.transpose(), 48);
855
856        assert!(program.set_transpose(49).is_err());
857        assert!(program.set_transpose(-49).is_err());
858    }
859
860    #[test]
861    fn changes_are_the_edits_that_close_the_gap() {
862        let before = program();
863        let mut after = before.clone();
864        after.set_lfo1_rate(64);
865        after.set_lfo1_shape(LfoShape::Square);
866
867        assert!(
868            before
869                .changes(&after)
870                .eq([(ParamId::Lfo1Rate, 64), (ParamId::Lfo1Shape, 2)]),
871            "both edits are reported, in offset order"
872        );
873
874        let mut applied = before.clone();
875        for (parameter, value) in before.changes(&after) {
876            applied.set(parameter, value).expect("a value it accepts");
877        }
878        assert_eq!(applied, after);
879        assert_eq!(before.changes(&before).count(), 0);
880    }
881
882    #[test]
883    fn a_dump_message_carries_a_program_and_nothing_else_does() {
884        let program = program();
885        let mut packed = [0; Program::PACKED_MAX_LEN];
886        let len = program.pack_into(&mut packed).expect("room to pack");
887        let packed = packed.get(..len).expect("packed");
888
889        let dump = Message::EditBufferDumpResponse {
890            version: ProtocolVersion::V6,
891            packed,
892        };
893        assert_eq!(Program::from_dump(&dump), Ok(program.clone()));
894
895        let stored = Message::ProgramDumpResponse {
896            version: ProtocolVersion::V6,
897            bank: Bank::new(0).expect("bank A"),
898            program: ProgramNumber::new(0).expect("program 0"),
899            packed,
900        };
901        assert_eq!(Program::from_dump(&stored), Ok(program));
902
903        assert_eq!(
904            Program::from_dump(&Message::EditBufferDumpRequest),
905            Err(Error::NotAProgramDump(0x03))
906        );
907    }
908
909    #[test]
910    fn a_bank_of_names_is_read_where_it_lies() {
911        let mut unpacked = [0; BankNames::LEN];
912        let first = unpacked.get_mut(..4).expect("the first name");
913        first.copy_from_slice(b"Bass");
914        let second = unpacked
915            .get_mut(PROGRAM_NAME_LEN..PROGRAM_NAME_LEN + 16)
916            .expect("the second name");
917        second.copy_from_slice(b"SixteenCharacter");
918        let names = BankNames::new(&unpacked).expect("a bank of names");
919
920        assert_eq!(
921            names
922                .get(ProgramNumber::new(0).expect("program 0"))
923                .as_str(),
924            "Bass"
925        );
926        // Sixteen bytes with no terminator is still a name.
927        assert_eq!(
928            names
929                .get(ProgramNumber::new(1).expect("program 1"))
930                .as_str(),
931            "SixteenCharacter"
932        );
933        assert_eq!(names.iter().count(), 128);
934        assert_eq!(
935            BankNames::new(&[0; 16]),
936            Err(Error::PayloadLength {
937                command: Command::BankProgramNamesDumpResponse.to_byte(),
938                expected: BankNames::LEN,
939                found: 16,
940            })
941        );
942    }
943}