qualia_audio/midi/message/
control_change.rs1use crate::types::AudioError;
8
9pub const STATUS_CONTROL_CHANGE: u8 = 0xB0;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct ControlChange {
15 pub channel: u8,
17 pub controller: u8,
19 pub value: u8,
21}
22
23impl ControlChange {
24 pub fn new(channel: u8, controller: u8, value: u8) -> Result<Self, AudioError> {
26 if channel > 15 || controller > 127 || value > 127 {
27 return Err(AudioError::InvalidParameter);
28 }
29 Ok(Self {
30 channel,
31 controller,
32 value,
33 })
34 }
35
36 #[inline]
38 pub fn to_bytes(self) -> [u8; 3] {
39 [
40 STATUS_CONTROL_CHANGE | (self.channel & 0x0F),
41 self.controller,
42 self.value,
43 ]
44 }
45
46 pub fn parse(bytes: &[u8]) -> Result<Self, AudioError> {
48 if bytes.len() < 3 {
49 return Err(AudioError::MalformedAudio);
50 }
51 if bytes[0] & 0xF0 != STATUS_CONTROL_CHANGE {
52 return Err(AudioError::UnsupportedFormat);
53 }
54 if bytes[1] > 127 || bytes[2] > 127 {
55 return Err(AudioError::MalformedAudio);
56 }
57 Ok(Self {
58 channel: bytes[0] & 0x0F,
59 controller: bytes[1],
60 value: bytes[2],
61 })
62 }
63
64 #[inline]
66 pub fn is_channel_mode(self) -> bool {
67 self.controller >= 120
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn cc_roundtrip() {
77 let cc = ControlChange::new(1, 7, 100).unwrap(); assert_eq!(cc.to_bytes(), [0xB1, 7, 100]);
79 assert_eq!(ControlChange::parse(&cc.to_bytes()).unwrap(), cc);
80 }
81
82 #[test]
83 fn channel_mode_range() {
84 assert!(ControlChange::new(0, 123, 0).unwrap().is_channel_mode());
85 assert!(!ControlChange::new(0, 64, 127).unwrap().is_channel_mode());
86 }
87
88 #[test]
89 fn rejects_bad() {
90 assert_eq!(
91 ControlChange::new(0, 128, 0),
92 Err(AudioError::InvalidParameter)
93 );
94 assert_eq!(
95 ControlChange::parse(&[0x90, 7, 100]),
96 Err(AudioError::UnsupportedFormat)
97 );
98 }
99}