Skip to main content

deepmind_midi/wire/
mod.rs

1//! MIDI bytes: status, channel messages and `SysEx` reassembly.
2//!
3//! This layer knows nothing about `DeepMind`s. It turns a byte stream from a MIDI
4//! port into whole messages, and whole messages back into bytes. What a `SysEx`
5//! frame means is [`crate::sysex`]'s question; what a controller number means is
6//! the parameter table's.
7//!
8//! ```
9//! use deepmind_midi::wire::{Channel, ChannelMessage, Decoder, Event};
10//!
11//! // `Decoder` on its own is the default buffer size; `Decoder<64>` picks another.
12//! let mut decoder: Decoder = Decoder::new();
13//! let mut keys = Vec::new();
14//!
15//! // Running status: one status byte, then two note-ons.
16//! decoder.feed(&[0x90, 0x3C, 0x40, 0x40, 0x40], |event| {
17//!     if let Ok(Event::Channel { channel, message: ChannelMessage::NoteOn { key, .. } }) = event {
18//!         assert_eq!(channel, Channel::ONE);
19//!         keys.push(key);
20//!     }
21//! });
22//!
23//! assert_eq!(keys, [0x3C, 0x40]);
24//! ```
25
26mod decoder;
27
28pub use decoder::{Decoder, Event, MAX_SYSEX_LEN};
29
30use core::fmt;
31
32use crate::error::{Error, Result};
33
34/// Status byte that opens a `SysEx` frame.
35pub const SYSEX_START: u8 = 0xF0;
36
37/// Status byte that closes a `SysEx` frame.
38pub const SYSEX_END: u8 = 0xF7;
39
40/// Number of MIDI channels.
41pub const CHANNEL_COUNT: u8 = 16;
42
43/// A MIDI channel.
44///
45/// Stored as the wire value, `0..=15`. [`Display`](fmt::Display) prints the number
46/// a musician reads off the front panel, `1..=16`.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
48#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
49pub struct Channel(u8);
50
51impl Channel {
52    /// Channel 1, which is `0` on the wire.
53    pub const ONE: Self = Self(0);
54    /// Channel 16, which is `15` on the wire.
55    pub const SIXTEEN: Self = Self(15);
56
57    /// Builds a channel from its wire value.
58    ///
59    /// # Errors
60    ///
61    /// Returns [`Error::ChannelOutOfRange`] for an index of 16 or more.
62    pub const fn new(index: u8) -> Result<Self> {
63        if index < CHANNEL_COUNT {
64            Ok(Self(index))
65        } else {
66            Err(Error::ChannelOutOfRange(index))
67        }
68    }
69
70    /// Returns the wire value, `0..=15`.
71    #[must_use]
72    pub const fn index(self) -> u8 {
73        self.0
74    }
75
76    /// Returns the number as the front panel shows it, `1..=16`.
77    #[must_use]
78    pub const fn number(self) -> u8 {
79        self.0 + 1
80    }
81}
82
83impl TryFrom<u8> for Channel {
84    type Error = Error;
85
86    fn try_from(byte: u8) -> Result<Self> {
87        Self::new(byte)
88    }
89}
90
91impl From<Channel> for u8 {
92    fn from(value: Channel) -> Self {
93        value.index()
94    }
95}
96
97impl fmt::Display for Channel {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        write!(f, "{}", self.number())
100    }
101}
102
103/// A channel voice message, without its channel.
104///
105/// Data bytes are 7-bit: every field except [`ChannelMessage::PitchBend`] holds
106/// `0..=127`, and the decoder never produces anything else. A note-on with
107/// velocity zero is reported as it arrived rather than rewritten into a note-off,
108/// because the two are distinguishable on the wire and some devices mean the
109/// difference.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub enum ChannelMessage {
113    /// Key released.
114    NoteOff {
115        /// Key number, `0..=127`.
116        key: u8,
117        /// Release velocity, `0..=127`.
118        velocity: u8,
119    },
120    /// Key pressed.
121    NoteOn {
122        /// Key number, `0..=127`.
123        key: u8,
124        /// Strike velocity, `0..=127`.
125        velocity: u8,
126    },
127    /// Per-key aftertouch.
128    PolyKeyPressure {
129        /// Key number, `0..=127`.
130        key: u8,
131        /// Pressure, `0..=127`.
132        pressure: u8,
133    },
134    /// Continuous controller.
135    ControlChange {
136        /// Controller number, `0..=127`.
137        controller: u8,
138        /// Controller value, `0..=127`.
139        value: u8,
140    },
141    /// Program change.
142    ProgramChange {
143        /// Program number, `0..=127`.
144        program: u8,
145    },
146    /// Channel aftertouch.
147    ChannelPressure {
148        /// Pressure, `0..=127`.
149        pressure: u8,
150    },
151    /// Pitch bend, 14 bits.
152    PitchBend {
153        /// Bend position, `0..=16383`, centred on [`ChannelMessage::BEND_CENTRE`].
154        value: u16,
155    },
156}
157
158impl fmt::Display for ChannelMessage {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::NoteOff { key, velocity } => write!(f, "note off {key} velocity {velocity}"),
162            Self::NoteOn { key, velocity } => write!(f, "note on {key} velocity {velocity}"),
163            Self::PolyKeyPressure { key, pressure } => {
164                write!(f, "key pressure {key} {pressure}")
165            }
166            Self::ControlChange { controller, value } => write!(f, "CC {controller} = {value}"),
167            Self::ProgramChange { program } => write!(f, "program change {program}"),
168            Self::ChannelPressure { pressure } => write!(f, "channel pressure {pressure}"),
169            Self::PitchBend { value } => write!(f, "pitch bend {value}"),
170        }
171    }
172}
173
174impl ChannelMessage {
175    /// Pitch bend value meaning no bend.
176    pub const BEND_CENTRE: u16 = 8192;
177
178    /// Returns the high nibble of this message's status byte.
179    #[must_use]
180    pub const fn status_nibble(self) -> u8 {
181        match self {
182            Self::NoteOff { .. } => 0x80,
183            Self::NoteOn { .. } => 0x90,
184            Self::PolyKeyPressure { .. } => 0xA0,
185            Self::ControlChange { .. } => 0xB0,
186            Self::ProgramChange { .. } => 0xC0,
187            Self::ChannelPressure { .. } => 0xD0,
188            Self::PitchBend { .. } => 0xE0,
189        }
190    }
191
192    /// Returns how many data bytes follow the status byte of `status`.
193    ///
194    /// Returns `None` for a byte that is not a channel status byte.
195    #[must_use]
196    pub const fn data_len_for(status: u8) -> Option<usize> {
197        match status & 0xF0 {
198            0x80 | 0x90 | 0xA0 | 0xB0 | 0xE0 => Some(2),
199            0xC0 | 0xD0 => Some(1),
200            _ => None,
201        }
202    }
203
204    /// Returns the number of bytes [`encode_into`](Self::encode_into) writes.
205    #[must_use]
206    pub const fn encoded_len(self) -> usize {
207        match self {
208            Self::ProgramChange { .. } | Self::ChannelPressure { .. } => 2,
209            _ => 3,
210        }
211    }
212
213    /// Writes this message to `out`, status byte first.
214    ///
215    /// Values wider than their field are masked to 7 bits rather than rejected,
216    /// so a caller that has already range-checked a value pays nothing and one
217    /// that has not cannot emit a byte that would be read as a status.
218    ///
219    /// # Errors
220    ///
221    /// Returns [`Error::BufferTooSmall`] when `out` is shorter than
222    /// [`encoded_len`](Self::encoded_len).
223    pub fn encode_into(self, channel: Channel, out: &mut [u8]) -> Result<usize> {
224        let needed = self.encoded_len();
225        let available = out.len();
226        let out = out
227            .get_mut(..needed)
228            .ok_or(Error::BufferTooSmall { needed, available })?;
229        let (first, second) = match self {
230            Self::NoteOff { key, velocity } | Self::NoteOn { key, velocity } => (key, velocity),
231            Self::PolyKeyPressure { key, pressure } => (key, pressure),
232            Self::ControlChange { controller, value } => (controller, value),
233            Self::ProgramChange { program } => (program, 0),
234            Self::ChannelPressure { pressure } => (pressure, 0),
235            Self::PitchBend { value } => ((value & 0x7F) as u8, ((value >> 7) & 0x7F) as u8),
236        };
237        let bytes = [
238            self.status_nibble() | channel.index(),
239            first & 0x7F,
240            second & 0x7F,
241        ];
242        for (slot, byte) in out.iter_mut().zip(bytes) {
243            *slot = byte;
244        }
245        Ok(needed)
246    }
247
248    /// Builds a message from a status byte and up to two data bytes.
249    ///
250    /// Returns `None` when `status` is not a channel status byte.
251    #[must_use]
252    pub const fn from_bytes(status: u8, first: u8, second: u8) -> Option<Self> {
253        let (key, velocity) = (first & 0x7F, second & 0x7F);
254        Some(match status & 0xF0 {
255            0x80 => Self::NoteOff { key, velocity },
256            0x90 => Self::NoteOn { key, velocity },
257            0xA0 => Self::PolyKeyPressure {
258                key,
259                pressure: velocity,
260            },
261            0xB0 => Self::ControlChange {
262                controller: key,
263                value: velocity,
264            },
265            0xC0 => Self::ProgramChange { program: key },
266            0xD0 => Self::ChannelPressure { pressure: key },
267            0xE0 => Self::PitchBend {
268                value: ((velocity as u16) << 7) | key as u16,
269            },
270            _ => return None,
271        })
272    }
273}
274
275/// A system common message.
276///
277/// The `DeepMind` sends none of these. They are decoded because a MIDI port
278/// carries whatever else is on the cable, and because every one of them clears
279/// running status, which a decoder that ignored them would get wrong.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
281#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
282pub enum SystemCommon {
283    /// One eighth of a MIDI time code frame.
284    TimeCodeQuarterFrame(u8),
285    /// Song position, in sixteenth notes since the start.
286    SongPosition(u16),
287    /// Song select.
288    SongSelect(u8),
289    /// Tune request.
290    TuneRequest,
291}
292
293/// A system real-time message.
294///
295/// These are single bytes and may arrive between any two other bytes, including
296/// inside a `SysEx` frame.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
298#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
299pub enum Realtime {
300    /// Timing clock, 24 per quarter note.
301    Clock,
302    /// Start playing from the beginning.
303    Start,
304    /// Resume playing.
305    Continue,
306    /// Stop playing.
307    Stop,
308    /// Active sensing.
309    ActiveSensing,
310    /// System reset.
311    SystemReset,
312}
313
314impl Realtime {
315    /// Builds a real-time message from its status byte.
316    ///
317    /// Returns `None` for `F9` and `FD`, which are undefined.
318    #[must_use]
319    pub const fn from_status(status: u8) -> Option<Self> {
320        Some(match status {
321            0xF8 => Self::Clock,
322            0xFA => Self::Start,
323            0xFB => Self::Continue,
324            0xFC => Self::Stop,
325            0xFE => Self::ActiveSensing,
326            0xFF => Self::SystemReset,
327            _ => return None,
328        })
329    }
330
331    /// Returns the status byte for this message.
332    #[must_use]
333    pub const fn to_status(self) -> u8 {
334        match self {
335            Self::Clock => 0xF8,
336            Self::Start => 0xFA,
337            Self::Continue => 0xFB,
338            Self::Stop => 0xFC,
339            Self::ActiveSensing => 0xFE,
340            Self::SystemReset => 0xFF,
341        }
342    }
343}
344
345#[cfg(test)]
346#[expect(
347    clippy::expect_used,
348    reason = "a failed expectation is the test failure"
349)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn channels_print_from_one_and_reject_out_of_range_values() {
355        assert_eq!(Channel::new(0).expect("0 is in range").number(), 1);
356        assert_eq!(Channel::SIXTEEN.index(), 15);
357        assert_eq!(Channel::new(16), Err(Error::ChannelOutOfRange(16)));
358    }
359
360    #[test]
361    fn channel_messages_round_trip_through_their_bytes() {
362        let cases = [
363            ChannelMessage::NoteOff {
364                key: 60,
365                velocity: 64,
366            },
367            ChannelMessage::NoteOn {
368                key: 127,
369                velocity: 1,
370            },
371            ChannelMessage::PolyKeyPressure {
372                key: 60,
373                pressure: 7,
374            },
375            ChannelMessage::ControlChange {
376                controller: 99,
377                value: 1,
378            },
379            ChannelMessage::ProgramChange { program: 42 },
380            ChannelMessage::ChannelPressure { pressure: 12 },
381            ChannelMessage::PitchBend { value: 0 },
382            ChannelMessage::PitchBend {
383                value: ChannelMessage::BEND_CENTRE,
384            },
385            ChannelMessage::PitchBend { value: 16383 },
386        ];
387        for message in cases {
388            let mut buf = [0u8; 3];
389            let channel = Channel::new(5).expect("5 is in range");
390            let len = message.encode_into(channel, &mut buf).expect("buffer fits");
391            assert_eq!(len, message.encoded_len());
392            assert_eq!(buf[0] & 0x0F, 5);
393            assert_eq!(
394                ChannelMessage::from_bytes(buf[0], buf[1], buf[2]),
395                Some(message)
396            );
397            assert_eq!(ChannelMessage::data_len_for(buf[0]), Some(len - 1));
398        }
399    }
400
401    #[test]
402    fn encoding_reports_a_buffer_it_cannot_fill() {
403        let mut buf = [0u8; 2];
404        assert_eq!(
405            ChannelMessage::NoteOn {
406                key: 60,
407                velocity: 1
408            }
409            .encode_into(Channel::ONE, &mut buf),
410            Err(Error::BufferTooSmall {
411                needed: 3,
412                available: 2
413            })
414        );
415        // A two byte message fits a two byte buffer.
416        assert_eq!(
417            ChannelMessage::ProgramChange { program: 3 }.encode_into(Channel::ONE, &mut buf),
418            Ok(2)
419        );
420        assert_eq!(buf, [0xC0, 3]);
421    }
422
423    #[test]
424    fn pitch_bend_splits_into_lsb_then_msb() {
425        let mut buf = [0u8; 3];
426        ChannelMessage::PitchBend {
427            value: ChannelMessage::BEND_CENTRE,
428        }
429        .encode_into(Channel::ONE, &mut buf)
430        .expect("buffer fits");
431        assert_eq!(buf, [0xE0, 0x00, 0x40]);
432    }
433
434    #[test]
435    fn real_time_status_bytes_round_trip_and_leave_the_undefined_ones_out() {
436        for status in 0xF8..=0xFF {
437            match Realtime::from_status(status) {
438                Some(message) => assert_eq!(message.to_status(), status),
439                None => assert!(matches!(status, 0xF9 | 0xFD)),
440            }
441        }
442    }
443
444    #[test]
445    fn non_channel_status_bytes_decode_to_nothing() {
446        assert_eq!(ChannelMessage::from_bytes(0xF0, 0, 0), None);
447        assert_eq!(ChannelMessage::data_len_for(0xF0), None);
448    }
449}