Skip to main content

deepmind_midi/
ids.rs

1//! Addressing primitives used throughout the protocol.
2//!
3//! Every type here is a validated newtype. Constructing one is the only place a
4//! range check happens, so downstream code never has to re-check a bank or program
5//! number that it already holds. Each converts from its wire byte through
6//! [`TryFrom<u8>`] and back through [`From`], for code that is generic over them;
7//! the inherent constructors say the same thing with a name.
8
9use core::fmt;
10
11use crate::error::Error;
12
13/// Behringer's three-byte MIDI manufacturer ID.
14pub const MANUFACTURER_ID: [u8; 3] = [0x00, 0x20, 0x32];
15
16/// Number of banks on every `DeepMind` model.
17pub const BANK_COUNT: u8 = 8;
18
19/// Number of programs in each bank.
20pub const PROGRAMS_PER_BANK: u8 = 128;
21
22/// Number of user arpeggiator/sequencer patterns.
23pub const USER_PATTERN_COUNT: u8 = 32;
24
25/// `SysEx` target address of a synthesizer on the wire.
26///
27/// The `DeepMind` reuses its global MIDI channel as its `SysEx` device ID. `Broadcast`
28/// (`0x7F`) addresses every unit on the port, which is what factory preset packs
29/// ship with.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub enum DeviceId {
33    /// A specific unit, 0 through 15.
34    Unit(u8),
35    /// Every unit on the port (`0x7F`).
36    Broadcast,
37}
38
39impl DeviceId {
40    /// Wire value used for [`DeviceId::Broadcast`].
41    pub const BROADCAST_BYTE: u8 = 0x7F;
42
43    /// Builds a device ID from its wire byte.
44    ///
45    /// # Errors
46    ///
47    /// Returns [`Error::InvalidDeviceId`] for anything outside `0..=15` and `0x7F`.
48    pub const fn from_byte(byte: u8) -> Result<Self, Error> {
49        match byte {
50            Self::BROADCAST_BYTE => Ok(Self::Broadcast),
51            0..=15 => Ok(Self::Unit(byte)),
52            _ => Err(Error::InvalidDeviceId(byte)),
53        }
54    }
55
56    /// Returns the wire byte for this device ID.
57    #[must_use]
58    pub const fn to_byte(self) -> u8 {
59        match self {
60            Self::Unit(id) => id,
61            Self::Broadcast => Self::BROADCAST_BYTE,
62        }
63    }
64
65    /// Returns `true` when a message addressed to `self` should be accepted by a
66    /// unit listening as `listener`.
67    #[must_use]
68    pub const fn addresses(self, listener: Self) -> bool {
69        matches!(self, Self::Broadcast) || self.to_byte() == listener.to_byte()
70    }
71}
72
73impl TryFrom<u8> for DeviceId {
74    type Error = Error;
75
76    fn try_from(byte: u8) -> Result<Self, Error> {
77        Self::from_byte(byte)
78    }
79}
80
81impl From<DeviceId> for u8 {
82    fn from(id: DeviceId) -> Self {
83        id.to_byte()
84    }
85}
86
87impl fmt::Display for DeviceId {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            Self::Unit(id) => write!(f, "unit {id}"),
91            Self::Broadcast => f.write_str("broadcast"),
92        }
93    }
94}
95
96/// Synthesizer model.
97///
98/// Every variant shares model ID `0x20` and one protocol, so the wire cannot tell
99/// them apart. They differ only in voice count and whether there is a keyboard.
100/// The X series is a later reskin with the same architecture and specification.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
102#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
103#[non_exhaustive]
104pub enum Model {
105    /// 6 voices, 37 keys.
106    DeepMind6,
107    /// 6 voices, 37 keys.
108    DeepMind6X,
109    /// 12 voices, 49 keys.
110    #[default]
111    DeepMind12,
112    /// 12 voices, 49 keys.
113    DeepMind12X,
114    /// 12 voices, desktop.
115    DeepMind12D,
116    /// 12 voices, desktop.
117    DeepMind12XD,
118}
119
120impl Model {
121    /// Model ID byte shared by every variant.
122    pub const MODEL_ID: u8 = 0x20;
123
124    /// Every known variant.
125    pub const ALL: &'static [Self] = &[
126        Self::DeepMind6,
127        Self::DeepMind6X,
128        Self::DeepMind12,
129        Self::DeepMind12X,
130        Self::DeepMind12D,
131        Self::DeepMind12XD,
132    ];
133
134    /// Returns the number of analog voices.
135    #[must_use]
136    pub const fn voice_count(self) -> u8 {
137        match self {
138            Self::DeepMind6 | Self::DeepMind6X => 6,
139            Self::DeepMind12 | Self::DeepMind12X | Self::DeepMind12D | Self::DeepMind12XD => 12,
140        }
141    }
142
143    /// Returns `true` if the model has a keyboard.
144    #[must_use]
145    pub const fn has_keyboard(self) -> bool {
146        !matches!(self, Self::DeepMind12D | Self::DeepMind12XD)
147    }
148
149    /// Returns the model name as Behringer writes it.
150    #[must_use]
151    pub const fn name(self) -> &'static str {
152        match self {
153            Self::DeepMind6 => "DeepMind 6",
154            Self::DeepMind6X => "DeepMind 6X",
155            Self::DeepMind12 => "DeepMind 12",
156            Self::DeepMind12X => "DeepMind 12X",
157            Self::DeepMind12D => "DeepMind 12D",
158            Self::DeepMind12XD => "DeepMind 12XD",
159        }
160    }
161}
162
163impl fmt::Display for Model {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.write_str(self.name())
166    }
167}
168
169/// Comms protocol version carried by every dump response.
170///
171/// The firmware stamps this into each dump and the payload length depends on it:
172/// version 6 carries 242 bytes of program data, version 7 carries 245. Only
173/// those two exist, so a dump stamped with anything else is rejected where it
174/// is parsed, with [`Error::UnsupportedProtocolVersion`].
175#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
176#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
177pub struct ProtocolVersion(u8);
178
179impl ProtocolVersion {
180    /// The version documented in the `DeepMind` 12 user manual.
181    pub const V6: Self = Self(6);
182
183    /// The version emitted by current firmware and by the factory preset packs.
184    pub const V7: Self = Self(7);
185
186    /// Builds a version from its wire byte.
187    ///
188    /// # Errors
189    ///
190    /// Returns [`Error::UnsupportedProtocolVersion`] for anything but 6 and 7.
191    pub const fn new(version: u8) -> Result<Self, Error> {
192        match version {
193            6 | 7 => Ok(Self(version)),
194            _ => Err(Error::UnsupportedProtocolVersion(version)),
195        }
196    }
197
198    /// Returns the wire byte.
199    #[must_use]
200    pub const fn get(self) -> u8 {
201        self.0
202    }
203
204    /// Returns how many bytes of program data a dump of this version carries.
205    #[must_use]
206    pub const fn program_data_len(self) -> usize {
207        match self.0 {
208            6 => 242,
209            _ => 245,
210        }
211    }
212}
213
214impl TryFrom<u8> for ProtocolVersion {
215    type Error = Error;
216
217    fn try_from(version: u8) -> Result<Self, Error> {
218        Self::new(version)
219    }
220}
221
222impl From<ProtocolVersion> for u8 {
223    fn from(version: ProtocolVersion) -> Self {
224        version.get()
225    }
226}
227
228impl fmt::Display for ProtocolVersion {
229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230        write!(f, "v{}", self.0)
231    }
232}
233
234/// One of the eight program banks, `A` through `H`.
235#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
236#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
237pub struct Bank(u8);
238
239impl Bank {
240    /// Bank A.
241    pub const A: Self = Self(0);
242    /// Bank H, the last bank.
243    pub const H: Self = Self(7);
244
245    /// Builds a bank from its zero-based index.
246    ///
247    /// # Errors
248    ///
249    /// Returns [`Error::BankOutOfRange`] for an index of 8 or more.
250    pub const fn new(index: u8) -> Result<Self, Error> {
251        if index < BANK_COUNT {
252            Ok(Self(index))
253        } else {
254            Err(Error::BankOutOfRange(index))
255        }
256    }
257
258    /// Builds a bank from its letter, case-insensitively.
259    ///
260    /// # Errors
261    ///
262    /// Returns [`Error::BankLetter`] for a character outside `A..=H`.
263    pub const fn from_letter(letter: char) -> Result<Self, Error> {
264        match letter {
265            'A'..='H' => Self::new(letter as u8 - b'A'),
266            'a'..='h' => Self::new(letter as u8 - b'a'),
267            _ => Err(Error::BankLetter(letter)),
268        }
269    }
270
271    /// Returns the zero-based index.
272    #[must_use]
273    pub const fn index(self) -> u8 {
274        self.0
275    }
276
277    /// Returns the bank letter, `A` through `H`.
278    #[must_use]
279    pub const fn letter(self) -> char {
280        (b'A' + self.0) as char
281    }
282}
283
284impl TryFrom<u8> for Bank {
285    type Error = Error;
286
287    fn try_from(index: u8) -> Result<Self, Error> {
288        Self::new(index)
289    }
290}
291
292impl From<Bank> for u8 {
293    fn from(bank: Bank) -> Self {
294        bank.index()
295    }
296}
297
298impl fmt::Display for Bank {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        write!(f, "{}", self.letter())
301    }
302}
303
304/// A program slot within a bank, 0 through 127.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
306#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
307pub struct ProgramNumber(u8);
308
309impl ProgramNumber {
310    /// The first program in a bank.
311    pub const FIRST: Self = Self(0);
312    /// The last program in a bank.
313    pub const LAST: Self = Self(127);
314
315    /// Builds a program number.
316    ///
317    /// # Errors
318    ///
319    /// Returns [`Error::ProgramOutOfRange`] for a number of 128 or more.
320    pub const fn new(number: u8) -> Result<Self, Error> {
321        if number < PROGRAMS_PER_BANK {
322            Ok(Self(number))
323        } else {
324            Err(Error::ProgramOutOfRange(number))
325        }
326    }
327
328    /// Returns the zero-based slot number.
329    #[must_use]
330    pub const fn get(self) -> u8 {
331        self.0
332    }
333}
334
335impl TryFrom<u8> for ProgramNumber {
336    type Error = Error;
337
338    fn try_from(number: u8) -> Result<Self, Error> {
339        Self::new(number)
340    }
341}
342
343impl From<ProgramNumber> for u8 {
344    fn from(number: ProgramNumber) -> Self {
345        number.get()
346    }
347}
348
349impl fmt::Display for ProgramNumber {
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        // The front panel numbers programs from 1.
352        write!(f, "{}", u16::from(self.0) + 1)
353    }
354}
355
356/// One of the 1024 places a program is stored: a bank and a number in it.
357///
358/// The two travel together everywhere a stored program does: a dump names both,
359/// a `.syx` file says both, and the front panel shows them as one label.
360///
361/// ```
362/// use deepmind_midi::ids::{Bank, ProgramNumber, Slot};
363///
364/// let slot = Slot::new(Bank::A, ProgramNumber::FIRST);
365/// assert_eq!(slot.to_string(), "A1");
366/// # Ok::<(), deepmind_midi::Error>(())
367/// ```
368#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
369#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
370pub struct Slot {
371    /// Bank the program is stored in.
372    pub bank: Bank,
373    /// Program within that bank.
374    pub number: ProgramNumber,
375}
376
377impl Slot {
378    /// The first program of the first bank.
379    pub const FIRST: Self = Self {
380        bank: Bank::A,
381        number: ProgramNumber::FIRST,
382    };
383
384    /// Builds a slot.
385    #[must_use]
386    pub const fn new(bank: Bank, number: ProgramNumber) -> Self {
387        Self { bank, number }
388    }
389}
390
391impl fmt::Display for Slot {
392    /// Writes the slot the way the front panel does: `A1` through `H128`.
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        write!(f, "{}{}", self.bank, self.number)
395    }
396}
397
398/// A user arpeggiator or sequencer pattern slot, 0 through 31.
399#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
400#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
401pub struct PatternNumber(u8);
402
403impl PatternNumber {
404    /// The first user pattern.
405    pub const FIRST: Self = Self(0);
406    /// The last user pattern.
407    pub const LAST: Self = Self(31);
408
409    /// Builds a pattern number.
410    ///
411    /// # Errors
412    ///
413    /// Returns [`Error::PatternOutOfRange`] for a number of 32 or more.
414    pub const fn new(number: u8) -> Result<Self, Error> {
415        if number < USER_PATTERN_COUNT {
416            Ok(Self(number))
417        } else {
418            Err(Error::PatternOutOfRange(number))
419        }
420    }
421
422    /// Returns the zero-based slot number.
423    #[must_use]
424    pub const fn get(self) -> u8 {
425        self.0
426    }
427}
428
429impl TryFrom<u8> for PatternNumber {
430    type Error = Error;
431
432    fn try_from(number: u8) -> Result<Self, Error> {
433        Self::new(number)
434    }
435}
436
437impl From<PatternNumber> for u8 {
438    fn from(number: PatternNumber) -> Self {
439        number.get()
440    }
441}
442
443impl fmt::Display for PatternNumber {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        // The front panel numbers patterns from 1.
446        write!(f, "{}", u16::from(self.0) + 1)
447    }
448}
449
450#[cfg(test)]
451#[expect(
452    clippy::expect_used,
453    reason = "a failed expectation is the test failure"
454)]
455mod tests {
456    use super::*;
457    use crate::testing::assert_display;
458
459    #[test]
460    fn a_slot_reads_as_the_front_panel_writes_it() {
461        assert_display(Slot::FIRST, "A1");
462        assert_display(Slot::new(Bank::H, ProgramNumber::LAST), "H128");
463    }
464
465    #[test]
466    fn device_id_round_trips_through_its_wire_byte() {
467        for byte in (0..=15).chain(core::iter::once(0x7F)) {
468            let id = DeviceId::from_byte(byte).expect("byte is in range");
469            assert_eq!(id.to_byte(), byte);
470        }
471        assert_eq!(DeviceId::from_byte(16), Err(Error::InvalidDeviceId(16)));
472        assert_eq!(DeviceId::from_byte(0x7E), Err(Error::InvalidDeviceId(0x7E)));
473    }
474
475    #[test]
476    fn broadcast_addresses_every_unit_but_a_unit_only_addresses_itself() {
477        let unit_3 = DeviceId::Unit(3);
478        assert!(DeviceId::Broadcast.addresses(unit_3));
479        assert!(unit_3.addresses(unit_3));
480        assert!(!unit_3.addresses(DeviceId::Unit(4)));
481    }
482
483    #[test]
484    fn every_model_reports_a_plausible_voice_count_and_name() {
485        for model in Model::ALL.iter().copied() {
486            assert!(matches!(model.voice_count(), 6 | 12));
487            assert!(model.name().starts_with("DeepMind "));
488        }
489        assert!(!Model::DeepMind12XD.has_keyboard());
490        assert!(Model::DeepMind6X.has_keyboard());
491    }
492
493    #[test]
494    fn banks_map_between_index_and_letter() {
495        for index in 0..BANK_COUNT {
496            let bank = Bank::new(index).expect("index is in range");
497            assert_eq!(bank.letter(), (b'A' + index) as char);
498            assert_eq!(Bank::from_letter(bank.letter()), Ok(bank));
499            assert_eq!(
500                Bank::from_letter(bank.letter().to_ascii_lowercase()),
501                Ok(bank)
502            );
503        }
504        assert!(Bank::new(BANK_COUNT).is_err());
505        assert_eq!(Bank::from_letter('I'), Err(Error::BankLetter('I')));
506        assert_display(Bank::H, "H");
507    }
508
509    #[test]
510    fn program_numbers_reject_out_of_range_slots() {
511        assert_eq!(ProgramNumber::new(127).map(ProgramNumber::get), Ok(127));
512        assert_eq!(ProgramNumber::new(128), Err(Error::ProgramOutOfRange(128)));
513    }
514
515    #[test]
516    fn pattern_numbers_reject_out_of_range_slots() {
517        assert_eq!(PatternNumber::new(31).map(PatternNumber::get), Ok(31));
518        assert_eq!(PatternNumber::new(32), Err(Error::PatternOutOfRange(32)));
519    }
520
521    #[test]
522    fn protocol_versions_carry_their_program_data_length() {
523        assert_eq!(ProtocolVersion::V6.program_data_len(), 242);
524        assert_eq!(ProtocolVersion::V7.program_data_len(), 245);
525        assert_eq!(ProtocolVersion::new(7), Ok(ProtocolVersion::V7));
526        assert_eq!(
527            ProtocolVersion::new(99),
528            Err(Error::UnsupportedProtocolVersion(99))
529        );
530    }
531
532    #[test]
533    fn every_id_converts_from_its_byte_and_back() {
534        assert_eq!(Bank::try_from(7).map(u8::from), Ok(7));
535        assert_eq!(ProgramNumber::try_from(127).map(u8::from), Ok(127));
536        assert_eq!(PatternNumber::try_from(31).map(u8::from), Ok(31));
537        assert_eq!(DeviceId::try_from(0x7F), Ok(DeviceId::Broadcast));
538        assert_eq!(u8::from(DeviceId::Unit(3)), 3);
539        assert_eq!(ProtocolVersion::try_from(6).map(u8::from), Ok(6));
540        assert!(Bank::try_from(8).is_err());
541    }
542}