1 //! MIDI sequencer I/O and enumeration
2
3 use libc::{c_uint, c_int, c_short, c_uchar, c_void, c_long, size_t, pollfd};
4 use super::error::*;
5 use crate::alsa;
6 use super::{Direction, poll};
7 use std::{ptr, fmt, mem, slice, time, cell};
8 use std::str::{FromStr, Split};
9 use std::ffi::{CStr};
10 use std::borrow::Cow;
11
12 // Workaround for improper alignment of snd_seq_ev_ext_t in alsa-sys
13 #[repr(packed)]
14 struct EvExtPacked {
15 len: c_uint,
16 ptr: *mut c_void,
17 }
18
19 /// [snd_seq_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___sequencer.html) wrapper
20 ///
21 /// To access the functions ``event_input`, `event_input_pending` and `set_input_buffer_size`,
22 /// you first have to obtain an instance of `Input` by calling `input()`. Only one instance of
23 /// `Input` may exist at any time for a given `Seq`.
24 pub struct Seq(*mut alsa::snd_seq_t, cell::Cell<bool>);
25
26 unsafe impl Send for Seq {}
27
28 impl Drop for Seq {
drop(&mut self)29 fn drop(&mut self) { unsafe { alsa::snd_seq_close(self.0) }; }
30 }
31
32 impl Seq {
check_has_input(&self)33 fn check_has_input(&self) {
34 if self.1.get() { panic!("No additional Input object allowed")}
35 }
36
37 /// Opens the sequencer.
38 ///
39 /// If name is None, "default" will be used. That's almost always what you usually want to use anyway.
open(name: Option<&CStr>, dir: Option<Direction>, nonblock: bool) -> Result<Seq>40 pub fn open(name: Option<&CStr>, dir: Option<Direction>, nonblock: bool) -> Result<Seq> {
41 let n2 = name.unwrap_or(unsafe { CStr::from_bytes_with_nul_unchecked(b"default\0") });
42 let mut h = ptr::null_mut();
43 let mode = if nonblock { alsa::SND_SEQ_NONBLOCK } else { 0 };
44 let streams = match dir {
45 None => alsa::SND_SEQ_OPEN_DUPLEX,
46 Some(Direction::Playback) => alsa::SND_SEQ_OPEN_OUTPUT,
47 Some(Direction::Capture) => alsa::SND_SEQ_OPEN_INPUT,
48 };
49 acheck!(snd_seq_open(&mut h, n2.as_ptr(), streams, mode))
50 .map(|_| Seq(h, cell::Cell::new(false)))
51 }
52
set_client_name(&self, name: &CStr) -> Result<()>53 pub fn set_client_name(&self, name: &CStr) -> Result<()> {
54 acheck!(snd_seq_set_client_name(self.0, name.as_ptr())).map(|_| ())
55 }
56
set_client_event_filter(&self, event_type: i32) -> Result<()>57 pub fn set_client_event_filter(&self, event_type: i32) -> Result<()> {
58 acheck!(snd_seq_set_client_event_filter(self.0, event_type as c_int)).map(|_| ())
59 }
60
set_client_pool_output(&self, size: u32) -> Result<()>61 pub fn set_client_pool_output(&self, size: u32) -> Result<()> {
62 acheck!(snd_seq_set_client_pool_output(self.0, size as size_t)).map(|_| ())
63 }
64
set_client_pool_input(&self, size: u32) -> Result<()>65 pub fn set_client_pool_input(&self, size: u32) -> Result<()> {
66 acheck!(snd_seq_set_client_pool_input(self.0, size as size_t)).map(|_| ())
67 }
68
set_client_pool_output_room(&self, size: u32) -> Result<()>69 pub fn set_client_pool_output_room(&self, size: u32) -> Result<()> {
70 acheck!(snd_seq_set_client_pool_output_room(self.0, size as size_t)).map(|_| ())
71 }
72
client_id(&self) -> Result<i32>73 pub fn client_id(&self) -> Result<i32> {
74 acheck!(snd_seq_client_id(self.0)).map(|q| q as i32)
75 }
76
drain_output(&self) -> Result<i32>77 pub fn drain_output(&self) -> Result<i32> {
78 acheck!(snd_seq_drain_output(self.0)).map(|q| q as i32)
79 }
80
get_any_client_info(&self, client: i32) -> Result<ClientInfo>81 pub fn get_any_client_info(&self, client: i32) -> Result<ClientInfo> {
82 let c = ClientInfo::new()?;
83 acheck!(snd_seq_get_any_client_info(self.0, client, c.0)).map(|_| c)
84 }
85
get_any_port_info(&self, a: Addr) -> Result<PortInfo>86 pub fn get_any_port_info(&self, a: Addr) -> Result<PortInfo> {
87 let c = PortInfo::new()?;
88 acheck!(snd_seq_get_any_port_info(self.0, a.client as c_int, a.port as c_int, c.0)).map(|_| c)
89 }
90
create_port(&self, port: &PortInfo) -> Result<()>91 pub fn create_port(&self, port: &PortInfo) -> Result<()> {
92 acheck!(snd_seq_create_port(self.0, port.0)).map(|_| ())
93 }
94
create_simple_port(&self, name: &CStr, caps: PortCap, t: PortType) -> Result<i32>95 pub fn create_simple_port(&self, name: &CStr, caps: PortCap, t: PortType) -> Result<i32> {
96 acheck!(snd_seq_create_simple_port(self.0, name.as_ptr(), caps.bits() as c_uint, t.bits() as c_uint)).map(|q| q as i32)
97 }
98
set_port_info(&self, port: i32, info: &mut PortInfo) -> Result<()>99 pub fn set_port_info(&self, port: i32, info: &mut PortInfo) -> Result<()> {
100 acheck!(snd_seq_set_port_info(self.0, port, info.0)).map(|_| ())
101 }
102
delete_port(&self, port: i32) -> Result<()>103 pub fn delete_port(&self, port: i32) -> Result<()> {
104 acheck!(snd_seq_delete_port(self.0, port as c_int)).map(|_| ())
105 }
106
subscribe_port(&self, info: &PortSubscribe) -> Result<()>107 pub fn subscribe_port(&self, info: &PortSubscribe) -> Result<()> {
108 acheck!(snd_seq_subscribe_port(self.0, info.0)).map(|_| ())
109 }
110
unsubscribe_port(&self, sender: Addr, dest: Addr) -> Result<()>111 pub fn unsubscribe_port(&self, sender: Addr, dest: Addr) -> Result<()> {
112 let z = PortSubscribe::new()?;
113 z.set_sender(sender);
114 z.set_dest(dest);
115 acheck!(snd_seq_unsubscribe_port(self.0, z.0)).map(|_| ())
116 }
117
control_queue(&self, q: i32, t: EventType, value: i32, e: Option<&mut Event>) -> Result<()>118 pub fn control_queue(&self, q: i32, t: EventType, value: i32, e: Option<&mut Event>) -> Result<()> {
119 assert!(EvQueueControl::<()>::has_data(t) || EvQueueControl::<i32>::has_data(t) || EvQueueControl::<u32>::has_data(t));
120 let p = e.map(|e| &mut e.0 as *mut _).unwrap_or(ptr::null_mut());
121 acheck!(snd_seq_control_queue(self.0, q as c_int, t as c_int, value as c_int, p)).map(|_| ())
122 }
123
event_output(&self, e: &mut Event) -> Result<u32>124 pub fn event_output(&self, e: &mut Event) -> Result<u32> {
125 e.ensure_buf();
126 acheck!(snd_seq_event_output(self.0, &mut e.0)).map(|q| q as u32)
127 }
128
event_output_buffer(&self, e: &mut Event) -> Result<u32>129 pub fn event_output_buffer(&self, e: &mut Event) -> Result<u32> {
130 e.ensure_buf();
131 acheck!(snd_seq_event_output_buffer(self.0, &mut e.0)).map(|q| q as u32)
132 }
133
event_output_direct(&self, e: &mut Event) -> Result<u32>134 pub fn event_output_direct(&self, e: &mut Event) -> Result<u32> {
135 e.ensure_buf();
136 acheck!(snd_seq_event_output_direct(self.0, &mut e.0)).map(|q| q as u32)
137 }
138
get_queue_tempo(&self, q: i32) -> Result<QueueTempo>139 pub fn get_queue_tempo(&self, q: i32) -> Result<QueueTempo> {
140 let value = QueueTempo::new()?;
141 acheck!(snd_seq_get_queue_tempo(self.0, q as c_int, value.0)).map(|_| value)
142 }
143
set_queue_tempo(&self, q: i32, value: &QueueTempo) -> Result<()>144 pub fn set_queue_tempo(&self, q: i32, value: &QueueTempo) -> Result<()> {
145 acheck!(snd_seq_set_queue_tempo(self.0, q as c_int, value.0)).map(|_| ())
146 }
147
get_queue_status(&self, q: i32) -> Result<QueueStatus>148 pub fn get_queue_status(&self, q: i32) -> Result<QueueStatus> {
149 let value = QueueStatus::new()?;
150 acheck!(snd_seq_get_queue_status(self.0, q as c_int, value.0)).map(|_| value)
151 }
152
free_queue(&self, q: i32) -> Result<()>153 pub fn free_queue(&self, q: i32) -> Result<()> { acheck!(snd_seq_free_queue(self.0, q)).map(|_| ()) }
alloc_queue(&self) -> Result<i32>154 pub fn alloc_queue(&self) -> Result<i32> { acheck!(snd_seq_alloc_queue(self.0)).map(|q| q as i32) }
alloc_named_queue(&self, n: &CStr) -> Result<i32>155 pub fn alloc_named_queue(&self, n: &CStr) -> Result<i32> {
156 acheck!(snd_seq_alloc_named_queue(self.0, n.as_ptr())).map(|q| q as i32)
157 }
158
sync_output_queue(&self) -> Result<()>159 pub fn sync_output_queue(&self) -> Result<()> {
160 acheck!(snd_seq_sync_output_queue(self.0)).map(|_| ())
161 }
162
drop_output(&self) -> Result<()>163 pub fn drop_output(&self) -> Result<()> {
164 acheck!(snd_seq_drop_output(self.0)).map(|_| ())
165 }
166
167 /// Call this function to obtain an instance of `Input` to access the functions `event_input`,
168 /// `event_input_pending` and `set_input_buffer_size`. See the documentation of `Input` for details.
input<'a>(&'a self) -> Input<'a>169 pub fn input<'a>(&'a self) -> Input<'a> {
170 Input::new(self)
171 }
172
remove_events(&self, condition: RemoveEvents) -> Result<()>173 pub fn remove_events(&self, condition: RemoveEvents) -> Result<()> {
174 acheck!(snd_seq_remove_events(self.0, condition.0)).map(|_| ())
175 }
176 }
177
178 /// Struct for receiving input events from a sequencer. The methods offered by this
179 /// object may modify the internal input buffer of the sequencer, which must not happen
180 /// while an `Event` is alive that has been obtained from a call to `event_input` (which
181 /// takes `Input` by mutable reference for this reason). This is because the event might
182 /// directly reference the sequencer's input buffer for variable-length messages (e.g. Sysex).
183 ///
184 /// Note: Only one `Input` object is allowed in scope at a time.
185 pub struct Input<'a>(&'a Seq);
186
187 impl<'a> Drop for Input<'a> {
drop(&mut self)188 fn drop(&mut self) { (self.0).1.set(false) }
189 }
190
191 impl<'a> Input<'a> {
new(s: &'a Seq) -> Input<'a>192 fn new(s: &'a Seq) -> Input<'a> {
193 s.check_has_input();
194 s.1.set(true);
195 Input(s)
196 }
197
event_input<'b>(&'b mut self) -> Result<Event<'b>>198 pub fn event_input<'b>(&'b mut self) -> Result<Event<'b>> {
199 // The returned event might reference the input buffer of the `Seq`.
200 // Therefore we mutably borrow the `Input` structure, preventing any
201 // other function call that might change the input buffer while the
202 // event is alive.
203 let mut z = ptr::null_mut();
204 acheck!(snd_seq_event_input((self.0).0, &mut z))?;
205 unsafe { Event::extract (&mut *z, "snd_seq_event_input") }
206 }
207
event_input_pending(&self, fetch_sequencer: bool) -> Result<u32>208 pub fn event_input_pending(&self, fetch_sequencer: bool) -> Result<u32> {
209 acheck!(snd_seq_event_input_pending((self.0).0, if fetch_sequencer {1} else {0})).map(|q| q as u32)
210 }
211
set_input_buffer_size(&self, size: u32) -> Result<()>212 pub fn set_input_buffer_size(&self, size: u32) -> Result<()> {
213 acheck!(snd_seq_set_input_buffer_size((self.0).0, size as size_t)).map(|_| ())
214 }
215
drop_input(&self) -> Result<()>216 pub fn drop_input(&self) -> Result<()> {
217 acheck!(snd_seq_drop_input((self.0).0)).map(|_| ())
218 }
219 }
220
polldir(o: Option<Direction>) -> c_short221 fn polldir(o: Option<Direction>) -> c_short {
222 match o {
223 None => poll::Flags::IN | poll::Flags::OUT,
224 Some(Direction::Playback) => poll::Flags::OUT,
225 Some(Direction::Capture) => poll::Flags::IN,
226 }.bits()
227 }
228
229 impl<'a> poll::Descriptors for (&'a Seq, Option<Direction>) {
230
count(&self) -> usize231 fn count(&self) -> usize {
232 unsafe { alsa::snd_seq_poll_descriptors_count((self.0).0, polldir(self.1)) as usize }
233 }
234
fill(&self, p: &mut [pollfd]) -> Result<usize>235 fn fill(&self, p: &mut [pollfd]) -> Result<usize> {
236 let z = unsafe { alsa::snd_seq_poll_descriptors((self.0).0, p.as_mut_ptr(), p.len() as c_uint, polldir(self.1)) };
237 from_code("snd_seq_poll_descriptors", z).map(|_| z as usize)
238 }
239
revents(&self, p: &[pollfd]) -> Result<poll::Flags>240 fn revents(&self, p: &[pollfd]) -> Result<poll::Flags> {
241 let mut r = 0;
242 let z = unsafe { alsa::snd_seq_poll_descriptors_revents((self.0).0, p.as_ptr() as *mut pollfd, p.len() as c_uint, &mut r) };
243 from_code("snd_seq_poll_descriptors_revents", z).map(|_| poll::Flags::from_bits_truncate(r as c_short))
244 }
245 }
246
247 /// [snd_seq_client_info_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_client.html) wrapper
248 pub struct ClientInfo(*mut alsa::snd_seq_client_info_t);
249
250 unsafe impl Send for ClientInfo {}
251
252 impl Drop for ClientInfo {
drop(&mut self)253 fn drop(&mut self) {
254 unsafe { alsa::snd_seq_client_info_free(self.0) };
255 }
256 }
257
258 impl ClientInfo {
new() -> Result<Self>259 fn new() -> Result<Self> {
260 let mut p = ptr::null_mut();
261 acheck!(snd_seq_client_info_malloc(&mut p)).map(|_| ClientInfo(p))
262 }
263
264 // Not sure if it's useful for this one to be public.
set_client(&self, client: i32)265 fn set_client(&self, client: i32) {
266 unsafe { alsa::snd_seq_client_info_set_client(self.0, client as c_int) };
267 }
268
get_client(&self) -> i32269 pub fn get_client(&self) -> i32 {
270 unsafe { alsa::snd_seq_client_info_get_client(self.0) as i32 }
271 }
272
get_name(&self) -> Result<&str>273 pub fn get_name(&self) -> Result<&str> {
274 let c = unsafe { alsa::snd_seq_client_info_get_name(self.0) };
275 from_const("snd_seq_client_info_get_name", c)
276 }
277 }
278
279 impl fmt::Debug for ClientInfo {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281 write!(f, "ClientInfo({},{:?})", self.get_client(), self.get_name())
282 }
283 }
284
285 #[derive(Copy, Clone)]
286 /// Iterates over clients connected to the seq API (both kernel and userspace clients).
287 pub struct ClientIter<'a>(&'a Seq, i32);
288
289 impl<'a> ClientIter<'a> {
new(seq: &'a Seq) -> Self290 pub fn new(seq: &'a Seq) -> Self { ClientIter(seq, -1) }
291 }
292
293 impl<'a> Iterator for ClientIter<'a> {
294 type Item = ClientInfo;
next(&mut self) -> Option<Self::Item>295 fn next(&mut self) -> Option<Self::Item> {
296 let z = ClientInfo::new().unwrap();
297 z.set_client(self.1);
298 let r = unsafe { alsa::snd_seq_query_next_client((self.0).0, z.0) };
299 if r < 0 { self.1 = -1; return None };
300 self.1 = z.get_client();
301 Some(z)
302 }
303 }
304
305 /// [snd_seq_port_info_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_port.html) wrapper
306 pub struct PortInfo(*mut alsa::snd_seq_port_info_t);
307
308 unsafe impl Send for PortInfo {}
309
310 impl Drop for PortInfo {
drop(&mut self)311 fn drop(&mut self) {
312 unsafe { alsa::snd_seq_port_info_free(self.0) };
313 }
314 }
315
316 impl PortInfo {
new() -> Result<Self>317 fn new() -> Result<Self> {
318 let mut p = ptr::null_mut();
319 acheck!(snd_seq_port_info_malloc(&mut p)).map(|_| PortInfo(p))
320 }
321
322 /// Creates a new PortInfo with all fields set to zero.
empty() -> Result<Self>323 pub fn empty() -> Result<Self> {
324 let z = Self::new()?;
325 unsafe { ptr::write_bytes(z.0 as *mut u8, 0, alsa::snd_seq_port_info_sizeof()) };
326 Ok(z)
327 }
328
get_client(&self) -> i32329 pub fn get_client(&self) -> i32 {
330 unsafe { alsa::snd_seq_port_info_get_client(self.0) as i32 }
331 }
332
get_port(&self) -> i32333 pub fn get_port(&self) -> i32 {
334 unsafe { alsa::snd_seq_port_info_get_port(self.0) as i32 }
335 }
336
337 // Not sure if it's useful for this one to be public.
set_client(&self, client: i32)338 fn set_client(&self, client: i32) {
339 unsafe { alsa::snd_seq_port_info_set_client(self.0, client as c_int) };
340 }
341
342 // Not sure if it's useful for this one to be public.
set_port(&self, port: i32)343 fn set_port(&self, port: i32) {
344 unsafe { alsa::snd_seq_port_info_set_port(self.0, port as c_int) };
345 }
346
get_name(&self) -> Result<&str>347 pub fn get_name(&self) -> Result<&str> {
348 let c = unsafe { alsa::snd_seq_port_info_get_name(self.0) };
349 from_const("snd_seq_port_info_get_name", c)
350 }
351
set_name(&mut self, name: &CStr)352 pub fn set_name(&mut self, name: &CStr) {
353 // Note: get_name returns an interior reference, so this one must take &mut self
354 unsafe { alsa::snd_seq_port_info_set_name(self.0, name.as_ptr()) };
355 }
356
get_capability(&self) -> PortCap357 pub fn get_capability(&self) -> PortCap {
358 PortCap::from_bits_truncate(unsafe { alsa::snd_seq_port_info_get_capability(self.0) as u32 })
359 }
360
get_type(&self) -> PortType361 pub fn get_type(&self) -> PortType {
362 PortType::from_bits_truncate(unsafe { alsa::snd_seq_port_info_get_type(self.0) as u32 })
363 }
364
set_capability(&self, c: PortCap)365 pub fn set_capability(&self, c: PortCap) {
366 unsafe { alsa::snd_seq_port_info_set_capability(self.0, c.bits() as c_uint) }
367 }
368
set_type(&self, c: PortType)369 pub fn set_type(&self, c: PortType) {
370 unsafe { alsa::snd_seq_port_info_set_type(self.0, c.bits() as c_uint) }
371 }
372
373 /// Returns an Addr containing this PortInfo's client and port id.
addr(&self) -> Addr374 pub fn addr(&self) -> Addr {
375 Addr {
376 client: self.get_client(),
377 port: self.get_port(),
378 }
379 }
380
get_midi_channels(&self) -> i32381 pub fn get_midi_channels(&self) -> i32 { unsafe { alsa::snd_seq_port_info_get_midi_channels(self.0) as i32 } }
get_midi_voices(&self) -> i32382 pub fn get_midi_voices(&self) -> i32 { unsafe { alsa::snd_seq_port_info_get_midi_voices(self.0) as i32 } }
get_synth_voices(&self) -> i32383 pub fn get_synth_voices(&self) -> i32 { unsafe { alsa::snd_seq_port_info_get_synth_voices(self.0) as i32 } }
get_read_use(&self) -> i32384 pub fn get_read_use(&self) -> i32 { unsafe { alsa::snd_seq_port_info_get_read_use(self.0) as i32 } }
get_write_use(&self) -> i32385 pub fn get_write_use(&self) -> i32 { unsafe { alsa::snd_seq_port_info_get_write_use(self.0) as i32 } }
get_port_specified(&self) -> bool386 pub fn get_port_specified(&self) -> bool { unsafe { alsa::snd_seq_port_info_get_port_specified(self.0) == 1 } }
get_timestamping(&self) -> bool387 pub fn get_timestamping(&self) -> bool { unsafe { alsa::snd_seq_port_info_get_timestamping(self.0) == 1 } }
get_timestamp_real(&self) -> bool388 pub fn get_timestamp_real(&self) -> bool { unsafe { alsa::snd_seq_port_info_get_timestamp_real(self.0) == 1 } }
get_timestamp_queue(&self) -> i32389 pub fn get_timestamp_queue(&self) -> i32 { unsafe { alsa::snd_seq_port_info_get_timestamp_queue(self.0) as i32 } }
390
set_midi_channels(&self, value: i32)391 pub fn set_midi_channels(&self, value: i32) { unsafe { alsa::snd_seq_port_info_set_midi_channels(self.0, value as c_int) } }
set_midi_voices(&self, value: i32)392 pub fn set_midi_voices(&self, value: i32) { unsafe { alsa::snd_seq_port_info_set_midi_voices(self.0, value as c_int) } }
set_synth_voices(&self, value: i32)393 pub fn set_synth_voices(&self, value: i32) { unsafe { alsa::snd_seq_port_info_set_synth_voices(self.0, value as c_int) } }
set_port_specified(&self, value: bool)394 pub fn set_port_specified(&self, value: bool) { unsafe { alsa::snd_seq_port_info_set_port_specified(self.0, if value { 1 } else { 0 } ) } }
set_timestamping(&self, value: bool)395 pub fn set_timestamping(&self, value: bool) { unsafe { alsa::snd_seq_port_info_set_timestamping(self.0, if value { 1 } else { 0 } ) } }
set_timestamp_real(&self, value: bool)396 pub fn set_timestamp_real(&self, value: bool) { unsafe { alsa::snd_seq_port_info_set_timestamp_real(self.0, if value { 1 } else { 0 } ) } }
set_timestamp_queue(&self, value: i32)397 pub fn set_timestamp_queue(&self, value: i32) { unsafe { alsa::snd_seq_port_info_set_timestamp_queue(self.0, value as c_int) } }
398 }
399
400 impl fmt::Debug for PortInfo {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result401 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
402 write!(f, "PortInfo({}:{},{:?})", self.get_client(), self.get_port(), self.get_name())
403 }
404 }
405
406 #[derive(Copy, Clone)]
407 /// Iterates over clients connected to the seq API (both kernel and userspace clients).
408 pub struct PortIter<'a>(&'a Seq, i32, i32);
409
410 impl<'a> PortIter<'a> {
new(seq: &'a Seq, client: i32) -> Self411 pub fn new(seq: &'a Seq, client: i32) -> Self { PortIter(seq, client, -1) }
412 }
413
414 impl<'a> Iterator for PortIter<'a> {
415 type Item = PortInfo;
next(&mut self) -> Option<Self::Item>416 fn next(&mut self) -> Option<Self::Item> {
417 let z = PortInfo::new().unwrap();
418 z.set_client(self.1);
419 z.set_port(self.2);
420 let r = unsafe { alsa::snd_seq_query_next_port((self.0).0, z.0) };
421 if r < 0 { self.2 = -1; return None };
422 self.2 = z.get_port();
423 Some(z)
424 }
425 }
426
427 bitflags! {
428 /// [SND_SEQ_PORT_CAP_xxx](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_port.html) constants
429 pub struct PortCap: u32 {
430 const READ = 1<<0;
431 const WRITE = 1<<1;
432 const SYNC_READ = 1<<2;
433 const SYNC_WRITE = 1<<3;
434 const DUPLEX = 1<<4;
435 const SUBS_READ = 1<<5;
436 const SUBS_WRITE = 1<<6;
437 const NO_EXPORT = 1<<7;
438 }
439 }
440
441 bitflags! {
442 /// [SND_SEQ_PORT_TYPE_xxx](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_port.html) constants
443 pub struct PortType: u32 {
444 const SPECIFIC = (1<<0);
445 const MIDI_GENERIC = (1<<1);
446 const MIDI_GM = (1<<2);
447 const MIDI_GS = (1<<3);
448 const MIDI_XG = (1<<4);
449 const MIDI_MT32 = (1<<5);
450 const MIDI_GM2 = (1<<6);
451 const SYNTH = (1<<10);
452 const DIRECT_SAMPLE = (1<<11);
453 const SAMPLE = (1<<12);
454 const HARDWARE = (1<<16);
455 const SOFTWARE = (1<<17);
456 const SYNTHESIZER = (1<<18);
457 const PORT = (1<<19);
458 const APPLICATION = (1<<20);
459 }
460 }
461
462 bitflags! {
463 /// [SND_SEQ_REMOVE_xxx](https://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_event.html) constants
464 pub struct Remove: u32 {
465 const INPUT = (1<<0);
466 const OUTPUT = (1<<1);
467 const DEST = (1<<2);
468 const DEST_CHANNEL = (1<<3);
469 const TIME_BEFORE = (1<<4);
470 const TIME_AFTER = (1<<5);
471 const TIME_TICK = (1<<6);
472 const EVENT_TYPE = (1<<7);
473 const IGNORE_OFF = (1<<8);
474 const TAG_MATCH = (1<<9);
475 }
476 }
477
478
479 /// [snd_seq_addr_t](http://www.alsa-project.org/alsa-doc/alsa-lib/structsnd__seq__addr__t.html) wrapper
480 #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
481 pub struct Addr {
482 pub client: i32,
483 pub port: i32,
484 }
485
486 impl FromStr for Addr {
487 type Err = Box<dyn std::error::Error>;
488
from_str(s: &str) -> std::result::Result<Self, Self::Err>489 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
490 let mut split: Split<'_, &str> = s.trim().split(":");
491 let client = split.next()
492 .ok_or_else(|| "no client provided")?
493 .parse::<i32>()?;
494 let port = split.next()
495 .ok_or_else(|| "no port provided")?
496 .parse::<i32>()?;
497 match split.next() {
498 Some(_) => {
499 Err("too many arguments".into())
500 },
501 None => {
502 Ok(Addr { client, port })
503 }
504 }
505 }
506 }
507
508 impl Addr {
system_timer() -> Addr509 pub fn system_timer() -> Addr { Addr { client: alsa::SND_SEQ_CLIENT_SYSTEM as i32, port: alsa::SND_SEQ_PORT_SYSTEM_TIMER as i32 } }
system_announce() -> Addr510 pub fn system_announce() -> Addr { Addr { client: alsa::SND_SEQ_CLIENT_SYSTEM as i32, port: alsa::SND_SEQ_PORT_SYSTEM_ANNOUNCE as i32 } }
broadcast() -> Addr511 pub fn broadcast() -> Addr { Addr { client: alsa::SND_SEQ_ADDRESS_BROADCAST as i32, port: alsa::SND_SEQ_ADDRESS_BROADCAST as i32 } }
512 }
513
514 /// [snd_seq_port_subscribe_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_subscribe.html) wrapper
515 pub struct PortSubscribe(*mut alsa::snd_seq_port_subscribe_t);
516
517 unsafe impl Send for PortSubscribe {}
518
519 impl Drop for PortSubscribe {
drop(&mut self)520 fn drop(&mut self) { unsafe { alsa::snd_seq_port_subscribe_free(self.0) }; }
521 }
522
523 impl PortSubscribe {
new() -> Result<Self>524 fn new() -> Result<Self> {
525 let mut p = ptr::null_mut();
526 acheck!(snd_seq_port_subscribe_malloc(&mut p)).map(|_| PortSubscribe(p))
527 }
528
529 /// Creates a new PortSubscribe with all fields set to zero.
empty() -> Result<Self>530 pub fn empty() -> Result<Self> {
531 let z = Self::new()?;
532 unsafe { ptr::write_bytes(z.0 as *mut u8, 0, alsa::snd_seq_port_subscribe_sizeof()) };
533 Ok(z)
534 }
535
get_sender(&self) -> Addr536 pub fn get_sender(&self) -> Addr { unsafe {
537 let z = alsa::snd_seq_port_subscribe_get_sender(self.0);
538 Addr { client: (*z).client as i32, port: (*z).port as i32 }
539 } }
540
get_dest(&self) -> Addr541 pub fn get_dest(&self) -> Addr { unsafe {
542 let z = alsa::snd_seq_port_subscribe_get_dest(self.0);
543 Addr { client: (*z).client as i32, port: (*z).port as i32 }
544 } }
545
get_queue(&self) -> i32546 pub fn get_queue(&self) -> i32 { unsafe { alsa::snd_seq_port_subscribe_get_queue(self.0) as i32 } }
get_exclusive(&self) -> bool547 pub fn get_exclusive(&self) -> bool { unsafe { alsa::snd_seq_port_subscribe_get_exclusive(self.0) == 1 } }
get_time_update(&self) -> bool548 pub fn get_time_update(&self) -> bool { unsafe { alsa::snd_seq_port_subscribe_get_time_update(self.0) == 1 } }
get_time_real(&self) -> bool549 pub fn get_time_real(&self) -> bool { unsafe { alsa::snd_seq_port_subscribe_get_time_real(self.0) == 1 } }
550
set_sender(&self, value: Addr)551 pub fn set_sender(&self, value: Addr) {
552 let z = alsa::snd_seq_addr_t { client: value.client as c_uchar, port: value.port as c_uchar };
553 unsafe { alsa::snd_seq_port_subscribe_set_sender(self.0, &z) };
554 }
555
set_dest(&self, value: Addr)556 pub fn set_dest(&self, value: Addr) {
557 let z = alsa::snd_seq_addr_t { client: value.client as c_uchar, port: value.port as c_uchar };
558 unsafe { alsa::snd_seq_port_subscribe_set_dest(self.0, &z) };
559 }
560
set_queue(&self, value: i32)561 pub fn set_queue(&self, value: i32) { unsafe { alsa::snd_seq_port_subscribe_set_queue(self.0, value as c_int) } }
set_exclusive(&self, value: bool)562 pub fn set_exclusive(&self, value: bool) { unsafe { alsa::snd_seq_port_subscribe_set_exclusive(self.0, if value { 1 } else { 0 } ) } }
set_time_update(&self, value: bool)563 pub fn set_time_update(&self, value: bool) { unsafe { alsa::snd_seq_port_subscribe_set_time_update(self.0, if value { 1 } else { 0 } ) } }
set_time_real(&self, value: bool)564 pub fn set_time_real(&self, value: bool) { unsafe { alsa::snd_seq_port_subscribe_set_time_real(self.0, if value { 1 } else { 0 } ) } }
565
566 }
567
568 /// [snd_seq_query_subs_type_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_subscribe.html) wrapper
569 #[derive(Copy, Clone)]
570 pub enum QuerySubsType {
571 READ = alsa::SND_SEQ_QUERY_SUBS_READ as isize,
572 WRITE = alsa::SND_SEQ_QUERY_SUBS_WRITE as isize,
573 }
574
575 /// [snd_seq_query_subscribe_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_subscribe.html) wrapper
576 //(kept private, functionality exposed by PortSubscribeIter)
577 struct QuerySubscribe(*mut alsa::snd_seq_query_subscribe_t);
578
579 unsafe impl Send for QuerySubscribe {}
580
581 impl Drop for QuerySubscribe {
drop(&mut self)582 fn drop(&mut self) { unsafe { alsa::snd_seq_query_subscribe_free(self.0) } }
583 }
584
585 impl QuerySubscribe {
new() -> Result<Self>586 pub fn new() -> Result<Self> {
587 let mut q = ptr::null_mut();
588 acheck!(snd_seq_query_subscribe_malloc(&mut q)).map(|_| QuerySubscribe(q))
589 }
590
get_index(&self) -> i32591 pub fn get_index(&self) -> i32 { unsafe { alsa::snd_seq_query_subscribe_get_index(self.0) as i32 } }
get_addr(&self) -> Addr592 pub fn get_addr(&self) -> Addr { unsafe {
593 let a = &(*alsa::snd_seq_query_subscribe_get_addr(self.0));
594 Addr { client: a.client as i32, port: a.port as i32 }
595 } }
get_queue(&self) -> i32596 pub fn get_queue(&self) -> i32 { unsafe { alsa::snd_seq_query_subscribe_get_queue(self.0) as i32 } }
get_exclusive(&self) -> bool597 pub fn get_exclusive(&self) -> bool { unsafe { alsa::snd_seq_query_subscribe_get_exclusive(self.0) == 1 } }
get_time_update(&self) -> bool598 pub fn get_time_update(&self) -> bool { unsafe { alsa::snd_seq_query_subscribe_get_time_update(self.0) == 1 } }
get_time_real(&self) -> bool599 pub fn get_time_real(&self) -> bool { unsafe { alsa::snd_seq_query_subscribe_get_time_real(self.0) == 1 } }
600
set_root(&self, value: Addr)601 pub fn set_root(&self, value: Addr) { unsafe {
602 let a = alsa::snd_seq_addr_t { client: value.client as c_uchar, port: value.port as c_uchar};
603 alsa::snd_seq_query_subscribe_set_root(self.0, &a);
604 } }
set_type(&self, value: QuerySubsType)605 pub fn set_type(&self, value: QuerySubsType) { unsafe {
606 alsa::snd_seq_query_subscribe_set_type(self.0, value as alsa::snd_seq_query_subs_type_t)
607 } }
set_index(&self, value: i32)608 pub fn set_index(&self, value: i32) { unsafe { alsa::snd_seq_query_subscribe_set_index(self.0, value as c_int) } }
609 }
610
611 #[derive(Copy, Clone)]
612 /// Iterates over port subscriptions for a givent client:port/type.
613 pub struct PortSubscribeIter<'a> {
614 seq: &'a Seq,
615 addr: Addr,
616 query_subs_type: QuerySubsType,
617 index: i32
618 }
619
620 impl<'a> PortSubscribeIter<'a> {
new(seq: &'a Seq, addr: Addr, query_subs_type: QuerySubsType) -> Self621 pub fn new(seq: &'a Seq, addr: Addr, query_subs_type: QuerySubsType) -> Self {
622 PortSubscribeIter {seq, addr, query_subs_type, index: 0 }
623 }
624 }
625
626 impl<'a> Iterator for PortSubscribeIter<'a> {
627 type Item = PortSubscribe;
628
next(&mut self) -> Option<Self::Item>629 fn next(&mut self) -> Option<Self::Item> {
630 let query = QuerySubscribe::new().unwrap();
631
632 query.set_root(self.addr);
633 query.set_type(self.query_subs_type);
634 query.set_index(self.index);
635
636 let r = unsafe { alsa::snd_seq_query_port_subscribers((self.seq).0, query.0) };
637 if r < 0 {
638 self.index = 0;
639 return None;
640 }
641
642 self.index = query.get_index() + 1;
643 let vtr = PortSubscribe::new().unwrap();
644 match self.query_subs_type {
645 QuerySubsType::READ => {
646 vtr.set_sender(self.addr);
647 vtr.set_dest(query.get_addr());
648 },
649 QuerySubsType:: WRITE => {
650 vtr.set_sender(query.get_addr());
651 vtr.set_dest(self.addr);
652 }
653 };
654 vtr.set_queue(query.get_queue());
655 vtr.set_exclusive(query.get_exclusive());
656 vtr.set_time_update(query.get_time_update());
657 vtr.set_time_real(query.get_time_real());
658
659 Some(vtr)
660 }
661 }
662
663 /// [snd_seq_event_t](http://www.alsa-project.org/alsa-doc/alsa-lib/structsnd__seq__event__t.html) wrapper
664 ///
665 /// Fields of the event is not directly exposed. Instead call `Event::new` to set data (which can be, e g, an EvNote).
666 /// Use `get_type` and `get_data` to retreive data.
667 ///
668 /// The lifetime parameter refers to the lifetime of an associated external buffer that might be used for
669 /// variable-length messages (e.g. SysEx).
670 pub struct Event<'a>(alsa::snd_seq_event_t, EventType, Option<Cow<'a, [u8]>>);
671
672 unsafe impl<'a> Send for Event<'a> {}
673
674 impl<'a> Event<'a> {
675 /// Creates a new event. For events that carry variable-length data (e.g. Sysex), `new_ext` has to be used instead.
new<D: EventData>(t: EventType, data: &D) -> Event<'static>676 pub fn new<D: EventData>(t: EventType, data: &D) -> Event<'static> {
677 assert!(!Event::has_ext_data(t), "event type must not carry variable-length data");
678 let mut z = Event(unsafe { mem::zeroed() }, t, None);
679 (z.0).type_ = t as c_uchar;
680 (z.0).flags |= Event::get_length_flag(t);
681 debug_assert!(D::has_data(t));
682 data.set_data(&mut z);
683 z
684 }
685
686 /// Creates a new event carrying variable-length data. This is required for event types `Sysex`, `Bounce`, and the `UsrVar` types.
new_ext<D: Into<Cow<'a, [u8]>>>(t: EventType, data: D) -> Event<'a>687 pub fn new_ext<D: Into<Cow<'a, [u8]>>>(t: EventType, data: D) -> Event<'a> {
688 assert!(Event::has_ext_data(t), "event type must carry variable-length data");
689 let mut z = Event(unsafe { mem::zeroed() }, t, Some(data.into()));
690 (z.0).type_ = t as c_uchar;
691 (z.0).flags |= Event::get_length_flag(t);
692 z
693 }
694
695 /// Consumes this event and returns an (otherwise unchanged) event where the externally referenced
696 /// buffer for variable length messages (e.g. SysEx) has been copied into the event.
697 /// The returned event has a static lifetime, i e, it's decoupled from the original buffer.
into_owned(self) -> Event<'static>698 pub fn into_owned(self) -> Event<'static> {
699 Event(self.0, self.1, self.2.map(|cow| Cow::Owned(cow.into_owned())))
700 }
701
get_length_flag(t: EventType) -> u8702 fn get_length_flag(t: EventType) -> u8 {
703 match t {
704 EventType::Sysex => alsa::SND_SEQ_EVENT_LENGTH_VARIABLE,
705 EventType::Bounce => alsa::SND_SEQ_EVENT_LENGTH_VARIABLE, // not clear whether this should be VARIABLE or VARUSR
706 EventType::UsrVar0 => alsa::SND_SEQ_EVENT_LENGTH_VARUSR,
707 EventType::UsrVar1 => alsa::SND_SEQ_EVENT_LENGTH_VARUSR,
708 EventType::UsrVar2 => alsa::SND_SEQ_EVENT_LENGTH_VARUSR,
709 EventType::UsrVar3 => alsa::SND_SEQ_EVENT_LENGTH_VARUSR,
710 EventType::UsrVar4 => alsa::SND_SEQ_EVENT_LENGTH_VARUSR,
711 _ => alsa::SND_SEQ_EVENT_LENGTH_FIXED
712 }
713 }
714
has_ext_data(t: EventType) -> bool715 fn has_ext_data(t: EventType) -> bool {
716 Event::get_length_flag(t) != alsa::SND_SEQ_EVENT_LENGTH_FIXED
717 }
718
719 /// Extracts event type and data. Produces a result with an arbitrary lifetime, hence the unsafety.
extract<'any>(z: &mut alsa::snd_seq_event_t, func: &'static str) -> Result<Event<'any>>720 unsafe fn extract<'any>(z: &mut alsa::snd_seq_event_t, func: &'static str) -> Result<Event<'any>> {
721 let t = EventType::from_c_int((*z).type_ as c_int, func)?;
722 let ext_data = if Event::has_ext_data(t) {
723 assert!((*z).flags & alsa::SND_SEQ_EVENT_LENGTH_MASK != alsa::SND_SEQ_EVENT_LENGTH_FIXED);
724 Some(Cow::Borrowed({
725 let zz: &EvExtPacked = &*(&(*z).data as *const alsa::snd_seq_event__bindgen_ty_1 as *const _);
726 slice::from_raw_parts((*zz).ptr as *mut u8, (*zz).len as usize)
727 }))
728 } else {
729 None
730 };
731 Ok(Event(ptr::read(z), t, ext_data))
732 }
733
734 /// Ensures that the ev.ext union element points to the correct resize_buffer for events
735 /// with variable length content
ensure_buf(&mut self)736 fn ensure_buf(&mut self) {
737 if !Event::has_ext_data(self.1) { return; }
738 let slice: &[u8] = match self.2 {
739 Some(Cow::Owned(ref mut vec)) => &vec[..],
740 Some(Cow::Borrowed(buf)) => buf,
741 // The following case is always a logic error in the program, thus panicking is okay.
742 None => panic!("event type requires variable-length data, but none was provided")
743 };
744 let z: &mut EvExtPacked = unsafe { &mut *(&mut self.0.data as *mut alsa::snd_seq_event__bindgen_ty_1 as *mut _) };
745 z.len = slice.len() as c_uint;
746 z.ptr = slice.as_ptr() as *mut c_void;
747 }
748
749 #[inline]
get_type(&self) -> EventType750 pub fn get_type(&self) -> EventType { self.1 }
751
752 /// Extract the event data from an event.
753 /// Use `get_ext` instead for events carrying variable-length data.
get_data<D: EventData>(&self) -> Option<D>754 pub fn get_data<D: EventData>(&self) -> Option<D> { if D::has_data(self.1) { Some(D::get_data(self)) } else { None } }
755
756 /// Extract the variable-length data carried by events of type `Sysex`, `Bounce`, or the `UsrVar` types.
get_ext<'b>(&'b self) -> Option<&'b [u8]>757 pub fn get_ext<'b>(&'b self) -> Option<&'b [u8]> {
758 if Event::has_ext_data(self.1) {
759 match self.2 {
760 Some(Cow::Owned(ref vec)) => Some(&vec[..]),
761 Some(Cow::Borrowed(buf)) => Some(buf),
762 // The following case is always a logic error in the program, thus panicking is okay.
763 None => panic!("event type requires variable-length data, but none was found")
764 }
765 } else {
766 None
767 }
768 }
769
set_subs(&mut self)770 pub fn set_subs(&mut self) {
771 self.0.dest.client = alsa::SND_SEQ_ADDRESS_SUBSCRIBERS;
772 self.0.dest.port = alsa::SND_SEQ_ADDRESS_UNKNOWN;
773 }
774
set_source(&mut self, p: i32)775 pub fn set_source(&mut self, p: i32) { self.0.source.port = p as u8 }
set_dest(&mut self, d: Addr)776 pub fn set_dest(&mut self, d: Addr) { self.0.dest.client = d.client as c_uchar; self.0.dest.port = d.port as c_uchar; }
set_tag(&mut self, t: u8)777 pub fn set_tag(&mut self, t: u8) { self.0.tag = t as c_uchar; }
set_queue(&mut self, q: i32)778 pub fn set_queue(&mut self, q: i32) { self.0.queue = q as c_uchar; }
779
get_source(&self) -> Addr780 pub fn get_source(&self) -> Addr { Addr { client: self.0.source.client as i32, port: self.0.source.port as i32 } }
get_dest(&self) -> Addr781 pub fn get_dest(&self) -> Addr { Addr { client: self.0.dest.client as i32, port: self.0.dest.port as i32 } }
get_tag(&self) -> u8782 pub fn get_tag(&self) -> u8 { self.0.tag as u8 }
get_queue(&self) -> i32783 pub fn get_queue(&self) -> i32 { self.0.queue as i32 }
784
schedule_real(&mut self, queue: i32, relative: bool, rtime: time::Duration)785 pub fn schedule_real(&mut self, queue: i32, relative: bool, rtime: time::Duration) {
786 self.0.flags &= !(alsa::SND_SEQ_TIME_STAMP_MASK | alsa::SND_SEQ_TIME_MODE_MASK);
787 self.0.flags |= alsa::SND_SEQ_TIME_STAMP_REAL | (if relative { alsa::SND_SEQ_TIME_MODE_REL } else { alsa::SND_SEQ_TIME_MODE_ABS });
788 self.0.queue = queue as u8;
789 let t = unsafe { &mut self.0.time.time };
790 t.tv_sec = rtime.as_secs() as c_uint;
791 t.tv_nsec = rtime.subsec_nanos() as c_uint;
792 }
793
schedule_tick(&mut self, queue: i32, relative: bool, ttime: u32)794 pub fn schedule_tick(&mut self, queue: i32, relative: bool, ttime: u32) {
795 self.0.flags &= !(alsa::SND_SEQ_TIME_STAMP_MASK | alsa::SND_SEQ_TIME_MODE_MASK);
796 self.0.flags |= alsa::SND_SEQ_TIME_STAMP_TICK | (if relative { alsa::SND_SEQ_TIME_MODE_REL } else { alsa::SND_SEQ_TIME_MODE_ABS });
797 self.0.queue = queue as u8;
798 let t = unsafe { &mut self.0.time.tick };
799 *t = ttime as c_uint;
800 }
801
set_direct(&mut self)802 pub fn set_direct(&mut self) { self.0.queue = alsa::SND_SEQ_QUEUE_DIRECT }
803
get_relative(&self) -> bool804 pub fn get_relative(&self) -> bool { (self.0.flags & alsa::SND_SEQ_TIME_MODE_REL) != 0 }
805
get_time(&self) -> Option<time::Duration>806 pub fn get_time(&self) -> Option<time::Duration> {
807 if (self.0.flags & alsa::SND_SEQ_TIME_STAMP_REAL) != 0 {
808 let d = self.0.time;
809 let t = unsafe { &d.time };
810 Some(time::Duration::new(t.tv_sec as u64, t.tv_nsec as u32))
811 } else { None }
812 }
813
get_tick(&self) -> Option<u32>814 pub fn get_tick(&self) -> Option<u32> {
815 if (self.0.flags & alsa::SND_SEQ_TIME_STAMP_REAL) == 0 {
816 let d = self.0.time;
817 let t = unsafe { &d.tick };
818 Some(*t)
819 } else { None }
820 }
821
822 /// Returns true if the message is high priority.
get_priority(&self) -> bool823 pub fn get_priority(&self) -> bool { (self.0.flags & alsa::SND_SEQ_PRIORITY_HIGH) != 0 }
824
set_priority(&mut self, is_high_prio: bool)825 pub fn set_priority(&mut self, is_high_prio: bool) {
826 if is_high_prio { self.0.flags |= alsa::SND_SEQ_PRIORITY_HIGH; }
827 else { self.0.flags &= !alsa::SND_SEQ_PRIORITY_HIGH; }
828 }
829 }
830
831 impl<'a> Clone for Event<'a> {
clone(&self) -> Self832 fn clone(&self) -> Self { Event(unsafe { ptr::read(&self.0) }, self.1, self.2.clone()) }
833 }
834
835 impl<'a> fmt::Debug for Event<'a> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837 let mut x = f.debug_tuple("Event");
838 x.field(&self.1);
839 if let Some(z) = self.get_data::<EvNote>() { x.field(&z); }
840 if let Some(z) = self.get_data::<EvCtrl>() { x.field(&z); }
841 if let Some(z) = self.get_data::<Addr>() { x.field(&z); }
842 if let Some(z) = self.get_data::<Connect>() { x.field(&z); }
843 if let Some(z) = self.get_data::<EvQueueControl<()>>() { x.field(&z); }
844 if let Some(z) = self.get_data::<EvQueueControl<i32>>() { x.field(&z); }
845 if let Some(z) = self.get_data::<EvQueueControl<u32>>() { x.field(&z); }
846 if let Some(z) = self.get_data::<EvQueueControl<time::Duration>>() { x.field(&z); }
847 if let Some(z) = self.get_data::<EvResult>() { x.field(&z); }
848 if let Some(z) = self.get_data::<[u8; 12]>() { x.field(&z); }
849 if let Some(z) = self.get_ext() { x.field(&z); }
850 x.finish()
851 }
852 }
853
854 /// Low level methods to set/get data on an Event. Don't use these directly, use generic methods on Event instead.
855 pub trait EventData {
has_data(e: EventType) -> bool856 fn has_data(e: EventType) -> bool;
set_data(&self, ev: &mut Event)857 fn set_data(&self, ev: &mut Event);
get_data(ev: &Event) -> Self858 fn get_data(ev: &Event) -> Self;
859 }
860
861 impl EventData for () {
has_data(e: EventType) -> bool862 fn has_data(e: EventType) -> bool {
863 match e {
864 EventType::TuneRequest => true,
865 EventType::Reset => true,
866 EventType::Sensing => true,
867 EventType::None => true,
868 _ => false,
869 }
870 }
set_data(&self, _: &mut Event)871 fn set_data(&self, _: &mut Event) {}
get_data(_: &Event) -> Self872 fn get_data(_: &Event) -> Self {}
873 }
874
875 impl EventData for [u8; 12] {
has_data(e: EventType) -> bool876 fn has_data(e: EventType) -> bool {
877 match e {
878 EventType::Echo => true,
879 EventType::Oss => true,
880 EventType::Usr0 => true,
881 EventType::Usr1 => true,
882 EventType::Usr2 => true,
883 EventType::Usr3 => true,
884 EventType::Usr4 => true,
885 EventType::Usr5 => true,
886 EventType::Usr6 => true,
887 EventType::Usr7 => true,
888 EventType::Usr8 => true,
889 EventType::Usr9 => true,
890 _ => false,
891 }
892 }
set_data(&self, ev: &mut Event)893 fn set_data(&self, ev: &mut Event) {
894 let z = unsafe { &mut ev.0.data.raw8 };
895 z.d = *self;
896 }
get_data(ev: &Event) -> Self897 fn get_data(ev: &Event) -> Self {
898 let d = unsafe { ptr::read(&ev.0.data) };
899 let z = unsafe { &d.raw8 };
900 z.d
901 }
902 }
903
904
905 #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
906 pub struct EvNote {
907 pub channel: u8,
908 pub note: u8,
909 pub velocity: u8,
910 pub off_velocity: u8,
911 pub duration: u32,
912 }
913
914 impl EventData for EvNote {
has_data(e: EventType) -> bool915 fn has_data(e: EventType) -> bool {
916 match e {
917 EventType::Note => true,
918 EventType::Noteon => true,
919 EventType::Noteoff => true,
920 EventType::Keypress => true,
921 _ => false,
922 }
923 }
get_data(ev: &Event) -> Self924 fn get_data(ev: &Event) -> Self {
925 let z: &alsa::snd_seq_ev_note_t = unsafe { &*(&ev.0.data as *const alsa::snd_seq_event__bindgen_ty_1 as *const _) };
926 EvNote { channel: z.channel as u8, note: z.note as u8, velocity: z.velocity as u8, off_velocity: z.off_velocity as u8, duration: z.duration as u32 }
927 }
set_data(&self, ev: &mut Event)928 fn set_data(&self, ev: &mut Event) {
929 let z: &mut alsa::snd_seq_ev_note_t = unsafe { &mut *(&mut ev.0.data as *mut alsa::snd_seq_event__bindgen_ty_1 as *mut _) };
930 z.channel = self.channel as c_uchar;
931 z.note = self.note as c_uchar;
932 z.velocity = self.velocity as c_uchar;
933 z.off_velocity = self.off_velocity as c_uchar;
934 z.duration = self.duration as c_uint;
935 }
936 }
937
938 #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
939 pub struct EvCtrl {
940 pub channel: u8,
941 pub param: u32,
942 pub value: i32,
943 }
944
945 impl EventData for EvCtrl {
has_data(e: EventType) -> bool946 fn has_data(e: EventType) -> bool {
947 match e {
948 EventType::Controller => true,
949 EventType::Pgmchange => true,
950 EventType::Chanpress => true,
951 EventType::Pitchbend => true,
952 EventType::Control14 => true,
953 EventType::Nonregparam => true,
954 EventType::Regparam => true,
955 EventType::Songpos => true,
956 EventType::Songsel => true,
957 EventType::Qframe => true,
958 EventType::Timesign => true,
959 EventType::Keysign => true,
960 _ => false,
961 }
962 }
get_data(ev: &Event) -> Self963 fn get_data(ev: &Event) -> Self {
964 let z: &alsa::snd_seq_ev_ctrl_t = unsafe { &*(&ev.0.data as *const alsa::snd_seq_event__bindgen_ty_1 as *const _) };
965 EvCtrl { channel: z.channel as u8, param: z.param as u32, value: z.value as i32 }
966 }
set_data(&self, ev: &mut Event)967 fn set_data(&self, ev: &mut Event) {
968 let z: &mut alsa::snd_seq_ev_ctrl_t = unsafe { &mut *(&mut ev.0.data as *mut alsa::snd_seq_event__bindgen_ty_1 as *mut _) };
969 z.channel = self.channel as c_uchar;
970 z.param = self.param as c_uint;
971 z.value = self.value as c_int;
972 }
973 }
974
975 impl EventData for Addr {
has_data(e: EventType) -> bool976 fn has_data(e: EventType) -> bool {
977 match e {
978 EventType::ClientStart => true,
979 EventType::ClientExit => true,
980 EventType::ClientChange => true,
981 EventType::PortStart => true,
982 EventType::PortExit => true,
983 EventType::PortChange => true,
984 _ => false,
985 }
986 }
get_data(ev: &Event) -> Self987 fn get_data(ev: &Event) -> Self {
988 let z: &alsa::snd_seq_addr_t = unsafe { &*(&ev.0.data as *const alsa::snd_seq_event__bindgen_ty_1 as *const _) };
989 Addr { client: z.client as i32, port: z.port as i32 }
990 }
set_data(&self, ev: &mut Event)991 fn set_data(&self, ev: &mut Event) {
992 let z: &mut alsa::snd_seq_addr_t = unsafe { &mut *(&mut ev.0.data as *mut alsa::snd_seq_event__bindgen_ty_1 as *mut _) };
993 z.client = self.client as c_uchar;
994 z.port = self.port as c_uchar;
995 }
996 }
997
998 #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
999 /// [snd_seq_connect_t](http://www.alsa-project.org/alsa-doc/alsa-lib/structsnd__seq__connect__t.html) wrapper
1000 pub struct Connect {
1001 pub sender: Addr,
1002 pub dest: Addr,
1003 }
1004
1005 impl EventData for Connect {
has_data(e: EventType) -> bool1006 fn has_data(e: EventType) -> bool {
1007 match e {
1008 EventType::PortSubscribed => true,
1009 EventType::PortUnsubscribed => true,
1010 _ => false,
1011 }
1012 }
get_data(ev: &Event) -> Self1013 fn get_data(ev: &Event) -> Self {
1014 let d = unsafe { ptr::read(&ev.0.data) };
1015 let z = unsafe { &d.connect };
1016 Connect {
1017 sender: Addr { client: z.sender.client as i32, port: z.sender.port as i32 },
1018 dest: Addr { client: z.dest.client as i32, port: z.dest.port as i32 }
1019 }
1020 }
set_data(&self, ev: &mut Event)1021 fn set_data(&self, ev: &mut Event) {
1022 let z = unsafe { &mut ev.0.data.connect };
1023 z.sender.client = self.sender.client as c_uchar;
1024 z.sender.port = self.sender.port as c_uchar;
1025 z.dest.client = self.dest.client as c_uchar;
1026 z.dest.port = self.dest.port as c_uchar;
1027 }
1028 }
1029
1030 #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
1031 /// [snd_seq_ev_queue_control_t](http://www.alsa-project.org/alsa-doc/alsa-lib/structsnd__seq__ev__queue__control__t.html) wrapper
1032 ///
1033 /// Note: This struct is generic, but what types of T are required for the different EvQueueControl messages is
1034 /// not very well documented in alsa-lib. Right now, Tempo is i32, Tick, SetposTick and SyncPos are u32, SetposTime is time::Duration,
1035 /// and the rest is (). If I guessed wrong, let me know.
1036 pub struct EvQueueControl<T> {
1037 pub queue: i32,
1038 pub value: T,
1039 }
1040
1041 impl EventData for EvQueueControl<()> {
has_data(e: EventType) -> bool1042 fn has_data(e: EventType) -> bool {
1043 match e {
1044 EventType::Start => true,
1045 EventType::Continue => true,
1046 EventType::Stop => true,
1047 EventType::Clock => true,
1048 EventType::QueueSkew => true,
1049 _ => false,
1050 }
1051 }
get_data(ev: &Event) -> Self1052 fn get_data(ev: &Event) -> Self {
1053 let d = unsafe { ptr::read(&ev.0.data) };
1054 let z = unsafe { &d.queue };
1055 EvQueueControl { queue: z.queue as i32, value: () }
1056 }
set_data(&self, ev: &mut Event)1057 fn set_data(&self, ev: &mut Event) {
1058 let z = unsafe { &mut ev.0.data.queue };
1059 z.queue = self.queue as c_uchar;
1060 }
1061 }
1062
1063 impl EventData for EvQueueControl<i32> {
has_data(e: EventType) -> bool1064 fn has_data(e: EventType) -> bool {
1065 match e {
1066 EventType::Tempo => true,
1067 _ => false,
1068 }
1069 }
get_data(ev: &Event) -> Self1070 fn get_data(ev: &Event) -> Self { unsafe {
1071 let mut d = ptr::read(&ev.0.data);
1072 let z = &mut d.queue;
1073 EvQueueControl { queue: z.queue as i32, value: z.param.value as i32 }
1074 } }
set_data(&self, ev: &mut Event)1075 fn set_data(&self, ev: &mut Event) { unsafe {
1076 let z = &mut ev.0.data.queue;
1077 z.queue = self.queue as c_uchar;
1078 z.param.value = self.value as c_int;
1079 } }
1080 }
1081
1082 impl EventData for EvQueueControl<u32> {
has_data(e: EventType) -> bool1083 fn has_data(e: EventType) -> bool {
1084 match e {
1085 EventType::SyncPos => true,
1086 EventType::Tick => true,
1087 EventType::SetposTick => true,
1088 _ => false,
1089 }
1090 }
get_data(ev: &Event) -> Self1091 fn get_data(ev: &Event) -> Self { unsafe {
1092 let mut d = ptr::read(&ev.0.data);
1093 let z = &mut d.queue;
1094 EvQueueControl { queue: z.queue as i32, value: z.param.position as u32 }
1095 } }
set_data(&self, ev: &mut Event)1096 fn set_data(&self, ev: &mut Event) { unsafe {
1097 let z = &mut ev.0.data.queue;
1098 z.queue = self.queue as c_uchar;
1099 z.param.position = self.value as c_uint;
1100 } }
1101 }
1102
1103 impl EventData for EvQueueControl<time::Duration> {
has_data(e: EventType) -> bool1104 fn has_data(e: EventType) -> bool {
1105 match e {
1106 EventType::SetposTime => true,
1107 _ => false,
1108 }
1109 }
get_data(ev: &Event) -> Self1110 fn get_data(ev: &Event) -> Self { unsafe {
1111 let mut d = ptr::read(&ev.0.data);
1112 let z = &mut d.queue;
1113 let t = &mut z.param.time.time;
1114 EvQueueControl { queue: z.queue as i32, value: time::Duration::new(t.tv_sec as u64, t.tv_nsec as u32) }
1115 } }
set_data(&self, ev: &mut Event)1116 fn set_data(&self, ev: &mut Event) { unsafe {
1117 let z = &mut ev.0.data.queue;
1118 z.queue = self.queue as c_uchar;
1119 let t = &mut z.param.time.time;
1120 t.tv_sec = self.value.as_secs() as c_uint;
1121 t.tv_nsec = self.value.subsec_nanos() as c_uint;
1122 } }
1123 }
1124
1125 #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
1126 /// [snd_seq_result_t](http://www.alsa-project.org/alsa-doc/alsa-lib/structsnd__seq__result__t.html) wrapper
1127 ///
1128 /// It's called EvResult instead of Result, in order to not be confused with Rust's Result type.
1129 pub struct EvResult {
1130 pub event: i32,
1131 pub result: i32,
1132 }
1133
1134 impl EventData for EvResult {
has_data(e: EventType) -> bool1135 fn has_data(e: EventType) -> bool {
1136 match e {
1137 EventType::System => true,
1138 EventType::Result => true,
1139 _ => false,
1140 }
1141 }
get_data(ev: &Event) -> Self1142 fn get_data(ev: &Event) -> Self {
1143 let d = unsafe { ptr::read(&ev.0.data) };
1144 let z = unsafe { &d.result };
1145 EvResult { event: z.event as i32, result: z.result as i32 }
1146 }
set_data(&self, ev: &mut Event)1147 fn set_data(&self, ev: &mut Event) {
1148 let z = unsafe { &mut ev.0.data.result };
1149 z.event = self.event as c_int;
1150 z.result = self.result as c_int;
1151 }
1152 }
1153
1154
1155
1156 alsa_enum!(
1157 /// [SND_SEQ_EVENT_xxx](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_events.html) constants
1158
1159 EventType, ALL_EVENT_TYPES[59],
1160
1161 Bounce = SND_SEQ_EVENT_BOUNCE,
1162 Chanpress = SND_SEQ_EVENT_CHANPRESS,
1163 ClientChange = SND_SEQ_EVENT_CLIENT_CHANGE,
1164 ClientExit = SND_SEQ_EVENT_CLIENT_EXIT,
1165 ClientStart = SND_SEQ_EVENT_CLIENT_START,
1166 Clock = SND_SEQ_EVENT_CLOCK,
1167 Continue = SND_SEQ_EVENT_CONTINUE,
1168 Control14 = SND_SEQ_EVENT_CONTROL14,
1169 Controller = SND_SEQ_EVENT_CONTROLLER,
1170 Echo = SND_SEQ_EVENT_ECHO,
1171 Keypress = SND_SEQ_EVENT_KEYPRESS,
1172 Keysign = SND_SEQ_EVENT_KEYSIGN,
1173 None = SND_SEQ_EVENT_NONE,
1174 Nonregparam = SND_SEQ_EVENT_NONREGPARAM,
1175 Note = SND_SEQ_EVENT_NOTE,
1176 Noteoff = SND_SEQ_EVENT_NOTEOFF,
1177 Noteon = SND_SEQ_EVENT_NOTEON,
1178 Oss = SND_SEQ_EVENT_OSS,
1179 Pgmchange = SND_SEQ_EVENT_PGMCHANGE,
1180 Pitchbend = SND_SEQ_EVENT_PITCHBEND,
1181 PortChange = SND_SEQ_EVENT_PORT_CHANGE,
1182 PortExit = SND_SEQ_EVENT_PORT_EXIT,
1183 PortStart = SND_SEQ_EVENT_PORT_START,
1184 PortSubscribed = SND_SEQ_EVENT_PORT_SUBSCRIBED,
1185 PortUnsubscribed = SND_SEQ_EVENT_PORT_UNSUBSCRIBED,
1186 Qframe = SND_SEQ_EVENT_QFRAME,
1187 QueueSkew = SND_SEQ_EVENT_QUEUE_SKEW,
1188 Regparam = SND_SEQ_EVENT_REGPARAM,
1189 Reset = SND_SEQ_EVENT_RESET,
1190 Result = SND_SEQ_EVENT_RESULT,
1191 Sensing = SND_SEQ_EVENT_SENSING,
1192 SetposTick = SND_SEQ_EVENT_SETPOS_TICK,
1193 SetposTime = SND_SEQ_EVENT_SETPOS_TIME,
1194 Songpos = SND_SEQ_EVENT_SONGPOS,
1195 Songsel = SND_SEQ_EVENT_SONGSEL,
1196 Start = SND_SEQ_EVENT_START,
1197 Stop = SND_SEQ_EVENT_STOP,
1198 SyncPos = SND_SEQ_EVENT_SYNC_POS,
1199 Sysex = SND_SEQ_EVENT_SYSEX,
1200 System = SND_SEQ_EVENT_SYSTEM,
1201 Tempo = SND_SEQ_EVENT_TEMPO,
1202 Tick = SND_SEQ_EVENT_TICK,
1203 Timesign = SND_SEQ_EVENT_TIMESIGN,
1204 TuneRequest = SND_SEQ_EVENT_TUNE_REQUEST,
1205 Usr0 = SND_SEQ_EVENT_USR0,
1206 Usr1 = SND_SEQ_EVENT_USR1,
1207 Usr2 = SND_SEQ_EVENT_USR2,
1208 Usr3 = SND_SEQ_EVENT_USR3,
1209 Usr4 = SND_SEQ_EVENT_USR4,
1210 Usr5 = SND_SEQ_EVENT_USR5,
1211 Usr6 = SND_SEQ_EVENT_USR6,
1212 Usr7 = SND_SEQ_EVENT_USR7,
1213 Usr8 = SND_SEQ_EVENT_USR8,
1214 Usr9 = SND_SEQ_EVENT_USR9,
1215 UsrVar0 = SND_SEQ_EVENT_USR_VAR0,
1216 UsrVar1 = SND_SEQ_EVENT_USR_VAR1,
1217 UsrVar2 = SND_SEQ_EVENT_USR_VAR2,
1218 UsrVar3 = SND_SEQ_EVENT_USR_VAR3,
1219 UsrVar4 = SND_SEQ_EVENT_USR_VAR4,
1220 );
1221
1222 /// [snd_seq_queue_tempo_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_queue.html) wrapper
1223 pub struct QueueTempo(*mut alsa::snd_seq_queue_tempo_t);
1224
1225 unsafe impl Send for QueueTempo {}
1226
1227 impl Drop for QueueTempo {
drop(&mut self)1228 fn drop(&mut self) { unsafe { alsa::snd_seq_queue_tempo_free(self.0) } }
1229 }
1230
1231 impl QueueTempo {
new() -> Result<Self>1232 fn new() -> Result<Self> {
1233 let mut q = ptr::null_mut();
1234 acheck!(snd_seq_queue_tempo_malloc(&mut q)).map(|_| QueueTempo(q))
1235 }
1236
1237 /// Creates a new QueueTempo with all fields set to zero.
empty() -> Result<Self>1238 pub fn empty() -> Result<Self> {
1239 let q = QueueTempo::new()?;
1240 unsafe { ptr::write_bytes(q.0 as *mut u8, 0, alsa::snd_seq_queue_tempo_sizeof()) };
1241 Ok(q)
1242 }
1243
get_queue(&self) -> i321244 pub fn get_queue(&self) -> i32 { unsafe { alsa::snd_seq_queue_tempo_get_queue(self.0) as i32 } }
get_tempo(&self) -> u321245 pub fn get_tempo(&self) -> u32 { unsafe { alsa::snd_seq_queue_tempo_get_tempo(self.0) as u32 } }
get_ppq(&self) -> i321246 pub fn get_ppq(&self) -> i32 { unsafe { alsa::snd_seq_queue_tempo_get_ppq(self.0) as i32 } }
get_skew(&self) -> u321247 pub fn get_skew(&self) -> u32 { unsafe { alsa::snd_seq_queue_tempo_get_skew(self.0) as u32 } }
get_skew_base(&self) -> u321248 pub fn get_skew_base(&self) -> u32 { unsafe { alsa::snd_seq_queue_tempo_get_skew_base(self.0) as u32 } }
1249
1250 // pub fn set_queue(&self, value: i32) { unsafe { alsa::snd_seq_queue_tempo_set_queue(self.0, value as c_int) } }
set_tempo(&self, value: u32)1251 pub fn set_tempo(&self, value: u32) { unsafe { alsa::snd_seq_queue_tempo_set_tempo(self.0, value as c_uint) } }
set_ppq(&self, value: i32)1252 pub fn set_ppq(&self, value: i32) { unsafe { alsa::snd_seq_queue_tempo_set_ppq(self.0, value as c_int) } }
set_skew(&self, value: u32)1253 pub fn set_skew(&self, value: u32) { unsafe { alsa::snd_seq_queue_tempo_set_skew(self.0, value as c_uint) } }
set_skew_base(&self, value: u32)1254 pub fn set_skew_base(&self, value: u32) { unsafe { alsa::snd_seq_queue_tempo_set_skew_base(self.0, value as c_uint) } }
1255 }
1256
1257 /// [snd_seq_queue_status_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_queue.html) wrapper
1258 pub struct QueueStatus(*mut alsa::snd_seq_queue_status_t);
1259
1260 unsafe impl Send for QueueStatus {}
1261
1262 impl Drop for QueueStatus {
drop(&mut self)1263 fn drop(&mut self) { unsafe { alsa::snd_seq_queue_status_free(self.0) } }
1264 }
1265
1266 impl QueueStatus {
new() -> Result<Self>1267 fn new() -> Result<Self> {
1268 let mut q = ptr::null_mut();
1269 acheck!(snd_seq_queue_status_malloc(&mut q)).map(|_| QueueStatus(q))
1270 }
1271
1272 /// Creates a new QueueStatus with all fields set to zero.
empty() -> Result<Self>1273 pub fn empty() -> Result<Self> {
1274 let q = QueueStatus::new()?;
1275 unsafe { ptr::write_bytes(q.0 as *mut u8, 0, alsa::snd_seq_queue_status_sizeof()) };
1276 Ok(q)
1277 }
1278
get_queue(&self) -> i321279 pub fn get_queue(&self) -> i32 { unsafe { alsa::snd_seq_queue_status_get_queue(self.0) as i32 } }
get_events(&self) -> i321280 pub fn get_events(&self) -> i32 { unsafe { alsa::snd_seq_queue_status_get_events(self.0) as i32 } }
get_tick_time(&self) -> u321281 pub fn get_tick_time(&self) -> u32 { unsafe {alsa::snd_seq_queue_status_get_tick_time(self.0) as u32 } }
get_real_time(&self) -> time::Duration1282 pub fn get_real_time(&self) -> time::Duration { unsafe {
1283 let t = &(*alsa::snd_seq_queue_status_get_real_time(self.0));
1284 time::Duration::new(t.tv_sec as u64, t.tv_nsec as u32)
1285 } }
get_status(&self) -> u321286 pub fn get_status(&self) -> u32 { unsafe { alsa::snd_seq_queue_status_get_status(self.0) as u32 } }
1287 }
1288
1289 /// [snd_seq_remove_events_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___seq_event.html) wrapper
1290 pub struct RemoveEvents(*mut alsa::snd_seq_remove_events_t);
1291
1292 unsafe impl Send for RemoveEvents {}
1293
1294 impl Drop for RemoveEvents {
drop(&mut self)1295 fn drop(&mut self) { unsafe { alsa::snd_seq_remove_events_free(self.0) } }
1296 }
1297
1298 impl RemoveEvents {
new() -> Result<Self>1299 pub fn new() -> Result<Self> {
1300 let mut q = ptr::null_mut();
1301 acheck!(snd_seq_remove_events_malloc(&mut q)).map(|_| RemoveEvents(q))
1302 }
1303
get_condition(&self) -> Remove1304 pub fn get_condition(&self) -> Remove { unsafe {
1305 Remove::from_bits_truncate(alsa::snd_seq_remove_events_get_condition(self.0) as u32)
1306 } }
get_queue(&self) -> i321307 pub fn get_queue(&self) -> i32 { unsafe { alsa::snd_seq_remove_events_get_queue(self.0) as i32 } }
get_time(&self) -> time::Duration1308 pub fn get_time(&self) -> time::Duration { unsafe {
1309 let d = ptr::read(alsa::snd_seq_remove_events_get_time(self.0));
1310 let t = &d.time;
1311
1312 time::Duration::new(t.tv_sec as u64, t.tv_nsec as u32)
1313 } }
get_dest(&self) -> Addr1314 pub fn get_dest(&self) -> Addr { unsafe {
1315 let a = &(*alsa::snd_seq_remove_events_get_dest(self.0));
1316
1317 Addr { client: a.client as i32, port: a.port as i32 }
1318 } }
get_channel(&self) -> i321319 pub fn get_channel(&self) -> i32 { unsafe { alsa::snd_seq_remove_events_get_channel(self.0) as i32 } }
get_event_type(&self) -> Result<EventType>1320 pub fn get_event_type(&self) -> Result<EventType> { unsafe {
1321 EventType::from_c_int(alsa::snd_seq_remove_events_get_event_type(self.0), "snd_seq_remove_events_get_event_type")
1322 } }
get_tag(&self) -> u81323 pub fn get_tag(&self) -> u8 { unsafe { alsa::snd_seq_remove_events_get_tag(self.0) as u8 } }
1324
1325
set_condition(&self, value: Remove)1326 pub fn set_condition(&self, value: Remove) { unsafe {
1327 alsa::snd_seq_remove_events_set_condition(self.0, value.bits() as c_uint);
1328 } }
set_queue(&self, value: i32)1329 pub fn set_queue(&self, value: i32) { unsafe { alsa::snd_seq_remove_events_set_queue(self.0, value as c_int) } }
set_time(&self, value: time::Duration)1330 pub fn set_time(&self, value: time::Duration) { unsafe {
1331 let mut d: alsa::snd_seq_timestamp_t = mem::zeroed();
1332 let mut t = &mut d.time;
1333
1334 t.tv_sec = value.as_secs() as c_uint;
1335 t.tv_nsec = value.subsec_nanos() as c_uint;
1336
1337 alsa::snd_seq_remove_events_set_time(self.0, &d);
1338 } }
set_dest(&self, value: Addr)1339 pub fn set_dest(&self, value: Addr) { unsafe {
1340 let a = alsa::snd_seq_addr_t { client: value.client as c_uchar, port: value.port as c_uchar};
1341
1342 alsa::snd_seq_remove_events_set_dest(self.0, &a);
1343 } }
set_channel(&self, value: i32)1344 pub fn set_channel(&self, value: i32) { unsafe { alsa::snd_seq_remove_events_set_channel(self.0, value as c_int) } }
set_event_type(&self, value: EventType)1345 pub fn set_event_type(&self, value: EventType) { unsafe { alsa::snd_seq_remove_events_set_event_type(self.0, value as i32); } }
set_tag(&self, value: u8)1346 pub fn set_tag(&self, value: u8) { unsafe { alsa::snd_seq_remove_events_set_tag(self.0, value as c_int) } }
1347 }
1348
1349 /// [snd_midi_event_t](http://www.alsa-project.org/alsa-doc/alsa-lib/group___m_i_d_i___event.html) Wrapper
1350 ///
1351 /// Sequencer event <-> MIDI byte stream coder
1352 pub struct MidiEvent(*mut alsa::snd_midi_event_t);
1353
1354 impl Drop for MidiEvent {
drop(&mut self)1355 fn drop(&mut self) { unsafe { alsa::snd_midi_event_free(self.0) } }
1356 }
1357
1358 impl MidiEvent {
new(bufsize: u32) -> Result<MidiEvent>1359 pub fn new(bufsize: u32) -> Result<MidiEvent> {
1360 let mut q = ptr::null_mut();
1361 acheck!(snd_midi_event_new(bufsize as size_t, &mut q)).map(|_| MidiEvent(q))
1362 }
1363
resize_buffer(&self, bufsize: u32) -> Result<()>1364 pub fn resize_buffer(&self, bufsize: u32) -> Result<()> { acheck!(snd_midi_event_resize_buffer(self.0, bufsize as size_t)).map(|_| ()) }
1365
1366 /// Note: this corresponds to snd_midi_event_no_status, but on and off are switched.
1367 ///
1368 /// Alsa-lib is a bit confusing here. Anyhow, set "enable" to true to enable running status.
enable_running_status(&self, enable: bool)1369 pub fn enable_running_status(&self, enable: bool) { unsafe { alsa::snd_midi_event_no_status(self.0, if enable {0} else {1}) } }
1370
1371 /// Resets both encoder and decoder
init(&self)1372 pub fn init(&self) { unsafe { alsa::snd_midi_event_init(self.0) } }
1373
reset_encode(&self)1374 pub fn reset_encode(&self) { unsafe { alsa::snd_midi_event_reset_encode(self.0) } }
1375
reset_decode(&self)1376 pub fn reset_decode(&self) { unsafe { alsa::snd_midi_event_reset_decode(self.0) } }
1377
decode(&self, buf: &mut [u8], ev: &mut Event) -> Result<usize>1378 pub fn decode(&self, buf: &mut [u8], ev: &mut Event) -> Result<usize> {
1379 ev.ensure_buf();
1380 acheck!(snd_midi_event_decode(self.0, buf.as_mut_ptr() as *mut c_uchar, buf.len() as c_long, &ev.0)).map(|r| r as usize)
1381 }
1382
1383 /// In case of success, returns a tuple of (bytes consumed from buf, found Event).
encode<'a>(&'a mut self, buf: &[u8]) -> Result<(usize, Option<Event<'a>>)>1384 pub fn encode<'a>(&'a mut self, buf: &[u8]) -> Result<(usize, Option<Event<'a>>)> {
1385 // The ALSA documentation clearly states that the event will be valid as long as the Encoder
1386 // is not messed with (because the data pointer for sysex events may point into the Encoder's
1387 // buffer). We make this safe by taking self by unique reference and coupling it to
1388 // the event's lifetime.
1389 let mut ev = unsafe { mem::zeroed() };
1390 let r = acheck!(snd_midi_event_encode(self.0, buf.as_ptr() as *const c_uchar, buf.len() as c_long, &mut ev))?;
1391 let e = if ev.type_ == alsa::SND_SEQ_EVENT_NONE as u8 {
1392 None
1393 } else {
1394 Some(unsafe { Event::extract(&mut ev, "snd_midi_event_encode") }?)
1395 };
1396 Ok((r as usize, e))
1397 }
1398 }
1399
1400 #[test]
print_seqs()1401 fn print_seqs() {
1402 use std::ffi::CString;
1403 let s = super::Seq::open(None, None, false).unwrap();
1404 s.set_client_name(&CString::new("rust_test_print_seqs").unwrap()).unwrap();
1405 let clients: Vec<_> = ClientIter::new(&s).collect();
1406 for a in &clients {
1407 let ports: Vec<_> = PortIter::new(&s, a.get_client()).collect();
1408 println!("{:?}: {:?}", a, ports);
1409 }
1410 }
1411
1412 #[test]
seq_subscribe()1413 fn seq_subscribe() {
1414 use std::ffi::CString;
1415 let s = super::Seq::open(None, None, false).unwrap();
1416 s.set_client_name(&CString::new("rust_test_seq_subscribe").unwrap()).unwrap();
1417 let timer_info = s.get_any_port_info(Addr { client: 0, port: 0 }).unwrap();
1418 assert_eq!(timer_info.get_name().unwrap(), "Timer");
1419 let info = PortInfo::empty().unwrap();
1420 let _port = s.create_port(&info);
1421 let subs = PortSubscribe::empty().unwrap();
1422 subs.set_sender(Addr { client: 0, port: 0 });
1423 subs.set_dest(Addr { client: s.client_id().unwrap(), port: info.get_port() });
1424 s.subscribe_port(&subs).unwrap();
1425 }
1426
1427 #[test]
seq_loopback()1428 fn seq_loopback() {
1429 use std::ffi::CString;
1430 let s = super::Seq::open(Some(&CString::new("default").unwrap()), None, false).unwrap();
1431 s.set_client_name(&CString::new("rust_test_seq_loopback").unwrap()).unwrap();
1432
1433 // Create ports
1434 let sinfo = PortInfo::empty().unwrap();
1435 sinfo.set_capability(PortCap::READ | PortCap::SUBS_READ);
1436 sinfo.set_type(PortType::MIDI_GENERIC | PortType::APPLICATION);
1437 s.create_port(&sinfo).unwrap();
1438 let sport = sinfo.get_port();
1439 let dinfo = PortInfo::empty().unwrap();
1440 dinfo.set_capability(PortCap::WRITE | PortCap::SUBS_WRITE);
1441 dinfo.set_type(PortType::MIDI_GENERIC | PortType::APPLICATION);
1442 s.create_port(&dinfo).unwrap();
1443 let dport = dinfo.get_port();
1444
1445 // Connect them
1446 let subs = PortSubscribe::empty().unwrap();
1447 subs.set_sender(Addr { client: s.client_id().unwrap(), port: sport });
1448 subs.set_dest(Addr { client: s.client_id().unwrap(), port: dport });
1449 s.subscribe_port(&subs).unwrap();
1450 println!("Connected {:?} to {:?}", subs.get_sender(), subs.get_dest());
1451
1452 // Send a note!
1453 let note = EvNote { channel: 0, note: 64, duration: 100, velocity: 100, off_velocity: 64 };
1454 let mut e = Event::new(EventType::Noteon, ¬e);
1455 e.set_subs();
1456 e.set_direct();
1457 e.set_source(sport);
1458 println!("Sending {:?}", e);
1459 s.event_output(&mut e).unwrap();
1460 s.drain_output().unwrap();
1461
1462 // Receive the note!
1463 let mut input = s.input();
1464 let e2 = input.event_input().unwrap();
1465 println!("Receiving {:?}", e2);
1466 assert_eq!(e2.get_type(), EventType::Noteon);
1467 assert_eq!(e2.get_data(), Some(note));
1468 }
1469
1470 #[test]
seq_encode_sysex()1471 fn seq_encode_sysex() {
1472 let mut me = MidiEvent::new(16).unwrap();
1473 let sysex = &[0xf0, 1, 2, 3, 4, 5, 6, 7, 0xf7];
1474 let (s, ev) = me.encode(sysex).unwrap();
1475 assert_eq!(s, 9);
1476 let ev = ev.unwrap();
1477 let v = ev.get_ext().unwrap();
1478 assert_eq!(&*v, sysex);
1479 }
1480
1481 #[test]
seq_decode_sysex()1482 fn seq_decode_sysex() {
1483 let sysex = [0xf0, 1, 2, 3, 4, 5, 6, 7, 0xf7];
1484 let mut ev = Event::new_ext(EventType::Sysex, &sysex[..]);
1485 let me = MidiEvent::new(0).unwrap();
1486 let mut buffer = vec![0; sysex.len()];
1487 assert_eq!(me.decode(&mut buffer[..], &mut ev).unwrap(), sysex.len());
1488 assert_eq!(buffer, sysex);
1489 }
1490
1491 #[test]
1492 #[should_panic]
seq_get_input_twice()1493 fn seq_get_input_twice() {
1494 use std::ffi::CString;
1495 let s = super::Seq::open(None, None, false).unwrap();
1496 s.set_client_name(&CString::new("rust_test_seq_get_input_twice").unwrap()).unwrap();
1497 let input1 = s.input();
1498 let input2 = s.input(); // this should panic
1499 let _ = (input1, input2);
1500 }
1501
1502 #[test]
seq_has_data()1503 fn seq_has_data() {
1504 for v in EventType::all() {
1505 let v = *v;
1506 let mut i = 0;
1507 if <() as EventData>::has_data(v) { i += 1; }
1508 if <[u8; 12] as EventData>::has_data(v) { i += 1; }
1509 if Event::has_ext_data(v) { i += 1; }
1510 if EvNote::has_data(v) { i += 1; }
1511 if EvCtrl::has_data(v) { i += 1; }
1512 if Addr::has_data(v) { i += 1; }
1513 if Connect::has_data(v) { i += 1; }
1514 if EvResult::has_data(v) { i += 1; }
1515 if EvQueueControl::<()>::has_data(v) { i += 1; }
1516 if EvQueueControl::<u32>::has_data(v) { i += 1; }
1517 if EvQueueControl::<i32>::has_data(v) { i += 1; }
1518 if EvQueueControl::<time::Duration>::has_data(v) { i += 1; }
1519 if i != 1 { panic!("{:?}: {} has_data", v, i) }
1520 }
1521 }
1522
1523 #[test]
seq_remove_events() -> std::result::Result<(), Box<dyn std::error::Error>>1524 fn seq_remove_events() -> std::result::Result<(), Box<dyn std::error::Error>> {
1525 let info = RemoveEvents::new()?;
1526
1527
1528 info.set_condition(Remove::INPUT | Remove::DEST | Remove::TIME_BEFORE | Remove::TAG_MATCH);
1529 info.set_queue(123);
1530 info.set_time(time::Duration::new(456, 789));
1531 info.set_dest(Addr { client: 212, port: 121 });
1532 info.set_channel(15);
1533 info.set_event_type(EventType::Noteon);
1534 info.set_tag(213);
1535
1536 assert_eq!(info.get_condition(), Remove::INPUT | Remove::DEST | Remove::TIME_BEFORE | Remove::TAG_MATCH);
1537 assert_eq!(info.get_queue(), 123);
1538 assert_eq!(info.get_time(), time::Duration::new(456, 789));
1539 assert_eq!(info.get_dest(), Addr { client: 212, port: 121 });
1540 assert_eq!(info.get_channel(), 15);
1541 assert_eq!(info.get_event_type()?, EventType::Noteon);
1542 assert_eq!(info.get_tag(), 213);
1543
1544 Ok(())
1545 }
1546
1547 #[test]
seq_portsubscribeiter()1548 fn seq_portsubscribeiter() {
1549 let s = super::Seq::open(None, None, false).unwrap();
1550
1551 // Create ports
1552 let sinfo = PortInfo::empty().unwrap();
1553 sinfo.set_capability(PortCap::READ | PortCap::SUBS_READ);
1554 sinfo.set_type(PortType::MIDI_GENERIC | PortType::APPLICATION);
1555 s.create_port(&sinfo).unwrap();
1556 let sport = sinfo.get_port();
1557 let dinfo = PortInfo::empty().unwrap();
1558 dinfo.set_capability(PortCap::WRITE | PortCap::SUBS_WRITE);
1559 dinfo.set_type(PortType::MIDI_GENERIC | PortType::APPLICATION);
1560 s.create_port(&dinfo).unwrap();
1561 let dport = dinfo.get_port();
1562
1563 // Connect them
1564 let subs = PortSubscribe::empty().unwrap();
1565 subs.set_sender(Addr { client: s.client_id().unwrap(), port: sport });
1566 subs.set_dest(Addr { client: s.client_id().unwrap(), port: dport });
1567 s.subscribe_port(&subs).unwrap();
1568
1569 // Query READ subs from sport's point of view
1570 let read_subs: Vec<PortSubscribe> = PortSubscribeIter::new(&s,
1571 Addr {client: s.client_id().unwrap(), port: sport },
1572 QuerySubsType::READ).collect();
1573 assert_eq!(read_subs.len(), 1);
1574 assert_eq!(read_subs[0].get_sender(), subs.get_sender());
1575 assert_eq!(read_subs[0].get_dest(), subs.get_dest());
1576
1577 let write_subs: Vec<PortSubscribe> = PortSubscribeIter::new(&s,
1578 Addr {client: s.client_id().unwrap(), port: sport },
1579 QuerySubsType::WRITE).collect();
1580 assert_eq!(write_subs.len(), 0);
1581
1582 // Now query WRITE subs from dport's point of view
1583 let write_subs: Vec<PortSubscribe> = PortSubscribeIter::new(&s,
1584 Addr {client: s.client_id().unwrap(), port: dport },
1585 QuerySubsType::WRITE).collect();
1586 assert_eq!(write_subs.len(), 1);
1587 assert_eq!(write_subs[0].get_sender(), subs.get_sender());
1588 assert_eq!(write_subs[0].get_dest(), subs.get_dest());
1589 }
1590