1mod decoder;
27
28pub use decoder::{Decoder, Event, MAX_SYSEX_LEN};
29
30use core::fmt;
31
32use crate::error::{Error, Result};
33
34pub const SYSEX_START: u8 = 0xF0;
36
37pub const SYSEX_END: u8 = 0xF7;
39
40pub const CHANNEL_COUNT: u8 = 16;
42
43#[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 pub const ONE: Self = Self(0);
54 pub const SIXTEEN: Self = Self(15);
56
57 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 #[must_use]
72 pub const fn index(self) -> u8 {
73 self.0
74 }
75
76 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub enum ChannelMessage {
113 NoteOff {
115 key: u8,
117 velocity: u8,
119 },
120 NoteOn {
122 key: u8,
124 velocity: u8,
126 },
127 PolyKeyPressure {
129 key: u8,
131 pressure: u8,
133 },
134 ControlChange {
136 controller: u8,
138 value: u8,
140 },
141 ProgramChange {
143 program: u8,
145 },
146 ChannelPressure {
148 pressure: u8,
150 },
151 PitchBend {
153 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 pub const BEND_CENTRE: u16 = 8192;
177
178 #[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 #[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 #[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 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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
281#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
282pub enum SystemCommon {
283 TimeCodeQuarterFrame(u8),
285 SongPosition(u16),
287 SongSelect(u8),
289 TuneRequest,
291}
292
293#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
298#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
299pub enum Realtime {
300 Clock,
302 Start,
304 Continue,
306 Stop,
308 ActiveSensing,
310 SystemReset,
312}
313
314impl Realtime {
315 #[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 #[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 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}