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
use {
    crate::{
        os::{OsMidiOutput,OsMidiInput},
        makepad_live_id::{LiveId, FromLiveId},
    }
};

#[derive(Clone, Debug)]
pub struct MidiPortsEvent {
    pub descs: Vec<MidiPortDesc>,
}

impl MidiPortsEvent {
    pub fn all_inputs(&self) -> Vec<MidiPortId> {
        let mut out = Vec::new();
        for d in &self.descs {
            if d.port_type.is_input() {
                out.push(d.port_id);
            }
        }
        out
    }
    pub fn all_outputs(&self) -> Vec<MidiPortId> {
        let mut out = Vec::new();
        for d in &self.descs {
            if d.port_type.is_output() {
                out.push(d.port_id);
            }
        }
        out
    }
}

impl std::fmt::Display for MidiPortsEvent {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        write!(f, "MIDI ports:\n").unwrap();
        for desc in &self.descs {
            if desc.port_type.is_input() {
                write!(f, "[Input] {}\n", desc.name).unwrap()
            }
            else {
                write!(f, "[Output] {}\n", desc.name).unwrap()
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for MidiPortDesc {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        f.debug_tuple("name").field(&self.name).finish()
    }
}

#[derive(Default)]
pub struct MidiInput(pub (crate) Option<OsMidiInput>);
unsafe impl Send for MidiInput {}

impl MidiInput {
    pub fn receive(&mut self) -> Option<(MidiPortId, MidiData)> {
        self.0.as_mut().unwrap().receive()
    }
}

pub struct MidiOutput(pub (crate) Option<OsMidiOutput>);
unsafe impl Send for MidiOutput {}

impl MidiOutput {
    pub fn send(&self, port: Option<MidiPortId>, data: MidiData) {
        let output = self.0.as_ref().unwrap();
        output.send(port, data);
    } 
}

#[derive(Clone, Copy, Debug, PartialEq)] 
pub struct MidiData {
    pub data: [u8; 3],
}

impl std::convert::From<u32> for MidiData {
    fn from(data: u32) -> Self {
        MidiData {
            data: [((data >> 16) & 0xff) as u8, ((data >> 8) & 0xff) as u8, ((data >> 0) & 0xff) as u8]
        }
    } 
}  

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MidiPortType {
    Input,
    Output,
}

impl MidiPortType {
    pub fn is_input(&self) -> bool {
        match self {
            Self::Input => true,
            _ => false
        }
    }
    pub fn is_output(&self) -> bool {
        match self {
            Self::Output => true,
            _ => false
        }
    }
}

#[derive(Clone, Debug, Default, Eq, Hash, Copy, PartialEq, FromLiveId)]
pub struct MidiPortId(pub LiveId);

#[derive(Clone, PartialEq)]
pub struct MidiPortDesc {
    pub name: String,
    pub port_id: MidiPortId,
    pub port_type: MidiPortType,
}


#[derive(Clone, Copy, Debug)]
pub struct MidiNote {
    pub is_on: bool,
    pub channel: u8,
    pub note_number: u8,
    pub velocity: u8,
}

impl Into<MidiData> for MidiNote {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                (if self.is_on {0x9}else {0x8} << 4) | self.channel,
                self.note_number,
                self.velocity
            ]
        }
    }
}


#[derive(Clone, Copy, Debug)]
pub struct MidiAftertouch {
    pub channel: u8,
    pub note_number: u8,
    pub velocity: u8
}

impl Into<MidiData> for MidiAftertouch {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                0xA0 | self.channel,
                self.note_number,
                self.velocity
            ]
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct MidiControlChange {
    pub channel: u8,
    pub param: u8,
    pub value: u8,
}

impl Into<MidiData> for MidiControlChange {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                0xB0 | self.channel,
                self.param,
                self.value
            ]
        }
    }
}


#[derive(Clone, Copy, Debug)]
pub struct MidiProgramChange {
    pub channel: u8,
    pub hi: u8,
    pub lo: u8
}

impl Into<MidiData> for MidiProgramChange {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                0xC0 | self.channel,
                self.hi,
                self.lo
            ]
        }
    }
}


#[derive(Clone, Copy, Debug)]
pub struct MidiChannelAftertouch {
    pub channel: u8,
    pub value: u16
}

impl Into<MidiData> for MidiChannelAftertouch {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                0xD0 | self.channel,
                (((self.value as u32)>>7)&0x7f) as u8,
                ((self.value as u32)&0x7f) as u8,
            ]
        }
    }
}


#[derive(Clone, Copy, Debug)]
pub struct MidiPitchBend {
    pub channel: u8,
    pub bend: u16,
}

impl Into<MidiData> for MidiPitchBend {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                0xE0 | self.channel,
                (((self.bend as u32)>>7)&0x7f) as u8,
                ((self.bend as u32)&0x7f) as u8,
            ]
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct MidiSystem {
    pub channel: u8,
    pub hi: u8,
    pub lo: u8
}

impl Into<MidiData> for MidiSystem {
    fn into(self) -> MidiData {
        MidiData {
            data: [
                0xF0 | self.channel,
                self.hi,
                self.lo
            ]
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum MidiEvent {
    Note(MidiNote),
    Aftertouch(MidiAftertouch),
    ControlChange(MidiControlChange),
    ProgramChange(MidiProgramChange),
    PitchBend(MidiPitchBend),
    ChannelAftertouch(MidiChannelAftertouch),
    System(MidiSystem),
    Unknown(MidiData)
}

impl MidiEvent {
    pub fn on_note(&self) -> Option<MidiNote> {
        match self {
            Self::Note(note) => Some(*note),
            _ => None
        }
    }
}

impl MidiData {
    pub fn status(&self) -> u8 {
        self.data[0] >> 4
    }
    pub fn channel(&self) -> u8 {
        self.data[0] & 0xf
    }
    
    pub fn decode(&self) -> MidiEvent {
        let status = self.status();
        let channel = self.channel();
        match status {
            0x8 | 0x9 => MidiEvent::Note(MidiNote {
                is_on: status == 0x9,
                channel,
                note_number: self.data[1],
                velocity: self.data[2]
            }),
            0xA => MidiEvent::Aftertouch(MidiAftertouch {
                channel,
                note_number: self.data[1],
                velocity: self.data[2],
            }),
            0xB => MidiEvent::ControlChange(MidiControlChange {
                channel,
                param: self.data[1],
                value: self.data[2]
            }),
            0xC => MidiEvent::ProgramChange(MidiProgramChange {
                channel,
                hi: self.data[1],
                lo: self.data[2]
            }),
            0xD => MidiEvent::ChannelAftertouch(MidiChannelAftertouch {
                channel,
                value: ((self.data[1] as u16) << 7) | self.data[2] as u16,
            }),
            0xE => MidiEvent::PitchBend(MidiPitchBend {
                channel,
                bend: ((self.data[1] as u16) << 7) | self.data[2] as u16,
            }),
            0xF => MidiEvent::System(MidiSystem {
                channel,
                hi: self.data[1],
                lo: self.data[2]
            }),
            _ => MidiEvent::Unknown(*self)
        }
    }
}