qualia_audio/midi/message/
channel_pressure.rs1use crate::types::AudioError;
4
5pub const STATUS_CHANNEL_PRESSURE: u8 = 0xD0;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct ChannelPressure {
11 pub channel: u8,
13 pub pressure: u8,
15}
16
17impl ChannelPressure {
18 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 #[inline]
28 pub fn to_bytes(self) -> [u8; 2] {
29 [
30 STATUS_CHANNEL_PRESSURE | (self.channel & 0x0F),
31 self.pressure,
32 ]
33 }
34
35 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}