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
use core_foundation::base::OSStatus;
use std::collections::HashMap;
use std::ffi::c_void;
use std::ops::Deref;
use std::ptr;

use coremidi_sys::{
    MIDIObjectRef, MIDIPortConnectSource, MIDIPortDisconnectSource, MIDIPortDispose, MIDIPortRef,
    MIDISend, MIDISendEventList,
};

use crate::endpoints::destinations::Destination;
use crate::endpoints::sources::Source;
use crate::object::Object;
use crate::packets::PacketList;
use crate::{EventBuffer, EventList, PacketBuffer};

pub enum Packets<'a> {
    BorrowedPacketList(&'a PacketList),
    BorrowedEventList(&'a EventList),
    OwnedEventBuffer(EventBuffer),
}

impl<'a> From<&'a PacketList> for Packets<'a> {
    fn from(packet_list: &'a PacketList) -> Self {
        Self::BorrowedPacketList(packet_list)
    }
}

impl<'a> From<&'a PacketBuffer> for Packets<'a> {
    fn from(packet_buffer: &'a PacketBuffer) -> Self {
        Self::BorrowedPacketList(&*packet_buffer)
    }
}

impl<'a> From<&'a EventList> for Packets<'a> {
    fn from(event_list: &'a EventList) -> Self {
        Self::BorrowedEventList(event_list)
    }
}

impl<'a> From<&'a EventBuffer> for Packets<'a> {
    fn from(event_buffer: &'a EventBuffer) -> Self {
        Self::BorrowedEventList(&*event_buffer)
    }
}

impl<'a> From<EventBuffer> for Packets<'a> {
    fn from(event_buffer: EventBuffer) -> Self {
        Self::OwnedEventBuffer(event_buffer)
    }
}

/// A MIDI connection port owned by a client.
/// See [MIDIPortRef](https://developer.apple.com/documentation/coremidi/midiportref).
///
/// Ports can't be instantiated directly, but through a client.
///
#[derive(Debug)]
pub struct Port {
    pub(crate) object: Object,
}

impl Port {
    pub(crate) fn new(port_ref: MIDIPortRef) -> Self {
        Self {
            object: Object(port_ref),
        }
    }
}

impl Deref for Port {
    type Target = Object;

    fn deref(&self) -> &Object {
        &self.object
    }
}

impl Drop for Port {
    fn drop(&mut self) {
        unsafe { MIDIPortDispose(self.object.0) };
    }
}

/// An output [MIDI port](https://developer.apple.com/documentation/coremidi/midiportref) owned by a client.
///
/// A simple example to create an output port and send a MIDI event:
///
/// ```rust,no_run
/// use coremidi::{Client, Destination, EventBuffer, Protocol};
/// let client = Client::new("example-client").unwrap();
/// let output_port = client.output_port("example-port").unwrap();
/// let destination = Destination::from_index(0).unwrap();
/// let events = EventBuffer::new(Protocol::Midi10).with_packet(0, &[0x2090407f]);
/// output_port.send(&destination, &events).unwrap();
/// ```
#[derive(Debug)]
pub struct OutputPort {
    pub(crate) port: Port,
}

impl OutputPort {
    pub(crate) fn new(port_ref: MIDIPortRef) -> Self {
        Self {
            port: Port::new(port_ref),
        }
    }

    /// Send a list of packets to a destination.
    /// See [MIDISendEventList](https://developer.apple.com/documentation/coremidi/3566494-midisendeventlist)
    /// See [MIDISend](https://developer.apple.com/documentation/coremidi/1495289-midisend).
    ///
    pub fn send<'a, P>(&self, destination: &Destination, packets: P) -> Result<(), OSStatus>
    where
        P: Into<Packets<'a>>,
    {
        let status = match packets.into() {
            Packets::BorrowedPacketList(packet_list) => unsafe {
                MIDISend(
                    self.port.object.0,
                    destination.endpoint.object.0,
                    packet_list.as_ptr(),
                )
            },
            Packets::BorrowedEventList(event_list) => unsafe {
                MIDISendEventList(
                    self.port.object.0,
                    destination.endpoint.object.0,
                    event_list.as_ptr(),
                )
            },
            Packets::OwnedEventBuffer(event_buffer) => unsafe {
                MIDISendEventList(
                    self.port.object.0,
                    destination.endpoint.object.0,
                    event_buffer.as_ptr(),
                )
            },
        };
        if status == 0 {
            Ok(())
        } else {
            Err(status)
        }
    }
}

impl Deref for OutputPort {
    type Target = Port;

    fn deref(&self) -> &Port {
        &self.port
    }
}

#[derive(Debug)]
pub struct InputPort {
    pub(crate) port: Port,
}

impl InputPort {
    pub(crate) fn new(port_ref: MIDIPortRef) -> Self {
        Self {
            port: Port::new(port_ref),
        }
    }

    pub fn connect_source(&self, source: &Source) -> Result<(), OSStatus> {
        let status =
            unsafe { MIDIPortConnectSource(self.object.0, source.object.0, ptr::null_mut()) };
        if status == 0 {
            Ok(())
        } else {
            Err(status)
        }
    }

    pub fn disconnect_source(&self, source: &Source) -> Result<(), OSStatus> {
        let status = unsafe { MIDIPortDisconnectSource(self.object.0, source.object.0) };
        if status == 0 {
            Ok(())
        } else {
            Err(status)
        }
    }
}

impl Deref for InputPort {
    type Target = Port;

    fn deref(&self) -> &Port {
        &self.port
    }
}

/// An input [MIDI port](https://developer.apple.com/documentation/coremidi/midiportref) owned by a client.
///
/// A simple example to create an input port:
///
/// ```rust,no_run
/// use coremidi::{Client, Protocol, Source};
/// let client = Client::new("example-client").unwrap();
/// let mut input_port = client.input_port_with_protocol("example-port", Protocol::Midi10, |event_list, context: &mut u32| println!("{:08x}: {:?}", context, event_list)).unwrap();
/// let source = Source::from_index(0).unwrap();
/// let context = source.unique_id().unwrap_or(0);
/// input_port.connect_source(&source, context);
/// ```
#[derive(Debug)]
pub struct InputPortWithContext<T> {
    pub(crate) port: Port,
    pub(crate) contexts: HashMap<MIDIObjectRef, Box<T>>,
}

impl<T> InputPortWithContext<T> {
    pub(crate) fn new(port_ref: MIDIPortRef) -> Self {
        Self {
            port: Port::new(port_ref),
            contexts: HashMap::new(),
        }
    }

    pub fn connect_source(&mut self, source: &Source, context: T) -> Result<(), OSStatus> {
        let mut context = Box::new(context);
        let context_ptr = context.as_mut() as *mut T;
        let status = unsafe {
            MIDIPortConnectSource(self.object.0, source.object.0, context_ptr as *mut c_void)
        };
        if status == 0 {
            self.contexts.insert(source.object.0, context);
            Ok(())
        } else {
            Err(status)
        }
    }

    pub fn disconnect_source(&mut self, source: &Source) -> Result<(), OSStatus> {
        let status = unsafe { MIDIPortDisconnectSource(self.object.0, source.object.0) };
        if status == 0 {
            self.contexts.remove(&source.object.0);
            Ok(())
        } else {
            Err(status)
        }
    }
}

impl<T> Deref for InputPortWithContext<T> {
    type Target = Port;

    fn deref(&self) -> &Port {
        &self.port
    }
}