Debian Codegraph @

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

raw
1 extern crate libc;
2 extern crate alsa;
3
4 use std::mem;
5 use std::thread::{Builder, JoinHandle};
6 use std::io::{stderr, Write};
7 use std::ffi::{CString, CStr};
8
9 use self::alsa::{Seq, Direction};
10 use self::alsa::seq::{PortInfo, PortSubscribe, Addr, QueueTempo, EventType, PortCap, PortType};
11
12 use ::{MidiMessage, Ignore};
13 use ::errors::*;
14
15 mod helpers {
16 use super::alsa::seq::{Seq, Addr, ClientIter, PortIter, PortInfo, PortCap, MidiEvent, PortType};
17 use ::errors::PortInfoError;
18
19 pub fn poll(fds: &mut [super::libc::pollfd], timeout: i32) -> i32 {
20 unsafe { super::libc::poll(fds.as_mut_ptr(), fds.len() as super::libc::nfds_t, timeout) }
21 }
22
23 #[inline]
24 pub fn get_ports<F, T>(s: &Seq, capability: PortCap, f: F) -> Vec<T> where F: Fn(PortInfo) -> T {
25 ClientIter::new(s).flat_map(|c| PortIter::new(s, c.get_client()))
26 .filter(|p| p.get_type().intersects(PortType::MIDI_GENERIC | PortType::SYNTH | PortType::APPLICATION))
27 .filter(|p| p.get_capability().intersects(capability))
28 .map(f)
29 .collect()
30 }
31
32 #[inline]
33 pub fn get_port_count(s: &Seq, capability: PortCap) -> usize {
34 ClientIter::new(s).flat_map(|c| PortIter::new(s, c.get_client()))
35 .filter(|p| p.get_type().intersects(PortType::MIDI_GENERIC | PortType::SYNTH | PortType::APPLICATION))
36 .filter(|p| p.get_capability().intersects(capability))
37 .count()
38 }
39
40 #[inline]
41 pub fn get_port_name(s: &Seq, addr: Addr) -> Result<String, PortInfoError> {
42 use std::fmt::Write;
43
44 let pinfo = match s.get_any_port_info(addr) {
45 Ok(p) => p,
46 Err(_) => return Err(PortInfoError::InvalidPort)
47 };
48
49 let cinfo = s.get_any_client_info(pinfo.get_client()).map_err(|_| PortInfoError::CannotRetrievePortName)?;
50 let mut output = String::new();
51 write!(&mut output, "{}:{} {}:{}",
52 cinfo.get_name().map_err(|_| PortInfoError::CannotRetrievePortName)?,
53 pinfo.get_name().map_err(|_| PortInfoError::CannotRetrievePortName)?,
54 pinfo.get_client(), // These lines added to make sure devices are listed
55 pinfo.get_port() // with full portnames added to ensure individual device names
56 ).unwrap();
57 Ok(output)
58 }
59
60 pub struct EventDecoder {
61 ev: MidiEvent
62 }
63
64 impl EventDecoder {
65 pub fn new(merge_commands: bool) -> EventDecoder {
66 let coder = MidiEvent::new(0).unwrap();
67 coder.enable_running_status(merge_commands);
68 EventDecoder { ev: coder }
69 }
70
71 #[inline]
72 pub fn get_wrapped(&mut self) -> &mut MidiEvent {
73 &mut self.ev
74 }
75 }
76
77 pub struct EventEncoder {
78 ev: MidiEvent,
79 buffer_size: u32
80 }
81
82 unsafe impl Send for EventEncoder {}
83
84 impl EventEncoder {
85 #[inline]
86 pub fn new(buffer_size: u32) -> EventEncoder {
87 EventEncoder {
88 ev: MidiEvent::new(buffer_size).unwrap(),
89 buffer_size: buffer_size
90 }
91 }
92
93 #[inline]
94 pub fn get_buffer_size(&self) -> u32 {
95 self.buffer_size
96 }
97
98 #[inline]
99 pub fn resize_buffer(&mut self, bufsize: u32) -> Result<(), ()> {
100 match self.ev.resize_buffer(bufsize) {
101 Ok(_) => {
102 self.buffer_size = bufsize;
103 Ok(())
104 },
105 Err(_) => Err(())
106 }
107 }
108
109 #[inline]
110 pub fn get_wrapped(&mut self) -> &mut MidiEvent {
111 &mut self.ev
112 }
113 }
114 }
115
116 const INITIAL_CODER_BUFFER_SIZE: usize = 32;
117
118 pub struct MidiInput {
119 ignore_flags: Ignore,
120 seq: Option<Seq>,
121 }
122
123 #[derive(Clone, PartialEq)]
124 pub struct MidiInputPort {
125 addr: Addr
126 }
127
128 pub struct MidiInputConnection<T: 'static> {
129 subscription: Option<PortSubscribe>,
130 thread: Option<JoinHandle<(HandlerData<T>, T)>>,
131 vport: i32, // TODO: probably port numbers are only u8, therefore could use Option<u8>
132 trigger_send_fd: i32,
133 }
134
135 struct HandlerData<T: 'static> {
136 ignore_flags: Ignore,
137 seq: Seq,
138 trigger_rcv_fd: i32,
139 callback: Box<dyn FnMut(u64, &[u8], &mut T) + Send>,
140 queue_id: i32, // an input queue is needed to get timestamped events
141 }
142
143 impl MidiInput {
144 pub fn new(client_name: &str) -> Result<Self, InitError> {
145 let seq = match Seq::open(None, None, true) {
146 Ok(s) => s,
147 Err(_) => { return Err(InitError); }
148 };
149
150 let c_client_name = CString::new(client_name).map_err(|_| InitError)?;
151 seq.set_client_name(&c_client_name).map_err(|_| InitError)?;
152
153 Ok(MidiInput {
154 ignore_flags: Ignore::None,
155 seq: Some(seq),
156 })
157 }
158
159 pub fn ignore(&mut self, flags: Ignore) {
160 self.ignore_flags = flags;
161 }
162
163 pub(crate) fn ports_internal(&self) -> Vec<::common::MidiInputPort> {
164 helpers::get_ports(self.seq.as_ref().unwrap(), PortCap::READ | PortCap::SUBS_READ, |p| ::common::MidiInputPort {
165 imp: MidiInputPort {
166 addr: p.addr()
167 }
168 })
169 }
170
171 pub fn port_count(&self) -> usize {
172 helpers::get_port_count(self.seq.as_ref().unwrap(), PortCap::READ | PortCap::SUBS_READ)
173 }
174
175 pub fn port_name(&self, port: &MidiInputPort) -> Result<String, PortInfoError> {
176 helpers::get_port_name(self.seq.as_ref().unwrap(), port.addr)
177 }
178
179 fn init_queue(&mut self) -> i32 {
180 let seq = self.seq.as_mut().unwrap();
181 let mut queue_id = 0;
182 // Create the input queue
183 if !cfg!(feature = "avoid_timestamping") {
184 queue_id = seq.alloc_named_queue(unsafe { CStr::from_bytes_with_nul_unchecked(b"midir queue\0") }).unwrap();
185 // Set arbitrary tempo (mm=100) and resolution (240)
186 let qtempo = QueueTempo::empty().unwrap();
187 qtempo.set_tempo(600_000);
188 qtempo.set_ppq(240);
189 seq.set_queue_tempo(queue_id, &qtempo).unwrap();
190 let _ = seq.drain_output();
191 }
192
193 queue_id
194 }
195
196 fn init_trigger(&mut self) -> Result<[i32; 2], ()> {
197 let mut trigger_fds = [-1, -1];
198
199 if unsafe { self::libc::pipe(trigger_fds.as_mut_ptr()) } == -1 {
200 Err(())
201 } else {
202 Ok(trigger_fds)
203 }
204 }
205
206 fn create_port(&mut self, port_name: &CStr, queue_id: i32) -> Result<i32, ()> {
207 let mut pinfo = PortInfo::empty().unwrap();
208 // these functions are private, and the values are zeroed already by `empty()`
209 //pinfo.set_client(0);
210 //pinfo.set_port(0);
211 pinfo.set_capability(PortCap::WRITE | PortCap::SUBS_WRITE);
212 pinfo.set_type(PortType::MIDI_GENERIC | PortType::APPLICATION);
213 pinfo.set_midi_channels(16);
214
215 if !cfg!(feature = "avoid_timestamping") {
216 pinfo.set_timestamping(true);
217 pinfo.set_timestamp_real(true);
218 pinfo.set_timestamp_queue(queue_id);
219 }
220
221 pinfo.set_name(port_name);
222 match self.seq.as_mut().unwrap().create_port(&mut pinfo) {
223 Ok(_) => Ok(pinfo.get_port()),
224 Err(_) => Err(())
225 }
226 }
227
228 fn start_input_queue(&mut self, queue_id: i32) {
229 if !cfg!(feature = "avoid_timestamping") {
230 let seq = self.seq.as_mut().unwrap();
231 let _ = seq.control_queue(queue_id, EventType::Start, 0, None);
232 let _ = seq.drain_output();
233 }
234 }
235
236 pub fn connect<F, T: Send>(
237 mut self, port: &MidiInputPort, port_name: &str, callback: F, data: T
238 ) -> Result<MidiInputConnection<T>, ConnectError<Self>>
239 where F: FnMut(u64, &[u8], &mut T) + Send + 'static {
240
241 let trigger_fds = match self.init_trigger() {
242 Ok(fds) => fds,
243 Err(()) => { return Err(ConnectError::other("could not create communication pipe for ALSA handler", self)); }
244 };
245
246 let queue_id = self.init_queue();
247
248 let src_pinfo = match self.seq.as_ref().unwrap().get_any_port_info(port.addr) {
249 Ok(p) => p,
250 Err(_) => return Err(ConnectError::new(ConnectErrorKind::InvalidPort, self))
251 };
252
253 let c_port_name = match CString::new(port_name) {
254 Ok(c_port_name) => c_port_name,
255 Err(_) => return Err(ConnectError::other("port_name must not contain null bytes", self))
256 };
257
258 let vport = match self.create_port(&c_port_name, queue_id) {
259 Ok(vp) => vp,
260 Err(_) => {
261 return Err(ConnectError::other("could not create ALSA input port", self));
262 }
263 };
264
265 // Make subscription
266 let sub = PortSubscribe::empty().unwrap();
267 sub.set_sender(src_pinfo.addr());
268 sub.set_dest(Addr { client: self.seq.as_ref().unwrap().client_id().unwrap(), port: vport});
269 if self.seq.as_ref().unwrap().subscribe_port(&sub).is_err() {
270 return Err(ConnectError::other("could not create ALSA input subscription", self));
271 }
272 let subscription = sub;
273
274 // Start the input queue
275 self.start_input_queue(queue_id);
276
277 // Start our MIDI input thread.
278 let handler_data = HandlerData {
279 ignore_flags: self.ignore_flags,
280 seq: self.seq.take().unwrap(),
281 trigger_rcv_fd: trigger_fds[0],
282 callback: Box::new(callback),
283 queue_id: queue_id
284 };
285
286 let threadbuilder = Builder::new();
287 let name = format!("midir ALSA input handler (port '{}')", port_name);
288 let threadbuilder = threadbuilder.name(name);
289 let thread = match threadbuilder.spawn(move || {
290 let mut d = data;
291 let h = handle_input(handler_data, &mut d);
292 (h, d) // return both the handler data and the user data
293 }) {
294 Ok(handle) => handle,
295 Err(_) => {
296 //unsafe { snd_seq_unsubscribe_port(self.seq.as_mut_ptr(), sub.as_ptr()) };
297 return Err(ConnectError::other("could not start ALSA input handler thread", self));
298 }
299 };
300
301 Ok(MidiInputConnection {
302 subscription: Some(subscription),
303 thread: Some(thread),
304 vport: vport,
305 trigger_send_fd: trigger_fds[1]
306 })
307 }
308
309 pub fn create_virtual<F, T: Send>(
310 mut self, port_name: &str, callback: F, data: T
311 ) -> Result<MidiInputConnection<T>, ConnectError<Self>>
312 where F: FnMut(u64, &[u8], &mut T) + Send + 'static {
313 let trigger_fds = match self.init_trigger() {
314 Ok(fds) => fds,
315 Err(()) => { return Err(ConnectError::other("could not create communication pipe for ALSA handler", self)); }
316 };
317
318 let queue_id = self.init_queue();
319
320 let c_port_name = match CString::new(port_name) {
321 Ok(c_port_name) => c_port_name,
322 Err(_) => return Err(ConnectError::other("port_name must not contain null bytes", self))
323 };
324
325 let vport = match self.create_port(&c_port_name, queue_id) {
326 Ok(vp) => vp,
327 Err(_) => {
328 return Err(ConnectError::other("could not create ALSA input port", self));
329 }
330 };
331
332 // Start the input queue
333 self.start_input_queue(queue_id);
334
335 // Start our MIDI input thread.
336 let handler_data = HandlerData {
337 ignore_flags: self.ignore_flags,
338 seq: self.seq.take().unwrap(),
339 trigger_rcv_fd: trigger_fds[0],
340 callback: Box::new(callback),
341 queue_id: queue_id
342 };
343
344 let threadbuilder = Builder::new();
345 let thread = match threadbuilder.spawn(move || {
346 let mut d = data;
347 let h = handle_input(handler_data, &mut d);
348 (h, d) // return both the handler data and the user data
349 }) {
350 Ok(handle) => handle,
351 Err(_) => {
352 //unsafe { snd_seq_unsubscribe_port(self.seq.as_mut_ptr(), sub.as_ptr()) };
353 return Err(ConnectError::other("could not start ALSA input handler thread", self));
354 }
355 };
356
357 Ok(MidiInputConnection {
358 subscription: None,
359 thread: Some(thread),
360 vport: vport,
361 trigger_send_fd: trigger_fds[1]
362 })
363 }
364 }
365
366 impl<T> MidiInputConnection<T> {
367 pub fn close(mut self) -> (MidiInput, T) {
368 let (handler_data, user_data) = self.close_internal();
369
370 (MidiInput {
371 ignore_flags: handler_data.ignore_flags,
372 seq: Some(handler_data.seq),
373 }, user_data)
374 }
375
376 /// This must only be called if the handler thread has not yet been shut down
377 fn close_internal(&mut self) -> (HandlerData<T>, T) {
378 // Request the thread to stop.
379 let _res = unsafe { self::libc::write(self.trigger_send_fd, &false as *const bool as *const _, mem::size_of::<bool>() as self::libc::size_t) };
380
381 let thread = self.thread.take().unwrap();
382 // Join the thread to get the handler_data back
383 let (handler_data, user_data) = match thread.join() {
384 Ok(data) => data,
385 // TODO: handle this more gracefully?
386 Err(e) => {
387 if let Some(e) = e.downcast_ref::<&'static str>() {
388 panic!("Error when joining ALSA thread: {}", e);
389 } else {
390 panic!("Unknown error when joining ALSA thread: {:?}", e);
391 }
392 }
393 };
394
395 // TODO: find out why snd_seq_unsubscribe_port takes a long time if there was not yet any input message
396 if let Some(ref subscription) = self.subscription {
397 let _ = handler_data.seq.unsubscribe_port(subscription.get_sender(), subscription.get_dest());
398 }
399
400 // Close the trigger fds (TODO: make sure that these are closed even in the presence of panic in thread)
401 unsafe {
402 self::libc::close(handler_data.trigger_rcv_fd);
403 self::libc::close(self.trigger_send_fd);
404 }
405
406 // Stop and free the input queue
407 if !cfg!(feature = "avoid_timestamping") {
408 let _ = handler_data.seq.control_queue(handler_data.queue_id, EventType::Stop, 0, None);
409 let _ = handler_data.seq.drain_output();
410 let _ = handler_data.seq.free_queue(handler_data.queue_id);
411 }
412
413 // Delete the port
414 let _ = handler_data.seq.delete_port(self.vport);
415
416 (handler_data, user_data)
417 }
418 }
419
420
421 impl<T> Drop for MidiInputConnection<T> {
422 fn drop(&mut self) {
423 // Use `self.thread` as a flag whether the connection has already been dropped
424 if self.thread.is_some() {
425 self.close_internal();
426 }
427 }
428 }
429
430 pub struct MidiOutput {
431 seq: Option<Seq>, // TODO: if `Seq` is marked as non-zero, this should just be pointer-sized
432 }
433
434 #[derive(Clone, PartialEq)]
435 pub struct MidiOutputPort {
436 addr: Addr
437 }
438
439 pub struct MidiOutputConnection {
440 seq: Option<Seq>,
441 vport: i32,
442 coder: helpers::EventEncoder,
443 subscription: Option<PortSubscribe>
444 }
445
446 impl MidiOutput {
447 pub fn new(client_name: &str) -> Result<Self, InitError> {
448 let seq = match Seq::open(None, Some(Direction::Playback), true) {
449 Ok(s) => s,
450 Err(_) => { return Err(InitError); }
451 };
452
453 let c_client_name = CString::new(client_name).map_err(|_| InitError)?;
454 seq.set_client_name(&c_client_name).map_err(|_| InitError)?;
455
456 Ok(MidiOutput {
457 seq: Some(seq),
458 })
459 }
460
461 pub(crate) fn ports_internal(&self) -> Vec<::common::MidiOutputPort> {
462 helpers::get_ports(self.seq.as_ref().unwrap(), PortCap::WRITE | PortCap::SUBS_WRITE, |p| ::common::MidiOutputPort {
463 imp: MidiOutputPort {
464 addr: p.addr()
465 }
466 })
467 }
468
469 pub fn port_count(&self) -> usize {
470 helpers::get_port_count(self.seq.as_ref().unwrap(), PortCap::WRITE | PortCap::SUBS_WRITE)
471 }
472
473 pub fn port_name(&self, port: &MidiOutputPort) -> Result<String, PortInfoError> {
474 helpers::get_port_name(self.seq.as_ref().unwrap(), port.addr)
475 }
476
477 pub fn connect(mut self, port: &MidiOutputPort, port_name: &str) -> Result<MidiOutputConnection, ConnectError<Self>> {
478 let pinfo = match self.seq.as_ref().unwrap().get_any_port_info(port.addr) {
479 Ok(p) => p,
480 Err(_) => return Err(ConnectError::new(ConnectErrorKind::InvalidPort, self))
481 };
482
483 let c_port_name = match CString::new(port_name) {
484 Ok(c_port_name) => c_port_name,
485 Err(_) => return Err(ConnectError::other("port_name must not contain null bytes", self))
486 };
487
488 let vport = match self.seq.as_ref().unwrap().create_simple_port(&c_port_name, PortCap::READ | PortCap::SUBS_READ, PortType::MIDI_GENERIC | PortType::APPLICATION) {
489 Ok(vport) => vport,
490 Err(_) => return Err(ConnectError::other("could not create ALSA output port", self))
491 };
492
493 // Make subscription
494 let sub = PortSubscribe::empty().unwrap();
495 sub.set_sender(Addr { client: self.seq.as_ref().unwrap().client_id().unwrap(), port: vport });
496 sub.set_dest(pinfo.addr());
497 sub.set_time_update(true);
498 sub.set_time_real(true);
499 if self.seq.as_ref().unwrap().subscribe_port(&sub).is_err() {
500 return Err(ConnectError::other("could not create ALSA output subscription", self));
501 }
502
503 Ok(MidiOutputConnection {
504 seq: self.seq.take(),
505 vport: vport,
506 coder: helpers::EventEncoder::new(INITIAL_CODER_BUFFER_SIZE as u32),
507 subscription: Some(sub)
508 })
509 }
510
511 pub fn create_virtual(
512 mut self, port_name: &str
513 ) -> Result<MidiOutputConnection, ConnectError<Self>> {
514 let c_port_name = match CString::new(port_name) {
515 Ok(c_port_name) => c_port_name,
516 Err(_) => return Err(ConnectError::other("port_name must not contain null bytes", self))
517 };
518
519 let vport = match self.seq.as_ref().unwrap().create_simple_port(&c_port_name, PortCap::READ | PortCap::SUBS_READ, PortType::MIDI_GENERIC | PortType::APPLICATION) {
520 Ok(vport) => vport,
521 Err(_) => return Err(ConnectError::other("could not create ALSA output port", self))
522 };
523
524 Ok(MidiOutputConnection {
525 seq: self.seq.take(),
526 vport: vport,
527 coder: helpers::EventEncoder::new(INITIAL_CODER_BUFFER_SIZE as u32),
528 subscription: None
529 })
530 }
531 }
532
533
534 impl MidiOutputConnection {
535 pub fn close(mut self) -> MidiOutput {
536 self.close_internal();
537
538 MidiOutput {
539 seq: self.seq.take(),
540 }
541 }
542
543 pub fn send(&mut self, message: &[u8]) -> Result<(), SendError> {
544 let nbytes = message.len();
545 assert!(nbytes <= u32::max_value() as usize);
546
547 if nbytes > self.coder.get_buffer_size() as usize {
548 if self.coder.resize_buffer(nbytes as u32).is_err() {
549 return Err(SendError::Other("could not resize ALSA encoding buffer"));
550 }
551 }
552
553 let mut ev = match self.coder.get_wrapped().encode(message) {
554 Ok((_, Some(ev))) => ev,
555 _ => return Err(SendError::InvalidData("ALSA encoder reported invalid data"))
556 };
557
558 ev.set_source(self.vport);
559 ev.set_subs();
560 ev.set_direct();
561
562 // Send the event.
563 if self.seq.as_ref().unwrap().event_output(&mut ev).is_err() {
564 return Err(SendError::Other("could not send encoded ALSA message"));
565 }
566
567 let _ = self.seq.as_mut().unwrap().drain_output();
568 Ok(())
569 }
570
571 fn close_internal(&mut self) {
572 let seq = self.seq.as_mut().unwrap();
573 if let Some(ref subscription) = self.subscription {
574 let _ = seq.unsubscribe_port(subscription.get_sender(), subscription.get_dest());
575 }
576 let _ = seq.delete_port(self.vport);
577 }
578 }
579
580 impl Drop for MidiOutputConnection {
581 fn drop(&mut self) {
582 if self.seq.is_some() {
583 self.close_internal();
584 }
585 }
586 }
587
588 fn handle_input<T>(mut data: HandlerData<T>, user_data: &mut T) -> HandlerData<T> {
589 use self::alsa::PollDescriptors;
590 use self::alsa::seq::Connect;
591
592 let mut continue_sysex: bool = false;
593
594 // ALSA documentation says:
595 // The required buffer size for a sequencer event it as most 12 bytes, except for System Exclusive events (which we handle separately)
596 let mut buffer = [0; 12];
597
598 let mut coder = helpers::EventDecoder::new(false);
599
600 let mut poll_fds: Box<[self::libc::pollfd]>;
601 {
602 let poll_desc_info = (&data.seq, Some(Direction::Capture));
603 let poll_fd_count = poll_desc_info.count() + 1;
604 let mut vec = Vec::with_capacity(poll_fd_count);
605 unsafe {
606 vec.set_len(poll_fd_count);
607 poll_fds = vec.into_boxed_slice();
608 }
609 poll_desc_info.fill(&mut poll_fds[1..]).unwrap();
610 }
611 poll_fds[0].fd = data.trigger_rcv_fd;
612 poll_fds[0].events = self::libc::POLLIN;
613
614
615 let mut message = MidiMessage::new();
616
617 { // open scope where we can borrow data.seq
618 let mut seq_input = data.seq.input();
619
620 let mut do_input = true;
621 while do_input {
622 if let Ok(0) = seq_input.event_input_pending(true) {
623 // No data pending
624 if helpers::poll(&mut poll_fds, -1) >= 0 {
625 // Read from our "channel" whether we should stop the thread
626 if poll_fds[0].revents & self::libc::POLLIN != 0 {
627 let _res = unsafe { self::libc::read(poll_fds[0].fd, mem::transmute(&mut do_input), mem::size_of::<bool>() as self::libc::size_t) };
628 }
629 }
630 continue;
631 }
632
633 // This is a bit weird, but we now have to decode an ALSA MIDI
634 // event (back) into MIDI bytes. We'll ignore non-MIDI types.
635
636 // The ALSA sequencer has a maximum buffer size for MIDI sysex
637 // events of 256 bytes. If a device sends sysex messages larger
638 // than this, they are segmented into 256 byte chunks. So,
639 // we'll watch for this and concatenate sysex chunks into a
640 // single sysex message if necessary.
641 //
642 // TODO: Figure out if this is still true (seems to not be the case)
643 // If not (i.e., each event represents a complete message), we can
644 // call the user callback with the byte buffer directly, without the
645 // copying to `message.bytes` first.
646 if !continue_sysex { message.bytes.clear() }
647
648 let ignore_flags = data.ignore_flags;
649
650 // If here, there should be data.
651 let mut ev = match seq_input.event_input() {
652 Ok(ev) => ev,
653 Err(ref e) if e.errno() == alsa::nix::errno::Errno::ENOSPC => {
654 let _ = writeln!(stderr(), "\nError in handle_input: ALSA MIDI input buffer overrun!\n");
655 continue;
656 },
657 Err(ref e) if e.errno() == alsa::nix::errno::Errno::EAGAIN => {
658 let _ = writeln!(stderr(), "\nError in handle_input: no input event from ALSA MIDI input buffer!\n");
659 continue;
660 },
661 Err(ref e) => {
662 let _ = writeln!(stderr(), "\nError in handle_input: unknown ALSA MIDI input error ({})!\n", e);
663 //perror("System reports");
664 continue;
665 }
666 };
667
668 let do_decode = match ev.get_type() {
669 EventType::PortSubscribed => {
670 if cfg!(debug) { println!("Notice from handle_input: ALSA port connection made!") };
671 false
672 },
673 EventType::PortUnsubscribed => {
674 if cfg!(debug) {
675 let _ = writeln!(stderr(), "Notice from handle_input: ALSA port connection has closed!");
676 let connect = ev.get_data::<Connect>().unwrap();
677 let _ = writeln!(stderr(), "sender = {}:{}, dest = {}:{}",
678 connect.sender.client,
679 connect.sender.port,
680 connect.dest.client,
681 connect.dest.port
682 );
683 }
684 false
685 },
686 EventType::Qframe => { // MIDI time code
687 !ignore_flags.contains(Ignore::Time)
688 },
689 EventType::Tick => { // 0xF9 ... MIDI timing tick
690 !ignore_flags.contains(Ignore::Time)
691 },
692 EventType::Clock => { // 0xF8 ... MIDI timing (clock) tick
693 !ignore_flags.contains(Ignore::Time)
694 },
695 EventType::Sensing => { // Active sensing
696 !ignore_flags.contains(Ignore::ActiveSense)
697 },
698 EventType::Sysex => {
699 if !ignore_flags.contains(Ignore::Sysex) {
700 // Directly copy the data from the external buffer to our message
701 message.bytes.extend_from_slice(ev.get_ext().unwrap());
702 continue_sysex = *message.bytes.last().unwrap() != 0xF7;
703 }
704 false // don't ever decode sysex messages (it would unnecessarily copy the message content to another buffer)
705 },
706 _ => true
707 };
708
709 // NOTE: SysEx messages have already been "decoded" at this point!
710 if do_decode {
711 if let Ok(nbytes) = coder.get_wrapped().decode(&mut buffer, &mut ev) {
712 if nbytes > 0 {
713 message.bytes.extend_from_slice(&buffer[0..nbytes]);
714 }
715 }
716 }
717
718 if message.bytes.len() == 0 || continue_sysex { continue; }
719
720 // Calculate the time stamp:
721 // Use the ALSA sequencer event time data.
722 // (thanks to Pedro Lopez-Cabanillas!).
723 let alsa_time = ev.get_time().unwrap();
724 let secs = alsa_time.as_secs();
725 let nsecs = alsa_time.subsec_nanos();
726
727 message.timestamp = ( secs as u64 * 1_000_000 ) + ( nsecs as u64 / 1_000 );
728 (data.callback)(message.timestamp, &message.bytes, user_data);
729 }
730
731 } // close scope where data.seq is borrowed
732 data // return data back to thread owner
733 }