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 pub(crate) fn encode(self, bytes: &mut [u8; 3]) -> io::Result<usize> {
85 let (channel, message) = match self {
86 Self::Play => {
87 bytes[0] = 0xfa;
88 return Ok(1);
89 }
90 Self::Stop => {
91 bytes[0] = 0xfc;
92 return Ok(1);
93 }
94 Self::NoteOn {
95 channel,
96 note,
97 velocity,
98 } => (
99 channel,
100 MidiMessage::On(Note {
101 number: note,
102 velocity,
103 }),
104 ),
105 Self::NoteOff { channel, note } => (channel, MidiMessage::Off(note)),
106 Self::ControlChange {
107 channel,
108 controller,
109 value,
110 } => (channel, MidiMessage::Control(controller, value)),
111 Self::AllNotesOff { channel } => (channel, MidiMessage::Control(123, 0)),
112 };
113 *bytes = message.encode(channel.index()).ok_or_else(|| {
114 invalid("MIDI data must fit seven bits; note-on velocity must be nonzero")
115 })?;
116 Ok(3)
117 }
118}
119
120fn invalid(message: &'static str) -> io::Error {
121 io::Error::new(io::ErrorKind::InvalidInput, message)
122}