Skip to main content

wavegraph_core/
midi.rs

1//! MIDI 1.0 voice messages for use as frame-timed [patch events](crate::Event).
2//! Routing (a mixer channel, USB cable or graph port) belongs to the sender.
3
4/// A seven-bit note number and strike velocity.
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub struct Note {
7    /// MIDI note number (60 is middle C).
8    pub number: u8,
9    /// Strike velocity in 1..=127.
10    pub velocity: u8,
11}
12
13/// The channel voice messages used by WaveGraph instruments and pattern clips.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum MidiMessage {
16    /// Strike a note.
17    On(Note),
18    /// Release a note.
19    Off(u8),
20    /// Set a controller to a seven-bit value.
21    Control(u8, u8),
22}
23
24impl MidiMessage {
25    /// Decode a three-byte note or controller message, normalizing zero-velocity note-ons.
26    #[must_use]
27    pub const fn decode([status, key, value]: [u8; 3]) -> Option<Self> {
28        if key >= 128 || value >= 128 {
29            return None;
30        }
31        match (status >> 4, value) {
32            (8, _) | (9, 0) => Some(Self::Off(key)),
33            (9, velocity) => Some(Self::On(Note {
34                number: key,
35                velocity,
36            })),
37            (11, _) => Some(Self::Control(key, value)),
38            _ => None,
39        }
40    }
41
42    /// Encode on a zero-based MIDI channel. Invalid data or channels return `None`.
43    #[must_use]
44    pub const fn encode(self, channel: u8) -> Option<[u8; 3]> {
45        let (status, key, value) = match self {
46            Self::On(Note { velocity: 0, .. }) => return None,
47            Self::On(Note { number, velocity }) => (0x90, number, velocity),
48            Self::Off(note) => (0x80, note, 64),
49            Self::Control(number, value) => (0xb0, number, value),
50        };
51        if channel < 16 && key < 128 && value < 128 {
52            Some([status | channel, key, value])
53        } else {
54            None
55        }
56    }
57}