Skip to main content

qualia_audio/midi/ump/
decode.rs

1//! Decode Universal MIDI Packets back into messages, and translate MIDI 2.0
2//! channel-voice → MIDI 1.0 channel-voice (with default resolution down-scaling).
3
4use crate::midi::message::channel_pressure::ChannelPressure;
5use crate::midi::message::control_change::ControlChange;
6use crate::midi::message::note::{NoteOff, NoteOn};
7use crate::midi::message::pitch_bend::PitchBend;
8use crate::midi::message::poly_pressure::PolyPressure;
9use crate::midi::message::program_change::ProgramChange;
10use crate::midi::message::MidiMessage;
11use crate::types::AudioError;
12
13use super::packet::{Midi2ChannelVoice, UmpPacket, MT_MIDI1_CHANNEL_VOICE, MT_MIDI2_CHANNEL_VOICE};
14use super::scale::scale_down;
15
16/// The decoded content of a UMP, spanning the message types this lane models.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum UmpDecoded {
19    /// MIDI 1.0 channel voice (MT 0x2).
20    Midi1(MidiMessage),
21    /// MIDI 2.0 channel voice (MT 0x4).
22    Midi2(Midi2ChannelVoice),
23    /// A message type this decoder does not expand (utility, system, data/SysEx).
24    /// Carries the raw Message Type nibble.
25    Unhandled(u8),
26}
27
28/// Decode a MIDI 1.0 channel-voice UMP (MT 0x2) into a [`MidiMessage`].
29/// Errors [`AudioError::UnsupportedFormat`] if the packet is not MT 0x2.
30pub fn decode_midi1_channel_voice(packet: UmpPacket) -> Result<MidiMessage, AudioError> {
31    if packet.message_type() != MT_MIDI1_CHANNEL_VOICE {
32        return Err(AudioError::UnsupportedFormat);
33    }
34    let w = packet.words[0];
35    let status = ((w >> 16) & 0xFF) as u8;
36    let channel = status & 0x0F;
37    let d1 = ((w >> 8) & 0x7F) as u8;
38    let d2 = (w & 0x7F) as u8;
39    let msg = match status & 0xF0 {
40        0x80 => MidiMessage::NoteOff(NoteOff {
41            channel,
42            note: d1,
43            velocity: d2,
44        }),
45        0x90 => MidiMessage::NoteOn(NoteOn {
46            channel,
47            note: d1,
48            velocity: d2,
49        }),
50        0xA0 => MidiMessage::PolyPressure(PolyPressure {
51            channel,
52            note: d1,
53            pressure: d2,
54        }),
55        0xB0 => MidiMessage::ControlChange(ControlChange {
56            channel,
57            controller: d1,
58            value: d2,
59        }),
60        0xC0 => MidiMessage::ProgramChange(ProgramChange {
61            channel,
62            program: d1,
63        }),
64        0xD0 => MidiMessage::ChannelPressure(ChannelPressure {
65            channel,
66            pressure: d1,
67        }),
68        0xE0 => MidiMessage::PitchBend(PitchBend {
69            channel,
70            value: ((d2 as u16) << 7) | (d1 as u16),
71        }),
72        _ => return Err(AudioError::UnsupportedFormat),
73    };
74    Ok(msg)
75}
76
77/// Decode a MIDI 2.0 channel-voice UMP (MT 0x4) into a [`Midi2ChannelVoice`].
78/// Errors [`AudioError::UnsupportedFormat`] if the packet is not MT 0x4, or
79/// [`AudioError::MalformedAudio`] if it does not carry two words.
80pub fn decode_midi2_channel_voice(packet: UmpPacket) -> Result<Midi2ChannelVoice, AudioError> {
81    if packet.message_type() != MT_MIDI2_CHANNEL_VOICE {
82        return Err(AudioError::UnsupportedFormat);
83    }
84    if packet.word_count < 2 {
85        return Err(AudioError::MalformedAudio);
86    }
87    let w0 = packet.words[0];
88    let w1 = packet.words[1];
89    let status = ((w0 >> 16) & 0xFF) as u8;
90    let channel = status & 0x0F;
91    let note = ((w0 >> 8) & 0x7F) as u8;
92    let index = ((w0 >> 8) & 0x7F) as u8;
93    let cv = match status & 0xF0 {
94        0x80 => Midi2ChannelVoice::NoteOff {
95            channel,
96            note,
97            velocity: (w1 >> 16) as u16,
98            attribute_type: (w0 & 0xFF) as u8,
99            attribute_data: (w1 & 0xFFFF) as u16,
100        },
101        0x90 => Midi2ChannelVoice::NoteOn {
102            channel,
103            note,
104            velocity: (w1 >> 16) as u16,
105            attribute_type: (w0 & 0xFF) as u8,
106            attribute_data: (w1 & 0xFFFF) as u16,
107        },
108        0xA0 => Midi2ChannelVoice::PolyPressure {
109            channel,
110            note,
111            pressure: w1,
112        },
113        0xB0 => Midi2ChannelVoice::ControlChange {
114            channel,
115            index,
116            value: w1,
117        },
118        0xC0 => Midi2ChannelVoice::ProgramChange {
119            channel,
120            program: (w1 >> 24) as u8,
121            bank_valid: (w0 & 0x01) != 0,
122            bank_msb: ((w1 >> 8) & 0x7F) as u8,
123            bank_lsb: (w1 & 0x7F) as u8,
124        },
125        0xD0 => Midi2ChannelVoice::ChannelPressure {
126            channel,
127            pressure: w1,
128        },
129        0xE0 => Midi2ChannelVoice::PitchBend { channel, value: w1 },
130        _ => return Err(AudioError::UnsupportedFormat),
131    };
132    Ok(cv)
133}
134
135/// Decode any modelled UMP, dispatching on Message Type.
136pub fn decode(packet: UmpPacket) -> Result<UmpDecoded, AudioError> {
137    match packet.message_type() {
138        MT_MIDI1_CHANNEL_VOICE => Ok(UmpDecoded::Midi1(decode_midi1_channel_voice(packet)?)),
139        MT_MIDI2_CHANNEL_VOICE => Ok(UmpDecoded::Midi2(decode_midi2_channel_voice(packet)?)),
140        mt => Ok(UmpDecoded::Unhandled(mt)),
141    }
142}
143
144/// Translate a MIDI 2.0 channel-voice message down to the MIDI 1.0 model,
145/// applying default resolution down-scaling. Per the MIDI 2.0 default
146/// translation, a MIDI 2.0 Note On whose velocity scales down to 0 is clamped to
147/// velocity 1 so it is not misread as a MIDI 1.0 implicit note-off.
148pub fn translate_midi2_to_midi1(cv: Midi2ChannelVoice) -> Result<MidiMessage, AudioError> {
149    let msg = match cv {
150        Midi2ChannelVoice::NoteOff {
151            channel,
152            note,
153            velocity,
154            ..
155        } => MidiMessage::NoteOff(NoteOff {
156            channel,
157            note,
158            velocity: scale_down(velocity as u32, 16, 7) as u8,
159        }),
160        Midi2ChannelVoice::NoteOn {
161            channel,
162            note,
163            velocity,
164            ..
165        } => {
166            let mut v7 = scale_down(velocity as u32, 16, 7) as u8;
167            if v7 == 0 {
168                v7 = 1; // avoid implicit note-off on down-translation
169            }
170            MidiMessage::NoteOn(NoteOn {
171                channel,
172                note,
173                velocity: v7,
174            })
175        }
176        Midi2ChannelVoice::PolyPressure {
177            channel,
178            note,
179            pressure,
180        } => MidiMessage::PolyPressure(PolyPressure {
181            channel,
182            note,
183            pressure: scale_down(pressure, 32, 7) as u8,
184        }),
185        Midi2ChannelVoice::ControlChange {
186            channel,
187            index,
188            value,
189        } => MidiMessage::ControlChange(ControlChange {
190            channel,
191            controller: index,
192            value: scale_down(value, 32, 7) as u8,
193        }),
194        Midi2ChannelVoice::ProgramChange {
195            channel, program, ..
196        } => MidiMessage::ProgramChange(ProgramChange { channel, program }),
197        Midi2ChannelVoice::ChannelPressure { channel, pressure } => {
198            MidiMessage::ChannelPressure(ChannelPressure {
199                channel,
200                pressure: scale_down(pressure, 32, 7) as u8,
201            })
202        }
203        Midi2ChannelVoice::PitchBend { channel, value } => MidiMessage::PitchBend(PitchBend {
204            channel,
205            value: scale_down(value, 32, 14) as u16,
206        }),
207    };
208    Ok(msg)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::midi::message::note::NoteOn as MsgNoteOn;
215    use crate::midi::ump::encode::{
216        encode_midi1_channel_voice, encode_midi2_channel_voice, translate_midi1_to_midi2,
217    };
218
219    #[test]
220    fn golden_ump32_note_on_roundtrip() {
221        // Encode a MIDI-1.0 note-on to a 32-bit UMP word, decode back the same.
222        let orig = MidiMessage::NoteOn(MsgNoteOn::new(0, 60, 100).unwrap());
223        let packet = encode_midi1_channel_voice(0, orig).unwrap();
224        let back = decode_midi1_channel_voice(packet).unwrap();
225        assert_eq!(back, orig);
226        match back {
227            MidiMessage::NoteOn(n) => {
228                assert_eq!(n.note, 60);
229                assert_eq!(n.velocity, 100);
230            }
231            other => panic!("expected NoteOn, got {other:?}"),
232        }
233    }
234
235    #[test]
236    fn golden_velocity_scale_roundtrip_via_translation() {
237        // MIDI1 vel 100 -> MIDI2 0xC924 -> MIDI1 100 (through decode of a real packet).
238        let orig = MidiMessage::NoteOn(MsgNoteOn::new(5, 72, 100).unwrap());
239        let cv = translate_midi1_to_midi2(orig).unwrap();
240        let packet = encode_midi2_channel_voice(0, cv).unwrap();
241        let cv_back = decode_midi2_channel_voice(packet).unwrap();
242        assert_eq!(cv_back, cv);
243        match cv_back {
244            Midi2ChannelVoice::NoteOn { velocity, .. } => assert_eq!(velocity, 0xC924),
245            other => panic!("expected NoteOn, got {other:?}"),
246        }
247        let back = translate_midi2_to_midi1(cv_back).unwrap();
248        assert_eq!(back, orig);
249    }
250
251    #[test]
252    fn decode_dispatch() {
253        let p =
254            encode_midi1_channel_voice(0, MidiMessage::NoteOn(MsgNoteOn::new(0, 60, 100).unwrap()))
255                .unwrap();
256        assert!(matches!(
257            decode(p).unwrap(),
258            UmpDecoded::Midi1(MidiMessage::NoteOn(_))
259        ));
260    }
261
262    #[test]
263    fn pitch_bend_14_to_32_roundtrip() {
264        let orig = MidiMessage::PitchBend(
265            crate::midi::message::pitch_bend::PitchBend::new(2, 8192).unwrap(),
266        );
267        let cv = translate_midi1_to_midi2(orig).unwrap();
268        match cv {
269            Midi2ChannelVoice::PitchBend { value, .. } => assert_eq!(value, 0x8000_0000),
270            other => panic!("expected PitchBend, got {other:?}"),
271        }
272        assert_eq!(translate_midi2_to_midi1(cv).unwrap(), orig);
273    }
274}