Skip to main content

qualia_audio/midi/mpe/
expression.rs

1//! Per-note MPE expression tracking — pitch-bend, pressure, and timbre (CC74)
2//! held per member channel.
3//!
4//! Because each MPE note owns a member channel, its three continuous expression
5//! dimensions are just that channel's current state:
6//! * **pitch-bend** — 14-bit, centered (stored as a signed offset from center),
7//! * **pressure** — channel pressure / aftertouch (0..=127),
8//! * **timbre** — CC 74 ("slide"), 0..=127.
9//!
10//! [`MpeExpression`] is a fixed `[ChannelExpr; 16]` table indexed by channel, so
11//! updating a controller value is an allocation-free array write — safe on the
12//! real-time thread.
13
14use crate::types::AudioError;
15
16/// Assignable MPE per-note continuous-controller number for timbre (CC 74).
17pub const CC_TIMBRE: u8 = 74;
18
19/// The live expression state of one member channel.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct ChannelExpr {
22    /// Pitch-bend as a signed offset from center (`-8192..=8191`).
23    pub pitch_bend: i16,
24    /// Channel pressure / aftertouch (`0..=127`).
25    pub pressure: u8,
26    /// Timbre — CC 74 value (`0..=127`).
27    pub timbre: u8,
28}
29
30impl ChannelExpr {
31    /// Neutral state: no bend, no pressure, mid timbre.
32    pub const NEUTRAL: ChannelExpr = ChannelExpr {
33        pitch_bend: 0,
34        pressure: 0,
35        timbre: 64,
36    };
37}
38
39/// Per-member-channel MPE expression table.
40#[derive(Debug, Clone)]
41pub struct MpeExpression {
42    channels: [ChannelExpr; 16],
43}
44
45impl Default for MpeExpression {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl MpeExpression {
52    /// A table with every channel at [`ChannelExpr::NEUTRAL`].
53    pub fn new() -> Self {
54        Self {
55            channels: [ChannelExpr::NEUTRAL; 16],
56        }
57    }
58
59    /// Set pitch-bend from the raw 14-bit MIDI value (`0..=16383`, center 8192).
60    ///
61    /// Errors if `channel > 15` or `raw14 > 16383`.
62    pub fn set_pitch_bend_raw(&mut self, channel: u8, raw14: u16) -> Result<(), AudioError> {
63        if channel > 15 || raw14 > 0x3FFF {
64            return Err(AudioError::InvalidParameter);
65        }
66        self.channels[channel as usize].pitch_bend = raw14 as i16 - 8192;
67        Ok(())
68    }
69
70    /// Set pitch-bend from two 7-bit MIDI data bytes `[LSB, MSB]`.
71    pub fn set_pitch_bend_bytes(
72        &mut self,
73        channel: u8,
74        lsb: u8,
75        msb: u8,
76    ) -> Result<(), AudioError> {
77        if lsb & 0x80 != 0 || msb & 0x80 != 0 {
78            return Err(AudioError::InvalidParameter);
79        }
80        let raw = ((msb as u16) << 7) | lsb as u16;
81        self.set_pitch_bend_raw(channel, raw)
82    }
83
84    /// Set channel pressure (`0..=127`).
85    pub fn set_pressure(&mut self, channel: u8, value: u8) -> Result<(), AudioError> {
86        if channel > 15 || value > 127 {
87            return Err(AudioError::InvalidParameter);
88        }
89        self.channels[channel as usize].pressure = value;
90        Ok(())
91    }
92
93    /// Set timbre from a CC message. Only CC 74 updates timbre; other CCs are
94    /// ignored (returns `Ok`). Errors on an out-of-range channel or value.
95    pub fn set_timbre_cc(&mut self, channel: u8, cc: u8, value: u8) -> Result<(), AudioError> {
96        if channel > 15 || value > 127 {
97            return Err(AudioError::InvalidParameter);
98        }
99        if cc == CC_TIMBRE {
100            self.channels[channel as usize].timbre = value;
101        }
102        Ok(())
103    }
104
105    /// Current expression state of `channel`.
106    pub fn get(&self, channel: u8) -> Result<ChannelExpr, AudioError> {
107        if channel > 15 {
108            return Err(AudioError::InvalidParameter);
109        }
110        Ok(self.channels[channel as usize])
111    }
112
113    /// Reset a channel to neutral (e.g. on note-off).
114    pub fn reset(&mut self, channel: u8) -> Result<(), AudioError> {
115        if channel > 15 {
116            return Err(AudioError::InvalidParameter);
117        }
118        self.channels[channel as usize] = ChannelExpr::NEUTRAL;
119        Ok(())
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn pitch_bend_centered() {
129        let mut e = MpeExpression::new();
130        e.set_pitch_bend_raw(2, 8192).unwrap();
131        assert_eq!(e.get(2).unwrap().pitch_bend, 0);
132        e.set_pitch_bend_raw(2, 0).unwrap();
133        assert_eq!(e.get(2).unwrap().pitch_bend, -8192);
134        e.set_pitch_bend_raw(2, 16383).unwrap();
135        assert_eq!(e.get(2).unwrap().pitch_bend, 8191);
136    }
137
138    #[test]
139    fn pitch_bend_from_bytes_matches_raw() {
140        let mut e = MpeExpression::new();
141        // raw 10000 -> lsb = 10000 & 0x7F, msb = 10000 >> 7
142        e.set_pitch_bend_bytes(3, (10000u16 & 0x7F) as u8, (10000u16 >> 7) as u8)
143            .unwrap();
144        assert_eq!(e.get(3).unwrap().pitch_bend, 10000i16 - 8192);
145    }
146
147    #[test]
148    fn pressure_and_timbre() {
149        let mut e = MpeExpression::new();
150        e.set_pressure(5, 100).unwrap();
151        e.set_timbre_cc(5, CC_TIMBRE, 20).unwrap();
152        e.set_timbre_cc(5, 1, 99).unwrap(); // CC1 must not change timbre
153        let s = e.get(5).unwrap();
154        assert_eq!(s.pressure, 100);
155        assert_eq!(s.timbre, 20);
156    }
157
158    #[test]
159    fn reset_and_range_checks() {
160        let mut e = MpeExpression::new();
161        e.set_pressure(1, 64).unwrap();
162        e.reset(1).unwrap();
163        assert_eq!(e.get(1).unwrap(), ChannelExpr::NEUTRAL);
164        assert!(e.set_pressure(16, 0).is_err());
165        assert!(e.set_pitch_bend_raw(0, 16384).is_err());
166        assert!(e.get(16).is_err());
167    }
168}