midi-control 0.2.0

Communicate with MIDI controllers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//
// (c) 2020 Hubert Figuière
//
// License: LGPL-3.0-or-later

//! MIDI messages
//!

use crate::consts;
use crate::note::MidiNote;
use crate::sysex;

/// The MIDI Channel
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum Channel {
    Ch1,
    Ch2,
    Ch3,
    Ch4,
    Ch5,
    Ch6,
    Ch7,
    Ch8,
    Ch9,
    Ch10,
    Ch11,
    Ch12,
    Ch13,
    Ch14,
    Ch15,
    Ch16,
    Invalid,
}

impl Channel {
    /// Convert the MIDI command byte to a Channel
    pub fn from_midi_cmd(v: u8) -> Channel {
        Self::from(v & consts::MIDI_CHANNEL_MASK)
    }
}

impl From<u8> for Channel {
    /// Convert a byte value 0-15 to the Channel.
    /// If you want to extract it from the MIDI event,
    /// use Channel::from_midi_cmd()
    fn from(v: u8) -> Channel {
        use Channel::*;
        match v {
            0 => Ch1,
            1 => Ch2,
            2 => Ch3,
            3 => Ch4,
            4 => Ch5,
            5 => Ch6,
            6 => Ch7,
            7 => Ch8,
            8 => Ch9,
            9 => Ch10,
            10 => Ch11,
            11 => Ch12,
            12 => Ch13,
            13 => Ch14,
            14 => Ch15,
            15 => Ch16,
            _ => Invalid,
        }
    }
}

/// Parameters of a key related event
///
/// This include note on and off and poly key pressure Value is
/// velocity for notes and pressure amount for pressure events.
#[derive(Clone, Debug, PartialEq)]
pub struct KeyEvent {
    /// The note to which this applies
    pub key: MidiNote,
    /// The velocity for notes or pressure value for pressure.
    pub value: u8,
}

/// Parameters for a control change
#[derive(Debug, PartialEq)]
pub struct ControlEvent {
    /// Control number
    pub control: u8,
    /// Value of the control
    pub value: u8,
}

/// The type of SysEx message
#[derive(Debug, PartialEq)]
pub enum SysExType {
    /// Manufacturer ID.
    Manufacturer(sysex::ManufacturerId),
    /// Non RealTime Universal SysEx
    /// Device ID, [sub id 1, sub id 2]
    NonRealTime(u8, [u8; 2]),
    /// Realtime Universal SysEx
    /// Device ID, [sub id 1, sub id 2]
    RealTime(u8, [u8; 2]),
}

/// SysEx message
#[derive(Debug, PartialEq)]
pub struct SysExEvent {
    /// Type of SysEx message
    r#type: SysExType,
    /// The raw data for the sysex. This include the terminating byte.
    data: Vec<u8>,
}

impl SysExEvent {
    /// Create a new SysEx message with a manufacturer ID
    /// * data is the data in the message, including the EOX
    pub fn new_manufacturer(manufacturer: sysex::ManufacturerId, data: &[u8]) -> SysExEvent {
        SysExEvent {
            r#type: SysExType::Manufacturer(manufacturer),
            data: Vec::from(data),
        }
    }

    /// Create a non realtime Universal System Exclusive message
    /// * device is the device. Use consts::usysex::ALL_CALL if you want all device to listen
    /// * subids is the two bytes for the message type.
    /// * data incude the rest of the data including EOX
    pub fn new_non_realtime(device: u8, subids: [u8; 2], data: &[u8]) -> SysExEvent {
        SysExEvent {
            r#type: SysExType::NonRealTime(device, subids),
            data: Vec::from(data),
        }
    }

    /// Create a realtime Universal System Exclusive message
    /// * device is the device. Use consts::usysex::ALL_CALL if you want all device to listen
    /// * subids is the two bytes for the message type.
    /// * data incude the rest of the data including EOX
    pub fn new_realtime(device: u8, subids: [u8; 2], data: &[u8]) -> SysExEvent {
        SysExEvent {
            r#type: SysExType::RealTime(device, subids),
            data: Vec::from(data),
        }
    }

    /// Get the SysEx type
    pub fn get_type(&self) -> &SysExType {
        &self.r#type
    }

    /// Get the data from the SysEx
    pub fn get_data(&self) -> &Vec<u8> {
        &self.data
    }
}

/// MIDI messages are what is being sent or received on the MIDI system
///
#[derive(Debug, PartialEq)]
pub enum MidiMessage {
    /// We don't know that message.
    Invalid,
    /// Note on.
    NoteOn(Channel, KeyEvent),
    /// Note off.
    NoteOff(Channel, KeyEvent),
    /// Pressure for notes (aftertouch).
    PolyKeyPressure(Channel, KeyEvent),
    /// Control value changed.
    ControlChange(Channel, ControlEvent),
    /// Program change.
    ProgramChange(Channel, u8),
    /// Channel pressure.
    ChannelPressure(Channel, u8),
    /// Pitch bending. LSB and MSB of the change.
    PitchBend(Channel, u8, u8),
    /// System extension event.
    SysEx(SysExEvent),
}

impl MidiMessage {
    /// Return the channel of the MIDI command
    /// This is a convenience helper to avoid having to destructure.
    /// Note: a SysEx message doesn't have a channel.
    pub fn get_channel(&self) -> Channel {
        use MidiMessage::*;
        match *self {
            Invalid | SysEx(_) => Channel::Invalid,
            NoteOn(ch, _)
            | NoteOff(ch, _)
            | PolyKeyPressure(ch, _)
            | ControlChange(ch, _)
            | ProgramChange(ch, _)
            | ChannelPressure(ch, _)
            | PitchBend(ch, _, _) => ch,
        }
    }

    /// Construct a SysEx message from the raw data.
    /// Will return an Invalid message of the data doesn't start
    /// with the SYSEX byte.
    fn sysex_message_from(data: &[u8]) -> MidiMessage {
        use consts::system_event::sysex::*;

        if data[0] != consts::SYSEX {
            return MidiMessage::Invalid;
        }

        let idx;
        let manufacturer = data[1];
        let r#type = match manufacturer {
            NON_REAL_TIME => {
                idx = 5;
                SysExType::NonRealTime(data[2], [data[3], data[4]])
            }
            REAL_TIME => {
                idx = 5;
                SysExType::RealTime(data[2], [data[3], data[4]])
            }
            _ => {
                let (_, d) = data.split_at(1);
                let manufacturer = sysex::ManufacturerId::from_raw(d).unwrap();
                idx = 1 + manufacturer.raw_len();
                SysExType::Manufacturer(manufacturer)
            }
        };
        MidiMessage::SysEx(SysExEvent {
            r#type,
            data: data.split_at(idx).1.to_vec(),
        })
    }
}

impl Into<Vec<u8>> for MidiMessage {
    /// Convert the MidiMessage into a raw buffer suited to be sent,
    /// to the MIDI device.
    /// An empty vector mean nothing could be made.
    fn into(self) -> Vec<u8> {
        use MidiMessage::*;
        match self {
            NoteOff(ch, e) => vec![consts::NOTE_OFF | ch as u8, e.key, e.value],
            NoteOn(ch, e) => vec![consts::NOTE_ON | ch as u8, e.key, e.value],
            PolyKeyPressure(ch, e) => {
                vec![consts::POLYPHONIC_KEY_PRESSURE | ch as u8, e.key, e.value]
            }
            ControlChange(ch, e) => vec![consts::CONTROL_CHANGE | ch as u8, e.control, e.value],
            ProgramChange(ch, p) => vec![consts::PROGRAM_CHANGE | ch as u8, p, 0],
            ChannelPressure(ch, p) => vec![consts::CHANNEL_KEY_PRESSURE | ch as u8, p, 0],
            PitchBend(ch, lsb, msb) => vec![consts::PITCH_BEND_CHANGE | ch as u8, lsb, msb],
            SysEx(ref e) => {
                let out_size = match e.r#type {
                    SysExType::Manufacturer(m) => 1 + m.raw_len() + e.data.len(),
                    SysExType::NonRealTime(_, _) | SysExType::RealTime(_, _) => 5 + e.data.len(),
                };
                let mut vec = Vec::with_capacity(out_size);
                vec.push(consts::SYSEX);
                use SysExType::*;
                match e.r#type {
                    Manufacturer(ref b) => b.push_to(&mut vec),
                    NonRealTime(d, id) => {
                        vec.push(consts::system_event::sysex::NON_REAL_TIME);
                        vec.push(d);
                        vec.extend_from_slice(&id);
                    }
                    RealTime(d, id) => {
                        vec.push(consts::system_event::sysex::REAL_TIME);
                        vec.push(d);
                        vec.extend_from_slice(&id);
                    }
                }
                vec.extend_from_slice(&e.data);
                vec
            }
            Invalid => vec![],
        }
    }
}

impl From<&[u8]> for MidiMessage {
    /// Create a MidiMessage from raw data as received from the MIDI driver.
    fn from(data: &[u8]) -> MidiMessage {
        if data.len() < 3 {
            MidiMessage::Invalid
        } else {
            let (event, channel) = if data[0] < consts::SYSEX {
                (
                    data[0] & consts::EVENT_TYPE_MASK,
                    data[0] & consts::MIDI_CHANNEL_MASK,
                )
            } else {
                (data[0], 0u8)
            };
            match event {
                consts::NOTE_OFF => {
                    // Note Off
                    MidiMessage::NoteOff(
                        Channel::from(channel),
                        KeyEvent {
                            key: data[1],
                            value: data[2],
                        },
                    )
                }
                consts::NOTE_ON => {
                    // Note On
                    MidiMessage::NoteOn(
                        Channel::from(channel),
                        KeyEvent {
                            key: data[1],
                            value: data[2],
                        },
                    )
                }
                consts::POLYPHONIC_KEY_PRESSURE => MidiMessage::PolyKeyPressure(
                    Channel::from(channel),
                    KeyEvent {
                        key: data[1],
                        value: data[2],
                    },
                ),
                consts::CONTROL_CHANGE => MidiMessage::ControlChange(
                    Channel::from(channel),
                    ControlEvent {
                        control: data[1],
                        value: data[2],
                    },
                ),
                consts::PROGRAM_CHANGE => {
                    MidiMessage::ProgramChange(Channel::from(channel), data[1])
                }
                consts::CHANNEL_KEY_PRESSURE => {
                    MidiMessage::ChannelPressure(Channel::from(channel), data[1])
                }
                consts::PITCH_BEND_CHANGE => {
                    MidiMessage::PitchBend(Channel::from(channel), data[1], data[2])
                }
                consts::SYSEX => MidiMessage::sysex_message_from(data),
                // TODO handle other system message
                _ => MidiMessage::Invalid,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    pub fn test_midi_channel() {
        let ch = Channel::from_midi_cmd(128);
        assert_eq!(ch, Channel::Ch1);

        let ch = Channel::from_midi_cmd(137);
        assert_eq!(ch, Channel::Ch10);
    }

    #[test]
    pub fn test_midi_from_to_raw() {
        // Invalid
        let raw = vec![0u8];
        let msg = MidiMessage::Invalid;
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert!(out.len() == 0);

        // NoteOn
        let raw = vec![144u8, 59u8, 88u8];
        let msg = MidiMessage::NoteOn(Channel::Ch1, KeyEvent { key: 59, value: 88 });
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);

        // NoteOff
        let raw = vec![128u8, 60u8, 0u8];
        let msg = MidiMessage::NoteOff(Channel::Ch1, KeyEvent { key: 60, value: 0 });
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);

        // ControlChange
        let raw = vec![176, 114, 65];
        let msg = MidiMessage::ControlChange(
            Channel::Ch1,
            ControlEvent {
                control: 114,
                value: 65,
            },
        );
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);

        // PitchBend
        let raw = vec![224, 0, 76];
        let msg = MidiMessage::PitchBend(Channel::Ch1, 0, 76);
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);

        // SysEx
        let raw = vec![240, 30, 127, 66, 2, 0, 0, 16, 127, 247];
        let msg = MidiMessage::SysEx(SysExEvent::new_manufacturer(
            sysex::ManufacturerId::Id(30),
            &[127, 66, 2, 0, 0, 16, 127, 247],
        ));
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);

        let raw = vec![240, 0, 32, 107, 127, 66, 2, 0, 0, 16, 127, 247];
        let msg = MidiMessage::SysEx(SysExEvent::new_manufacturer(
            sysex::ManufacturerId::ExtId(32, 107),
            &[127, 66, 2, 0, 0, 16, 127, 247],
        ));
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);

        // Universal SysEx
        let raw = vec![240, 126, 0, 6, 2, 0, 32, 107, 2, 0, 4, 2, 67, 7, 0, 1, 247];
        let msg = MidiMessage::SysEx(SysExEvent::new_non_realtime(
            0,
            [6, 2],
            &[0, 32, 107, 2, 0, 4, 2, 67, 7, 0, 1, 247],
        ));
        assert_eq!(MidiMessage::from(raw.as_slice()), msg);
        let out: Vec<u8> = msg.into();
        assert_eq!(out, raw);
    }
}