Skip to main content

qualia_audio/midi/message/
program_change.rs

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