Skip to main content

qualia_audio/midi/message/
poly_pressure.rs

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