midir 0.11.0

A cross-platform, realtime MIDI processing library, inspired by RtMidi.
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use jack_sys::jack_nframes_t;
use libc::c_void;

use std::ffi::CString;
use std::{mem, slice};

mod wrappers;
use self::wrappers::*;

use crate::errors::*;
use crate::{Ignore, MidiMessage};

const OUTPUT_RINGBUFFER_SIZE: usize = 16384;

type CallbackFn<T> = dyn FnMut(u64, &[u8], &mut T) + Send;

struct InputHandlerData<T> {
    port: Option<MidiPort>,
    ignore_flags: Ignore,
    callback: Box<CallbackFn<T>>,
    user_data: Option<T>,
}

pub struct MidiInput {
    ignore_flags: Ignore,
    client: Option<Client>,
}

#[derive(Clone, PartialEq)]
pub struct MidiInputPort {
    name: CString,
}

impl MidiInputPort {
    pub fn id(&self) -> String {
        self.name.to_string_lossy().to_string()
    }
}

pub struct MidiInputConnection<T> {
    handler_data: Box<InputHandlerData<T>>,
    client: Option<Client>,
}

impl MidiInput {
    pub fn new(client_name: &str) -> Result<Self, InitError> {
        let client = match Client::open(client_name, JackOpenOptions::NoStartServer) {
            Ok(c) => c,
            Err(_) => {
                return Err(InitError);
            } // TODO: maybe add message that Jack server might not be running
        };

        Ok(MidiInput {
            ignore_flags: Ignore::None,
            client: Some(client),
        })
    }

    pub fn ignore(&mut self, flags: Ignore) {
        self.ignore_flags = flags;
    }

    pub(crate) fn ports_internal(&self) -> Vec<crate::common::MidiInputPort> {
        let ports = self
            .client
            .as_ref()
            .unwrap()
            .get_midi_ports(PortFlags::PortIsOutput);
        let mut result = Vec::with_capacity(ports.count());
        for i in 0..ports.count() {
            result.push(crate::common::MidiInputPort {
                imp: MidiInputPort {
                    name: ports.get_c_name(i).into(),
                },
            })
        }
        result
    }

    pub fn port_count(&self) -> usize {
        self.client
            .as_ref()
            .unwrap()
            .get_midi_ports(PortFlags::PortIsOutput)
            .count()
    }

    pub fn port_name(&self, port: &MidiInputPort) -> Result<String, PortInfoError> {
        Ok(port.name.to_string_lossy().into())
    }

    fn activate_callback<F, T: Send>(&mut self, callback: F, data: T) -> Box<InputHandlerData<T>>
    where
        F: FnMut(u64, &[u8], &mut T) + Send + 'static,
    {
        let handler_data = Box::new(InputHandlerData {
            port: None,
            ignore_flags: self.ignore_flags,
            callback: Box::new(callback),
            user_data: Some(data),
        });

        let data_ptr = unsafe { mem::transmute_copy::<_, *mut InputHandlerData<T>>(&handler_data) };

        self.client
            .as_mut()
            .unwrap()
            .set_process_callback(handle_input::<T>, data_ptr as *mut c_void);
        self.client.as_mut().unwrap().activate();
        handler_data
    }

    pub fn connect<F, T: Send>(
        mut self,
        port: &MidiInputPort,
        port_name: &str,
        callback: F,
        data: T,
    ) -> Result<MidiInputConnection<T>, ConnectError<MidiInput>>
    where
        F: FnMut(u64, &[u8], &mut T) + Send + 'static,
    {
        let mut handler_data = self.activate_callback(callback, data);

        // Create port ...
        let dest_port = match self
            .client
            .as_mut()
            .unwrap()
            .register_midi_port(port_name, PortFlags::PortIsInput)
        {
            Ok(p) => p,
            Err(()) => {
                return Err(ConnectError::other("could not register JACK port", self));
            }
        };

        // ... and connect it to the output
        if self
            .client
            .as_mut()
            .unwrap()
            .connect(&port.name, dest_port.get_name())
            .is_err()
        {
            return Err(ConnectError::new(ConnectErrorKind::InvalidPort, self));
        }

        handler_data.port = Some(dest_port);

        Ok(MidiInputConnection {
            handler_data,
            client: self.client.take(),
        })
    }

    pub fn create_virtual<F, T: Send>(
        mut self,
        port_name: &str,
        callback: F,
        data: T,
    ) -> Result<MidiInputConnection<T>, ConnectError<Self>>
    where
        F: FnMut(u64, &[u8], &mut T) + Send + 'static,
    {
        let mut handler_data = self.activate_callback(callback, data);

        // Create port
        let port = match self
            .client
            .as_mut()
            .unwrap()
            .register_midi_port(port_name, PortFlags::PortIsInput)
        {
            Ok(p) => p,
            Err(()) => {
                return Err(ConnectError::other("could not register JACK port", self));
            }
        };

        handler_data.port = Some(port);

        Ok(MidiInputConnection {
            handler_data,
            client: self.client.take(),
        })
    }
}

impl<T> MidiInputConnection<T> {
    pub fn close(mut self) -> (MidiInput, T) {
        self.close_internal();

        (
            MidiInput {
                client: self.client.take(),
                ignore_flags: self.handler_data.ignore_flags,
            },
            self.handler_data.user_data.take().unwrap(),
        )
    }

    fn close_internal(&mut self) {
        let port = self.handler_data.port.take().unwrap();
        self.client.as_mut().unwrap().unregister_midi_port(port);
        self.client.as_mut().unwrap().deactivate();
    }
}

impl<T> Drop for MidiInputConnection<T> {
    fn drop(&mut self) {
        if self.client.is_some() {
            self.close_internal();
        }
    }
}

extern "C" fn handle_input<T>(nframes: jack_nframes_t, arg: *mut c_void) -> i32 {
    let data: &mut InputHandlerData<T> = unsafe { &mut *(arg as *mut InputHandlerData<T>) };

    // Is port created?
    if let Some(ref port) = data.port {
        let buff = port.get_midi_buffer(nframes);

        let mut message = MidiMessage::new(); // TODO: create MidiMessage once and reuse its buffer for every handle_input call

        // We have midi events in buffer
        let evcount = buff.get_event_count();
        let mut event = mem::MaybeUninit::uninit();

        for j in 0..evcount {
            message.bytes.clear();
            unsafe { buff.get_event(event.as_mut_ptr(), j) };
            let event = unsafe { event.assume_init() };

            for i in 0..event.size {
                message.bytes.push(unsafe { *event.buffer.add(i) });
            }

            message.timestamp = Client::get_time(); // this is in microseconds
            (data.callback)(
                message.timestamp,
                &message.bytes,
                data.user_data.as_mut().unwrap(),
            );
        }
    }

    0
}

struct OutputHandlerData {
    port: Option<MidiPort>,
    buff_size: Ringbuffer,
    buff_message: Ringbuffer,
}

pub struct MidiOutput {
    client: Option<Client>,
}

#[derive(Clone, PartialEq)]
pub struct MidiOutputPort {
    name: CString,
}

impl MidiOutputPort {
    pub fn id(&self) -> String {
        self.name.to_string_lossy().to_string()
    }
}

pub struct MidiOutputConnection {
    handler_data: Box<OutputHandlerData>,
    client: Option<Client>,
}

impl MidiOutput {
    pub fn new(client_name: &str) -> Result<Self, InitError> {
        let client = match Client::open(client_name, JackOpenOptions::NoStartServer) {
            Ok(c) => c,
            Err(_) => {
                return Err(InitError);
            } // TODO: maybe add message that Jack server might not be running
        };

        Ok(MidiOutput {
            client: Some(client),
        })
    }

    pub(crate) fn ports_internal(&self) -> Vec<crate::common::MidiOutputPort> {
        let ports = self
            .client
            .as_ref()
            .unwrap()
            .get_midi_ports(PortFlags::PortIsInput);
        let mut result = Vec::with_capacity(ports.count());
        for i in 0..ports.count() {
            result.push(crate::common::MidiOutputPort {
                imp: MidiOutputPort {
                    name: ports.get_c_name(i).into(),
                },
            })
        }
        result
    }

    pub fn port_count(&self) -> usize {
        self.client
            .as_ref()
            .unwrap()
            .get_midi_ports(PortFlags::PortIsInput)
            .count()
    }

    pub fn port_name(&self, port: &MidiOutputPort) -> Result<String, PortInfoError> {
        Ok(port.name.to_string_lossy().into())
    }

    fn activate_callback(&mut self) -> Box<OutputHandlerData> {
        let handler_data = Box::new(OutputHandlerData {
            port: None,
            buff_size: Ringbuffer::new(OUTPUT_RINGBUFFER_SIZE),
            buff_message: Ringbuffer::new(OUTPUT_RINGBUFFER_SIZE),
        });

        let data_ptr = unsafe { mem::transmute_copy::<_, *mut OutputHandlerData>(&handler_data) };

        self.client
            .as_mut()
            .unwrap()
            .set_process_callback(handle_output, data_ptr as *mut c_void);
        self.client.as_mut().unwrap().activate();
        handler_data
    }

    pub fn connect(
        mut self,
        port: &MidiOutputPort,
        port_name: &str,
    ) -> Result<MidiOutputConnection, ConnectError<MidiOutput>> {
        let mut handler_data = self.activate_callback();

        // Create port ...
        let source_port = match self
            .client
            .as_mut()
            .unwrap()
            .register_midi_port(port_name, PortFlags::PortIsOutput)
        {
            Ok(p) => p,
            Err(()) => {
                return Err(ConnectError::other("could not register JACK port", self));
            }
        };

        // ... and connect it to the input
        if self
            .client
            .as_mut()
            .unwrap()
            .connect(source_port.get_name(), &port.name)
            .is_err()
        {
            return Err(ConnectError::new(ConnectErrorKind::InvalidPort, self));
        }

        handler_data.port = Some(source_port);

        Ok(MidiOutputConnection {
            handler_data,
            client: self.client.take(),
        })
    }

    pub fn create_virtual(
        mut self,
        port_name: &str,
    ) -> Result<MidiOutputConnection, ConnectError<Self>> {
        let mut handler_data = self.activate_callback();

        // Create port
        let port = match self
            .client
            .as_mut()
            .unwrap()
            .register_midi_port(port_name, PortFlags::PortIsOutput)
        {
            Ok(p) => p,
            Err(()) => {
                return Err(ConnectError::other("could not register JACK port", self));
            }
        };

        handler_data.port = Some(port);

        Ok(MidiOutputConnection {
            handler_data,
            client: self.client.take(),
        })
    }
}

impl MidiOutputConnection {
    pub fn send(&mut self, message: &[u8]) -> Result<(), SendError> {
        let nbytes = message.len();

        // Write full message to buffer
        let written = self.handler_data.buff_message.write(message);
        debug_assert!(
            written == nbytes,
            "not enough bytes written to ALSA ringbuffer `message`"
        );
        let nbytes_slice = unsafe {
            slice::from_raw_parts(
                &nbytes as *const usize as *const u8,
                mem::size_of_val(&nbytes),
            )
        };
        let written = self.handler_data.buff_size.write(nbytes_slice);
        debug_assert!(
            written == mem::size_of_val(&nbytes),
            "not enough bytes written to ALSA ringbuffer `size`"
        );
        Ok(())
    }

    pub fn close(mut self) -> MidiOutput {
        self.close_internal();

        MidiOutput {
            client: self.client.take(),
        }
    }

    fn close_internal(&mut self) {
        let port = self.handler_data.port.take().unwrap();
        self.client.as_mut().unwrap().unregister_midi_port(port);
        self.client.as_mut().unwrap().deactivate();
    }
}

impl Drop for MidiOutputConnection {
    fn drop(&mut self) {
        if self.client.is_some() {
            self.close_internal();
        }
    }
}

extern "C" fn handle_output(nframes: jack_nframes_t, arg: *mut c_void) -> i32 {
    let data: &mut OutputHandlerData = unsafe { &mut *(arg as *mut OutputHandlerData) };

    // Is port created?
    if let Some(ref port) = data.port {
        let mut space: usize = 0;

        let mut buff = port.get_midi_buffer(nframes);
        buff.clear();

        while data.buff_size.get_read_space() > 0 {
            let read = data
                .buff_size
                .read(&mut space as *mut usize as *mut u8, mem::size_of::<usize>());
            debug_assert!(
                read == mem::size_of::<usize>(),
                "not enough bytes read from `size` ringbuffer"
            );
            let midi_data = buff.event_reserve(0, space);
            let read = data.buff_message.read(midi_data, space);
            debug_assert!(
                read == space,
                "not enough bytes read from `message` ringbuffer"
            );
        }
    }

    0
}