Debian Codegraph @

third_party/rust/midir/src/backend/winmm/mod.rs

raw
1 extern crate winapi;
2
3 use std::{mem, ptr, slice};
4 use std::ffi::OsString;
5 use std::os::windows::ffi::OsStringExt;
6 use std::sync::Mutex;
7 use std::io::{Write, stderr};
8 use std::thread::sleep;
9 use std::time::Duration;
10 use memalloc::{allocate, deallocate};
11 use std::mem::MaybeUninit;
12 use std::ptr::null_mut;
13
14 use self::winapi::shared::basetsd::{DWORD_PTR, UINT_PTR};
15 use self::winapi::shared::minwindef::{DWORD, UINT};
16
17 use self::winapi::um::mmeapi::{midiInAddBuffer, midiInClose, midiInGetDevCapsW, midiInGetNumDevs,
18 midiInOpen, midiInPrepareHeader, midiInReset, midiInStart,
19 midiInStop, midiInUnprepareHeader, midiOutClose,
20 midiOutGetDevCapsW, midiOutGetNumDevs, midiOutLongMsg, midiOutOpen,
21 midiOutPrepareHeader, midiOutReset, midiOutShortMsg,
22 midiOutUnprepareHeader};
23
24 use self::winapi::um::mmsystem::{CALLBACK_FUNCTION, CALLBACK_NULL, HMIDIIN, HMIDIOUT, LPMIDIHDR,
25 MIDIERR_NOTREADY, MIDIERR_STILLPLAYING, MIDIHDR, MIDIINCAPSW,
26 MIDIOUTCAPSW, MMSYSERR_BADDEVICEID, MMSYSERR_NOERROR, MMSYSERR_ALLOCATED};
27
28 use {Ignore, MidiMessage};
29 use errors::*;
30
31 mod handler;
32
33 const DRV_QUERYDEVICEINTERFACE: UINT = 0x80c;
34 const DRV_QUERYDEVICEINTERFACESIZE: UINT = 0x80d;
35
36 const RT_SYSEX_BUFFER_SIZE: usize = 1024;
37 const RT_SYSEX_BUFFER_COUNT: usize = 4;
38
39 // helper for string conversion
40 fn from_wide_ptr(ptr: *const u16, max_len: usize) -> OsString {
41 unsafe {
42 assert!(!ptr.is_null());
43 let len = (0..max_len as isize).position(|i| *ptr.offset(i) == 0).unwrap();
44 let slice = slice::from_raw_parts(ptr, len);
45 OsString::from_wide(slice)
46 }
47 }
48
49 #[derive(Debug)]
50 pub struct MidiInput {
51 ignore_flags: Ignore
52 }
53
54 #[derive(Clone)]
55 pub struct MidiInputPort {
56 name: String,
57 interface_id: Box<[u16]>
58 }
59
60 impl PartialEq for MidiInputPort {
61 fn eq(&self, other: &Self) -> bool {
62 self.interface_id == other.interface_id
63 }
64 }
65
66 pub struct MidiInputConnection<T> {
67 handler_data: Box<HandlerData<T>>,
68 }
69
70 impl MidiInputPort {
71 pub fn count() -> UINT {
72 unsafe { midiInGetNumDevs() }
73 }
74
75 fn interface_id(port_number: UINT) -> Result<Box<[u16]>, PortInfoError> {
76 let mut buffer_size: winapi::shared::minwindef::ULONG = 0;
77 let result = unsafe { winapi::um::mmeapi::midiInMessage(port_number as HMIDIIN, DRV_QUERYDEVICEINTERFACESIZE, &mut buffer_size as *mut _ as DWORD_PTR, 0) };
78 if result == MMSYSERR_BADDEVICEID {
79 return Err(PortInfoError::PortNumberOutOfRange)
80 } else if result != MMSYSERR_NOERROR {
81 return Err(PortInfoError::CannotRetrievePortName)
82 }
83 let mut buffer = Vec::<u16>::with_capacity(buffer_size as usize / 2);
84 unsafe {
85 let result = winapi::um::mmeapi::midiInMessage(port_number as HMIDIIN, DRV_QUERYDEVICEINTERFACE, buffer.as_mut_ptr() as DWORD_PTR, buffer_size as DWORD_PTR);
86 if result == MMSYSERR_BADDEVICEID {
87 return Err(PortInfoError::PortNumberOutOfRange)
88 } else if result != MMSYSERR_NOERROR {
89 return Err(PortInfoError::CannotRetrievePortName)
90 }
91 buffer.set_len(buffer_size as usize / 2);
92 }
93 //println!("{}", from_wide_ptr(buffer.as_ptr(), buffer.len()).to_string_lossy().into_owned());
94 Ok(buffer.into_boxed_slice())
95 }
96
97 fn name(port_number: UINT) -> Result<String, PortInfoError> {
98 let mut device_caps: MaybeUninit<MIDIINCAPSW> = MaybeUninit::uninit();
99 let result = unsafe { midiInGetDevCapsW(port_number as UINT_PTR, device_caps.as_mut_ptr(), mem::size_of::<MIDIINCAPSW>() as u32) };
100 if result == MMSYSERR_BADDEVICEID {
101 return Err(PortInfoError::PortNumberOutOfRange)
102 } else if result != MMSYSERR_NOERROR {
103 return Err(PortInfoError::CannotRetrievePortName)
104 }
105 let device_caps = unsafe { device_caps.assume_init() };
106 let pname = device_caps.szPname;
107 let output = from_wide_ptr(pname.as_ptr(), pname.len()).to_string_lossy().into_owned();
108 Ok(output)
109 }
110
111 fn from_port_number(port_number: UINT) -> Result<Self, PortInfoError> {
112 Ok(MidiInputPort {
113 name: Self::name(port_number)?,
114 interface_id: Self::interface_id(port_number)?
115 })
116 }
117
118 fn current_port_number(&self) -> Option<UINT> {
119 for i in 0..Self::count() {
120 if let Ok(name) = Self::name(i) {
121 if name != self.name { continue; }
122 if let Ok(id) = Self::interface_id(i) {
123 if id == self.interface_id {
124 return Some(i);
125 }
126 }
127 }
128 }
129 None
130 }
131 }
132
133 struct SysexBuffer([LPMIDIHDR; RT_SYSEX_BUFFER_COUNT]);
134 unsafe impl Send for SysexBuffer {}
135
136 struct MidiInHandle(Mutex<HMIDIIN>);
137 unsafe impl Send for MidiInHandle {}
138
139 /// This is all the data that is stored on the heap as long as a connection
140 /// is opened and passed to the callback handler.
141 ///
142 /// It is important that `user_data` is the last field to not influence
143 /// offsets after monomorphization.
144 struct HandlerData<T> {
145 message: MidiMessage,
146 sysex_buffer: SysexBuffer,
147 in_handle: Option<MidiInHandle>,
148 ignore_flags: Ignore,
149 callback: Box<dyn FnMut(u64, &[u8], &mut T) + Send + 'static>,
150 user_data: Option<T>
151 }
152
153 impl MidiInput {
154 pub fn new(_client_name: &str) -> Result<Self, InitError> {
155 Ok(MidiInput { ignore_flags: Ignore::None })
156 }
157
158 pub fn ignore(&mut self, flags: Ignore) {
159 self.ignore_flags = flags;
160 }
161
162 pub(crate) fn ports_internal(&self) -> Vec<::common::MidiInputPort> {
163 let count = MidiInputPort::count();
164 let mut result = Vec::with_capacity(count as usize);
165 for i in 0..count {
166 let port = match MidiInputPort::from_port_number(i) {
167 Ok(p) => p,
168 Err(_) => continue
169 };
170 result.push(::common::MidiInputPort {
171 imp: port
172 });
173 }
174 result
175 }
176
177 pub fn port_count(&self) -> usize {
178 MidiInputPort::count() as usize
179 }
180
181 pub fn port_name(&self, port: &MidiInputPort) -> Result<String, PortInfoError> {
182 Ok(port.name.clone())
183 }
184
185 pub fn connect<F, T: Send>(
186 self, port: &MidiInputPort, _port_name: &str, callback: F, data: T
187 ) -> Result<MidiInputConnection<T>, ConnectError<MidiInput>>
188 where F: FnMut(u64, &[u8], &mut T) + Send + 'static {
189
190 let port_number = match port.current_port_number() {
191 Some(p) => p,
192 None => return Err(ConnectError::new(ConnectErrorKind::InvalidPort, self))
193 };
194
195 let mut handler_data = Box::new(HandlerData {
196 message: MidiMessage::new(),
197 sysex_buffer: SysexBuffer([null_mut(); RT_SYSEX_BUFFER_COUNT]),
198 in_handle: None,
199 ignore_flags: self.ignore_flags,
200 callback: Box::new(callback),
201 user_data: Some(data)
202 });
203
204 let mut in_handle: MaybeUninit<HMIDIIN> = MaybeUninit::uninit();
205 let handler_data_ptr: *mut HandlerData<T> = &mut *handler_data;
206 let result = unsafe { midiInOpen(in_handle.as_mut_ptr(),
207 port_number as UINT,
208 handler::handle_input::<T> as DWORD_PTR,
209 handler_data_ptr as DWORD_PTR,
210 CALLBACK_FUNCTION) };
211 if result == MMSYSERR_ALLOCATED {
212 return Err(ConnectError::other("could not create Windows MM MIDI input port (MMSYSERR_ALLOCATED)", self));
213 } else if result != MMSYSERR_NOERROR {
214 return Err(ConnectError::other("could not create Windows MM MIDI input port", self));
215 }
216 let in_handle = unsafe { in_handle.assume_init() };
217
218 // Allocate and init the sysex buffers.
219 for i in 0..RT_SYSEX_BUFFER_COUNT {
220 handler_data.sysex_buffer.0[i] = Box::into_raw(Box::new(MIDIHDR {
221 lpData: unsafe { allocate(RT_SYSEX_BUFFER_SIZE/*, mem::align_of::<u8>()*/) } as *mut i8,
222 dwBufferLength: RT_SYSEX_BUFFER_SIZE as u32,
223 dwBytesRecorded: 0,
224 dwUser: i as DWORD_PTR, // We use the dwUser parameter as buffer indicator
225 dwFlags: 0,
226 lpNext: ptr::null_mut(),
227 reserved: 0,
228 dwOffset: 0,
229 dwReserved: unsafe { mem::zeroed() },
230 }));
231
232 // TODO: are those buffers ever freed if an error occurs here (altough these calls probably only fail with out-of-memory)?
233 // TODO: close port in case of error?
234
235 let result = unsafe { midiInPrepareHeader(in_handle, handler_data.sysex_buffer.0[i], mem::size_of::<MIDIHDR>() as u32) };
236 if result != MMSYSERR_NOERROR {
237 return Err(ConnectError::other("could not initialize Windows MM MIDI input port (PrepareHeader)", self));
238 }
239
240 // Register the buffer.
241 let result = unsafe { midiInAddBuffer(in_handle, handler_data.sysex_buffer.0[i], mem::size_of::<MIDIHDR>() as u32) };
242 if result != MMSYSERR_NOERROR {
243 return Err(ConnectError::other("could not initialize Windows MM MIDI input port (AddBuffer)", self));
244 }
245 }
246
247 handler_data.in_handle = Some(MidiInHandle(Mutex::new(in_handle)));
248
249 // We can safely access (a copy of) `in_handle` here, although
250 // it has been copied into the Mutex already, because the callback
251 // has not been called yet.
252 let result = unsafe { midiInStart(in_handle) };
253 if result != MMSYSERR_NOERROR {
254 unsafe { midiInClose(in_handle) };
255 return Err(ConnectError::other("could not start Windows MM MIDI input port", self));
256 }
257
258 Ok(MidiInputConnection {
259 handler_data: handler_data
260 })
261 }
262 }
263
264 impl<T> MidiInputConnection<T> {
265 pub fn close(mut self) -> (MidiInput, T) {
266 self.close_internal();
267
268 (MidiInput {
269 ignore_flags: self.handler_data.ignore_flags,
270 }, self.handler_data.user_data.take().unwrap())
271 }
272
273 fn close_internal(&mut self) {
274 // for information about his lock, see https://groups.google.com/forum/#!topic/mididev/6OUjHutMpEo
275 let in_handle_lock = self.handler_data.in_handle.as_ref().unwrap().0.lock().unwrap();
276
277 // TODO: Call both reset and stop here? The difference seems to be that
278 // reset "returns all pending input buffers to the callback function"
279 unsafe {
280 midiInReset(*in_handle_lock);
281 midiInStop(*in_handle_lock);
282 }
283
284 for i in 0..RT_SYSEX_BUFFER_COUNT {
285 let result;
286 unsafe {
287 result = midiInUnprepareHeader(*in_handle_lock, self.handler_data.sysex_buffer.0[i], mem::size_of::<MIDIHDR>() as u32);
288 deallocate((*self.handler_data.sysex_buffer.0[i]).lpData as *mut u8, RT_SYSEX_BUFFER_SIZE/*, mem::align_of::<u8>()*/);
289 // recreate the Box so that it will be dropped/deallocated at the end of this scope
290 let _ = Box::from_raw(self.handler_data.sysex_buffer.0[i]);
291 }
292
293 if result != MMSYSERR_NOERROR {
294 let _ = writeln!(stderr(), "Warning: Ignoring error shutting down Windows MM input port (UnprepareHeader).");
295 }
296 }
297
298 unsafe { midiInClose(*in_handle_lock) };
299 }
300 }
301
302 impl<T> Drop for MidiInputConnection<T> {
303 fn drop(&mut self) {
304 // If user_data has been emptied, we know that we already have closed the connection
305 if self.handler_data.user_data.is_some() {
306 self.close_internal()
307 }
308 }
309 }
310
311 #[derive(Debug)]
312 pub struct MidiOutput;
313
314 #[derive(Clone)]
315 pub struct MidiOutputPort {
316 name: String,
317 interface_id: Box<[u16]>
318 }
319
320 impl PartialEq for MidiOutputPort {
321 fn eq(&self, other: &Self) -> bool {
322 self.interface_id == other.interface_id
323 }
324 }
325
326 pub struct MidiOutputConnection {
327 out_handle: HMIDIOUT,
328 }
329
330 unsafe impl Send for MidiOutputConnection {}
331
332 impl MidiOutputPort {
333 pub fn count() -> UINT {
334 unsafe { midiOutGetNumDevs() }
335 }
336
337 fn interface_id(port_number: UINT) -> Result<Box<[u16]>, PortInfoError> {
338 let mut buffer_size: winapi::shared::minwindef::ULONG = 0;
339 let result = unsafe { winapi::um::mmeapi::midiOutMessage(port_number as HMIDIOUT, DRV_QUERYDEVICEINTERFACESIZE, &mut buffer_size as *mut _ as DWORD_PTR, 0) };
340 if result == MMSYSERR_BADDEVICEID {
341 return Err(PortInfoError::PortNumberOutOfRange)
342 } else if result != MMSYSERR_NOERROR {
343 return Err(PortInfoError::CannotRetrievePortName)
344 }
345 let mut buffer = Vec::<u16>::with_capacity(buffer_size as usize / 2);
346 unsafe {
347 let result = winapi::um::mmeapi::midiOutMessage(port_number as HMIDIOUT, DRV_QUERYDEVICEINTERFACE, buffer.as_mut_ptr() as DWORD_PTR, buffer_size as DWORD_PTR);
348 if result == MMSYSERR_BADDEVICEID {
349 return Err(PortInfoError::PortNumberOutOfRange)
350 } else if result != MMSYSERR_NOERROR {
351 return Err(PortInfoError::CannotRetrievePortName)
352 }
353 buffer.set_len(buffer_size as usize / 2);
354 }
355 //println!("{}", from_wide_ptr(buffer.as_ptr(), buffer.len()).to_string_lossy().into_owned());
356 Ok(buffer.into_boxed_slice())
357 }
358
359 fn name(port_number: UINT) -> Result<String, PortInfoError> {
360 let mut device_caps: MaybeUninit<MIDIOUTCAPSW> = MaybeUninit::uninit();
361 let result = unsafe { midiOutGetDevCapsW(port_number as UINT_PTR, device_caps.as_mut_ptr(), mem::size_of::<MIDIOUTCAPSW>() as u32) };
362 if result == MMSYSERR_BADDEVICEID {
363 return Err(PortInfoError::PortNumberOutOfRange)
364 } else if result != MMSYSERR_NOERROR {
365 return Err(PortInfoError::CannotRetrievePortName)
366 }
367 let device_caps = unsafe { device_caps.assume_init() };
368 let pname = device_caps.szPname;
369 let output = from_wide_ptr(pname.as_ptr(), pname.len()).to_string_lossy().into_owned();
370 Ok(output)
371 }
372
373 fn from_port_number(port_number: UINT) -> Result<Self, PortInfoError> {
374 Ok(MidiOutputPort {
375 name: Self::name(port_number)?,
376 interface_id: Self::interface_id(port_number)?
377 })
378 }
379
380 fn current_port_number(&self) -> Option<UINT> {
381 for i in 0..Self::count() {
382 if let Ok(name) = Self::name(i) {
383 if name != self.name { continue; }
384 if let Ok(id) = Self::interface_id(i) {
385 if id == self.interface_id {
386 return Some(i);
387 }
388 }
389 }
390 }
391 None
392 }
393 }
394
395 impl MidiOutput {
396 pub fn new(_client_name: &str) -> Result<Self, InitError> {
397 Ok(MidiOutput)
398 }
399
400 pub(crate) fn ports_internal(&self) -> Vec<::common::MidiOutputPort> {
401 let count = MidiOutputPort::count();
402 let mut result = Vec::with_capacity(count as usize);
403 for i in 0..count {
404 let port = match MidiOutputPort::from_port_number(i) {
405 Ok(p) => p,
406 Err(_) => continue
407 };
408 result.push(::common::MidiOutputPort {
409 imp: port
410 });
411 }
412 result
413 }
414
415 pub fn port_count(&self) -> usize {
416 MidiOutputPort::count() as usize
417 }
418
419 pub fn port_name(&self, port: &MidiOutputPort) -> Result<String, PortInfoError> {
420 Ok(port.name.clone())
421 }
422
423 pub fn connect(self, port: &MidiOutputPort, _port_name: &str) -> Result<MidiOutputConnection, ConnectError<MidiOutput>> {
424 let port_number = match port.current_port_number() {
425 Some(p) => p,
426 None => return Err(ConnectError::new(ConnectErrorKind::InvalidPort, self))
427 };
428 let mut out_handle: MaybeUninit<HMIDIOUT> = MaybeUninit::uninit();
429 let result = unsafe { midiOutOpen(out_handle.as_mut_ptr(), port_number as UINT, 0, 0, CALLBACK_NULL) };
430 if result == MMSYSERR_ALLOCATED {
431 return Err(ConnectError::other("could not create Windows MM MIDI output port (MMSYSERR_ALLOCATED)", self));
432 } else if result != MMSYSERR_NOERROR {
433 return Err(ConnectError::other("could not create Windows MM MIDI output port", self));
434 }
435 Ok(MidiOutputConnection {
436 out_handle: unsafe { out_handle.assume_init() },
437 })
438 }
439 }
440
441 impl MidiOutputConnection {
442 pub fn close(self) -> MidiOutput {
443 // The actual closing is done by the implementation of Drop
444 MidiOutput // In this API this is a noop
445 }
446
447 pub fn send(&mut self, message: &[u8]) -> Result<(), SendError> {
448 let nbytes = message.len();
449 if nbytes == 0 {
450 return Err(SendError::InvalidData("message to be sent must not be empty"));
451 }
452
453 if message[0] == 0xF0 { // Sysex message
454 // Allocate buffer for sysex data and copy message
455 let mut buffer = message.to_vec();
456
457 // Create and prepare MIDIHDR structure.
458 let mut sysex = MIDIHDR {
459 lpData: buffer.as_mut_ptr() as *mut i8,
460 dwBufferLength: nbytes as u32,
461 dwBytesRecorded: 0,
462 dwUser: 0,
463 dwFlags: 0,
464 lpNext: ptr::null_mut(),
465 reserved: 0,
466 dwOffset: 0,
467 dwReserved: unsafe { mem::zeroed() },
468 };
469
470 let result = unsafe { midiOutPrepareHeader(self.out_handle, &mut sysex, mem::size_of::<MIDIHDR>() as u32) };
471
472 if result != MMSYSERR_NOERROR {
473 return Err(SendError::Other("preparation for sending sysex message failed (OutPrepareHeader)"));
474 }
475
476 // Send the message.
477 loop {
478 let result = unsafe { midiOutLongMsg(self.out_handle, &mut sysex, mem::size_of::<MIDIHDR>() as u32) };
479 if result == MIDIERR_NOTREADY {
480 sleep(Duration::from_millis(1));
481 continue;
482 } else {
483 if result != MMSYSERR_NOERROR {
484 return Err(SendError::Other("sending sysex message failed"));
485 }
486 break;
487 }
488 }
489
490 loop {
491 let result = unsafe { midiOutUnprepareHeader(self.out_handle, &mut sysex, mem::size_of::<MIDIHDR>() as u32) };
492 if result == MIDIERR_STILLPLAYING {
493 sleep(Duration::from_millis(1));
494 continue;
495 } else { break; }
496 }
497 } else { // Channel or system message.
498 // Make sure the message size isn't too big.
499 if nbytes > 3 {
500 return Err(SendError::InvalidData("non-sysex message must not be longer than 3 bytes"));
501 }
502
503 // Pack MIDI bytes into double word.
504 let packet: DWORD = 0;
505 let ptr = &packet as *const u32 as *mut u8;
506 for i in 0..nbytes {
507 unsafe { *ptr.offset(i as isize) = message[i] };
508 }
509
510 // Send the message immediately.
511 loop {
512 let result = unsafe { midiOutShortMsg(self.out_handle, packet) };
513 if result == MIDIERR_NOTREADY {
514 sleep(Duration::from_millis(1));
515 continue;
516 } else {
517 if result != MMSYSERR_NOERROR {
518 return Err(SendError::Other("sending non-sysex message failed"));
519 }
520 break;
521 }
522 }
523 }
524
525 Ok(())
526 }
527 }
528
529 impl Drop for MidiOutputConnection {
530 fn drop(&mut self) {
531 unsafe {
532 midiOutReset(self.out_handle);
533 midiOutClose(self.out_handle);
534 }
535 }
536 }