Skip to main content

qualia_audio/midi/ump/
encode.rs

1//! Encode MIDI messages into Universal MIDI Packets, and translate MIDI 1.0
2//! channel-voice → MIDI 2.0 channel-voice (with default resolution up-scaling).
3
4use crate::midi::message::MidiMessage;
5use crate::types::AudioError;
6
7use super::packet::{Midi2ChannelVoice, UmpPacket};
8use super::scale::scale_up;
9
10/// Build the first word of a channel-voice UMP (MT nibble + group + status).
11#[inline]
12const fn word0_head(message_type: u8, group: u8, status_byte: u8) -> u32 {
13    ((message_type as u32 & 0x0F) << 28)
14        | ((group as u32 & 0x0F) << 24)
15        | ((status_byte as u32) << 16)
16}
17
18/// Encode a MIDI 1.0 **channel-voice** message into a 32-bit UMP (Message Type
19/// 0x2) on `group`. Returns [`AudioError::UnsupportedFormat`] for non
20/// channel-voice messages (system real-time/common are not MT 0x2).
21pub fn encode_midi1_channel_voice(group: u8, msg: MidiMessage) -> Result<UmpPacket, AudioError> {
22    if group > 15 {
23        return Err(AudioError::InvalidParameter);
24    }
25    let (status, d1, d2) = match msg {
26        MidiMessage::NoteOff(n) => (0x80 | n.channel, n.note, n.velocity),
27        MidiMessage::NoteOn(n) => (0x90 | n.channel, n.note, n.velocity),
28        MidiMessage::PolyPressure(p) => (0xA0 | p.channel, p.note, p.pressure),
29        MidiMessage::ControlChange(c) => (0xB0 | c.channel, c.controller, c.value),
30        MidiMessage::ProgramChange(p) => (0xC0 | p.channel, p.program, 0),
31        MidiMessage::ChannelPressure(p) => (0xD0 | p.channel, p.pressure, 0),
32        MidiMessage::PitchBend(b) => (
33            0xE0 | b.channel,
34            (b.value & 0x7F) as u8,
35            ((b.value >> 7) & 0x7F) as u8,
36        ),
37        _ => return Err(AudioError::UnsupportedFormat),
38    };
39    let word = word0_head(0x2, group, status) | ((d1 as u32) << 8) | (d2 as u32);
40    Ok(UmpPacket::new32(word))
41}
42
43/// Encode a MIDI 2.0 channel-voice message into a 64-bit UMP (Message Type 0x4)
44/// on `group`.
45pub fn encode_midi2_channel_voice(
46    group: u8,
47    cv: Midi2ChannelVoice,
48) -> Result<UmpPacket, AudioError> {
49    if group > 15 {
50        return Err(AudioError::InvalidParameter);
51    }
52    let (word0, word1) = match cv {
53        Midi2ChannelVoice::NoteOff {
54            channel,
55            note,
56            velocity,
57            attribute_type,
58            attribute_data,
59        } => (
60            word0_head(0x4, group, 0x80 | channel) | ((note as u32) << 8) | attribute_type as u32,
61            ((velocity as u32) << 16) | attribute_data as u32,
62        ),
63        Midi2ChannelVoice::NoteOn {
64            channel,
65            note,
66            velocity,
67            attribute_type,
68            attribute_data,
69        } => (
70            word0_head(0x4, group, 0x90 | channel) | ((note as u32) << 8) | attribute_type as u32,
71            ((velocity as u32) << 16) | attribute_data as u32,
72        ),
73        Midi2ChannelVoice::PolyPressure {
74            channel,
75            note,
76            pressure,
77        } => (
78            word0_head(0x4, group, 0xA0 | channel) | ((note as u32) << 8),
79            pressure,
80        ),
81        Midi2ChannelVoice::ControlChange {
82            channel,
83            index,
84            value,
85        } => (
86            word0_head(0x4, group, 0xB0 | channel) | ((index as u32) << 8),
87            value,
88        ),
89        Midi2ChannelVoice::ProgramChange {
90            channel,
91            program,
92            bank_valid,
93            bank_msb,
94            bank_lsb,
95        } => (
96            word0_head(0x4, group, 0xC0 | channel) | (bank_valid as u32),
97            ((program as u32) << 24) | ((bank_msb as u32) << 8) | (bank_lsb as u32),
98        ),
99        Midi2ChannelVoice::ChannelPressure { channel, pressure } => {
100            (word0_head(0x4, group, 0xD0 | channel), pressure)
101        }
102        Midi2ChannelVoice::PitchBend { channel, value } => {
103            (word0_head(0x4, group, 0xE0 | channel), value)
104        }
105    };
106    Ok(UmpPacket::new64(word0, word1))
107}
108
109/// Translate a MIDI 1.0 channel-voice message to the MIDI 2.0 channel-voice
110/// model, applying default resolution up-scaling (7-bit→16-bit velocity,
111/// 7-bit→32-bit controllers/pressure, 14-bit→32-bit pitch bend).
112///
113/// Per the MIDI 2.0 default translation, a MIDI 1.0 Note On with velocity 0 is
114/// translated to a MIDI 2.0 Note Off. Returns [`AudioError::UnsupportedFormat`]
115/// for non channel-voice input.
116pub fn translate_midi1_to_midi2(msg: MidiMessage) -> Result<Midi2ChannelVoice, AudioError> {
117    let cv = match msg {
118        MidiMessage::NoteOff(n) => Midi2ChannelVoice::NoteOff {
119            channel: n.channel,
120            note: n.note,
121            velocity: scale_up(n.velocity as u32, 7, 16) as u16,
122            attribute_type: 0,
123            attribute_data: 0,
124        },
125        MidiMessage::NoteOn(n) if n.velocity == 0 => Midi2ChannelVoice::NoteOff {
126            channel: n.channel,
127            note: n.note,
128            velocity: 0,
129            attribute_type: 0,
130            attribute_data: 0,
131        },
132        MidiMessage::NoteOn(n) => Midi2ChannelVoice::NoteOn {
133            channel: n.channel,
134            note: n.note,
135            velocity: scale_up(n.velocity as u32, 7, 16) as u16,
136            attribute_type: 0,
137            attribute_data: 0,
138        },
139        MidiMessage::PolyPressure(p) => Midi2ChannelVoice::PolyPressure {
140            channel: p.channel,
141            note: p.note,
142            pressure: scale_up(p.pressure as u32, 7, 32),
143        },
144        MidiMessage::ControlChange(c) => Midi2ChannelVoice::ControlChange {
145            channel: c.channel,
146            index: c.controller,
147            value: scale_up(c.value as u32, 7, 32),
148        },
149        MidiMessage::ProgramChange(p) => Midi2ChannelVoice::ProgramChange {
150            channel: p.channel,
151            program: p.program,
152            bank_valid: false,
153            bank_msb: 0,
154            bank_lsb: 0,
155        },
156        MidiMessage::ChannelPressure(p) => Midi2ChannelVoice::ChannelPressure {
157            channel: p.channel,
158            pressure: scale_up(p.pressure as u32, 7, 32),
159        },
160        MidiMessage::PitchBend(b) => Midi2ChannelVoice::PitchBend {
161            channel: b.channel,
162            value: scale_up(b.value as u32, 14, 32),
163        },
164        _ => return Err(AudioError::UnsupportedFormat),
165    };
166    Ok(cv)
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::midi::message::note::NoteOn;
173
174    #[test]
175    fn golden_midi1_note_on_to_ump32() {
176        // NoteOn ch0 note60 vel100 on group0 -> 0x2090_3C64.
177        let msg = MidiMessage::NoteOn(NoteOn::new(0, 60, 100).unwrap());
178        let p = encode_midi1_channel_voice(0, msg).unwrap();
179        assert_eq!(p.word_count, 1);
180        assert_eq!(p.words[0], 0x2090_3C64);
181    }
182
183    #[test]
184    fn golden_velocity_scale_7_to_16() {
185        let msg = MidiMessage::NoteOn(NoteOn::new(0, 60, 100).unwrap());
186        match translate_midi1_to_midi2(msg).unwrap() {
187            Midi2ChannelVoice::NoteOn {
188                velocity,
189                note,
190                channel,
191                ..
192            } => {
193                assert_eq!(channel, 0);
194                assert_eq!(note, 60);
195                assert_eq!(velocity, 0xC924);
196            }
197            other => panic!("expected NoteOn, got {other:?}"),
198        }
199    }
200
201    #[test]
202    fn note_on_velocity_zero_becomes_note_off() {
203        let msg = MidiMessage::NoteOn(NoteOn::new(3, 40, 0).unwrap());
204        assert!(matches!(
205            translate_midi1_to_midi2(msg).unwrap(),
206            Midi2ChannelVoice::NoteOff {
207                channel: 3,
208                note: 40,
209                ..
210            }
211        ));
212    }
213
214    #[test]
215    fn midi2_note_on_encodes_two_words() {
216        let cv = Midi2ChannelVoice::NoteOn {
217            channel: 0,
218            note: 60,
219            velocity: 0xC924,
220            attribute_type: 0,
221            attribute_data: 0,
222        };
223        let p = encode_midi2_channel_voice(0, cv).unwrap();
224        assert_eq!(p.word_count, 2);
225        assert_eq!(p.words[0], 0x4090_3C00);
226        assert_eq!(p.words[1], 0xC924_0000);
227    }
228}