mod decoder;
pub use decoder::{Decoder, Event, MAX_SYSEX_LEN};
use core::fmt;
use crate::error::{Error, Result};
pub const SYSEX_START: u8 = 0xF0;
pub const SYSEX_END: u8 = 0xF7;
pub const CHANNEL_COUNT: u8 = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Channel(u8);
impl Channel {
pub const ONE: Self = Self(0);
pub const SIXTEEN: Self = Self(15);
pub const fn new(index: u8) -> Result<Self> {
if index < CHANNEL_COUNT {
Ok(Self(index))
} else {
Err(Error::ChannelOutOfRange(index))
}
}
#[must_use]
pub const fn index(self) -> u8 {
self.0
}
#[must_use]
pub const fn number(self) -> u8 {
self.0 + 1
}
}
impl TryFrom<u8> for Channel {
type Error = Error;
fn try_from(byte: u8) -> Result<Self> {
Self::new(byte)
}
}
impl From<Channel> for u8 {
fn from(value: Channel) -> Self {
value.index()
}
}
impl fmt::Display for Channel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.number())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ChannelMessage {
NoteOff {
key: u8,
velocity: u8,
},
NoteOn {
key: u8,
velocity: u8,
},
PolyKeyPressure {
key: u8,
pressure: u8,
},
ControlChange {
controller: u8,
value: u8,
},
ProgramChange {
program: u8,
},
ChannelPressure {
pressure: u8,
},
PitchBend {
value: u16,
},
}
impl fmt::Display for ChannelMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoteOff { key, velocity } => write!(f, "note off {key} velocity {velocity}"),
Self::NoteOn { key, velocity } => write!(f, "note on {key} velocity {velocity}"),
Self::PolyKeyPressure { key, pressure } => {
write!(f, "key pressure {key} {pressure}")
}
Self::ControlChange { controller, value } => write!(f, "CC {controller} = {value}"),
Self::ProgramChange { program } => write!(f, "program change {program}"),
Self::ChannelPressure { pressure } => write!(f, "channel pressure {pressure}"),
Self::PitchBend { value } => write!(f, "pitch bend {value}"),
}
}
}
impl ChannelMessage {
pub const BEND_CENTRE: u16 = 8192;
#[must_use]
pub const fn status_nibble(self) -> u8 {
match self {
Self::NoteOff { .. } => 0x80,
Self::NoteOn { .. } => 0x90,
Self::PolyKeyPressure { .. } => 0xA0,
Self::ControlChange { .. } => 0xB0,
Self::ProgramChange { .. } => 0xC0,
Self::ChannelPressure { .. } => 0xD0,
Self::PitchBend { .. } => 0xE0,
}
}
#[must_use]
pub const fn data_len_for(status: u8) -> Option<usize> {
match status & 0xF0 {
0x80 | 0x90 | 0xA0 | 0xB0 | 0xE0 => Some(2),
0xC0 | 0xD0 => Some(1),
_ => None,
}
}
#[must_use]
pub const fn encoded_len(self) -> usize {
match self {
Self::ProgramChange { .. } | Self::ChannelPressure { .. } => 2,
_ => 3,
}
}
pub fn encode_into(self, channel: Channel, out: &mut [u8]) -> Result<usize> {
let needed = self.encoded_len();
let available = out.len();
let out = out
.get_mut(..needed)
.ok_or(Error::BufferTooSmall { needed, available })?;
let (first, second) = match self {
Self::NoteOff { key, velocity } | Self::NoteOn { key, velocity } => (key, velocity),
Self::PolyKeyPressure { key, pressure } => (key, pressure),
Self::ControlChange { controller, value } => (controller, value),
Self::ProgramChange { program } => (program, 0),
Self::ChannelPressure { pressure } => (pressure, 0),
Self::PitchBend { value } => ((value & 0x7F) as u8, ((value >> 7) & 0x7F) as u8),
};
let bytes = [
self.status_nibble() | channel.index(),
first & 0x7F,
second & 0x7F,
];
for (slot, byte) in out.iter_mut().zip(bytes) {
*slot = byte;
}
Ok(needed)
}
#[must_use]
pub const fn from_bytes(status: u8, first: u8, second: u8) -> Option<Self> {
let (key, velocity) = (first & 0x7F, second & 0x7F);
Some(match status & 0xF0 {
0x80 => Self::NoteOff { key, velocity },
0x90 => Self::NoteOn { key, velocity },
0xA0 => Self::PolyKeyPressure {
key,
pressure: velocity,
},
0xB0 => Self::ControlChange {
controller: key,
value: velocity,
},
0xC0 => Self::ProgramChange { program: key },
0xD0 => Self::ChannelPressure { pressure: key },
0xE0 => Self::PitchBend {
value: ((velocity as u16) << 7) | key as u16,
},
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SystemCommon {
TimeCodeQuarterFrame(u8),
SongPosition(u16),
SongSelect(u8),
TuneRequest,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Realtime {
Clock,
Start,
Continue,
Stop,
ActiveSensing,
SystemReset,
}
impl Realtime {
#[must_use]
pub const fn from_status(status: u8) -> Option<Self> {
Some(match status {
0xF8 => Self::Clock,
0xFA => Self::Start,
0xFB => Self::Continue,
0xFC => Self::Stop,
0xFE => Self::ActiveSensing,
0xFF => Self::SystemReset,
_ => return None,
})
}
#[must_use]
pub const fn to_status(self) -> u8 {
match self {
Self::Clock => 0xF8,
Self::Start => 0xFA,
Self::Continue => 0xFB,
Self::Stop => 0xFC,
Self::ActiveSensing => 0xFE,
Self::SystemReset => 0xFF,
}
}
}
#[cfg(test)]
#[expect(
clippy::expect_used,
reason = "a failed expectation is the test failure"
)]
mod tests {
use super::*;
#[test]
fn channels_print_from_one_and_reject_out_of_range_values() {
assert_eq!(Channel::new(0).expect("0 is in range").number(), 1);
assert_eq!(Channel::SIXTEEN.index(), 15);
assert_eq!(Channel::new(16), Err(Error::ChannelOutOfRange(16)));
}
#[test]
fn channel_messages_round_trip_through_their_bytes() {
let cases = [
ChannelMessage::NoteOff {
key: 60,
velocity: 64,
},
ChannelMessage::NoteOn {
key: 127,
velocity: 1,
},
ChannelMessage::PolyKeyPressure {
key: 60,
pressure: 7,
},
ChannelMessage::ControlChange {
controller: 99,
value: 1,
},
ChannelMessage::ProgramChange { program: 42 },
ChannelMessage::ChannelPressure { pressure: 12 },
ChannelMessage::PitchBend { value: 0 },
ChannelMessage::PitchBend {
value: ChannelMessage::BEND_CENTRE,
},
ChannelMessage::PitchBend { value: 16383 },
];
for message in cases {
let mut buf = [0u8; 3];
let channel = Channel::new(5).expect("5 is in range");
let len = message.encode_into(channel, &mut buf).expect("buffer fits");
assert_eq!(len, message.encoded_len());
assert_eq!(buf[0] & 0x0F, 5);
assert_eq!(
ChannelMessage::from_bytes(buf[0], buf[1], buf[2]),
Some(message)
);
assert_eq!(ChannelMessage::data_len_for(buf[0]), Some(len - 1));
}
}
#[test]
fn encoding_reports_a_buffer_it_cannot_fill() {
let mut buf = [0u8; 2];
assert_eq!(
ChannelMessage::NoteOn {
key: 60,
velocity: 1
}
.encode_into(Channel::ONE, &mut buf),
Err(Error::BufferTooSmall {
needed: 3,
available: 2
})
);
assert_eq!(
ChannelMessage::ProgramChange { program: 3 }.encode_into(Channel::ONE, &mut buf),
Ok(2)
);
assert_eq!(buf, [0xC0, 3]);
}
#[test]
fn pitch_bend_splits_into_lsb_then_msb() {
let mut buf = [0u8; 3];
ChannelMessage::PitchBend {
value: ChannelMessage::BEND_CENTRE,
}
.encode_into(Channel::ONE, &mut buf)
.expect("buffer fits");
assert_eq!(buf, [0xE0, 0x00, 0x40]);
}
#[test]
fn real_time_status_bytes_round_trip_and_leave_the_undefined_ones_out() {
for status in 0xF8..=0xFF {
match Realtime::from_status(status) {
Some(message) => assert_eq!(message.to_status(), status),
None => assert!(matches!(status, 0xF9 | 0xFD)),
}
}
}
#[test]
fn non_channel_status_bytes_decode_to_nothing() {
assert_eq!(ChannelMessage::from_bytes(0xF0, 0, 0), None);
assert_eq!(ChannelMessage::data_len_for(0xF0), None);
}
}