deepmind-midi 26.5.2

Sans-IO protocol library for Behringer DeepMind synthesizers: SysEx, NRPN, programs and device state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! A program: the 242 bytes that are one sound, and the types that read them.
//!
//! A [`Program`] holds a dump exactly as the synthesizer sent it and lends every
//! byte a name. The parameter layer says what each byte means; this layer is
//! where the bytes live.
//!
//! ```
//! use deepmind_midi::ids::ProtocolVersion;
//! use deepmind_midi::param::ParamId;
//! use deepmind_midi::program::{LfoShape, Program, ProgramName};
//!
//! let mut program = Program::new(ProtocolVersion::V6);
//! program.set_name(ProgramName::new("Bass Sweep")?);
//! program.set_lfo1_shape(LfoShape::Triangle);
//! program.set_vcf_frequency(200);
//!
//! assert_eq!(program.name().as_str(), "Bass Sweep");
//! assert_eq!(program.lfo1_shape(), Some(LfoShape::Triangle));
//! assert_eq!(program.get(ParamId::VcfFrequency), 200);
//! # Ok::<(), deepmind_midi::Error>(())
//! ```
//!
//! # The bytes are what is stored
//!
//! A program is its dump, not a decoded copy of one. Reading is a lookup and
//! writing is a byte, so a dump that goes in comes out unchanged. That includes
//! the reserved bytes a comms protocol version 7 dump carries, and any value no
//! table lists, which hardware may send and a library must not lose.
//!
//! It is also why the typed accessors answer `Option` for a parameter with a
//! value table. `None` means the byte is not one the table names; the byte is
//! still there, and [`Program::get`] returns it.
//!
//! # Firmware
//!
//! Three value tables were renumbered by firmware 1.1, and nothing in a stored
//! program says which firmware wrote it. The generated accessors assume
//! [`DEFAULT_FIRMWARE`]. Where the host knows better,
//! [`ModSource::from_raw_for`] and its neighbours take the version a device
//! inquiry reported, and [`Program::get`] hands them the byte.
//!
//! # Getting one on and off the wire
//!
//! [`Program::from_dump`] takes the two messages that carry a program.
//! [`Program::pack_into`] is the way back, into a buffer a [`Message`] can
//! borrow:
//!
//! ```
//! use deepmind_midi::ids::{DeviceId, ProtocolVersion};
//! use deepmind_midi::program::Program;
//! use deepmind_midi::sysex::{Frame, Message};
//!
//! let program = Program::new(ProtocolVersion::V6);
//!
//! let mut packed = [0; Program::PACKED_MAX_LEN];
//! let len = program.pack_into(&mut packed)?;
//! let frame = Frame::new(
//!     DeviceId::Unit(0),
//!     Message::EditBufferDumpResponse {
//!         version: program.version(),
//!         packed: packed.get(..len).unwrap_or_default(),
//!     },
//! );
//!
//! let mut bytes = [0; 320];
//! let len = frame.encode_into(&mut bytes)?;
//! assert_eq!(bytes.get(..2), Some(&[0xF0, 0x00][..]));
//! # Ok::<(), deepmind_midi::Error>(())
//! ```
//!
//! # Serde
//!
//! Under the `serde` feature a [`Program`] is two fields: `version`, the comms
//! protocol version, and `data`, the unpacked dump as a byte string.
//! [`ProgramName`] is a string, and the value types are their variant names.
//! Reading a program back goes through [`Program::from_bytes`], so the length
//! rule holds for one that came out of a file. A host that would rather embed the
//! raw dump has [`Program::as_bytes`] and [`Program::from_bytes`] directly.

mod generated;
mod name;
#[cfg(feature = "serde")]
mod serde;

// The generated module is this module's other half: it holds a type per value
// table and a pair of accessors per parameter, both of which are this module's
// public surface. Naming its twenty-two value types here would be a list to keep
// in step by hand, and a table added to `spec/` would go missing from the API
// rather than fail to build.
pub use generated::*;
pub use name::ProgramName;

use core::fmt;

use crate::effect::{Algorithm, Engine};
use crate::error::{Error, Result};
use crate::ids::{PROGRAMS_PER_BANK, ProgramNumber, ProtocolVersion};
use crate::param::{DEFAULT_FIRMWARE, PARAMETER_COUNT, ParamId};
use crate::sysex::inquiry::Version;
use crate::sysex::{Command, Message, PROGRAM_NAME_LEN, packed};

/// One program: a sound, as the synthesizer stores and sends it.
///
/// See the [module documentation](self) for what it is and how it travels.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Program {
    version: ProtocolVersion,
    data: [u8; Program::MAX_LEN],
}

impl Program {
    /// Bytes the longest documented program carries.
    ///
    /// A comms protocol version 7 program; a version 6 program is three bytes
    /// shorter and those three bytes are the reserved ones.
    pub const MAX_LEN: usize = ProtocolVersion::V7.program_data_len();

    /// Bytes [`Program::pack_into`] needs at most.
    pub const PACKED_MAX_LEN: usize = packed::packed_len(Self::MAX_LEN);

    /// Builds a program with every parameter at the lowest value it accepts.
    ///
    /// Not the initialised program the synthesizer's INIT button loads, which is
    /// a factory sound this specification does not record. It is a program that
    /// every parameter accepts, which is what building one from nothing needs.
    ///
    #[must_use]
    pub fn new(version: ProtocolVersion) -> Self {
        let mut program = Self {
            version,
            data: [0; Self::MAX_LEN],
        };
        for parameter in ParamId::ALL.iter().copied() {
            let min = u8::try_from(parameter.min()).unwrap_or(0);
            program.set_clamped(parameter, min);
        }
        program
    }

    /// Reads a program from the bytes of an unpacked dump.
    ///
    /// Nothing is checked beyond the length. A value outside what its parameter
    /// accepts is kept and reported by [`Program::invalid`], since the
    /// synthesizer is the authority on what it holds.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ProgramLength`] when `bytes` is not as long as that
    /// version's program.
    pub fn from_bytes(version: ProtocolVersion, bytes: &[u8]) -> Result<Self> {
        let expected = version.program_data_len();
        if bytes.len() != expected {
            return Err(Error::ProgramLength {
                expected,
                found: bytes.len(),
            });
        }
        let mut data = [0; Self::MAX_LEN];
        for (slot, byte) in data.iter_mut().zip(bytes) {
            *slot = *byte;
        }
        Ok(Self { version, data })
    }

    /// Reads a program from the packed payload of a dump.
    ///
    /// A packed run is padded to a multiple of eight bytes, so it can carry up
    /// to six bytes more than the program needs; the version says how much of
    /// it is the program and the rest is dropped. That is the same rule
    /// [`Frame::parse`](crate::sysex::Frame::parse) applies to a program dump,
    /// so a frame that parses is a program that decodes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::PackedRunLength`] for a run that cannot be unpacked and
    /// [`Error::ProgramLength`] for one that unpacks to fewer bytes than this
    /// version's program, or to a whole group more.
    pub fn from_packed(version: ProtocolVersion, packed: &[u8]) -> Result<Self> {
        let expected = version.program_data_len();
        let found = packed::unpacked_len(packed.len())?;
        if found < expected || found >= expected + packed::RAW_GROUP {
            return Err(Error::ProgramLength { expected, found });
        }
        // Room for the padding of a last group, which is dropped.
        let mut scratch = [0; Self::MAX_LEN + packed::RAW_GROUP - 1];
        packed::unpack_into(packed, &mut scratch)?;
        let mut data = [0; Self::MAX_LEN];
        for (slot, byte) in data.iter_mut().zip(scratch).take(expected) {
            *slot = byte;
        }
        Ok(Self { version, data })
    }

    /// Reads a program from the message that carried it.
    ///
    /// Both dumps that carry a program are accepted: one stored in a bank, and
    /// the edit buffer.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotAProgramDump`] for any other message, and whatever
    /// [`Program::from_packed`] returns for the payload.
    pub fn from_dump(message: &Message<'_>) -> Result<Self> {
        match *message {
            Message::ProgramDumpResponse {
                version, packed, ..
            }
            | Message::EditBufferDumpResponse { version, packed } => {
                Self::from_packed(version, packed)
            }
            other => Err(Error::NotAProgramDump(other.command().to_byte())),
        }
    }

    /// Returns the comms protocol version this program is stored in.
    #[must_use]
    pub const fn version(&self) -> ProtocolVersion {
        self.version
    }

    /// Returns the program as an unpacked dump.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.data.get(..self.data_len()).unwrap_or(&self.data)
    }

    /// Returns the bytes past the last parameter.
    ///
    /// Empty under comms protocol version 6. Version 7 adds three reserved
    /// bytes, which are zero in every factory program examined and are carried
    /// through rather than decoded.
    #[must_use]
    pub fn reserved(&self) -> &[u8] {
        self.as_bytes().get(PARAMETER_COUNT..).unwrap_or_default()
    }

    /// Returns the number of bytes [`Program::pack_into`] writes.
    #[must_use]
    pub fn packed_len(&self) -> usize {
        packed::packed_len(self.data_len())
    }

    /// Packs the program into `out`, ready for a dump message to borrow.
    ///
    /// # Errors
    ///
    /// Returns [`Error::BufferTooSmall`] when `out` is shorter than
    /// [`Program::packed_len`].
    pub fn pack_into(&self, out: &mut [u8]) -> Result<usize> {
        packed::pack_into(self.as_bytes(), out)
    }

    /// Returns the raw value of one parameter.
    #[must_use]
    pub fn get(&self, parameter: ParamId) -> u8 {
        self.data
            .get(usize::from(parameter.offset()))
            .copied()
            .unwrap_or(0)
    }

    /// Returns the algorithm an effect engine is running, on
    /// [`DEFAULT_FIRMWARE`].
    ///
    /// The join between the twelve raw bytes the engine holds and what they
    /// mean: [`Algorithm::slots`] says what each of them is, and
    /// [`Engine::slot_parameter`] which byte to read.
    ///
    /// `None` when the stored byte names no algorithm, which a program written
    /// on a firmware this one does not describe can do.
    ///
    /// ```
    /// use deepmind_midi::effect::Engine;
    /// use deepmind_midi::ids::ProtocolVersion;
    /// use deepmind_midi::param::ParamId;
    /// use deepmind_midi::program::Program;
    ///
    /// let mut program = Program::new(ProtocolVersion::V7);
    /// program.set(ParamId::Fx1Type, 2)?;                 // a Room Reverb
    ///
    /// let room = program.algorithm(Engine::One).expect("byte 2 names one");
    /// assert_eq!(room.full_name, "Room Reverb");
    /// assert_eq!(room.slot(3).map(|slot| slot.title), Some("Size"));
    /// # Ok::<(), deepmind_midi::Error>(())
    /// ```
    #[must_use]
    pub fn algorithm(&self, engine: Engine) -> Option<&'static Algorithm> {
        self.algorithm_for(engine, DEFAULT_FIRMWARE)
    }

    /// Returns the algorithm an effect engine is running, on the firmware a
    /// device inquiry reported.
    ///
    /// Use this wherever [`ParamId::label_for`] applies: firmware 1.1 inserted an
    /// algorithm rather than appending one, so byte 33 is Rotary Speaker on 1.0
    /// and Vintage Pitch on 1.1, and every slot of the panel follows from which
    /// of the two it is.
    #[must_use]
    pub fn algorithm_for(&self, engine: Engine, firmware: Version) -> Option<&'static Algorithm> {
        Algorithm::for_value(self.get(engine.algorithm_parameter()), firmware)
    }

    /// Sets one parameter, refusing a value it does not accept.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ValueOutOfRange`] when the parameter does not accept the
    /// value. [`Program::set_clamped`] is there for callers that would rather
    /// bend the value than refuse it.
    pub fn set(&mut self, parameter: ParamId, value: u8) -> Result<()> {
        if !parameter.accepts(u16::from(value)) {
            return Err(Error::ValueOutOfRange {
                parameter: parameter.offset(),
                value: u16::from(value),
                max: parameter.max(),
            });
        }
        self.write(parameter, value);
        Ok(())
    }

    /// Sets one parameter, bringing the value inside its range first.
    ///
    /// Returns what was stored. This is what the generated accessors use, since
    /// a `u8` reaches values a parameter does not.
    pub fn set_clamped(&mut self, parameter: ParamId, value: u8) -> u8 {
        // Every parameter's range fits in the byte it occupies in a dump, so the
        // clamped value is always a byte.
        let clamped = u8::try_from(parameter.clamp(u16::from(value))).unwrap_or(value);
        self.write(parameter, clamped);
        clamped
    }

    /// Returns every parameter and the value it holds, in offset order.
    pub fn values(&self) -> impl Iterator<Item = (ParamId, u8)> + '_ {
        ParamId::ALL
            .iter()
            .copied()
            .map(move |parameter| (parameter, self.get(parameter)))
    }

    /// Returns the parameters whose values differ, and what `target` holds.
    ///
    /// The list of edits that turn this program into `target`.
    /// [`ParamId::edit`] turns one into the NRPN message that sends it.
    ///
    /// ```
    /// use deepmind_midi::ids::ProtocolVersion;
    /// use deepmind_midi::param::ParamId;
    /// use deepmind_midi::program::Program;
    ///
    /// let before = Program::new(ProtocolVersion::V6);
    /// let mut after = before.clone();
    /// after.set_lfo1_rate(64);
    ///
    /// let changed: Vec<_> = before.changes(&after).collect();
    /// assert_eq!(changed, [(ParamId::Lfo1Rate, 64)]);
    /// # Ok::<(), deepmind_midi::Error>(())
    /// ```
    pub fn changes<'a>(&'a self, target: &'a Self) -> impl Iterator<Item = (ParamId, u8)> + 'a {
        ParamId::ALL.iter().copied().filter_map(move |parameter| {
            let value = target.get(parameter);
            (self.get(parameter) != value).then_some((parameter, value))
        })
    }

    /// Returns the parameters holding a value they do not accept.
    ///
    /// Empty for anything the synthesizer sent, on the evidence so far. A dump
    /// read from a file is another matter.
    pub fn invalid(&self) -> impl Iterator<Item = (ParamId, u8)> + '_ {
        self.values()
            .filter(|(parameter, value)| !parameter.accepts(u16::from(*value)))
    }

    /// Returns whether every parameter holds a value it accepts.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ValueOutOfRange`] for the first parameter that does not,
    /// in offset order. [`Program::invalid`] lists them all.
    pub fn validate(&self) -> Result<()> {
        match self.invalid().next() {
            None => Ok(()),
            Some((parameter, value)) => Err(Error::ValueOutOfRange {
                parameter: parameter.offset(),
                value: u16::from(value),
                max: parameter.max(),
            }),
        }
    }

    /// Returns the program's name.
    #[must_use]
    pub fn name(&self) -> ProgramName {
        let start = usize::from(NAME_OFFSET);
        ProgramName::from_field(
            self.data
                .get(start..start.saturating_add(NAME_LEN))
                .unwrap_or_default(),
        )
    }

    /// Sets the program's name.
    ///
    /// [`ProgramName::new`] is where a string becomes one of these, and where a
    /// string that cannot be a program name is refused.
    pub fn set_name(&mut self, name: ProgramName) {
        let start = usize::from(NAME_OFFSET);
        let field = self
            .data
            .get_mut(start..start.saturating_add(NAME_LEN))
            .unwrap_or_default();
        for (slot, byte) in field
            .iter_mut()
            .zip(name.as_bytes().iter().copied().chain(core::iter::repeat(0)))
        {
            *slot = byte;
        }
    }

    /// Returns the program's transposition in semitones, -48 to 48.
    ///
    /// The one parameter that does not start at zero: the manual gives it as 80
    /// to 176 for -48 to +48, so the value it carries is its distance from the
    /// middle of that range. A byte outside 80 to 176, which
    /// [`invalid`](Program::invalid) reports, is clamped to the nearer end.
    #[must_use]
    pub fn transpose(&self) -> i8 {
        let raw = i16::from(self.get(ParamId::ProgramTranspose));
        i8::try_from((raw - i16::from(transpose_centre())).clamp(-48, 48)).unwrap_or(0)
    }

    /// Sets the program's transposition in semitones.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ValueOutOfRange`] outside -48 to 48.
    pub fn set_transpose(&mut self, semitones: i8) -> Result<()> {
        let raw = i16::from(transpose_centre()) + i16::from(semitones);
        let raw = u8::try_from(raw).unwrap_or(0);
        self.set(ParamId::ProgramTranspose, raw)
    }

    /// Returns the length of this program's dump.
    fn data_len(&self) -> usize {
        self.version.program_data_len()
    }

    /// Writes one byte, at an offset the parameter table guarantees is inside
    /// the program.
    fn write(&mut self, parameter: ParamId, value: u8) {
        if let Some(slot) = self.data.get_mut(usize::from(parameter.offset())) {
            *slot = value;
        }
    }
}

/// Returns the raw value that transposes by nothing, which is the middle of the
/// parameter's range.
fn transpose_centre() -> u8 {
    let parameter = ParamId::ProgramTranspose;
    u8::try_from(parameter.min().midpoint(parameter.max())).unwrap_or(0)
}

impl fmt::Debug for Program {
    /// Names the program rather than listing 242 bytes.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Program")
            .field("version", &self.version)
            .field("name", &self.name())
            .finish_non_exhaustive()
    }
}

impl fmt::Display for Program {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.name(), f)
    }
}

/// The names of the 128 programs in one bank, as the bank names dump carries
/// them.
///
/// Sixteen bytes each, borrowed where they lie. The dump answers a whole bank at
/// once, which is how a host fills a program list without asking for 128
/// programs.
///
/// ```
/// use deepmind_midi::ids::ProgramNumber;
/// use deepmind_midi::program::BankNames;
///
/// let mut unpacked = [0; BankNames::LEN];
/// unpacked.get_mut(..4).unwrap_or_default().copy_from_slice(b"Bass");
///
/// let names = BankNames::new(&unpacked)?;
/// assert_eq!(names.get(ProgramNumber::new(0)?).as_str(), "Bass");
/// assert_eq!(names.iter().count(), BankNames::COUNT);
/// # Ok::<(), deepmind_midi::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BankNames<'a> {
    unpacked: &'a [u8],
}

impl<'a> BankNames<'a> {
    /// Names one dump carries, which is every program in a bank.
    pub const COUNT: usize = PROGRAMS_PER_BANK as usize;

    /// Bytes the unpacked dump holds.
    pub const LEN: usize = PROGRAM_NAME_LEN * Self::COUNT;

    /// Reads the names out of an unpacked bank names dump.
    ///
    /// # Errors
    ///
    /// Returns [`Error::PayloadLength`] when `unpacked` is not [`BankNames::LEN`]
    /// bytes, naming the bank program names dump as the command.
    pub fn new(unpacked: &'a [u8]) -> Result<Self> {
        if unpacked.len() != Self::LEN {
            return Err(Error::PayloadLength {
                command: Command::BankProgramNamesDumpResponse.to_byte(),
                expected: Self::LEN,
                found: unpacked.len(),
            });
        }
        Ok(Self { unpacked })
    }

    /// Returns one program's name.
    #[must_use]
    pub fn get(&self, program: ProgramNumber) -> ProgramName {
        let start = usize::from(program.get()) * PROGRAM_NAME_LEN;
        ProgramName::from_field(
            self.unpacked
                .get(start..start.saturating_add(PROGRAM_NAME_LEN))
                .unwrap_or_default(),
        )
    }

    /// Returns every name, in program order.
    pub fn iter(&self) -> impl Iterator<Item = ProgramName> + '_ {
        self.unpacked
            .chunks_exact(PROGRAM_NAME_LEN)
            .map(ProgramName::from_field)
    }
}

#[cfg(test)]
#[expect(
    clippy::expect_used,
    reason = "a failed expectation is the test failure"
)]
mod tests {
    use super::*;
    use crate::ids::Bank;
    use crate::param::Group;
    use crate::sysex::inquiry::Version;

    /// Firmware 1.0, which numbers three value tables differently.
    const FIRMWARE_1_0: Version = Version { major: 1, minor: 0 };

    fn program() -> Program {
        Program::new(ProtocolVersion::V6)
    }

    /// Seventeen parameters holding a character each are one word to whoever
    /// is reading them, and a host has to know which seventeen.
    #[test]
    fn the_name_is_the_parameters_at_the_offsets_the_field_occupies() {
        assert_eq!(NAME_PARAMETERS.len(), NAME_LEN);
        assert_eq!(
            NAME_PARAMETERS.first().map(|parameter| parameter.offset()),
            Some(NAME_OFFSET)
        );
        for (index, parameter) in NAME_PARAMETERS.iter().enumerate() {
            let offset = NAME_OFFSET + u8::try_from(index).expect("seventeen fit in a byte");
            assert_eq!(parameter.offset(), offset);
            assert_eq!(parameter.group(), Group::Program);
        }

        // The seventeenth byte is the terminator and belongs to the field
        // rather than to the name.
        assert_eq!(NAME_PARAMETERS.len(), ProgramName::MAX_CHARS + 1);
    }

    /// A keystroke costs one message to the one character it moved, which is
    /// what makes drawing the seventeen as one field free.
    #[test]
    fn naming_a_program_moves_only_the_characters_that_changed() {
        let mut program = program();
        program.set_name(ProgramName::new("Bass").expect("a name the display can write"));

        let mut renamed = program.clone();
        renamed.set_name(ProgramName::new("Bassy").expect("a name the display can write"));

        assert!(
            program
                .changes(&renamed)
                .eq([(ParamId::ProgramNameChar5, b'y')]),
            "one character moved"
        );
        assert!(
            program
                .changes(&renamed)
                .all(|(parameter, _)| NAME_PARAMETERS.contains(&parameter))
        );
    }

    #[test]
    fn a_dump_survives_the_round_trip_byte_for_byte() {
        let mut bytes = [0; PARAMETER_COUNT];
        for (offset, byte) in bytes.iter_mut().enumerate() {
            // Every byte pattern, including values no parameter accepts.
            *byte = u8::try_from(offset).unwrap_or(0).wrapping_mul(7);
        }
        let program = Program::from_bytes(ProtocolVersion::V6, &bytes).expect("a v6 program");
        assert_eq!(program.as_bytes(), bytes);

        let mut packed = [0; Program::PACKED_MAX_LEN];
        let len = program.pack_into(&mut packed).expect("room to pack");
        let read = Program::from_packed(ProtocolVersion::V6, packed.get(..len).expect("packed"))
            .expect("a v6 program");
        assert_eq!(read, program);
    }

    /// A packed run is padded to a multiple of eight, so 242 bytes travel as
    /// 280 and the last three are not the program's.
    #[test]
    fn padding_on_the_wire_is_not_part_of_the_program() {
        let program = program();
        assert_eq!(program.as_bytes().len(), 242);
        assert_eq!(program.packed_len(), 280);

        let mut packed = [0xFF; Program::PACKED_MAX_LEN];
        let len = program.pack_into(&mut packed).expect("room to pack");
        assert_eq!(len, 280);
        let read = Program::from_packed(ProtocolVersion::V6, packed.get(..len).expect("packed"))
            .expect("a v6 program");
        assert_eq!(read, program);
    }

    #[test]
    fn version_seven_keeps_its_reserved_bytes() {
        let mut bytes = [0; 245];
        for (index, byte) in bytes.iter_mut().enumerate().skip(PARAMETER_COUNT) {
            *byte = u8::try_from(index).unwrap_or(0);
        }
        let seven = Program::from_bytes(ProtocolVersion::V7, &bytes).expect("a v7 program");
        assert_eq!(seven.reserved(), &[242, 243, 244]);
        assert_eq!(seven.as_bytes(), bytes);
        assert!(program().reserved().is_empty());
    }

    /// Every parameter's range fits in the byte it occupies, over every byte a
    /// caller can offer. The clamp relies on it, and 242 rows are too many to
    /// take on trust.
    #[test]
    fn clamping_lands_inside_every_parameters_range() {
        let mut program = program();
        for parameter in ParamId::ALL.iter().copied() {
            for value in 0..=u8::MAX {
                let stored = program.set_clamped(parameter, value);
                assert_eq!(program.get(parameter), stored);
                assert!(
                    parameter.accepts(u16::from(stored)),
                    "{parameter} clamped {value} to {stored}"
                );
            }
        }
    }

    #[test]
    fn a_dump_of_the_wrong_length_is_refused() {
        assert_eq!(
            Program::from_bytes(ProtocolVersion::V6, &[0; 240]),
            Err(Error::ProgramLength {
                expected: 242,
                found: 240,
            })
        );
    }

    /// A run that unpacks to more than the program is the padding of a last
    /// group, up to six bytes; a whole group more is not a program.
    #[test]
    fn a_packed_run_may_carry_the_padding_of_its_last_group_and_no_more() {
        let program = program();
        let mut packed = [0; Program::PACKED_MAX_LEN + packed::PACKED_GROUP];
        let len = program.pack_into(&mut packed).expect("room to pack");
        // 242 bytes pack to 280, which unpack to 245: three bytes of padding.
        assert_eq!(len, 280);
        assert_eq!(
            Program::from_packed(ProtocolVersion::V6, packed.get(..len).expect("in range")),
            Ok(program.clone())
        );
        // One more group, unpacking to 252, is more than the padding.
        assert_eq!(
            Program::from_packed(
                ProtocolVersion::V6,
                packed.get(..len + packed::PACKED_GROUP).expect("in range")
            ),
            Err(Error::ProgramLength {
                expected: 242,
                found: 252,
            })
        );
        // Two bytes short of a group is still short of the program.
        assert_eq!(
            Program::from_packed(
                ProtocolVersion::V6,
                packed.get(..len - packed::PACKED_GROUP).expect("in range")
            ),
            Err(Error::ProgramLength {
                expected: 242,
                found: 238,
            })
        );
    }

    #[test]
    fn transpose_is_clamped_to_the_range_the_manual_gives() {
        let mut program = program();
        program.set_clamped(ParamId::ProgramTranspose, 0);
        assert_eq!(program.transpose(), -48);
        program.set_clamped(ParamId::ProgramTranspose, 255);
        assert_eq!(program.transpose(), 48);
    }

    #[test]
    fn a_new_program_holds_what_every_parameter_accepts() {
        let program = program();
        assert_eq!(program.validate(), Ok(()));
        assert_eq!(program.invalid().count(), 0);
        // The one parameter that does not start at zero.
        assert_eq!(program.program_transpose(), 80);
        assert_eq!(program.transpose(), -48);
    }

    #[test]
    fn a_value_outside_the_range_is_kept_but_reported() {
        let mut bytes = [0; PARAMETER_COUNT];
        // Offset 2 is LFO 1 Shape, which stops at 6.
        *bytes.get_mut(2).expect("offset 2") = 9;
        let program = Program::from_bytes(ProtocolVersion::V6, &bytes).expect("a v6 program");

        assert_eq!(program.get(ParamId::Lfo1Shape), 9);
        assert_eq!(program.lfo1_shape(), None);
        assert!(
            program
                .invalid()
                .eq([(ParamId::Lfo1Shape, 9), (ParamId::ProgramTranspose, 0)]),
            "both out-of-range bytes are reported, in offset order"
        );
    }

    #[test]
    fn setting_refuses_what_clamping_bends() {
        let mut program = program();
        assert_eq!(
            program.set(ParamId::Lfo1Shape, 9),
            Err(Error::ValueOutOfRange {
                parameter: 2,
                value: 9,
                max: 6,
            })
        );
        assert_eq!(program.set_clamped(ParamId::Lfo1Shape, 9), 6);
        assert_eq!(program.lfo1_shape(), Some(LfoShape::SampleAndGlide));
    }

    #[test]
    fn the_typed_accessors_are_the_bytes_under_another_name() {
        let mut program = program();
        program.set_lfo1_shape(LfoShape::Square);
        program.set_lfo1_key_sync(true);
        program.set_vcf_frequency(128);

        assert_eq!(program.get(ParamId::Lfo1Shape), 2);
        assert_eq!(program.get(ParamId::Lfo1KeySync), 1);
        assert_eq!(program.get(ParamId::VcfFrequency), 128);
        assert!(program.lfo1_key_sync());
        assert_eq!(program.vcf_frequency(), 128);
    }

    /// Firmware 1.1 renumbered the modulation sources, so the same byte is a
    /// different source depending on which firmware wrote the program.
    #[test]
    fn a_renumbered_table_reads_by_firmware() {
        let mut program = program();
        program.set_mod1_source(ModSource::Expression);
        let raw = program.get(ParamId::Mod1Source);

        assert_eq!(raw, 6);
        assert_eq!(program.mod1_source(), Some(ModSource::Expression));
        assert_eq!(
            ModSource::from_raw_for(raw, FIRMWARE_1_0),
            Some(ModSource::Lfo1)
        );
        assert_eq!(ModSource::Expression.raw_for(FIRMWARE_1_0), None);
        assert_eq!(ModSource::Lfo1.raw_for(FIRMWARE_1_0), Some(6));
        assert_eq!(ModSource::Expression.name(), "Expression");
        assert_eq!(ModSource::Expression.name_for(FIRMWARE_1_0), None);
    }

    #[test]
    fn every_value_of_every_table_survives_the_round_trip() {
        for source in ModSource::ALL.iter().copied() {
            assert_eq!(ModSource::from_raw(source.raw()), Some(source));
        }
        for destination in ModDestination::ALL.iter().copied() {
            assert_eq!(
                ModDestination::from_raw(destination.raw()),
                Some(destination)
            );
        }
        for effect in FxType::ALL.iter().copied() {
            assert_eq!(FxType::from_raw(effect.raw()), Some(effect));
        }
        for shape in LfoShape::ALL.iter().copied() {
            assert_eq!(LfoShape::from_raw(shape.raw()), Some(shape));
            assert_eq!(
                Some(shape.name()),
                shape.name_for(crate::param::DEFAULT_FIRMWARE)
            );
        }
    }

    #[test]
    fn a_name_is_written_and_read_back() {
        let mut program = program();
        program.set_name(ProgramName::new("Bass Sweep").expect("a valid name"));

        assert_eq!(program.name().as_str(), "Bass Sweep");
        assert_eq!(program.get(ParamId::ProgramNameChar1), b'B');
        // The terminator, and everything after it, is cleared.
        assert_eq!(program.get(ParamId::ProgramNameChar11), 0);
        assert_eq!(program.get(ParamId::ProgramNameChar17), 0);

        program.set_name(ProgramName::new("A").expect("a valid name"));
        assert_eq!(program.name().as_str(), "A");
        assert_eq!(program.get(ParamId::ProgramNameChar2), 0);
    }

    #[test]
    fn transposition_counts_from_the_middle_of_its_range() {
        let mut program = program();
        program.set_transpose(0).expect("no transposition");
        assert_eq!(program.program_transpose(), 128);
        assert_eq!(program.transpose(), 0);

        program.set_transpose(48).expect("four octaves up");
        assert_eq!(program.program_transpose(), 176);
        assert_eq!(program.transpose(), 48);

        assert!(program.set_transpose(49).is_err());
        assert!(program.set_transpose(-49).is_err());
    }

    #[test]
    fn changes_are_the_edits_that_close_the_gap() {
        let before = program();
        let mut after = before.clone();
        after.set_lfo1_rate(64);
        after.set_lfo1_shape(LfoShape::Square);

        assert!(
            before
                .changes(&after)
                .eq([(ParamId::Lfo1Rate, 64), (ParamId::Lfo1Shape, 2)]),
            "both edits are reported, in offset order"
        );

        let mut applied = before.clone();
        for (parameter, value) in before.changes(&after) {
            applied.set(parameter, value).expect("a value it accepts");
        }
        assert_eq!(applied, after);
        assert_eq!(before.changes(&before).count(), 0);
    }

    #[test]
    fn a_dump_message_carries_a_program_and_nothing_else_does() {
        let program = program();
        let mut packed = [0; Program::PACKED_MAX_LEN];
        let len = program.pack_into(&mut packed).expect("room to pack");
        let packed = packed.get(..len).expect("packed");

        let dump = Message::EditBufferDumpResponse {
            version: ProtocolVersion::V6,
            packed,
        };
        assert_eq!(Program::from_dump(&dump), Ok(program.clone()));

        let stored = Message::ProgramDumpResponse {
            version: ProtocolVersion::V6,
            bank: Bank::new(0).expect("bank A"),
            program: ProgramNumber::new(0).expect("program 0"),
            packed,
        };
        assert_eq!(Program::from_dump(&stored), Ok(program));

        assert_eq!(
            Program::from_dump(&Message::EditBufferDumpRequest),
            Err(Error::NotAProgramDump(0x03))
        );
    }

    #[test]
    fn a_bank_of_names_is_read_where_it_lies() {
        let mut unpacked = [0; BankNames::LEN];
        let first = unpacked.get_mut(..4).expect("the first name");
        first.copy_from_slice(b"Bass");
        let second = unpacked
            .get_mut(PROGRAM_NAME_LEN..PROGRAM_NAME_LEN + 16)
            .expect("the second name");
        second.copy_from_slice(b"SixteenCharacter");
        let names = BankNames::new(&unpacked).expect("a bank of names");

        assert_eq!(
            names
                .get(ProgramNumber::new(0).expect("program 0"))
                .as_str(),
            "Bass"
        );
        // Sixteen bytes with no terminator is still a name.
        assert_eq!(
            names
                .get(ProgramNumber::new(1).expect("program 1"))
                .as_str(),
            "SixteenCharacter"
        );
        assert_eq!(names.iter().count(), 128);
        assert_eq!(
            BankNames::new(&[0; 16]),
            Err(Error::PayloadLength {
                command: Command::BankProgramNamesDumpResponse.to_byte(),
                expected: BankNames::LEN,
                found: 16,
            })
        );
    }
}