Skip to main content

qualia_audio/midi/message/
channel_pressure.rs

1//! MIDI 1.0 Channel Pressure / Aftertouch (`0xDn`) — a 2-byte message.
2
3use crate::types::AudioError;
4
5/// Channel Pressure status nibble (`0xDn`).
6pub const STATUS_CHANNEL_PRESSURE: u8 = 0xD0;
7
8/// A MIDI 1.0 Channel Pressure (channel aftertouch) message.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct ChannelPressure {
11    /// MIDI channel, 0..=15.
12    pub channel: u8,
13    /// Pressure amount, 0..=127.
14    pub pressure: u8,
15}
16
17impl ChannelPressure {
18    /// Construct a validated Channel Pressure.
19    pub fn new(channel: u8, pressure: u8) -> Result<Self, AudioError> {
20        if channel > 15 || pressure > 127 {
21            return Err(AudioError::InvalidParameter);
22        }
23        Ok(Self { channel, pressure })
24    }
25
26    /// Serialize to the 2 bytes `[0xDn, pressure]`.
27    #[inline]
28    pub fn to_bytes(self) -> [u8; 2] {
29        [
30            STATUS_CHANNEL_PRESSURE | (self.channel & 0x0F),
31            self.pressure,
32        ]
33    }
34
35    /// Parse from a slice whose first byte is a Channel Pressure status.
36    pub fn parse(bytes: &[u8]) -> Result<Self, AudioError> {
37        if bytes.len() < 2 {
38            return Err(AudioError::MalformedAudio);
39        }
40        if bytes[0] & 0xF0 != STATUS_CHANNEL_PRESSURE {
41            return Err(AudioError::UnsupportedFormat);
42        }
43        if bytes[1] > 127 {
44            return Err(AudioError::MalformedAudio);
45        }
46        Ok(Self {
47            channel: bytes[0] & 0x0F,
48            pressure: bytes[1],
49        })
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn roundtrip() {
59        let cp = ChannelPressure::new(2, 90).unwrap();
60        assert_eq!(cp.to_bytes(), [0xD2, 90]);
61        assert_eq!(ChannelPressure::parse(&cp.to_bytes()).unwrap(), cp);
62    }
63
64    #[test]
65    fn rejects_bad() {
66        assert_eq!(
67            ChannelPressure::new(0, 128),
68            Err(AudioError::InvalidParameter)
69        );
70        assert_eq!(
71            ChannelPressure::parse(&[0xE0, 10]),
72            Err(AudioError::UnsupportedFormat)
73        );
74        assert_eq!(
75            ChannelPressure::parse(&[0xD0]),
76            Err(AudioError::MalformedAudio)
77        );
78    }
79}