use core::fmt;
use std::io;
use wavegraph_core::midi::{MidiMessage, Note};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Channel(u8);
impl Channel {
pub fn new(number: u8) -> io::Result<Self> {
if (1..=16).contains(&number) {
Ok(Self(number))
} else {
Err(invalid("MIDI channel must be between 1 and 16"))
}
}
#[must_use]
pub const fn number(self) -> u8 {
self.0
}
#[must_use]
pub const fn index(self) -> u8 {
self.0.saturating_sub(1)
}
}
impl fmt::Display for Channel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MidiCommand {
Play,
Stop,
NoteOn {
channel: Channel,
note: u8,
velocity: u8,
},
NoteOff {
channel: Channel,
note: u8,
},
ControlChange {
channel: Channel,
controller: u8,
value: u8,
},
AllNotesOff {
channel: Channel,
},
}
impl MidiCommand {
#[must_use]
pub fn decode(bytes: &[u8]) -> Option<Self> {
match bytes {
[0xfa] => Some(Self::Play),
[0xfc] => Some(Self::Stop),
&[status, key, value] => {
let channel = Channel((status & 0x0f).saturating_add(1));
Some(match MidiMessage::decode([status, key, value])? {
MidiMessage::On(note) => Self::NoteOn {
channel,
note: note.number,
velocity: note.velocity,
},
MidiMessage::Off(note) => Self::NoteOff { channel, note },
MidiMessage::Control(123, _) => Self::AllNotesOff { channel },
MidiMessage::Control(controller, value) => Self::ControlChange {
channel,
controller,
value,
},
})
}
_ => None,
}
}
pub(crate) fn encode(self, bytes: &mut [u8; 3]) -> io::Result<usize> {
let (channel, message) = match self {
Self::Play => {
bytes[0] = 0xfa;
return Ok(1);
}
Self::Stop => {
bytes[0] = 0xfc;
return Ok(1);
}
Self::NoteOn {
channel,
note,
velocity,
} => (
channel,
MidiMessage::On(Note {
number: note,
velocity,
}),
),
Self::NoteOff { channel, note } => (channel, MidiMessage::Off(note)),
Self::ControlChange {
channel,
controller,
value,
} => (channel, MidiMessage::Control(controller, value)),
Self::AllNotesOff { channel } => (channel, MidiMessage::Control(123, 0)),
};
*bytes = message.encode(channel.index()).ok_or_else(|| {
invalid("MIDI data must fit seven bits; note-on velocity must be nonzero")
})?;
Ok(3)
}
}
fn invalid(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}