Skip to main content

qualia_audio/midi/message/
note.rs

1//! MIDI 1.0 Note On / Note Off channel-voice messages.
2//!
3//! Zero-heap: build returns a fixed `[u8; 3]`; parse reads a caller slice and
4//! returns a small `Copy` struct. Channel is 0..=15; note/velocity 0..=127.
5
6use crate::types::AudioError;
7
8/// Note Off status nibble (`0x8n`).
9pub const STATUS_NOTE_OFF: u8 = 0x80;
10/// Note On status nibble (`0x9n`).
11pub const STATUS_NOTE_ON: u8 = 0x90;
12
13/// A MIDI 1.0 Note On message. A Note On with `velocity == 0` is, by
14/// convention, an implied Note Off (see [`NoteOn::is_effectively_note_off`]).
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct NoteOn {
17    /// MIDI channel, 0..=15.
18    pub channel: u8,
19    /// Note number, 0..=127 (60 = middle C).
20    pub note: u8,
21    /// Attack velocity, 0..=127.
22    pub velocity: u8,
23}
24
25/// A MIDI 1.0 Note Off message. `velocity` is release velocity.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct NoteOff {
28    /// MIDI channel, 0..=15.
29    pub channel: u8,
30    /// Note number, 0..=127.
31    pub note: u8,
32    /// Release velocity, 0..=127.
33    pub velocity: u8,
34}
35
36impl NoteOn {
37    /// Construct a validated Note On. Returns [`AudioError::InvalidParameter`]
38    /// if any field is out of range.
39    pub fn new(channel: u8, note: u8, velocity: u8) -> Result<Self, AudioError> {
40        if channel > 15 || note > 127 || velocity > 127 {
41            return Err(AudioError::InvalidParameter);
42        }
43        Ok(Self {
44            channel,
45            note,
46            velocity,
47        })
48    }
49
50    /// Serialize to the 3 status/data bytes `[0x9n, note, velocity]`.
51    #[inline]
52    pub fn to_bytes(self) -> [u8; 3] {
53        [
54            STATUS_NOTE_ON | (self.channel & 0x0F),
55            self.note,
56            self.velocity,
57        ]
58    }
59
60    /// Parse from a byte slice whose first byte is a Note On status.
61    /// Returns [`AudioError::UnsupportedFormat`] if the status nibble is not
62    /// `0x9n`, or [`AudioError::MalformedAudio`] if the slice is too short or a
63    /// data byte has its high bit set.
64    pub fn parse(bytes: &[u8]) -> Result<Self, AudioError> {
65        if bytes.len() < 3 {
66            return Err(AudioError::MalformedAudio);
67        }
68        if bytes[0] & 0xF0 != STATUS_NOTE_ON {
69            return Err(AudioError::UnsupportedFormat);
70        }
71        if bytes[1] > 127 || bytes[2] > 127 {
72            return Err(AudioError::MalformedAudio);
73        }
74        Ok(Self {
75            channel: bytes[0] & 0x0F,
76            note: bytes[1],
77            velocity: bytes[2],
78        })
79    }
80
81    /// True if this is a running-status "note off" (velocity 0).
82    #[inline]
83    pub fn is_effectively_note_off(self) -> bool {
84        self.velocity == 0
85    }
86}
87
88impl NoteOff {
89    /// Construct a validated Note Off.
90    pub fn new(channel: u8, note: u8, velocity: u8) -> Result<Self, AudioError> {
91        if channel > 15 || note > 127 || velocity > 127 {
92            return Err(AudioError::InvalidParameter);
93        }
94        Ok(Self {
95            channel,
96            note,
97            velocity,
98        })
99    }
100
101    /// Serialize to `[0x8n, note, velocity]`.
102    #[inline]
103    pub fn to_bytes(self) -> [u8; 3] {
104        [
105            STATUS_NOTE_OFF | (self.channel & 0x0F),
106            self.note,
107            self.velocity,
108        ]
109    }
110
111    /// Parse from a byte slice whose first byte is a Note Off status.
112    pub fn parse(bytes: &[u8]) -> Result<Self, AudioError> {
113        if bytes.len() < 3 {
114            return Err(AudioError::MalformedAudio);
115        }
116        if bytes[0] & 0xF0 != STATUS_NOTE_OFF {
117            return Err(AudioError::UnsupportedFormat);
118        }
119        if bytes[1] > 127 || bytes[2] > 127 {
120            return Err(AudioError::MalformedAudio);
121        }
122        Ok(Self {
123            channel: bytes[0] & 0x0F,
124            note: bytes[1],
125            velocity: bytes[2],
126        })
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn golden_note_on_parse() {
136        // Canonical golden vector: 0x90 0x3C 0x64 -> NoteOn(ch0, note60, vel100).
137        let n = NoteOn::parse(&[0x90, 0x3C, 0x64]).unwrap();
138        assert_eq!(n.channel, 0);
139        assert_eq!(n.note, 60);
140        assert_eq!(n.velocity, 100);
141    }
142
143    #[test]
144    fn note_on_roundtrip() {
145        let n = NoteOn::new(9, 64, 127).unwrap();
146        assert_eq!(n.to_bytes(), [0x99, 64, 127]);
147        assert_eq!(NoteOn::parse(&n.to_bytes()).unwrap(), n);
148    }
149
150    #[test]
151    fn note_off_roundtrip() {
152        let n = NoteOff::new(0, 60, 0).unwrap();
153        assert_eq!(n.to_bytes(), [0x80, 60, 0]);
154        assert_eq!(NoteOff::parse(&n.to_bytes()).unwrap(), n);
155    }
156
157    #[test]
158    fn note_on_zero_velocity_is_note_off() {
159        assert!(NoteOn::new(0, 60, 0).unwrap().is_effectively_note_off());
160        assert!(!NoteOn::new(0, 60, 1).unwrap().is_effectively_note_off());
161    }
162
163    #[test]
164    fn out_of_range_rejected() {
165        assert_eq!(NoteOn::new(16, 0, 0), Err(AudioError::InvalidParameter));
166        assert_eq!(NoteOn::new(0, 128, 0), Err(AudioError::InvalidParameter));
167        assert_eq!(
168            NoteOn::parse(&[0x90, 0x3C]),
169            Err(AudioError::MalformedAudio)
170        );
171        assert_eq!(
172            NoteOn::parse(&[0x80, 0x3C, 0x64]),
173            Err(AudioError::UnsupportedFormat)
174        );
175    }
176}