Skip to main content

qualia_audio/midi/message/
channel_mode.rs

1//! MIDI 1.0 Channel Mode messages.
2//!
3//! Channel-mode messages are Control Change messages with controller numbers
4//! 120..=127. They are modelled here as a distinct typed enum for clarity.
5
6use crate::types::AudioError;
7
8/// Control Change status nibble (`0xBn`) — channel-mode messages ride on CC.
9pub const STATUS_CONTROL_CHANGE: u8 = 0xB0;
10
11// Channel-mode controller numbers.
12/// All Sound Off (CC 120).
13pub const CC_ALL_SOUND_OFF: u8 = 120;
14/// Reset All Controllers (CC 121).
15pub const CC_RESET_ALL_CONTROLLERS: u8 = 121;
16/// Local Control On/Off (CC 122).
17pub const CC_LOCAL_CONTROL: u8 = 122;
18/// All Notes Off (CC 123).
19pub const CC_ALL_NOTES_OFF: u8 = 123;
20/// Omni Mode Off (CC 124).
21pub const CC_OMNI_OFF: u8 = 124;
22/// Omni Mode On (CC 125).
23pub const CC_OMNI_ON: u8 = 125;
24/// Mono Mode On / Poly Off (CC 126); data = number of channels.
25pub const CC_MONO_ON: u8 = 126;
26/// Poly Mode On / Mono Off (CC 127).
27pub const CC_POLY_ON: u8 = 127;
28
29/// The specific channel-mode operation.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ChannelModeMessage {
32    /// All Sound Off (immediately mute all voices).
33    AllSoundOff,
34    /// Reset All Controllers.
35    ResetAllControllers,
36    /// Local Control on (`true`) or off (`false`).
37    LocalControl(bool),
38    /// All Notes Off.
39    AllNotesOff,
40    /// Omni Mode Off.
41    OmniModeOff,
42    /// Omni Mode On.
43    OmniModeOn,
44    /// Mono Mode On; payload is the channel count (0 = "all voices on 1 ch").
45    MonoModeOn(u8),
46    /// Poly Mode On.
47    PolyModeOn,
48}
49
50/// A channel-mode message on a specific channel.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct ChannelMode {
53    /// MIDI channel, 0..=15.
54    pub channel: u8,
55    /// The channel-mode operation.
56    pub message: ChannelModeMessage,
57}
58
59impl ChannelMode {
60    /// Construct a validated channel-mode message.
61    pub fn new(channel: u8, message: ChannelModeMessage) -> Result<Self, AudioError> {
62        if channel > 15 {
63            return Err(AudioError::InvalidParameter);
64        }
65        if let ChannelModeMessage::MonoModeOn(n) = message {
66            if n > 127 {
67                return Err(AudioError::InvalidParameter);
68            }
69        }
70        Ok(Self { channel, message })
71    }
72
73    /// The (controller, value) data-byte pair for this mode message.
74    #[inline]
75    fn controller_value(self) -> (u8, u8) {
76        match self.message {
77            ChannelModeMessage::AllSoundOff => (CC_ALL_SOUND_OFF, 0),
78            ChannelModeMessage::ResetAllControllers => (CC_RESET_ALL_CONTROLLERS, 0),
79            ChannelModeMessage::LocalControl(on) => (CC_LOCAL_CONTROL, if on { 127 } else { 0 }),
80            ChannelModeMessage::AllNotesOff => (CC_ALL_NOTES_OFF, 0),
81            ChannelModeMessage::OmniModeOff => (CC_OMNI_OFF, 0),
82            ChannelModeMessage::OmniModeOn => (CC_OMNI_ON, 0),
83            ChannelModeMessage::MonoModeOn(n) => (CC_MONO_ON, n),
84            ChannelModeMessage::PolyModeOn => (CC_POLY_ON, 0),
85        }
86    }
87
88    /// Serialize to `[0xBn, controller, value]`.
89    #[inline]
90    pub fn to_bytes(self) -> [u8; 3] {
91        let (controller, value) = self.controller_value();
92        [
93            STATUS_CONTROL_CHANGE | (self.channel & 0x0F),
94            controller,
95            value,
96        ]
97    }
98
99    /// Parse from a slice whose first byte is a Control Change status with a
100    /// channel-mode controller (120..=127).
101    pub fn parse(bytes: &[u8]) -> Result<Self, AudioError> {
102        if bytes.len() < 3 {
103            return Err(AudioError::MalformedAudio);
104        }
105        if bytes[0] & 0xF0 != STATUS_CONTROL_CHANGE {
106            return Err(AudioError::UnsupportedFormat);
107        }
108        if bytes[1] > 127 || bytes[2] > 127 {
109            return Err(AudioError::MalformedAudio);
110        }
111        let channel = bytes[0] & 0x0F;
112        let value = bytes[2];
113        let message = match bytes[1] {
114            CC_ALL_SOUND_OFF => ChannelModeMessage::AllSoundOff,
115            CC_RESET_ALL_CONTROLLERS => ChannelModeMessage::ResetAllControllers,
116            CC_LOCAL_CONTROL => ChannelModeMessage::LocalControl(value >= 64),
117            CC_ALL_NOTES_OFF => ChannelModeMessage::AllNotesOff,
118            CC_OMNI_OFF => ChannelModeMessage::OmniModeOff,
119            CC_OMNI_ON => ChannelModeMessage::OmniModeOn,
120            CC_MONO_ON => ChannelModeMessage::MonoModeOn(value),
121            CC_POLY_ON => ChannelModeMessage::PolyModeOn,
122            // Not a channel-mode controller (0..=119 is a normal CC).
123            _ => return Err(AudioError::UnsupportedFormat),
124        };
125        Ok(Self { channel, message })
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn all_notes_off_roundtrip() {
135        let m = ChannelMode::new(0, ChannelModeMessage::AllNotesOff).unwrap();
136        assert_eq!(m.to_bytes(), [0xB0, 123, 0]);
137        assert_eq!(ChannelMode::parse(&m.to_bytes()).unwrap(), m);
138    }
139
140    #[test]
141    fn local_control_and_mono() {
142        let off = ChannelMode::new(1, ChannelModeMessage::LocalControl(false)).unwrap();
143        assert_eq!(off.to_bytes(), [0xB1, 122, 0]);
144        let on = ChannelMode::new(1, ChannelModeMessage::LocalControl(true)).unwrap();
145        assert_eq!(on.to_bytes(), [0xB1, 122, 127]);
146
147        let mono = ChannelMode::new(2, ChannelModeMessage::MonoModeOn(4)).unwrap();
148        assert_eq!(mono.to_bytes(), [0xB2, 126, 4]);
149        assert_eq!(ChannelMode::parse(&mono.to_bytes()).unwrap(), mono);
150    }
151
152    #[test]
153    fn non_mode_cc_rejected() {
154        // Controller 7 is channel volume, not a channel-mode message.
155        assert_eq!(
156            ChannelMode::parse(&[0xB0, 7, 100]),
157            Err(AudioError::UnsupportedFormat)
158        );
159    }
160}