| 1 |
extern crate coremidi; |
| 2 |
|
| 3 |
use std::sync::{Arc, Mutex}; |
| 4 |
|
| 5 |
use ::errors::*; |
| 6 |
use ::Ignore; |
| 7 |
use ::MidiMessage; |
| 8 |
|
| 9 |
use self::coremidi::*; |
| 10 |
|
| 11 |
mod external { |
| 12 |
#[link(name = "CoreAudio", kind = "framework")] |
| 13 |
extern "C" { |
| 14 |
pub fn AudioConvertHostTimeToNanos(inHostTime: u64) -> u64; |
| 15 |
pub fn AudioGetCurrentHostTime() -> u64; |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
pub struct MidiInput { |
| 20 |
client: Client, |
| 21 |
ignore_flags: Ignore |
| 22 |
} |
| 23 |
|
| 24 |
#[derive(Clone)] |
| 25 |
pub struct MidiInputPort { |
| 26 |
source: Arc<Source> |
| 27 |
} |
| 28 |
|
| 29 |
impl PartialEq for MidiInputPort { |
| 30 |
fn eq(&self, other: &Self) -> bool { |
| 31 |
if let (Some(id1), Some(id2)) = (self.source.unique_id(), other.source.unique_id()) { |
| 32 |
id1 == id2 |
| 33 |
} else { |
| 34 |
// Acording to macos docs "The system assigns unique IDs to all objects.", so I think we can ignore this case |
| 35 |
false |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
impl MidiInput { |
| 41 |
pub fn new(client_name: &str) -> Result<Self, InitError> { |
| 42 |
match Client::new(client_name) { |
| 43 |
Ok(cl) => Ok(MidiInput { client: cl, ignore_flags: Ignore::None }), |
| 44 |
Err(_) => Err(InitError) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
pub(crate) fn ports_internal(&self) -> Vec<::common::MidiInputPort> { |
| 49 |
Sources.into_iter().map(|s| ::common::MidiInputPort { |
| 50 |
imp: MidiInputPort { source: Arc::new(s) } |
| 51 |
}).collect() |
| 52 |
} |
| 53 |
|
| 54 |
pub fn ignore(&mut self, flags: Ignore) { |
| 55 |
self.ignore_flags = flags; |
| 56 |
} |
| 57 |
|
| 58 |
pub fn port_count(&self) -> usize { |
| 59 |
Sources::count() |
| 60 |
} |
| 61 |
|
| 62 |
pub fn port_name(&self, port: &MidiInputPort) -> Result<String, PortInfoError> { |
| 63 |
match port.source.display_name() { |
| 64 |
Some(name) => Ok(name), |
| 65 |
None => Err(PortInfoError::CannotRetrievePortName) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
fn handle_input<T>(packets: &PacketList, handler_data: &mut HandlerData<T>) { |
| 70 |
let continue_sysex = &mut handler_data.continue_sysex; |
| 71 |
let ignore = handler_data.ignore_flags; |
| 72 |
let message = &mut handler_data.message; |
| 73 |
let data = &mut handler_data.user_data.as_mut().unwrap(); |
| 74 |
for p in packets.iter() { |
| 75 |
let pdata = p.data(); |
| 76 |
if pdata.len() == 0 { continue; } |
| 77 |
|
| 78 |
let mut timestamp = p.timestamp(); |
| 79 |
if timestamp == 0 { // this might happen for asnychronous sysex messages (?) |
| 80 |
timestamp = unsafe { external::AudioGetCurrentHostTime() }; |
| 81 |
} |
| 82 |
|
| 83 |
if !*continue_sysex { |
| 84 |
message.timestamp = unsafe { external::AudioConvertHostTimeToNanos(timestamp) } as u64 / 1000; |
| 85 |
} |
| 86 |
|
| 87 |
let mut cur_byte = 0; |
| 88 |
if *continue_sysex { |
| 89 |
// We have a continuing, segmented sysex message. |
| 90 |
if !ignore.contains(Ignore::Sysex) { |
| 91 |
// If we're not ignoring sysex messages, copy the entire packet. |
| 92 |
message.bytes.extend_from_slice(pdata); |
| 93 |
} |
| 94 |
*continue_sysex = pdata[pdata.len() - 1] != 0xF7; |
| 95 |
|
| 96 |
if !ignore.contains(Ignore::Sysex) && !*continue_sysex { |
| 97 |
// If we reached the end of the sysex, invoke the user callback |
| 98 |
(handler_data.callback)(message.timestamp, &message.bytes, data); |
| 99 |
message.bytes.clear(); |
| 100 |
} |
| 101 |
} else { |
| 102 |
while cur_byte < pdata.len() { |
| 103 |
// We are expecting that the next byte in the packet is a status byte. |
| 104 |
let status = pdata[cur_byte]; |
| 105 |
if status & 0x80 == 0 { break; } |
| 106 |
// Determine the number of bytes in the MIDI message. |
| 107 |
let size; |
| 108 |
if status < 0xC0 { size = 3; } |
| 109 |
else if status < 0xE0 { size = 2; } |
| 110 |
else if status < 0xF0 { size = 3; } |
| 111 |
else if status == 0xF0 { |
| 112 |
// A MIDI sysex |
| 113 |
if ignore.contains(Ignore::Sysex) { |
| 114 |
size = 0; |
| 115 |
cur_byte = pdata.len(); |
| 116 |
} else { |
| 117 |
size = pdata.len() - cur_byte; |
| 118 |
} |
| 119 |
*continue_sysex = pdata[pdata.len() - 1] != 0xF7; |
| 120 |
} |
| 121 |
else if status == 0xF1 { |
| 122 |
// A MIDI time code message |
| 123 |
if ignore.contains(Ignore::Time) { |
| 124 |
size = 0; |
| 125 |
cur_byte += 2; |
| 126 |
} else { |
| 127 |
size = 2; |
| 128 |
} |
| 129 |
} |
| 130 |
else if status == 0xF2 { size = 3; } |
| 131 |
else if status == 0xF3 { size = 2; } |
| 132 |
else if status == 0xF8 && ignore.contains(Ignore::Time) { |
| 133 |
// A MIDI timing tick message and we're ignoring it. |
| 134 |
size = 0; |
| 135 |
cur_byte += 1; |
| 136 |
} |
| 137 |
else if status == 0xFE && ignore.contains(Ignore::ActiveSense) { |
| 138 |
// A MIDI active sensing message and we're ignoring it. |
| 139 |
size = 0; |
| 140 |
cur_byte += 1; |
| 141 |
} |
| 142 |
else { size = 1; } |
| 143 |
|
| 144 |
// Copy the MIDI data to our vector. |
| 145 |
if size > 0 { |
| 146 |
let message_bytes = &pdata[cur_byte..(cur_byte + size)]; |
| 147 |
if !*continue_sysex { |
| 148 |
// This is either a non-sysex message or a non-segmented sysex message |
| 149 |
(handler_data.callback)(message.timestamp, message_bytes, data); |
| 150 |
message.bytes.clear(); |
| 151 |
} else { |
| 152 |
// This is the beginning of a segmented sysex message |
| 153 |
message.bytes.extend_from_slice(message_bytes); |
| 154 |
} |
| 155 |
cur_byte += size; |
| 156 |
} |
| 157 |
} |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
pub fn connect<F, T: Send + 'static>( |
| 163 |
self, port: &MidiInputPort, port_name: &str, callback: F, data: T |
| 164 |
) -> Result<MidiInputConnection<T>, ConnectError<MidiInput>> |
| 165 |
where F: FnMut(u64, &[u8], &mut T) + Send + 'static { |
| 166 |
let handler_data = Arc::new(Mutex::new(HandlerData { |
| 167 |
message: MidiMessage::new(), |
| 168 |
ignore_flags: self.ignore_flags, |
| 169 |
continue_sysex: false, |
| 170 |
callback: Box::new(callback), |
| 171 |
user_data: Some(data) |
| 172 |
})); |
| 173 |
let handler_data2 = handler_data.clone(); |
| 174 |
let iport = match self.client.input_port(port_name, move |packets| { |
| 175 |
MidiInput::handle_input(packets, &mut *handler_data2.lock().unwrap()) |
| 176 |
}) { |
| 177 |
Ok(p) => p, |
| 178 |
Err(_) => return Err(ConnectError::other("error creating MIDI input port", self)) |
| 179 |
}; |
| 180 |
if let Err(_) = iport.connect_source(&port.source) { |
| 181 |
return Err(ConnectError::other("error connecting MIDI input port", self)); |
| 182 |
} |
| 183 |
Ok(MidiInputConnection { |
| 184 |
client: self.client, |
| 185 |
details: InputConnectionDetails::Explicit(iport), |
| 186 |
handler_data: handler_data |
| 187 |
}) |
| 188 |
} |
| 189 |
|
| 190 |
pub fn create_virtual<F, T: Send + 'static>( |
| 191 |
self, port_name: &str, callback: F, data: T |
| 192 |
) -> Result<MidiInputConnection<T>, ConnectError<MidiInput>> |
| 193 |
where F: FnMut(u64, &[u8], &mut T) + Send + 'static { |
| 194 |
|
| 195 |
let handler_data = Arc::new(Mutex::new(HandlerData { |
| 196 |
message: MidiMessage::new(), |
| 197 |
ignore_flags: self.ignore_flags, |
| 198 |
continue_sysex: false, |
| 199 |
callback: Box::new(callback), |
| 200 |
user_data: Some(data) |
| 201 |
})); |
| 202 |
let handler_data2 = handler_data.clone(); |
| 203 |
let vrt = match self.client.virtual_destination(port_name, move |packets| { |
| 204 |
MidiInput::handle_input(packets, &mut *handler_data2.lock().unwrap()) |
| 205 |
}) { |
| 206 |
Ok(p) => p, |
| 207 |
Err(_) => return Err(ConnectError::other("error creating MIDI input port", self)) |
| 208 |
}; |
| 209 |
Ok(MidiInputConnection { |
| 210 |
client: self.client, |
| 211 |
details: InputConnectionDetails::Virtual(vrt), |
| 212 |
handler_data: handler_data |
| 213 |
}) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
enum InputConnectionDetails { |
| 218 |
Explicit(InputPort), |
| 219 |
Virtual(VirtualDestination) |
| 220 |
} |
| 221 |
|
| 222 |
pub struct MidiInputConnection<T> { |
| 223 |
client: Client, |
| 224 |
#[allow(dead_code)] |
| 225 |
details: InputConnectionDetails, |
| 226 |
// TODO: get rid of Arc & Mutex? |
| 227 |
// synchronization is required because the borrow checker does not |
| 228 |
// know that the callback we're in here is never called concurrently |
| 229 |
// (always in sequence) |
| 230 |
handler_data: Arc<Mutex<HandlerData<T>>> |
| 231 |
} |
| 232 |
|
| 233 |
impl<T> MidiInputConnection<T> { |
| 234 |
pub fn close(self) -> (MidiInput, T) { |
| 235 |
let mut handler_data_locked = self.handler_data.lock().unwrap(); |
| 236 |
(MidiInput { |
| 237 |
client: self.client, |
| 238 |
ignore_flags: handler_data_locked.ignore_flags |
| 239 |
}, handler_data_locked.user_data.take().unwrap()) |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
/// This is all the data that is stored on the heap as long as a connection |
| 244 |
/// is opened and passed to the callback handler. |
| 245 |
/// |
| 246 |
/// It is important that `user_data` is the last field to not influence |
| 247 |
/// offsets after monomorphization. |
| 248 |
struct HandlerData<T> { |
| 249 |
message: MidiMessage, |
| 250 |
ignore_flags: Ignore, |
| 251 |
continue_sysex: bool, |
| 252 |
callback: Box<dyn FnMut(u64, &[u8], &mut T) + Send>, |
| 253 |
user_data: Option<T> |
| 254 |
} |
| 255 |
|
| 256 |
pub struct MidiOutput { |
| 257 |
client: Client |
| 258 |
} |
| 259 |
|
| 260 |
#[derive(Clone)] |
| 261 |
pub struct MidiOutputPort { |
| 262 |
dest: Arc<Destination> |
| 263 |
} |
| 264 |
|
| 265 |
impl PartialEq for MidiOutputPort { |
| 266 |
fn eq(&self, other: &Self) -> bool { |
| 267 |
if let (Some(id1), Some(id2)) = (self.dest.unique_id(), other.dest.unique_id()) { |
| 268 |
id1 == id2 |
| 269 |
} else { |
| 270 |
// Acording to macos docs "The system assigns unique IDs to all objects.", so I think we can ignore this case |
| 271 |
false |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
impl MidiOutput { |
| 277 |
pub fn new(client_name: &str) -> Result<Self, InitError> { |
| 278 |
match Client::new(client_name) { |
| 279 |
Ok(cl) => Ok(MidiOutput { client: cl }), |
| 280 |
Err(_) => Err(InitError) |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
pub(crate) fn ports_internal(&self) -> Vec<::common::MidiOutputPort> { |
| 285 |
Destinations.into_iter().map(|d| ::common::MidiOutputPort { |
| 286 |
imp: MidiOutputPort { dest: Arc::new(d) } |
| 287 |
}).collect() |
| 288 |
} |
| 289 |
|
| 290 |
pub fn port_count(&self) -> usize { |
| 291 |
Destinations::count() |
| 292 |
} |
| 293 |
|
| 294 |
pub fn port_name(&self, port: &MidiOutputPort) -> Result<String, PortInfoError> { |
| 295 |
match port.dest.display_name() { |
| 296 |
Some(name) => Ok(name), |
| 297 |
None => Err(PortInfoError::CannotRetrievePortName) |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
pub fn connect(self, port: &MidiOutputPort, port_name: &str) -> Result<MidiOutputConnection, ConnectError<MidiOutput>> { |
| 302 |
let oport = match self.client.output_port(port_name) { |
| 303 |
Ok(p) => p, |
| 304 |
Err(_) => return Err(ConnectError::other("error creating MIDI output port", self)) |
| 305 |
}; |
| 306 |
Ok(MidiOutputConnection { |
| 307 |
client: self.client, |
| 308 |
details: OutputConnectionDetails::Explicit(oport, port.dest.clone()) |
| 309 |
}) |
| 310 |
} |
| 311 |
|
| 312 |
pub fn create_virtual(self, port_name: &str) -> Result<MidiOutputConnection, ConnectError<MidiOutput>> { |
| 313 |
let vrt = match self.client.virtual_source(port_name) { |
| 314 |
Ok(p) => p, |
| 315 |
Err(_) => return Err(ConnectError::other("error creating virtual MIDI source", self)) |
| 316 |
}; |
| 317 |
Ok(MidiOutputConnection { |
| 318 |
client: self.client, |
| 319 |
details: OutputConnectionDetails::Virtual(vrt) |
| 320 |
}) |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
enum OutputConnectionDetails { |
| 325 |
Explicit(OutputPort, Arc<Destination>), |
| 326 |
Virtual(VirtualSource) |
| 327 |
} |
| 328 |
|
| 329 |
pub struct MidiOutputConnection { |
| 330 |
client: Client, |
| 331 |
details: OutputConnectionDetails |
| 332 |
} |
| 333 |
|
| 334 |
impl MidiOutputConnection { |
| 335 |
pub fn close(self) -> MidiOutput { |
| 336 |
MidiOutput { client: self.client } |
| 337 |
} |
| 338 |
|
| 339 |
pub fn send(&mut self, message: &[u8]) -> Result<(), SendError> { |
| 340 |
let packets = PacketBuffer::new(0, message); |
| 341 |
match self.details { |
| 342 |
OutputConnectionDetails::Explicit(ref port, ref dest) => { |
| 343 |
port.send(&dest, &packets).map_err(|_| SendError::Other("error sending MIDI message to port")) |
| 344 |
}, |
| 345 |
OutputConnectionDetails::Virtual(ref vrt) => { |
| 346 |
vrt.received(&packets).map_err(|_| SendError::Other("error sending MIDI to virtual destinations")) |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
} |
| 351 |
} |