Skip to main content

qualia_audio/midi/ump/
packet.rs

1//! MIDI 2.0 Universal MIDI Packet (UMP) container + the MIDI 2.0 channel-voice
2//! message model.
3//!
4//! A UMP is 1..=4 big-endian 32-bit words. The top nibble of word 0 is the
5//! Message Type (MT), which fixes the packet size; the next nibble is the Group
6//! (0..=15). [`UmpPacket`] is a fixed 4-word `Copy` container tagged with the
7//! number of valid words.
8
9use crate::types::AudioError;
10
11/// Utility messages (MT 0x0) — 32-bit.
12pub const MT_UTILITY: u8 = 0x0;
13/// System real-time / common (MT 0x1) — 32-bit.
14pub const MT_SYSTEM: u8 = 0x1;
15/// MIDI 1.0 channel voice (MT 0x2) — 32-bit.
16pub const MT_MIDI1_CHANNEL_VOICE: u8 = 0x2;
17/// Data / SysEx7 (MT 0x3) — 64-bit.
18pub const MT_DATA_64: u8 = 0x3;
19/// MIDI 2.0 channel voice (MT 0x4) — 64-bit.
20pub const MT_MIDI2_CHANNEL_VOICE: u8 = 0x4;
21/// Data / SysEx8 & Mixed Data Set (MT 0x5) — 128-bit.
22pub const MT_DATA_128: u8 = 0x5;
23
24/// Number of 32-bit words in a UMP for a given Message Type, per the UMP spec.
25///
26/// `0x0,0x1,0x2,0x6,0x7` → 1 word; `0x3,0x4,0x8,0x9,0xA` → 2 words;
27/// `0xB,0xC` → 3 words; `0x5,0xD,0xE,0xF` → 4 words.
28pub const fn packet_word_count(message_type: u8) -> usize {
29    match message_type & 0x0F {
30        0x0 | 0x1 | 0x2 | 0x6 | 0x7 => 1,
31        0x3 | 0x4 | 0x8 | 0x9 | 0xA => 2,
32        0xB | 0xC => 3,
33        _ => 4, // 0x5, 0xD, 0xE, 0xF
34    }
35}
36
37/// A fixed-capacity Universal MIDI Packet (1..=4 valid 32-bit words).
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct UmpPacket {
40    /// Packet words, big-endian per the spec; only `word_count` are valid.
41    pub words: [u32; 4],
42    /// Number of valid words (1..=4).
43    pub word_count: u8,
44}
45
46impl UmpPacket {
47    /// A 32-bit (1-word) packet.
48    #[inline]
49    pub const fn new32(word0: u32) -> Self {
50        Self {
51            words: [word0, 0, 0, 0],
52            word_count: 1,
53        }
54    }
55
56    /// A 64-bit (2-word) packet.
57    #[inline]
58    pub const fn new64(word0: u32, word1: u32) -> Self {
59        Self {
60            words: [word0, word1, 0, 0],
61            word_count: 2,
62        }
63    }
64
65    /// A 96-bit (3-word) packet.
66    #[inline]
67    pub const fn new96(word0: u32, word1: u32, word2: u32) -> Self {
68        Self {
69            words: [word0, word1, word2, 0],
70            word_count: 3,
71        }
72    }
73
74    /// A 128-bit (4-word) packet.
75    #[inline]
76    pub const fn new128(word0: u32, word1: u32, word2: u32, word3: u32) -> Self {
77        Self {
78            words: [word0, word1, word2, word3],
79            word_count: 4,
80        }
81    }
82
83    /// The Message Type (top nibble of word 0), 0x0..=0xF.
84    #[inline]
85    pub const fn message_type(self) -> u8 {
86        (self.words[0] >> 28) as u8 & 0x0F
87    }
88
89    /// The Group (second nibble of word 0), 0..=15.
90    #[inline]
91    pub const fn group(self) -> u8 {
92        ((self.words[0] >> 24) & 0x0F) as u8
93    }
94
95    /// Valid words as a slice.
96    #[inline]
97    pub fn as_words(&self) -> &[u32] {
98        &self.words[..self.word_count as usize]
99    }
100
101    /// Write the valid words as big-endian bytes into `out`; returns bytes
102    /// written (`word_count * 4`). Errors [`AudioError::OutputBufferTooSmall`].
103    pub fn to_be_bytes(self, out: &mut [u8]) -> Result<usize, AudioError> {
104        let n = self.word_count as usize * 4;
105        if out.len() < n {
106            return Err(AudioError::OutputBufferTooSmall);
107        }
108        for (i, w) in self.words[..self.word_count as usize].iter().enumerate() {
109            out[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes());
110        }
111        Ok(n)
112    }
113}
114
115/// A MIDI 2.0 channel-voice message (MT 0x4 payload), decoded into fields.
116/// Values are at MIDI 2.0 resolution (16-bit velocity, 32-bit controllers/bend).
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum Midi2ChannelVoice {
119    /// Note Off. `attribute_type`/`attribute_data` carry the optional attribute.
120    NoteOff {
121        /// Channel 0..=15.
122        channel: u8,
123        /// Note number 0..=127.
124        note: u8,
125        /// 16-bit release velocity.
126        velocity: u16,
127        /// Attribute type (0 = none).
128        attribute_type: u8,
129        /// 16-bit attribute data.
130        attribute_data: u16,
131    },
132    /// Note On.
133    NoteOn {
134        /// Channel 0..=15.
135        channel: u8,
136        /// Note number 0..=127.
137        note: u8,
138        /// 16-bit attack velocity.
139        velocity: u16,
140        /// Attribute type (0 = none).
141        attribute_type: u8,
142        /// 16-bit attribute data.
143        attribute_data: u16,
144    },
145    /// Polyphonic Key Pressure.
146    PolyPressure {
147        /// Channel 0..=15.
148        channel: u8,
149        /// Note number 0..=127.
150        note: u8,
151        /// 32-bit pressure.
152        pressure: u32,
153    },
154    /// Control Change.
155    ControlChange {
156        /// Channel 0..=15.
157        channel: u8,
158        /// Controller index 0..=127.
159        index: u8,
160        /// 32-bit controller value.
161        value: u32,
162    },
163    /// Program Change (with optional bank).
164    ProgramChange {
165        /// Channel 0..=15.
166        channel: u8,
167        /// Program number 0..=127.
168        program: u8,
169        /// Whether the bank fields are valid.
170        bank_valid: bool,
171        /// Bank MSB 0..=127.
172        bank_msb: u8,
173        /// Bank LSB 0..=127.
174        bank_lsb: u8,
175    },
176    /// Channel Pressure.
177    ChannelPressure {
178        /// Channel 0..=15.
179        channel: u8,
180        /// 32-bit pressure.
181        pressure: u32,
182    },
183    /// Pitch Bend.
184    PitchBend {
185        /// Channel 0..=15.
186        channel: u8,
187        /// 32-bit bend value (0x8000_0000 = center).
188        value: u32,
189    },
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn word_counts() {
198        assert_eq!(packet_word_count(MT_MIDI1_CHANNEL_VOICE), 1);
199        assert_eq!(packet_word_count(MT_MIDI2_CHANNEL_VOICE), 2);
200        assert_eq!(packet_word_count(MT_DATA_128), 4);
201        assert_eq!(packet_word_count(0xB), 3);
202    }
203
204    #[test]
205    fn mt_group_fields() {
206        let p = UmpPacket::new32(0x2A90_3C64); // MT=2, group=0xA
207        assert_eq!(p.message_type(), 0x2);
208        assert_eq!(p.group(), 0xA);
209        assert_eq!(p.word_count, 1);
210    }
211
212    #[test]
213    fn be_bytes() {
214        let p = UmpPacket::new32(0x2090_3C64);
215        let mut buf = [0u8; 4];
216        assert_eq!(p.to_be_bytes(&mut buf).unwrap(), 4);
217        assert_eq!(buf, [0x20, 0x90, 0x3C, 0x64]);
218        let mut small = [0u8; 3];
219        assert_eq!(
220            p.to_be_bytes(&mut small),
221            Err(AudioError::OutputBufferTooSmall)
222        );
223    }
224}