Skip to main content

wavegraph_remote/
midi.rs

1use core::fmt;
2use std::io;
3use wavegraph_core::midi::{MidiMessage, Note};
4
5/// A validated, human-numbered MIDI channel (1 through 16).
6#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
7pub struct Channel(u8);
8
9impl Channel {
10    /// Validate a one-based channel number.
11    ///
12    /// # Errors
13    /// Returns `InvalidInput` for a number outside 1 through 16.
14    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    /// Human-facing channel number, from 1 through 16.
23    #[must_use]
24    pub const fn number(self) -> u8 {
25        self.0
26    }
27
28    /// Zero-based MIDI wire channel, from 0 through 15.
29    #[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/// Musical commands sent as ordinary MIDI, independently of graph discovery.
42///
43/// Sending confirms submission to the transport, not application by the DSP.
44/// Receivers decide which channels and controllers they support.
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub enum MidiCommand {
47    /// MIDI Start: start or restart the sequencer.
48    Play,
49    /// MIDI Stop: stop the sequencer.
50    Stop,
51    /// Strike a note with nonzero velocity.
52    NoteOn {
53        /// Destination channel.
54        channel: Channel,
55        /// Note number, 0 through 127.
56        note: u8,
57        /// Strike velocity, 1 through 127.
58        velocity: u8,
59    },
60    /// Release a previously struck note.
61    NoteOff {
62        /// Destination channel.
63        channel: Channel,
64        /// Note number, 0 through 127.
65        note: u8,
66    },
67    /// Set a MIDI controller, including channel-mode controllers.
68    ControlChange {
69        /// Destination channel.
70        channel: Channel,
71        /// Controller number, 0 through 127.
72        controller: u8,
73        /// Controller value, 0 through 127.
74        value: u8,
75    },
76    /// Send All Notes Off (CC123) on one channel.
77    AllNotesOff {
78        /// Destination channel.
79        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}