Debian Codegraph @

third_party/rust/cubeb-pulse/src/backend/stream.rs

raw
1 // Copyright © 2017-2018 Mozilla Foundation
2 //
3 // This program is made available under an ISC-style license. See the
4 // accompanying file LICENSE for details.
5
6 use backend::cork_state::CorkState;
7 use backend::*;
8 use cubeb_backend::{
9 ffi, log_enabled, ChannelLayout, DeviceId, DeviceRef, Error, InputProcessingParams, Result,
10 SampleFormat, StreamOps, StreamParamsRef, StreamPrefs,
11 };
12 use pulse::{self, CVolumeExt, ChannelMapExt, SampleSpecExt, StreamLatency, USecExt};
13 use pulse_ffi::*;
14 use ringbuf::RingBuffer;
15 use std::ffi::{CStr, CString};
16 use std::os::raw::{c_long, c_void};
17 use std::slice;
18 use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
19 use std::{mem, ptr};
20
21 use self::LinearInputBuffer::*;
22 use self::RingBufferConsumer::*;
23 use self::RingBufferProducer::*;
24
25 const PULSE_NO_GAIN: f32 = -1.0;
26
27 /// Iterator interface to `ChannelLayout`.
28 ///
29 /// Iterates each channel in the set represented by `ChannelLayout`.
30 struct ChannelLayoutIter {
31 /// The layout set being iterated
32 layout: ChannelLayout,
33 /// The next flag to test
34 index: u8,
35 }
36
37 fn channel_layout_iter(layout: ChannelLayout) -> ChannelLayoutIter {
38 let index = 0;
39 ChannelLayoutIter { layout, index }
40 }
41
42 impl Iterator for ChannelLayoutIter {
43 type Item = ChannelLayout;
44
45 fn next(&mut self) -> Option<Self::Item> {
46 while !self.layout.is_empty() {
47 let test = Self::Item::from_bits_truncate(1 << self.index);
48 self.index += 1;
49 if self.layout.contains(test) {
50 self.layout.remove(test);
51 return Some(test);
52 }
53 }
54 None
55 }
56 }
57
58 fn cubeb_channel_to_pa_channel(channel: ffi::cubeb_channel) -> pa_channel_position_t {
59 match channel {
60 ffi::CHANNEL_FRONT_LEFT => PA_CHANNEL_POSITION_FRONT_LEFT,
61 ffi::CHANNEL_FRONT_RIGHT => PA_CHANNEL_POSITION_FRONT_RIGHT,
62 ffi::CHANNEL_FRONT_CENTER => PA_CHANNEL_POSITION_FRONT_CENTER,
63 ffi::CHANNEL_LOW_FREQUENCY => PA_CHANNEL_POSITION_LFE,
64 ffi::CHANNEL_BACK_LEFT => PA_CHANNEL_POSITION_REAR_LEFT,
65 ffi::CHANNEL_BACK_RIGHT => PA_CHANNEL_POSITION_REAR_RIGHT,
66 ffi::CHANNEL_FRONT_LEFT_OF_CENTER => PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER,
67 ffi::CHANNEL_FRONT_RIGHT_OF_CENTER => PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER,
68 ffi::CHANNEL_BACK_CENTER => PA_CHANNEL_POSITION_REAR_CENTER,
69 ffi::CHANNEL_SIDE_LEFT => PA_CHANNEL_POSITION_SIDE_LEFT,
70 ffi::CHANNEL_SIDE_RIGHT => PA_CHANNEL_POSITION_SIDE_RIGHT,
71 ffi::CHANNEL_TOP_CENTER => PA_CHANNEL_POSITION_TOP_CENTER,
72 ffi::CHANNEL_TOP_FRONT_LEFT => PA_CHANNEL_POSITION_TOP_FRONT_LEFT,
73 ffi::CHANNEL_TOP_FRONT_CENTER => PA_CHANNEL_POSITION_TOP_FRONT_CENTER,
74 ffi::CHANNEL_TOP_FRONT_RIGHT => PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
75 ffi::CHANNEL_TOP_BACK_LEFT => PA_CHANNEL_POSITION_TOP_REAR_LEFT,
76 ffi::CHANNEL_TOP_BACK_CENTER => PA_CHANNEL_POSITION_TOP_REAR_CENTER,
77 ffi::CHANNEL_TOP_BACK_RIGHT => PA_CHANNEL_POSITION_TOP_REAR_RIGHT,
78 _ => PA_CHANNEL_POSITION_INVALID,
79 }
80 }
81
82 fn layout_to_channel_map(layout: ChannelLayout) -> pulse::ChannelMap {
83 assert_ne!(layout, ChannelLayout::UNDEFINED);
84
85 let mut cm = pulse::ChannelMap::init();
86 for (i, channel) in channel_layout_iter(layout).enumerate() {
87 cm.map[i] = cubeb_channel_to_pa_channel(channel.into());
88 }
89 cm.channels = layout.num_channels() as _;
90
91 // Special case single channel center mapping as mono.
92 if cm.channels == 1 && cm.map[0] == PA_CHANNEL_POSITION_FRONT_CENTER {
93 cm.map[0] = PA_CHANNEL_POSITION_MONO;
94 }
95
96 cm
97 }
98
99 fn default_layout_for_channels(ch: u32) -> ChannelLayout {
100 match ch {
101 1 => ChannelLayout::MONO,
102 2 => ChannelLayout::STEREO,
103 3 => ChannelLayout::_3F,
104 4 => ChannelLayout::QUAD,
105 5 => ChannelLayout::_3F2,
106 6 => ChannelLayout::_3F_LFE | ChannelLayout::SIDE_LEFT | ChannelLayout::SIDE_RIGHT,
107 7 => ChannelLayout::_3F3R_LFE,
108 8 => ChannelLayout::_3F4_LFE,
109 _ => panic!("channel must be between 1 to 8."),
110 }
111 }
112
113 pub struct Device(ffi::cubeb_device);
114
115 impl Drop for Device {
116 fn drop(&mut self) {
117 unsafe {
118 if !self.0.input_name.is_null() {
119 let _ = CString::from_raw(self.0.input_name as *mut _);
120 }
121 if !self.0.output_name.is_null() {
122 let _ = CString::from_raw(self.0.output_name as *mut _);
123 }
124 }
125 }
126 }
127
128 enum RingBufferConsumer {
129 IntegerRingBufferConsumer(ringbuf::Consumer<i16>),
130 FloatRingBufferConsumer(ringbuf::Consumer<f32>),
131 }
132
133 enum RingBufferProducer {
134 IntegerRingBufferProducer(ringbuf::Producer<i16>),
135 FloatRingBufferProducer(ringbuf::Producer<f32>),
136 }
137
138 enum LinearInputBuffer {
139 IntegerLinearInputBuffer(Vec<i16>),
140 FloatLinearInputBuffer(Vec<f32>),
141 }
142
143 struct BufferManager {
144 consumer: RingBufferConsumer,
145 producer: RingBufferProducer,
146 linear_input_buffer: LinearInputBuffer,
147 }
148
149 impl BufferManager {
150 // When opening a duplex stream, the sample-spec are guaranteed to match. It's ok to have
151 // either the input or output sample-spec here.
152 fn new(input_buffer_size: usize, sample_spec: &pulse::SampleSpec) -> BufferManager {
153 if sample_spec.format == PA_SAMPLE_S16BE || sample_spec.format == PA_SAMPLE_S16LE {
154 let ring = RingBuffer::<i16>::new(input_buffer_size);
155 let (prod, cons) = ring.split();
156 BufferManager {
157 producer: IntegerRingBufferProducer(prod),
158 consumer: IntegerRingBufferConsumer(cons),
159 linear_input_buffer: IntegerLinearInputBuffer(Vec::<i16>::with_capacity(
160 input_buffer_size,
161 )),
162 }
163 } else {
164 let ring = RingBuffer::<f32>::new(input_buffer_size);
165 let (prod, cons) = ring.split();
166 BufferManager {
167 producer: FloatRingBufferProducer(prod),
168 consumer: FloatRingBufferConsumer(cons),
169 linear_input_buffer: FloatLinearInputBuffer(Vec::<f32>::with_capacity(
170 input_buffer_size,
171 )),
172 }
173 }
174 }
175
176 fn push_input_data(&mut self, input_data: *const c_void, read_samples: usize) {
177 match &mut self.producer {
178 RingBufferProducer::FloatRingBufferProducer(p) => {
179 let input_data =
180 unsafe { slice::from_raw_parts::<f32>(input_data as *const f32, read_samples) };
181 // we don't do anything in particular if we can't push everything
182 p.push_slice(input_data);
183 }
184 RingBufferProducer::IntegerRingBufferProducer(p) => {
185 let input_data =
186 unsafe { slice::from_raw_parts::<i16>(input_data as *const i16, read_samples) };
187 p.push_slice(input_data);
188 }
189 }
190 }
191
192 fn pull_input_data(&mut self, input_data: *mut c_void, needed_samples: usize) {
193 match &mut self.consumer {
194 IntegerRingBufferConsumer(p) => {
195 let input: &mut [i16] = unsafe {
196 slice::from_raw_parts_mut::<i16>(input_data as *mut i16, needed_samples)
197 };
198 let read = p.pop_slice(input);
199 if read < needed_samples {
200 for i in 0..(needed_samples - read) {
201 input[read + i] = 0;
202 }
203 }
204 }
205 FloatRingBufferConsumer(p) => {
206 let input: &mut [f32] = unsafe {
207 slice::from_raw_parts_mut::<f32>(input_data as *mut f32, needed_samples)
208 };
209 let read = p.pop_slice(input);
210 if read < needed_samples {
211 for i in 0..(needed_samples - read) {
212 input[read + i] = 0.;
213 }
214 }
215 }
216 }
217 }
218
219 fn get_linear_input_data(&mut self, nsamples: usize) -> *const c_void {
220 let p = match &mut self.linear_input_buffer {
221 LinearInputBuffer::IntegerLinearInputBuffer(b) => {
222 b.resize(nsamples, 0);
223 b.as_mut_ptr() as *mut c_void
224 }
225 LinearInputBuffer::FloatLinearInputBuffer(b) => {
226 b.resize(nsamples, 0.);
227 b.as_mut_ptr() as *mut c_void
228 }
229 };
230 self.pull_input_data(p, nsamples);
231
232 p
233 }
234
235 pub fn trim(&mut self, final_size: usize) {
236 match &self.linear_input_buffer {
237 LinearInputBuffer::IntegerLinearInputBuffer(b) => {
238 let length = b.len();
239 assert!(final_size <= length);
240 let nframes_to_pop = length - final_size;
241 self.get_linear_input_data(nframes_to_pop);
242 }
243 LinearInputBuffer::FloatLinearInputBuffer(b) => {
244 let length = b.len();
245 assert!(final_size <= length);
246 let nframes_to_pop = length - final_size;
247 self.get_linear_input_data(nframes_to_pop);
248 }
249 }
250 }
251 pub fn available_samples(&mut self) -> usize {
252 match &self.linear_input_buffer {
253 LinearInputBuffer::IntegerLinearInputBuffer(b) => b.len(),
254 LinearInputBuffer::FloatLinearInputBuffer(b) => b.len(),
255 }
256 }
257 }
258
259 impl std::fmt::Debug for BufferManager {
260 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
261 write!(f, "")
262 }
263 }
264
265 #[repr(C)]
266 #[derive(Debug)]
267 pub struct PulseStream<'ctx> {
268 context: &'ctx PulseContext,
269 user_ptr: *mut c_void,
270 output_stream: Option<pulse::Stream>,
271 input_stream: Option<pulse::Stream>,
272 data_callback: ffi::cubeb_data_callback,
273 state_callback: ffi::cubeb_state_callback,
274 drain_timer: AtomicPtr<pa_time_event>,
275 output_sample_spec: pulse::SampleSpec,
276 input_sample_spec: pulse::SampleSpec,
277 // output frames count excluding pre-buffering
278 output_frame_count: AtomicUsize,
279 shutdown: bool,
280 volume: f32,
281 state: ffi::cubeb_state,
282 input_buffer_manager: Option<BufferManager>,
283 }
284
285 impl<'ctx> PulseStream<'ctx> {
286 #[allow(clippy::too_many_arguments)]
287 pub fn new(
288 context: &'ctx PulseContext,
289 stream_name: Option<&CStr>,
290 input_device: DeviceId,
291 input_stream_params: Option<&StreamParamsRef>,
292 output_device: DeviceId,
293 output_stream_params: Option<&StreamParamsRef>,
294 latency_frames: u32,
295 data_callback: ffi::cubeb_data_callback,
296 state_callback: ffi::cubeb_state_callback,
297 user_ptr: *mut c_void,
298 ) -> Result<Box<Self>> {
299 fn check_error(s: &pulse::Stream, u: *mut c_void) {
300 let stm = unsafe { &mut *(u as *mut PulseStream) };
301 if !s.get_state().is_good() {
302 cubeb_alog!("Calling error callback");
303 stm.state_change_callback(ffi::CUBEB_STATE_ERROR);
304 }
305 stm.context.mainloop.signal();
306 }
307
308 fn read_data(s: &pulse::Stream, nbytes: usize, u: *mut c_void) {
309 fn read_from_input(
310 s: &pulse::Stream,
311 buffer: *mut *const c_void,
312 size: *mut usize,
313 ) -> i32 {
314 let readable_size = s.readable_size().map(|s| s as i32).unwrap_or(-1);
315 if readable_size > 0 && unsafe { s.peek(buffer, size).is_err() } {
316 cubeb_logv!("Error while peeking the input stream");
317 return -1;
318 }
319 readable_size
320 }
321
322 cubeb_alogv!("Input callback buffer size {}", nbytes);
323 let stm = unsafe { &mut *(u as *mut PulseStream) };
324 if stm.shutdown {
325 return;
326 }
327
328 let mut read_data: *const c_void = ptr::null();
329 let mut read_size: usize = 0;
330 while read_from_input(s, &mut read_data, &mut read_size) > 0 {
331 /* read_data can be NULL in case of a hole. */
332 if !read_data.is_null() {
333 let in_frame_size = stm.input_sample_spec.frame_size();
334 let read_frames = read_size / in_frame_size;
335 let read_samples = read_size / stm.input_sample_spec.sample_size();
336
337 if stm.output_stream.is_some() {
338 // duplex stream: push the input data to the ring buffer.
339 stm.input_buffer_manager
340 .as_mut()
341 .unwrap()
342 .push_input_data(read_data, read_samples);
343 } else {
344 // input/capture only operation. Call callback directly
345 let got = unsafe {
346 stm.data_callback.unwrap()(
347 stm as *mut _ as *mut _,
348 stm.user_ptr,
349 read_data,
350 ptr::null_mut(),
351 read_frames as c_long,
352 )
353 };
354
355 if got < 0 || got as usize != read_frames {
356 let _ = s.cancel_write();
357 stm.shutdown = true;
358 if got < 0 {
359 unsafe {
360 stm.state_callback.unwrap()(
361 stm as *mut _ as *mut _,
362 stm.user_ptr,
363 ffi::CUBEB_STATE_ERROR,
364 );
365 }
366 }
367 break;
368 }
369 }
370 }
371
372 if read_size > 0 {
373 let _ = s.drop();
374 }
375
376 if stm.shutdown {
377 return;
378 }
379 }
380 }
381
382 fn write_data(_: &pulse::Stream, nbytes: usize, u: *mut c_void) {
383 cubeb_alogv!("Output callback to be written buffer size {}", nbytes);
384 let stm = unsafe { &mut *(u as *mut PulseStream) };
385 if stm.shutdown || stm.state != ffi::CUBEB_STATE_STARTED {
386 return;
387 }
388
389 let nframes = nbytes / stm.output_sample_spec.frame_size();
390 let first_callback = stm.output_frame_count.fetch_add(nframes, Ordering::SeqCst) == 0;
391 if stm.input_stream.is_some() {
392 let nsamples_input = nframes * stm.input_sample_spec.channels as usize;
393 let input_buffer_manager = stm.input_buffer_manager.as_mut().unwrap();
394
395 if first_callback {
396 let buffered_input_frames = input_buffer_manager.available_samples()
397 / stm.input_sample_spec.channels as usize;
398 if buffered_input_frames > nframes {
399 // Trim the buffer to ensure minimal roundtrip latency
400 let popped_frames = buffered_input_frames - nframes;
401 input_buffer_manager
402 .trim(nframes * stm.input_sample_spec.channels as usize);
403 cubeb_alog!("Dropping {} frames in input buffer.", popped_frames);
404 }
405 }
406
407 let p = input_buffer_manager.get_linear_input_data(nsamples_input);
408 stm.trigger_user_callback(p, nbytes);
409 } else {
410 // Output/playback only operation.
411 // Write directly to output
412 debug_assert!(stm.output_stream.is_some());
413 stm.trigger_user_callback(ptr::null(), nbytes);
414 }
415 }
416
417 let mut stm = Box::new(PulseStream {
418 context,
419 output_stream: None,
420 input_stream: None,
421 data_callback,
422 state_callback,
423 user_ptr,
424 drain_timer: AtomicPtr::new(ptr::null_mut()),
425 output_sample_spec: pulse::SampleSpec::default(),
426 input_sample_spec: pulse::SampleSpec::default(),
427 output_frame_count: AtomicUsize::new(0),
428 shutdown: false,
429 volume: PULSE_NO_GAIN,
430 state: ffi::CUBEB_STATE_ERROR,
431 input_buffer_manager: None,
432 });
433
434 if let Some(ref context) = stm.context.context {
435 stm.context.mainloop.lock();
436
437 // Setup output stream
438 if let Some(stream_params) = output_stream_params {
439 match PulseStream::stream_init(context, stream_params, stream_name) {
440 Ok(s) => {
441 stm.output_sample_spec = *s.get_sample_spec();
442
443 s.set_state_callback(check_error, stm.as_mut() as *mut _ as *mut _);
444 s.set_write_callback(write_data, stm.as_mut() as *mut _ as *mut _);
445
446 let buffer_size_bytes =
447 latency_frames * stm.output_sample_spec.frame_size() as u32;
448
449 let battr = pa_buffer_attr {
450 maxlength: u32::MAX,
451 prebuf: u32::MAX,
452 fragsize: u32::MAX,
453 tlength: buffer_size_bytes * 2,
454 minreq: buffer_size_bytes / 4,
455 };
456 let device_name = super::try_cstr_from(output_device as *const _);
457 let mut stream_flags = pulse::StreamFlags::AUTO_TIMING_UPDATE
458 | pulse::StreamFlags::INTERPOLATE_TIMING
459 | pulse::StreamFlags::START_CORKED
460 | pulse::StreamFlags::ADJUST_LATENCY;
461 if device_name.is_some()
462 || stream_params
463 .prefs()
464 .contains(StreamPrefs::DISABLE_DEVICE_SWITCHING)
465 {
466 stream_flags |= pulse::StreamFlags::DONT_MOVE;
467 }
468 let _ = s.connect_playback(device_name, &battr, stream_flags, None, None);
469
470 stm.output_stream = Some(s);
471 }
472 Err(e) => {
473 cubeb_log!("Output stream initialization error");
474 stm.context.mainloop.unlock();
475 stm.destroy();
476 return Err(e);
477 }
478 }
479 }
480
481 // Set up input stream
482 if let Some(stream_params) = input_stream_params {
483 match PulseStream::stream_init(context, stream_params, stream_name) {
484 Ok(s) => {
485 stm.input_sample_spec = *s.get_sample_spec();
486
487 s.set_state_callback(check_error, stm.as_mut() as *mut _ as *mut _);
488 s.set_read_callback(read_data, stm.as_mut() as *mut _ as *mut _);
489
490 let buffer_size_bytes =
491 latency_frames * stm.input_sample_spec.frame_size() as u32;
492 let battr = pa_buffer_attr {
493 maxlength: u32::MAX,
494 prebuf: u32::MAX,
495 fragsize: buffer_size_bytes,
496 tlength: buffer_size_bytes,
497 minreq: buffer_size_bytes,
498 };
499 let device_name = super::try_cstr_from(input_device as *const _);
500 let mut stream_flags = pulse::StreamFlags::AUTO_TIMING_UPDATE
501 | pulse::StreamFlags::INTERPOLATE_TIMING
502 | pulse::StreamFlags::START_CORKED
503 | pulse::StreamFlags::ADJUST_LATENCY;
504 if device_name.is_some()
505 || stream_params
506 .prefs()
507 .contains(StreamPrefs::DISABLE_DEVICE_SWITCHING)
508 {
509 stream_flags |= pulse::StreamFlags::DONT_MOVE;
510 }
511 let _ = s.connect_record(device_name, &battr, stream_flags);
512
513 stm.input_stream = Some(s);
514 }
515 Err(e) => {
516 cubeb_log!("Input stream initialization error");
517 stm.context.mainloop.unlock();
518 stm.destroy();
519 return Err(e);
520 }
521 }
522 }
523
524 // Duplex, set up the ringbuffer
525 if input_stream_params.is_some() && output_stream_params.is_some() {
526 // A bit more room in case of output underrun.
527 let buffer_size_bytes =
528 2 * latency_frames * stm.input_sample_spec.frame_size() as u32;
529 stm.input_buffer_manager = Some(BufferManager::new(
530 buffer_size_bytes as usize,
531 &stm.input_sample_spec,
532 ))
533 }
534
535 let r = if stm.wait_until_ready() {
536 /* force a timing update now, otherwise timing info does not become valid
537 until some point after initialization has completed. */
538 stm.update_timing_info()
539 } else {
540 false
541 };
542
543 stm.context.mainloop.unlock();
544
545 if !r {
546 stm.destroy();
547 cubeb_log!("Error while waiting for the stream to be ready");
548 return Err(Error::error());
549 }
550
551 // TODO:
552 if log_enabled() {
553 if let Some(ref output_stream) = stm.output_stream {
554 let output_att = output_stream.get_buffer_attr();
555 cubeb_log!(
556 "Output buffer attributes maxlength {}, tlength {}, \
557 prebuf {}, minreq {}, fragsize {}",
558 output_att.maxlength,
559 output_att.tlength,
560 output_att.prebuf,
561 output_att.minreq,
562 output_att.fragsize
563 );
564 }
565
566 if let Some(ref input_stream) = stm.input_stream {
567 let input_att = input_stream.get_buffer_attr();
568 cubeb_log!(
569 "Input buffer attributes maxlength {}, tlength {}, \
570 prebuf {}, minreq {}, fragsize {}",
571 input_att.maxlength,
572 input_att.tlength,
573 input_att.prebuf,
574 input_att.minreq,
575 input_att.fragsize
576 );
577 }
578 }
579 }
580
581 Ok(stm)
582 }
583
584 fn destroy(&mut self) {
585 self.cork(CorkState::cork());
586
587 self.context.mainloop.lock();
588 {
589 if let Some(stm) = self.output_stream.take() {
590 let drain_timer = self.drain_timer.load(Ordering::Acquire);
591 if !drain_timer.is_null() {
592 /* there's no pa_rttime_free, so use this instead. */
593 self.context.mainloop.get_api().time_free(drain_timer);
594 }
595 stm.clear_state_callback();
596 stm.clear_write_callback();
597 let _ = stm.disconnect();
598 stm.unref();
599 }
600
601 if let Some(stm) = self.input_stream.take() {
602 stm.clear_state_callback();
603 stm.clear_read_callback();
604 let _ = stm.disconnect();
605 stm.unref();
606 }
607 }
608 self.context.mainloop.unlock();
609 }
610 }
611
612 impl<'ctx> Drop for PulseStream<'ctx> {
613 fn drop(&mut self) {
614 self.destroy();
615 }
616 }
617
618 impl<'ctx> StreamOps for PulseStream<'ctx> {
619 fn start(&mut self) -> Result<()> {
620 fn output_preroll(_: &pulse::MainloopApi, u: *mut c_void) {
621 let stm = unsafe { &mut *(u as *mut PulseStream) };
622 if !stm.shutdown {
623 let size = stm
624 .output_stream
625 .as_ref()
626 .map_or(0, |s| s.writable_size().unwrap_or(0));
627 stm.trigger_user_callback(std::ptr::null(), size);
628 }
629 }
630 self.shutdown = false;
631 self.cork(CorkState::uncork() | CorkState::notify());
632
633 if self.output_stream.is_some() {
634 /* When doing output-only or duplex, we need to manually call user cb once in order to
635 * make things roll. This is done via a defer event in order to execute it from PA
636 * server thread. */
637 self.context.mainloop.lock();
638 self.context
639 .mainloop
640 .get_api()
641 .once(output_preroll, self as *const _ as *mut _);
642 self.context.mainloop.unlock();
643 }
644
645 Ok(())
646 }
647
648 fn stop(&mut self) -> Result<()> {
649 {
650 self.context.mainloop.lock();
651 self.shutdown = true;
652 // If draining is taking place wait to finish
653 cubeb_log!("Stream stop: waiting for drain");
654 while !self.drain_timer.load(Ordering::Acquire).is_null() {
655 self.context.mainloop.wait();
656 }
657 cubeb_log!("Stream stop: waited for drain");
658 self.context.mainloop.unlock();
659 }
660 self.cork(CorkState::cork() | CorkState::notify());
661
662 Ok(())
663 }
664
665 fn position(&mut self) -> Result<u64> {
666 let in_thread = self.context.mainloop.in_thread();
667
668 if !in_thread {
669 self.context.mainloop.lock();
670 }
671
672 if self.output_stream.is_none() {
673 cubeb_log!("Calling position() on an input-only stream");
674 return Err(Error::error());
675 }
676
677 let stm = self.output_stream.as_ref().unwrap();
678 let r = match stm.get_time() {
679 Ok(r_usec) => {
680 let bytes = USecExt::to_bytes(r_usec, &self.output_sample_spec);
681 Ok((bytes / self.output_sample_spec.frame_size()) as u64)
682 }
683 Err(_) => {
684 cubeb_log!("Error: stm.get_time failed");
685 Err(Error::error())
686 }
687 };
688
689 if !in_thread {
690 self.context.mainloop.unlock();
691 }
692
693 r
694 }
695
696 fn latency(&mut self) -> Result<u32> {
697 match self.output_stream {
698 None => {
699 cubeb_log!("Error: calling latency() on an input-only stream");
700 Err(Error::error())
701 }
702 Some(ref stm) => match stm.get_latency() {
703 Ok(StreamLatency::Positive(r_usec)) => {
704 let latency = (r_usec * pa_usec_t::from(self.output_sample_spec.rate)
705 / PA_USEC_PER_SEC) as u32;
706 Ok(latency)
707 }
708 Ok(_) => {
709 panic!("Can not handle negative latency values.");
710 }
711 Err(_) => {
712 cubeb_log!("Error: get_latency() failed for an output stream");
713 Err(Error::error())
714 }
715 },
716 }
717 }
718
719 fn input_latency(&mut self) -> Result<u32> {
720 match self.input_stream {
721 None => {
722 cubeb_log!("Error: calling input_latency() on an output-only stream");
723 Err(Error::error())
724 }
725 Some(ref stm) => match stm.get_latency() {
726 Ok(StreamLatency::Positive(w_usec)) => {
727 let latency = (w_usec * pa_usec_t::from(self.input_sample_spec.rate)
728 / PA_USEC_PER_SEC) as u32;
729 Ok(latency)
730 }
731 // Input stream can be negative only if it is attached to a
732 // monitor source device
733 Ok(StreamLatency::Negative(_)) => Ok(0),
734 Err(_) => {
735 cubeb_log!("Error: stm.get_latency() failed for an input stream");
736 Err(Error::error())
737 }
738 },
739 }
740 }
741
742 fn set_volume(&mut self, volume: f32) -> Result<()> {
743 match self.output_stream {
744 None => {
745 cubeb_log!("Error: can't set volume on an input-only stream");
746 Err(Error::error())
747 }
748 Some(ref stm) => {
749 if let Some(ref context) = self.context.context {
750 self.context.mainloop.lock();
751
752 let mut cvol: pa_cvolume = Default::default();
753
754 /* if the pulse daemon is configured to use flat
755 * volumes, apply our own gain instead of changing
756 * the input volume on the sink. */
757 let flags = {
758 match self.context.default_sink_info {
759 Some(ref info) => info.flags,
760 _ => pulse::SinkFlags::empty(),
761 }
762 };
763
764 if flags.contains(pulse::SinkFlags::FLAT_VOLUME) {
765 self.volume = volume;
766 } else {
767 let channels = stm.get_sample_spec().channels;
768 let vol = pulse::sw_volume_from_linear(f64::from(volume));
769 cvol.set(u32::from(channels), vol);
770
771 let index = stm.get_index();
772
773 let context_ptr = self.context as *const _ as *mut _;
774 if let Ok(o) = context.set_sink_input_volume(
775 index,
776 &cvol,
777 context_success,
778 context_ptr,
779 ) {
780 self.context.operation_wait(stm, &o);
781 }
782 }
783
784 self.context.mainloop.unlock();
785 Ok(())
786 } else {
787 cubeb_log!("Error: set_volume: no context?");
788 Err(Error::error())
789 }
790 }
791 }
792 }
793
794 fn set_name(&mut self, name: &CStr) -> Result<()> {
795 match self.output_stream {
796 None => {
797 cubeb_log!("Error: can't set the name on a input-only stream.");
798 Err(Error::error())
799 }
800 Some(ref stm) => {
801 self.context.mainloop.lock();
802 if let Ok(o) = stm.set_name(name, stream_success, self as *const _ as *mut _) {
803 self.context.operation_wait(stm, &o);
804 }
805 self.context.mainloop.unlock();
806 Ok(())
807 }
808 }
809 }
810
811 fn current_device(&mut self) -> Result<&DeviceRef> {
812 if self.context.version_0_9_8 {
813 let mut dev: Box<ffi::cubeb_device> = Box::new(unsafe { mem::zeroed() });
814
815 if let Some(ref stm) = self.input_stream {
816 dev.input_name = match stm.get_device_name() {
817 Ok(name) => name.to_owned().into_raw(),
818 Err(_) => {
819 cubeb_log!("Error: couldn't get the input stream's device name");
820 return Err(Error::error());
821 }
822 }
823 }
824
825 if let Some(ref stm) = self.output_stream {
826 dev.output_name = match stm.get_device_name() {
827 Ok(name) => name.to_owned().into_raw(),
828 Err(_) => {
829 cubeb_log!("Error: couldn't get the output stream's device name");
830 return Err(Error::error());
831 }
832 }
833 }
834
835 Ok(unsafe { DeviceRef::from_ptr(Box::into_raw(dev) as *mut _) })
836 } else {
837 cubeb_log!("Error: PulseAudio context too old");
838 Err(not_supported())
839 }
840 }
841
842 fn set_input_mute(&mut self, _mute: bool) -> Result<()> {
843 Err(not_supported())
844 }
845
846 fn set_input_processing_params(&mut self, _params: InputProcessingParams) -> Result<()> {
847 Err(not_supported())
848 }
849
850 fn device_destroy(&mut self, device: &DeviceRef) -> Result<()> {
851 if device.as_ptr().is_null() {
852 cubeb_log!("Error: can't destroy null device");
853 Err(Error::error())
854 } else {
855 unsafe {
856 let _: Box<Device> = Box::from_raw(device.as_ptr() as *mut _);
857 }
858 Ok(())
859 }
860 }
861
862 fn register_device_changed_callback(
863 &mut self,
864 _: ffi::cubeb_device_changed_callback,
865 ) -> Result<()> {
866 cubeb_log!("Error: register_device_change_callback unimplemented");
867 Err(Error::error())
868 }
869 }
870
871 impl<'ctx> PulseStream<'ctx> {
872 fn stream_init(
873 context: &pulse::Context,
874 stream_params: &StreamParamsRef,
875 stream_name: Option<&CStr>,
876 ) -> Result<pulse::Stream> {
877 if stream_params.prefs() == StreamPrefs::LOOPBACK {
878 cubeb_log!("Error: StreamPref::LOOPBACK unimplemented");
879 return Err(not_supported());
880 }
881
882 fn to_pulse_format(format: SampleFormat) -> pulse::SampleFormat {
883 match format {
884 SampleFormat::S16LE => pulse::SampleFormat::Signed16LE,
885 SampleFormat::S16BE => pulse::SampleFormat::Signed16BE,
886 SampleFormat::Float32LE => pulse::SampleFormat::Float32LE,
887 SampleFormat::Float32BE => pulse::SampleFormat::Float32BE,
888 _ => pulse::SampleFormat::Invalid,
889 }
890 }
891
892 let fmt = to_pulse_format(stream_params.format());
893 if fmt == pulse::SampleFormat::Invalid {
894 cubeb_log!("Error: invalid sample format");
895 return Err(invalid_format());
896 }
897
898 let ss = pulse::SampleSpec {
899 channels: stream_params.channels() as u8,
900 format: fmt.into(),
901 rate: stream_params.rate(),
902 };
903
904 let cm: Option<pa_channel_map> = match stream_params.layout() {
905 ChannelLayout::UNDEFINED => {
906 if stream_params.channels() <= 8
907 && pulse::ChannelMap::init_auto(
908 stream_params.channels(),
909 PA_CHANNEL_MAP_DEFAULT,
910 )
911 .is_none()
912 {
913 cubeb_log!("Layout undefined and PulseAudio's default layout has not been configured, guess one.");
914 Some(layout_to_channel_map(default_layout_for_channels(
915 stream_params.channels(),
916 )))
917 } else {
918 cubeb_log!("Layout undefined, PulseAudio will use its default.");
919 None
920 }
921 }
922 _ => Some(layout_to_channel_map(stream_params.layout())),
923 };
924
925 let stream = pulse::Stream::new(context, stream_name.unwrap(), &ss, cm.as_ref());
926
927 match stream {
928 None => {
929 cubeb_log!("Error: pulse::Stream::new failure");
930 Err(Error::error())
931 }
932 Some(stm) => Ok(stm),
933 }
934 }
935
936 pub fn cork_stream(&self, stream: Option<&pulse::Stream>, state: CorkState) {
937 if let Some(stm) = stream {
938 if let Ok(o) = stm.cork(
939 state.is_cork() as i32,
940 stream_success,
941 self as *const _ as *mut _,
942 ) {
943 self.context.operation_wait(stream, &o);
944 }
945 }
946 }
947
948 fn cork(&mut self, state: CorkState) {
949 {
950 self.context.mainloop.lock();
951 self.cork_stream(self.output_stream.as_ref(), state);
952 self.cork_stream(self.input_stream.as_ref(), state);
953 self.context.mainloop.unlock()
954 }
955
956 if state.is_notify() {
957 self.state_change_callback(if state.is_cork() {
958 ffi::CUBEB_STATE_STOPPED
959 } else {
960 ffi::CUBEB_STATE_STARTED
961 });
962 }
963 }
964
965 fn update_timing_info(&self) -> bool {
966 let mut r = false;
967
968 if let Some(ref stm) = self.output_stream {
969 if let Ok(o) = stm.update_timing_info(stream_success, self as *const _ as *mut _) {
970 r = self.context.operation_wait(stm, &o);
971 }
972
973 if !r {
974 return r;
975 }
976 }
977
978 if let Some(ref stm) = self.input_stream {
979 if let Ok(o) = stm.update_timing_info(stream_success, self as *const _ as *mut _) {
980 r = self.context.operation_wait(stm, &o);
981 }
982 }
983
984 r
985 }
986
987 pub fn state_change_callback(&mut self, s: ffi::cubeb_state) {
988 self.state = s;
989 unsafe {
990 (self.state_callback.unwrap())(
991 self as *mut PulseStream as *mut ffi::cubeb_stream,
992 self.user_ptr,
993 s,
994 )
995 };
996 }
997
998 fn wait_until_ready(&self) -> bool {
999 fn wait_until_io_stream_ready(
1000 stm: &pulse::Stream,
1001 mainloop: &pulse::ThreadedMainloop,
1002 ) -> bool {
1003 if mainloop.is_null() {
1004 return false;
1005 }
1006
1007 loop {
1008 let state = stm.get_state();
1009 if !state.is_good() {
1010 return false;
1011 }
1012 if state == pulse::StreamState::Ready {
1013 break;
1014 }
1015 mainloop.wait();
1016 }
1017
1018 true
1019 }
1020
1021 if let Some(ref stm) = self.output_stream {
1022 if !wait_until_io_stream_ready(stm, &self.context.mainloop) {
1023 return false;
1024 }
1025 }
1026
1027 if let Some(ref stm) = self.input_stream {
1028 if !wait_until_io_stream_ready(stm, &self.context.mainloop) {
1029 return false;
1030 }
1031 }
1032
1033 true
1034 }
1035
1036 #[allow(clippy::cognitive_complexity)]
1037 fn trigger_user_callback(&mut self, input_data: *const c_void, nbytes: usize) {
1038 fn drained_cb(
1039 a: &pulse::MainloopApi,
1040 e: *mut pa_time_event,
1041 _tv: &pulse::TimeVal,
1042 u: *mut c_void,
1043 ) {
1044 cubeb_logv!("Drain finished callback.");
1045 let stm = unsafe { &mut *(u as *mut PulseStream) };
1046 let drain_timer = stm.drain_timer.load(Ordering::Acquire);
1047 debug_assert_eq!(drain_timer, e);
1048 stm.state_change_callback(ffi::CUBEB_STATE_DRAINED);
1049 /* there's no pa_rttime_free, so use this instead. */
1050 a.time_free(drain_timer);
1051 stm.drain_timer.store(ptr::null_mut(), Ordering::Release);
1052 stm.context.mainloop.signal();
1053 }
1054
1055 if let Some(ref stm) = self.output_stream {
1056 let frame_size = self.output_sample_spec.frame_size();
1057 debug_assert_eq!(nbytes % frame_size, 0);
1058
1059 let mut towrite = nbytes;
1060 let mut read_offset = 0usize;
1061 while towrite > 0 {
1062 match stm.begin_write(towrite) {
1063 Err(e) => {
1064 cubeb_logv!("Error: failure to write data");
1065 panic!("Failed to write data: {}", e);
1066 }
1067 Ok((buffer, size)) => {
1068 debug_assert!(size > 0);
1069 debug_assert_eq!(size % frame_size, 0);
1070
1071 cubeb_logv!(
1072 "Trigger user callback with output buffer size={}, read_offset={}",
1073 size,
1074 read_offset
1075 );
1076 let read_ptr = unsafe { (input_data as *const u8).add(read_offset) };
1077 #[allow(clippy::unnecessary_cast)]
1078 let mut got = unsafe {
1079 self.data_callback.unwrap()(
1080 self as *const _ as *mut _,
1081 self.user_ptr,
1082 read_ptr as *const _ as *mut _,
1083 buffer,
1084 (size / frame_size) as c_long,
1085 ) as i64
1086 };
1087 if got < 0 {
1088 let _ = stm.cancel_write();
1089 self.shutdown = true;
1090 unsafe {
1091 self.state_callback.unwrap()(
1092 self as *const _ as *mut _,
1093 self.user_ptr,
1094 ffi::CUBEB_STATE_ERROR,
1095 );
1096 }
1097 return;
1098 }
1099
1100 // If more iterations move offset of read buffer
1101 if !input_data.is_null() {
1102 let in_frame_size = self.input_sample_spec.frame_size();
1103 read_offset += (size / frame_size) * in_frame_size;
1104 }
1105
1106 if self.volume != PULSE_NO_GAIN {
1107 let samples = (self.output_sample_spec.channels as usize * size
1108 / frame_size) as isize;
1109
1110 if self.output_sample_spec.format == PA_SAMPLE_S16BE
1111 || self.output_sample_spec.format == PA_SAMPLE_S16LE
1112 {
1113 let b = buffer as *mut i16;
1114 for i in 0..samples {
1115 unsafe { *b.offset(i) *= self.volume as i16 };
1116 }
1117 } else {
1118 let b = buffer as *mut f32;
1119 for i in 0..samples {
1120 unsafe { *b.offset(i) *= self.volume };
1121 }
1122 }
1123 }
1124
1125 let should_drain = (got as usize) < size / frame_size;
1126
1127 if should_drain && self.output_frame_count.load(Ordering::SeqCst) == 0 {
1128 // Draining during preroll, ensure `prebuf` frames are written so
1129 // the stream starts. If not, pad with a bit of silence.
1130 let prebuf_size_bytes = stm.get_buffer_attr().prebuf as usize;
1131 let got_bytes = got as usize * frame_size;
1132 if prebuf_size_bytes > got_bytes {
1133 let padding_bytes = prebuf_size_bytes - got_bytes;
1134 if padding_bytes + got_bytes <= size {
1135 // A slice that starts after the data provided by the callback,
1136 // with just enough room to provide a final buffer big enough.
1137 let padding_buf: &mut [u8] = unsafe {
1138 slice::from_raw_parts_mut::<u8>(
1139 buffer.add(got_bytes) as *mut u8,
1140 padding_bytes,
1141 )
1142 };
1143 padding_buf.fill(0);
1144 got += (padding_bytes / frame_size) as i64;
1145 }
1146 } else {
1147 cubeb_logv!(
1148 "Not enough room to pad up to prebuf when prebuffering."
1149 )
1150 }
1151 }
1152
1153 let r = stm.write(
1154 buffer,
1155 got as usize * frame_size,
1156 0,
1157 pulse::SeekMode::Relative,
1158 );
1159
1160 if should_drain {
1161 cubeb_logv!("Draining {} < {}", got, size / frame_size);
1162 let latency = match stm.get_latency() {
1163 Ok(StreamLatency::Positive(l)) => l,
1164 Ok(_) => {
1165 panic!("Can not handle negative latency values.");
1166 }
1167 Err(e) => {
1168 debug_assert_eq!(
1169 e,
1170 pulse::ErrorCode::from_error_code(PA_ERR_NODATA)
1171 );
1172 /* this needs a better guess. */
1173 100 * PA_USEC_PER_MSEC
1174 }
1175 };
1176
1177 /* pa_stream_drain is useless, see PA bug# 866. this is a workaround. */
1178 /* arbitrary safety margin: double the current latency. */
1179 debug_assert!(self.drain_timer.load(Ordering::Acquire).is_null());
1180 let stream_ptr = self as *const _ as *mut _;
1181 if let Some(ref context) = self.context.context {
1182 self.drain_timer.store(
1183 context.rttime_new(
1184 pulse::rtclock_now() + 2 * latency,
1185 drained_cb,
1186 stream_ptr,
1187 ),
1188 Ordering::Release,
1189 );
1190 }
1191 self.shutdown = true;
1192 return;
1193 }
1194
1195 debug_assert!(r.is_ok());
1196
1197 towrite -= size;
1198 }
1199 }
1200 }
1201 debug_assert_eq!(towrite, 0);
1202 }
1203 }
1204 }
1205
1206 fn stream_success(_: &pulse::Stream, success: i32, u: *mut c_void) {
1207 let stm = unsafe { &*(u as *mut PulseStream) };
1208 if success != 1 {
1209 cubeb_log!("stream_success ignored failure: {}", success);
1210 }
1211 stm.context.mainloop.signal();
1212 }
1213
1214 fn context_success(_: &pulse::Context, success: i32, u: *mut c_void) {
1215 let ctx = unsafe { &*(u as *mut PulseContext) };
1216 if success != 1 {
1217 cubeb_log!("context_success ignored failure: {}", success);
1218 }
1219 ctx.mainloop.signal();
1220 }
1221
1222 fn invalid_format() -> Error {
1223 Error::from_raw(ffi::CUBEB_ERROR_INVALID_FORMAT)
1224 }
1225
1226 fn not_supported() -> Error {
1227 Error::from_raw(ffi::CUBEB_ERROR_NOT_SUPPORTED)
1228 }
1229
1230 #[cfg(all(test, not(feature = "pulse-dlopen")))]
1231 mod test {
1232 use super::layout_to_channel_map;
1233 use cubeb_backend::ChannelLayout;
1234 use pulse_ffi::*;
1235
1236 macro_rules! channel_tests {
1237 {$($name: ident, $layout: ident => [ $($channels: ident),* ]),+} => {
1238 $(
1239 #[test]
1240 fn $name() {
1241 let layout = ChannelLayout::$layout;
1242 let mut iter = super::channel_layout_iter(layout);
1243 $(
1244 assert_eq!(Some(ChannelLayout::$channels), iter.next());
1245 )*
1246 assert_eq!(None, iter.next());
1247 }
1248
1249 )*
1250 }
1251 }
1252
1253 channel_tests! {
1254 channels_unknown, UNDEFINED => [ ],
1255 channels_mono, MONO => [
1256 FRONT_CENTER
1257 ],
1258 channels_mono_lfe, MONO_LFE => [
1259 FRONT_CENTER,
1260 LOW_FREQUENCY
1261 ],
1262 channels_stereo, STEREO => [
1263 FRONT_LEFT,
1264 FRONT_RIGHT
1265 ],
1266 channels_stereo_lfe, STEREO_LFE => [
1267 FRONT_LEFT,
1268 FRONT_RIGHT,
1269 LOW_FREQUENCY
1270 ],
1271 channels_3f, _3F => [
1272 FRONT_LEFT,
1273 FRONT_RIGHT,
1274 FRONT_CENTER
1275 ],
1276 channels_3f_lfe, _3F_LFE => [
1277 FRONT_LEFT,
1278 FRONT_RIGHT,
1279 FRONT_CENTER,
1280 LOW_FREQUENCY
1281 ],
1282 channels_2f1, _2F1 => [
1283 FRONT_LEFT,
1284 FRONT_RIGHT,
1285 BACK_CENTER
1286 ],
1287 channels_2f1_lfe, _2F1_LFE => [
1288 FRONT_LEFT,
1289 FRONT_RIGHT,
1290 LOW_FREQUENCY,
1291 BACK_CENTER
1292 ],
1293 channels_3f1, _3F1 => [
1294 FRONT_LEFT,
1295 FRONT_RIGHT,
1296 FRONT_CENTER,
1297 BACK_CENTER
1298 ],
1299 channels_3f1_lfe, _3F1_LFE => [
1300 FRONT_LEFT,
1301 FRONT_RIGHT,
1302 FRONT_CENTER,
1303 LOW_FREQUENCY,
1304 BACK_CENTER
1305 ],
1306 channels_2f2, _2F2 => [
1307 FRONT_LEFT,
1308 FRONT_RIGHT,
1309 SIDE_LEFT,
1310 SIDE_RIGHT
1311 ],
1312 channels_2f2_lfe, _2F2_LFE => [
1313 FRONT_LEFT,
1314 FRONT_RIGHT,
1315 LOW_FREQUENCY,
1316 SIDE_LEFT,
1317 SIDE_RIGHT
1318 ],
1319 channels_quad, QUAD => [
1320 FRONT_LEFT,
1321 FRONT_RIGHT,
1322 BACK_LEFT,
1323 BACK_RIGHT
1324 ],
1325 channels_quad_lfe, QUAD_LFE => [
1326 FRONT_LEFT,
1327 FRONT_RIGHT,
1328 LOW_FREQUENCY,
1329 BACK_LEFT,
1330 BACK_RIGHT
1331 ],
1332 channels_3f2, _3F2 => [
1333 FRONT_LEFT,
1334 FRONT_RIGHT,
1335 FRONT_CENTER,
1336 SIDE_LEFT,
1337 SIDE_RIGHT
1338 ],
1339 channels_3f2_lfe, _3F2_LFE => [
1340 FRONT_LEFT,
1341 FRONT_RIGHT,
1342 FRONT_CENTER,
1343 LOW_FREQUENCY,
1344 SIDE_LEFT,
1345 SIDE_RIGHT
1346 ],
1347 channels_3f2_back, _3F2_BACK => [
1348 FRONT_LEFT,
1349 FRONT_RIGHT,
1350 FRONT_CENTER,
1351 BACK_LEFT,
1352 BACK_RIGHT
1353 ],
1354 channels_3f2_lfe_back, _3F2_LFE_BACK => [
1355 FRONT_LEFT,
1356 FRONT_RIGHT,
1357 FRONT_CENTER,
1358 LOW_FREQUENCY,
1359 BACK_LEFT,
1360 BACK_RIGHT
1361 ],
1362 channels_3f3r_lfe, _3F3R_LFE => [
1363 FRONT_LEFT,
1364 FRONT_RIGHT,
1365 FRONT_CENTER,
1366 LOW_FREQUENCY,
1367 BACK_CENTER,
1368 SIDE_LEFT,
1369 SIDE_RIGHT
1370 ],
1371 channels_3f4_lfe, _3F4_LFE => [
1372 FRONT_LEFT,
1373 FRONT_RIGHT,
1374 FRONT_CENTER,
1375 LOW_FREQUENCY,
1376 BACK_LEFT,
1377 BACK_RIGHT,
1378 SIDE_LEFT,
1379 SIDE_RIGHT
1380 ]
1381 }
1382
1383 #[test]
1384 fn mono_channels_enumerate() {
1385 let layout = ChannelLayout::MONO;
1386 let mut iter = super::channel_layout_iter(layout).enumerate();
1387 assert_eq!(Some((0, ChannelLayout::FRONT_CENTER)), iter.next());
1388 assert_eq!(None, iter.next());
1389 }
1390
1391 #[test]
1392 fn stereo_channels_enumerate() {
1393 let layout = ChannelLayout::STEREO;
1394 let mut iter = super::channel_layout_iter(layout).enumerate();
1395 assert_eq!(Some((0, ChannelLayout::FRONT_LEFT)), iter.next());
1396 assert_eq!(Some((1, ChannelLayout::FRONT_RIGHT)), iter.next());
1397 assert_eq!(None, iter.next());
1398 }
1399
1400 #[test]
1401 fn quad_channels_enumerate() {
1402 let layout = ChannelLayout::QUAD;
1403 let mut iter = super::channel_layout_iter(layout).enumerate();
1404 assert_eq!(Some((0, ChannelLayout::FRONT_LEFT)), iter.next());
1405 assert_eq!(Some((1, ChannelLayout::FRONT_RIGHT)), iter.next());
1406 assert_eq!(Some((2, ChannelLayout::BACK_LEFT)), iter.next());
1407 assert_eq!(Some((3, ChannelLayout::BACK_RIGHT)), iter.next());
1408 assert_eq!(None, iter.next());
1409 }
1410
1411 macro_rules! map_channel_tests {
1412 {$($name: ident, $layout: ident => [ $($channels: ident),* ]),+} => {
1413 $(
1414 #[test]
1415 fn $name() {
1416 let map = layout_to_channel_map(ChannelLayout::$layout);
1417 assert_eq!(map.channels, map_channel_tests!(__COUNT__ $($channels)*));
1418 map_channel_tests!(__EACH__ map, 0, $($channels)*);
1419 }
1420
1421 )*
1422 };
1423 (__COUNT__) => (0u8);
1424 (__COUNT__ $x:ident $($xs: ident)*) => (1u8 + map_channel_tests!(__COUNT__ $($xs)*));
1425 (__EACH__ $map:expr, $i:expr, ) => {};
1426 (__EACH__ $map:expr, $i:expr, $x:ident $($xs: ident)*) => {
1427 assert_eq!($map.map[$i], $x);
1428 map_channel_tests!(__EACH__ $map, $i+1, $($xs)* );
1429 };
1430 }
1431
1432 map_channel_tests! {
1433 map_channel_mono, MONO => [
1434 PA_CHANNEL_POSITION_MONO
1435 ],
1436 map_channel_mono_lfe, MONO_LFE => [
1437 PA_CHANNEL_POSITION_FRONT_CENTER,
1438 PA_CHANNEL_POSITION_LFE
1439 ],
1440 map_channel_stereo, STEREO => [
1441 PA_CHANNEL_POSITION_FRONT_LEFT,
1442 PA_CHANNEL_POSITION_FRONT_RIGHT
1443 ],
1444 map_channel_stereo_lfe, STEREO_LFE => [
1445 PA_CHANNEL_POSITION_FRONT_LEFT,
1446 PA_CHANNEL_POSITION_FRONT_RIGHT,
1447 PA_CHANNEL_POSITION_LFE
1448 ],
1449 map_channel_3f, _3F => [
1450 PA_CHANNEL_POSITION_FRONT_LEFT,
1451 PA_CHANNEL_POSITION_FRONT_RIGHT,
1452 PA_CHANNEL_POSITION_FRONT_CENTER
1453 ],
1454 map_channel_3f_lfe, _3F_LFE => [
1455 PA_CHANNEL_POSITION_FRONT_LEFT,
1456 PA_CHANNEL_POSITION_FRONT_RIGHT,
1457 PA_CHANNEL_POSITION_FRONT_CENTER,
1458 PA_CHANNEL_POSITION_LFE
1459 ],
1460 map_channel_2f1, _2F1 => [
1461 PA_CHANNEL_POSITION_FRONT_LEFT,
1462 PA_CHANNEL_POSITION_FRONT_RIGHT,
1463 PA_CHANNEL_POSITION_REAR_CENTER
1464 ],
1465 map_channel_2f1_lfe, _2F1_LFE => [
1466 PA_CHANNEL_POSITION_FRONT_LEFT,
1467 PA_CHANNEL_POSITION_FRONT_RIGHT,
1468 PA_CHANNEL_POSITION_LFE,
1469 PA_CHANNEL_POSITION_REAR_CENTER
1470 ],
1471 map_channel_3f1, _3F1 => [
1472 PA_CHANNEL_POSITION_FRONT_LEFT,
1473 PA_CHANNEL_POSITION_FRONT_RIGHT,
1474 PA_CHANNEL_POSITION_FRONT_CENTER,
1475 PA_CHANNEL_POSITION_REAR_CENTER
1476 ],
1477 map_channel_3f1_lfe, _3F1_LFE =>[
1478 PA_CHANNEL_POSITION_FRONT_LEFT,
1479 PA_CHANNEL_POSITION_FRONT_RIGHT,
1480 PA_CHANNEL_POSITION_FRONT_CENTER,
1481 PA_CHANNEL_POSITION_LFE,
1482 PA_CHANNEL_POSITION_REAR_CENTER
1483 ],
1484 map_channel_2f2, _2F2 => [
1485 PA_CHANNEL_POSITION_FRONT_LEFT,
1486 PA_CHANNEL_POSITION_FRONT_RIGHT,
1487 PA_CHANNEL_POSITION_SIDE_LEFT,
1488 PA_CHANNEL_POSITION_SIDE_RIGHT
1489 ],
1490 map_channel_2f2_lfe, _2F2_LFE => [
1491 PA_CHANNEL_POSITION_FRONT_LEFT,
1492 PA_CHANNEL_POSITION_FRONT_RIGHT,
1493 PA_CHANNEL_POSITION_LFE,
1494 PA_CHANNEL_POSITION_SIDE_LEFT,
1495 PA_CHANNEL_POSITION_SIDE_RIGHT
1496 ],
1497 map_channel_quad, QUAD => [
1498 PA_CHANNEL_POSITION_FRONT_LEFT,
1499 PA_CHANNEL_POSITION_FRONT_RIGHT,
1500 PA_CHANNEL_POSITION_REAR_LEFT,
1501 PA_CHANNEL_POSITION_REAR_RIGHT
1502 ],
1503 map_channel_quad_lfe, QUAD_LFE => [
1504 PA_CHANNEL_POSITION_FRONT_LEFT,
1505 PA_CHANNEL_POSITION_FRONT_RIGHT,
1506 PA_CHANNEL_POSITION_LFE,
1507 PA_CHANNEL_POSITION_REAR_LEFT,
1508 PA_CHANNEL_POSITION_REAR_RIGHT
1509 ],
1510 map_channel_3f2, _3F2 => [
1511 PA_CHANNEL_POSITION_FRONT_LEFT,
1512 PA_CHANNEL_POSITION_FRONT_RIGHT,
1513 PA_CHANNEL_POSITION_FRONT_CENTER,
1514 PA_CHANNEL_POSITION_SIDE_LEFT,
1515 PA_CHANNEL_POSITION_SIDE_RIGHT
1516 ],
1517 map_channel_3f2_lfe, _3F2_LFE => [
1518 PA_CHANNEL_POSITION_FRONT_LEFT,
1519 PA_CHANNEL_POSITION_FRONT_RIGHT,
1520 PA_CHANNEL_POSITION_FRONT_CENTER,
1521 PA_CHANNEL_POSITION_LFE,
1522 PA_CHANNEL_POSITION_SIDE_LEFT,
1523 PA_CHANNEL_POSITION_SIDE_RIGHT
1524 ],
1525 map_channel_3f2_back, _3F2_BACK => [
1526 PA_CHANNEL_POSITION_FRONT_LEFT,
1527 PA_CHANNEL_POSITION_FRONT_RIGHT,
1528 PA_CHANNEL_POSITION_FRONT_CENTER,
1529 PA_CHANNEL_POSITION_REAR_LEFT,
1530 PA_CHANNEL_POSITION_REAR_RIGHT
1531 ],
1532 map_channel_3f2_lfe_back, _3F2_LFE_BACK => [
1533 PA_CHANNEL_POSITION_FRONT_LEFT,
1534 PA_CHANNEL_POSITION_FRONT_RIGHT,
1535 PA_CHANNEL_POSITION_FRONT_CENTER,
1536 PA_CHANNEL_POSITION_LFE,
1537 PA_CHANNEL_POSITION_REAR_LEFT,
1538 PA_CHANNEL_POSITION_REAR_RIGHT
1539 ],
1540 map_channel_3f3r_lfe, _3F3R_LFE => [
1541 PA_CHANNEL_POSITION_FRONT_LEFT,
1542 PA_CHANNEL_POSITION_FRONT_RIGHT,
1543 PA_CHANNEL_POSITION_FRONT_CENTER,
1544 PA_CHANNEL_POSITION_LFE,
1545 PA_CHANNEL_POSITION_REAR_CENTER,
1546 PA_CHANNEL_POSITION_SIDE_LEFT,
1547 PA_CHANNEL_POSITION_SIDE_RIGHT
1548 ],
1549 map_channel_3f4_lfe, _3F4_LFE => [
1550 PA_CHANNEL_POSITION_FRONT_LEFT,
1551 PA_CHANNEL_POSITION_FRONT_RIGHT,
1552 PA_CHANNEL_POSITION_FRONT_CENTER,
1553 PA_CHANNEL_POSITION_LFE,
1554 PA_CHANNEL_POSITION_REAR_LEFT,
1555 PA_CHANNEL_POSITION_REAR_RIGHT,
1556 PA_CHANNEL_POSITION_SIDE_LEFT,
1557 PA_CHANNEL_POSITION_SIDE_RIGHT
1558 ]
1559 }
1560 }