1use core::fmt;
2use std::io;
3use wavegraph_core::midi::{MidiMessage, Note};
4
5#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct Channel(u8);
8
9impl Channel {
10 pub fn new(number: u8) -> io::Result<Self> {
15 if (1..=16).contains(&number) {
16 Ok(Self(number))
17 } else {
18 Err(invalid("MIDI channel must be between 1 and 16"))
19 }
20 }
21
22 #[must_use]
24 pub const fn number(self) -> u8 {
25 self.0
26 }
27
28 #[must_use]
30 pub const fn index(self) -> u8 {
31 self.0.saturating_sub(1)
32 }
33}
34
35impl fmt::Display for Channel {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 self.0.fmt(f)
38 }
39}
40
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub enum MidiCommand {
47 Play,
49 Stop,
51 NoteOn {
53 channel: Channel,
55 note: u8,
57 velocity: u8,
59 },
60 NoteOff {
62 channel: Channel,
64 note: u8,
66 },
67 ControlChange {
69 channel: Channel,
71 controller: u8,
73 value: u8,
75 },
76 AllNotesOff {
78 channel: Channel,
80 },
81}
82
83impl MidiCommand {
84 #[must_use]
86 pub fn decode(bytes: &[u8]) -> Option<Self> {
87 match bytes {
88 [0xfa] => Some(Self::Play),
89 [0xfc] => Some(Self::Stop),
90 &[status, key, value] => {
91 let channel = Channel((status & 0x0f).saturating_add(1));
92 Some(match MidiMessage::decode([status, key, value])? {
93 MidiMessage::On(note) => Self::NoteOn {
94 channel,
95 note: note.number,
96 velocity: note.velocity,
97 },
98 MidiMessage::Off(note) => Self::NoteOff { channel, note },
99 MidiMessage::Control(123, _) => Self::AllNotesOff { channel },
100 MidiMessage::Control(controller, value) => Self::ControlChange {
101 channel,
102 controller,
103 value,
104 },
105 })
106 }
107 _ => None,
108 }
109 }
110
111 pub(crate) fn encode(self, bytes: &mut [u8; 3]) -> io::Result<usize> {
112 let (channel, message) = match self {
113 Self::Play => {
114 bytes[0] = 0xfa;
115 return Ok(1);
116 }
117 Self::Stop => {
118 bytes[0] = 0xfc;
119 return Ok(1);
120 }
121 Self::NoteOn {
122 channel,
123 note,
124 velocity,
125 } => (
126 channel,
127 MidiMessage::On(Note {
128 number: note,
129 velocity,
130 }),
131 ),
132 Self::NoteOff { channel, note } => (channel, MidiMessage::Off(note)),
133 Self::ControlChange {
134 channel,
135 controller,
136 value,
137 } => (channel, MidiMessage::Control(controller, value)),
138 Self::AllNotesOff { channel } => (channel, MidiMessage::Control(123, 0)),
139 };
140 *bytes = message.encode(channel.index()).ok_or_else(|| {
141 invalid("MIDI data must fit seven bits; note-on velocity must be nonzero")
142 })?;
143 Ok(3)
144 }
145}
146
147fn invalid(message: &'static str) -> io::Error {
148 io::Error::new(io::ErrorKind::InvalidInput, message)
149}