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
631 // Restarting a stream that is still draining is a cubeb API contract
632 // violation: the pending drain_timer holds a pointer to this stream,
633 // and re-prerolling would arm a second timer and leak the first.
634 if !self.drain_timer.load(Ordering::Acquire).is_null() {
635 cubeb_log!("Rejecting start() on a draining stream");
636 return Err(Error::error());
637 }
638
639 self.shutdown = false;
640 self.cork(CorkState::uncork() | CorkState::notify());
641
642 if self.output_stream.is_some() {
643 /* When doing output-only or duplex, we need to manually call user cb once in order to
644 * make things roll. This is done via a defer event in order to execute it from PA
645 * server thread. */
646 self.context.mainloop.lock();
647 self.context
648 .mainloop
649 .get_api()
650 .once(output_preroll, self as *const _ as *mut _);
651 self.context.mainloop.unlock();
652 }
653
654 Ok(())
655 }
656
657 fn stop(&mut self) -> Result<()> {
658 {
659 self.context.mainloop.lock();
660 self.shutdown = true;
661 // If draining is taking place wait to finish
662 cubeb_log!("Stream stop: waiting for drain");
663 while !self.drain_timer.load(Ordering::Acquire).is_null() {
664 self.context.mainloop.wait();
665 }
666 cubeb_log!("Stream stop: waited for drain");
667 self.context.mainloop.unlock();
668 }
669 self.cork(CorkState::cork() | CorkState::notify());
670
671 Ok(())
672 }
673
674 fn position(&mut self) -> Result<u64> {
675 let in_thread = self.context.mainloop.in_thread();
676
677 if !in_thread {
678 self.context.mainloop.lock();
679 }
680
681 if self.output_stream.is_none() {
682 cubeb_log!("Calling position() on an input-only stream");
683 return Err(Error::error());
684 }
685
686 let stm = self.output_stream.as_ref().unwrap();
687 let r = match stm.get_time() {
688 Ok(r_usec) => {
689 let bytes = USecExt::to_bytes(r_usec, &self.output_sample_spec);
690 Ok((bytes / self.output_sample_spec.frame_size()) as u64)
691 }
692 Err(_) => {
693 cubeb_log!("Error: stm.get_time failed");
694 Err(Error::error())
695 }
696 };
697
698 if !in_thread {
699 self.context.mainloop.unlock();
700 }
701
702 r
703 }
704
705 fn latency(&mut self) -> Result<u32> {
706 match self.output_stream {
707 None => {
708 cubeb_log!("Error: calling latency() on an input-only stream");
709 Err(Error::error())
710 }
711 Some(ref stm) => match stm.get_latency() {
712 Ok(StreamLatency::Positive(r_usec)) => {
713 let latency = (r_usec * pa_usec_t::from(self.output_sample_spec.rate)
714 / PA_USEC_PER_SEC) as u32;
715 Ok(latency)
716 }
717 Ok(_) => {
718 panic!("Can not handle negative latency values.");
719 }
720 Err(_) => {
721 cubeb_log!("Error: get_latency() failed for an output stream");
722 Err(Error::error())
723 }
724 },
725 }
726 }
727
728 fn input_latency(&mut self) -> Result<u32> {
729 match self.input_stream {
730 None => {
731 cubeb_log!("Error: calling input_latency() on an output-only stream");
732 Err(Error::error())
733 }
734 Some(ref stm) => match stm.get_latency() {
735 Ok(StreamLatency::Positive(w_usec)) => {
736 let latency = (w_usec * pa_usec_t::from(self.input_sample_spec.rate)
737 / PA_USEC_PER_SEC) as u32;
738 Ok(latency)
739 }
740 // Input stream can be negative only if it is attached to a
741 // monitor source device
742 Ok(StreamLatency::Negative(_)) => Ok(0),
743 Err(_) => {
744 cubeb_log!("Error: stm.get_latency() failed for an input stream");
745 Err(Error::error())
746 }
747 },
748 }
749 }
750
751 fn set_volume(&mut self, volume: f32) -> Result<()> {
752 match self.output_stream {
753 None => {
754 cubeb_log!("Error: can't set volume on an input-only stream");
755 Err(Error::error())
756 }
757 Some(ref stm) => {
758 if let Some(ref context) = self.context.context {
759 self.context.mainloop.lock();
760
761 let mut cvol: pa_cvolume = Default::default();
762
763 /* if the pulse daemon is configured to use flat
764 * volumes, apply our own gain instead of changing
765 * the input volume on the sink. */
766 let flags = {
767 match self.context.default_sink_info {
768 Some(ref info) => info.flags,
769 _ => pulse::SinkFlags::empty(),
770 }
771 };
772
773 if flags.contains(pulse::SinkFlags::FLAT_VOLUME) {
774 self.volume = volume;
775 } else {
776 let channels = stm.get_sample_spec().channels;
777 let vol = pulse::sw_volume_from_linear(f64::from(volume));
778 cvol.set(u32::from(channels), vol);
779
780 let index = stm.get_index();
781
782 let context_ptr = self.context as *const _ as *mut _;
783 if let Ok(o) = context.set_sink_input_volume(
784 index,
785 &cvol,
786 context_success,
787 context_ptr,
788 ) {
789 self.context.operation_wait(stm, &o);
790 }
791 }
792
793 self.context.mainloop.unlock();
794 Ok(())
795 } else {
796 cubeb_log!("Error: set_volume: no context?");
797 Err(Error::error())
798 }
799 }
800 }
801 }
802
803 fn set_name(&mut self, name: &CStr) -> Result<()> {
804 match self.output_stream {
805 None => {
806 cubeb_log!("Error: can't set the name on a input-only stream.");
807 Err(Error::error())
808 }
809 Some(ref stm) => {
810 self.context.mainloop.lock();
811 if let Ok(o) = stm.set_name(name, stream_success, self as *const _ as *mut _) {
812 self.context.operation_wait(stm, &o);
813 }
814 self.context.mainloop.unlock();
815 Ok(())
816 }
817 }
818 }
819
820 fn current_device(&mut self) -> Result<&DeviceRef> {
821 if self.context.version_0_9_8 {
822 let mut dev: Box<ffi::cubeb_device> = Box::new(unsafe { mem::zeroed() });
823
824 if let Some(ref stm) = self.input_stream {
825 dev.input_name = match stm.get_device_name() {
826 Ok(name) => name.to_owned().into_raw(),
827 Err(_) => {
828 cubeb_log!("Error: couldn't get the input stream's device name");
829 return Err(Error::error());
830 }
831 }
832 }
833
834 if let Some(ref stm) = self.output_stream {
835 dev.output_name = match stm.get_device_name() {
836 Ok(name) => name.to_owned().into_raw(),
837 Err(_) => {
838 cubeb_log!("Error: couldn't get the output stream's device name");
839 return Err(Error::error());
840 }
841 }
842 }
843
844 Ok(unsafe { DeviceRef::from_ptr(Box::into_raw(dev) as *mut _) })
845 } else {
846 cubeb_log!("Error: PulseAudio context too old");
847 Err(not_supported())
848 }
849 }
850
851 fn set_input_mute(&mut self, _mute: bool) -> Result<()> {
852 Err(not_supported())
853 }
854
855 fn set_input_processing_params(&mut self, _params: InputProcessingParams) -> Result<()> {
856 Err(not_supported())
857 }
858
859 fn device_destroy(&mut self, device: &DeviceRef) -> Result<()> {
860 if device.as_ptr().is_null() {
861 cubeb_log!("Error: can't destroy null device");
862 Err(Error::error())
863 } else {
864 unsafe {
865 let _: Box<Device> = Box::from_raw(device.as_ptr() as *mut _);
866 }
867 Ok(())
868 }
869 }
870
871 fn register_device_changed_callback(
872 &mut self,
873 _: ffi::cubeb_device_changed_callback,
874 ) -> Result<()> {
875 cubeb_log!("Error: register_device_change_callback unimplemented");
876 Err(Error::error())
877 }
878 }
879
880 impl<'ctx> PulseStream<'ctx> {
881 fn stream_init(
882 context: &pulse::Context,
883 stream_params: &StreamParamsRef,
884 stream_name: Option<&CStr>,
885 ) -> Result<pulse::Stream> {
886 if stream_params.prefs() == StreamPrefs::LOOPBACK {
887 cubeb_log!("Error: StreamPref::LOOPBACK unimplemented");
888 return Err(not_supported());
889 }
890
891 fn to_pulse_format(format: SampleFormat) -> pulse::SampleFormat {
892 match format {
893 SampleFormat::S16LE => pulse::SampleFormat::Signed16LE,
894 SampleFormat::S16BE => pulse::SampleFormat::Signed16BE,
895 SampleFormat::Float32LE => pulse::SampleFormat::Float32LE,
896 SampleFormat::Float32BE => pulse::SampleFormat::Float32BE,
897 _ => pulse::SampleFormat::Invalid,
898 }
899 }
900
901 let fmt = to_pulse_format(stream_params.format());
902 if fmt == pulse::SampleFormat::Invalid {
903 cubeb_log!("Error: invalid sample format");
904 return Err(invalid_format());
905 }
906
907 let ss = pulse::SampleSpec {
908 channels: stream_params.channels() as u8,
909 format: fmt.into(),
910 rate: stream_params.rate(),
911 };
912
913 let cm: Option<pa_channel_map> = match stream_params.layout() {
914 ChannelLayout::UNDEFINED => {
915 if stream_params.channels() <= 8
916 && pulse::ChannelMap::init_auto(
917 stream_params.channels(),
918 PA_CHANNEL_MAP_DEFAULT,
919 )
920 .is_none()
921 {
922 cubeb_log!("Layout undefined and PulseAudio's default layout has not been configured, guess one.");
923 Some(layout_to_channel_map(default_layout_for_channels(
924 stream_params.channels(),
925 )))
926 } else {
927 cubeb_log!("Layout undefined, PulseAudio will use its default.");
928 None
929 }
930 }
931 _ => Some(layout_to_channel_map(stream_params.layout())),
932 };
933
934 let stream = pulse::Stream::new(context, stream_name.unwrap(), &ss, cm.as_ref());
935
936 match stream {
937 None => {
938 cubeb_log!("Error: pulse::Stream::new failure");
939 Err(Error::error())
940 }
941 Some(stm) => Ok(stm),
942 }
943 }
944
945 pub fn cork_stream(&self, stream: Option<&pulse::Stream>, state: CorkState) {
946 if let Some(stm) = stream {
947 if let Ok(o) = stm.cork(
948 state.is_cork() as i32,
949 stream_success,
950 self as *const _ as *mut _,
951 ) {
952 self.context.operation_wait(stream, &o);
953 }
954 }
955 }
956
957 fn cork(&mut self, state: CorkState) {
958 {
959 self.context.mainloop.lock();
960 self.cork_stream(self.output_stream.as_ref(), state);
961 self.cork_stream(self.input_stream.as_ref(), state);
962 self.context.mainloop.unlock()
963 }
964
965 if state.is_notify() {
966 self.state_change_callback(if state.is_cork() {
967 ffi::CUBEB_STATE_STOPPED
968 } else {
969 ffi::CUBEB_STATE_STARTED
970 });
971 }
972 }
973
974 fn update_timing_info(&self) -> bool {
975 let mut r = false;
976
977 if let Some(ref stm) = self.output_stream {
978 if let Ok(o) = stm.update_timing_info(stream_success, self as *const _ as *mut _) {
979 r = self.context.operation_wait(stm, &o);
980 }
981
982 if !r {
983 return r;
984 }
985 }
986
987 if let Some(ref stm) = self.input_stream {
988 if let Ok(o) = stm.update_timing_info(stream_success, self as *const _ as *mut _) {
989 r = self.context.operation_wait(stm, &o);
990 }
991 }
992
993 r
994 }
995
996 pub fn state_change_callback(&mut self, s: ffi::cubeb_state) {
997 self.state = s;
998 unsafe {
999 (self.state_callback.unwrap())(
1000 self as *mut PulseStream as *mut ffi::cubeb_stream,
1001 self.user_ptr,
1002 s,
1003 )
1004 };
1005 }
1006
1007 fn wait_until_ready(&self) -> bool {
1008 fn wait_until_io_stream_ready(
1009 stm: &pulse::Stream,
1010 mainloop: &pulse::ThreadedMainloop,
1011 ) -> bool {
1012 if mainloop.is_null() {
1013 return false;
1014 }
1015
1016 loop {
1017 let state = stm.get_state();
1018 if !state.is_good() {
1019 return false;
1020 }
1021 if state == pulse::StreamState::Ready {
1022 break;
1023 }
1024 mainloop.wait();
1025 }
1026
1027 true
1028 }
1029
1030 if let Some(ref stm) = self.output_stream {
1031 if !wait_until_io_stream_ready(stm, &self.context.mainloop) {
1032 return false;
1033 }
1034 }
1035
1036 if let Some(ref stm) = self.input_stream {
1037 if !wait_until_io_stream_ready(stm, &self.context.mainloop) {
1038 return false;
1039 }
1040 }
1041
1042 true
1043 }
1044
1045 #[allow(clippy::cognitive_complexity)]
1046 fn trigger_user_callback(&mut self, input_data: *const c_void, nbytes: usize) {
1047 fn drained_cb(
1048 a: &pulse::MainloopApi,
1049 e: *mut pa_time_event,
1050 _tv: &pulse::TimeVal,
1051 u: *mut c_void,
1052 ) {
1053 cubeb_logv!("Drain finished callback.");
1054 let stm = unsafe { &mut *(u as *mut PulseStream) };
1055 let drain_timer = stm.drain_timer.load(Ordering::Acquire);
1056 debug_assert_eq!(drain_timer, e);
1057 stm.state_change_callback(ffi::CUBEB_STATE_DRAINED);
1058 /* there's no pa_rttime_free, so use this instead. */
1059 a.time_free(drain_timer);
1060 stm.drain_timer.store(ptr::null_mut(), Ordering::Release);
1061 stm.context.mainloop.signal();
1062 }
1063
1064 if let Some(ref stm) = self.output_stream {
1065 let frame_size = self.output_sample_spec.frame_size();
1066 debug_assert_eq!(nbytes % frame_size, 0);
1067
1068 let mut towrite = nbytes;
1069 let mut read_offset = 0usize;
1070 while towrite > 0 {
1071 match stm.begin_write(towrite) {
1072 Err(e) => {
1073 cubeb_logv!("Error: failure to write data");
1074 panic!("Failed to write data: {}", e);
1075 }
1076 Ok((buffer, size)) => {
1077 debug_assert!(size > 0);
1078 debug_assert_eq!(size % frame_size, 0);
1079
1080 cubeb_logv!(
1081 "Trigger user callback with output buffer size={}, read_offset={}",
1082 size,
1083 read_offset
1084 );
1085 let read_ptr = unsafe { (input_data as *const u8).add(read_offset) };
1086 #[allow(clippy::unnecessary_cast)]
1087 let mut got = unsafe {
1088 self.data_callback.unwrap()(
1089 self as *const _ as *mut _,
1090 self.user_ptr,
1091 read_ptr as *const _ as *mut _,
1092 buffer,
1093 (size / frame_size) as c_long,
1094 ) as i64
1095 };
1096 if got < 0 {
1097 let _ = stm.cancel_write();
1098 self.shutdown = true;
1099 unsafe {
1100 self.state_callback.unwrap()(
1101 self as *const _ as *mut _,
1102 self.user_ptr,
1103 ffi::CUBEB_STATE_ERROR,
1104 );
1105 }
1106 return;
1107 }
1108
1109 // If more iterations move offset of read buffer
1110 if !input_data.is_null() {
1111 let in_frame_size = self.input_sample_spec.frame_size();
1112 read_offset += (size / frame_size) * in_frame_size;
1113 }
1114
1115 if self.volume != PULSE_NO_GAIN {
1116 let samples = (self.output_sample_spec.channels as usize * size
1117 / frame_size) as isize;
1118
1119 if self.output_sample_spec.format == PA_SAMPLE_S16BE
1120 || self.output_sample_spec.format == PA_SAMPLE_S16LE
1121 {
1122 let b = buffer as *mut i16;
1123 for i in 0..samples {
1124 unsafe { *b.offset(i) *= self.volume as i16 };
1125 }
1126 } else {
1127 let b = buffer as *mut f32;
1128 for i in 0..samples {
1129 unsafe { *b.offset(i) *= self.volume };
1130 }
1131 }
1132 }
1133
1134 let should_drain = (got as usize) < size / frame_size;
1135
1136 if should_drain && self.output_frame_count.load(Ordering::SeqCst) == 0 {
1137 // Draining during preroll, ensure `prebuf` frames are written so
1138 // the stream starts. If not, pad with a bit of silence.
1139 let prebuf_size_bytes = stm.get_buffer_attr().prebuf as usize;
1140 let got_bytes = got as usize * frame_size;
1141 if prebuf_size_bytes > got_bytes {
1142 let padding_bytes = prebuf_size_bytes - got_bytes;
1143 if padding_bytes + got_bytes <= size {
1144 // A slice that starts after the data provided by the callback,
1145 // with just enough room to provide a final buffer big enough.
1146 let padding_buf: &mut [u8] = unsafe {
1147 slice::from_raw_parts_mut::<u8>(
1148 buffer.add(got_bytes) as *mut u8,
1149 padding_bytes,
1150 )
1151 };
1152 padding_buf.fill(0);
1153 got += (padding_bytes / frame_size) as i64;
1154 }
1155 } else {
1156 cubeb_logv!(
1157 "Not enough room to pad up to prebuf when prebuffering."
1158 )
1159 }
1160 }
1161
1162 let r = stm.write(
1163 buffer,
1164 got as usize * frame_size,
1165 0,
1166 pulse::SeekMode::Relative,
1167 );
1168
1169 if should_drain {
1170 cubeb_logv!("Draining {} < {}", got, size / frame_size);
1171 let latency = match stm.get_latency() {
1172 Ok(StreamLatency::Positive(l)) => l,
1173 Ok(_) => {
1174 panic!("Can not handle negative latency values.");
1175 }
1176 Err(e) => {
1177 debug_assert_eq!(
1178 e,
1179 pulse::ErrorCode::from_error_code(PA_ERR_NODATA)
1180 );
1181 /* this needs a better guess. */
1182 100 * PA_USEC_PER_MSEC
1183 }
1184 };
1185
1186 /* pa_stream_drain is useless, see PA bug# 866. this is a workaround. */
1187 /* arbitrary safety margin: double the current latency. */
1188 assert!(
1189 self.drain_timer.load(Ordering::Acquire).is_null(),
1190 "drain timer already armed; stream restarted while draining"
1191 );
1192 let stream_ptr = self as *const _ as *mut _;
1193 if let Some(ref context) = self.context.context {
1194 self.drain_timer.store(
1195 context.rttime_new(
1196 pulse::rtclock_now() + 2 * latency,
1197 drained_cb,
1198 stream_ptr,
1199 ),
1200 Ordering::Release,
1201 );
1202 }
1203 self.shutdown = true;
1204 return;
1205 }
1206
1207 debug_assert!(r.is_ok());
1208
1209 towrite -= size;
1210 }
1211 }
1212 }
1213 debug_assert_eq!(towrite, 0);
1214 }
1215 }
1216 }
1217
1218 fn stream_success(_: &pulse::Stream, success: i32, u: *mut c_void) {
1219 let stm = unsafe { &*(u as *mut PulseStream) };
1220 if success != 1 {
1221 cubeb_log!("stream_success ignored failure: {}", success);
1222 }
1223 stm.context.mainloop.signal();
1224 }
1225
1226 fn context_success(_: &pulse::Context, success: i32, u: *mut c_void) {
1227 let ctx = unsafe { &*(u as *mut PulseContext) };
1228 if success != 1 {
1229 cubeb_log!("context_success ignored failure: {}", success);
1230 }
1231 ctx.mainloop.signal();
1232 }
1233
1234 fn invalid_format() -> Error {
1235 Error::from_raw(ffi::CUBEB_ERROR_INVALID_FORMAT)
1236 }
1237
1238 fn not_supported() -> Error {
1239 Error::from_raw(ffi::CUBEB_ERROR_NOT_SUPPORTED)
1240 }
1241
1242 #[cfg(all(test, not(feature = "pulse-dlopen")))]
1243 mod test {
1244 use super::layout_to_channel_map;
1245 use cubeb_backend::ChannelLayout;
1246 use pulse_ffi::*;
1247
1248 macro_rules! channel_tests {
1249 {$($name: ident, $layout: ident => [ $($channels: ident),* ]),+} => {
1250 $(
1251 #[test]
1252 fn $name() {
1253 let layout = ChannelLayout::$layout;
1254 let mut iter = super::channel_layout_iter(layout);
1255 $(
1256 assert_eq!(Some(ChannelLayout::$channels), iter.next());
1257 )*
1258 assert_eq!(None, iter.next());
1259 }
1260
1261 )*
1262 }
1263 }
1264
1265 channel_tests! {
1266 channels_unknown, UNDEFINED => [ ],
1267 channels_mono, MONO => [
1268 FRONT_CENTER
1269 ],
1270 channels_mono_lfe, MONO_LFE => [
1271 FRONT_CENTER,
1272 LOW_FREQUENCY
1273 ],
1274 channels_stereo, STEREO => [
1275 FRONT_LEFT,
1276 FRONT_RIGHT
1277 ],
1278 channels_stereo_lfe, STEREO_LFE => [
1279 FRONT_LEFT,
1280 FRONT_RIGHT,
1281 LOW_FREQUENCY
1282 ],
1283 channels_3f, _3F => [
1284 FRONT_LEFT,
1285 FRONT_RIGHT,
1286 FRONT_CENTER
1287 ],
1288 channels_3f_lfe, _3F_LFE => [
1289 FRONT_LEFT,
1290 FRONT_RIGHT,
1291 FRONT_CENTER,
1292 LOW_FREQUENCY
1293 ],
1294 channels_2f1, _2F1 => [
1295 FRONT_LEFT,
1296 FRONT_RIGHT,
1297 BACK_CENTER
1298 ],
1299 channels_2f1_lfe, _2F1_LFE => [
1300 FRONT_LEFT,
1301 FRONT_RIGHT,
1302 LOW_FREQUENCY,
1303 BACK_CENTER
1304 ],
1305 channels_3f1, _3F1 => [
1306 FRONT_LEFT,
1307 FRONT_RIGHT,
1308 FRONT_CENTER,
1309 BACK_CENTER
1310 ],
1311 channels_3f1_lfe, _3F1_LFE => [
1312 FRONT_LEFT,
1313 FRONT_RIGHT,
1314 FRONT_CENTER,
1315 LOW_FREQUENCY,
1316 BACK_CENTER
1317 ],
1318 channels_2f2, _2F2 => [
1319 FRONT_LEFT,
1320 FRONT_RIGHT,
1321 SIDE_LEFT,
1322 SIDE_RIGHT
1323 ],
1324 channels_2f2_lfe, _2F2_LFE => [
1325 FRONT_LEFT,
1326 FRONT_RIGHT,
1327 LOW_FREQUENCY,
1328 SIDE_LEFT,
1329 SIDE_RIGHT
1330 ],
1331 channels_quad, QUAD => [
1332 FRONT_LEFT,
1333 FRONT_RIGHT,
1334 BACK_LEFT,
1335 BACK_RIGHT
1336 ],
1337 channels_quad_lfe, QUAD_LFE => [
1338 FRONT_LEFT,
1339 FRONT_RIGHT,
1340 LOW_FREQUENCY,
1341 BACK_LEFT,
1342 BACK_RIGHT
1343 ],
1344 channels_3f2, _3F2 => [
1345 FRONT_LEFT,
1346 FRONT_RIGHT,
1347 FRONT_CENTER,
1348 SIDE_LEFT,
1349 SIDE_RIGHT
1350 ],
1351 channels_3f2_lfe, _3F2_LFE => [
1352 FRONT_LEFT,
1353 FRONT_RIGHT,
1354 FRONT_CENTER,
1355 LOW_FREQUENCY,
1356 SIDE_LEFT,
1357 SIDE_RIGHT
1358 ],
1359 channels_3f2_back, _3F2_BACK => [
1360 FRONT_LEFT,
1361 FRONT_RIGHT,
1362 FRONT_CENTER,
1363 BACK_LEFT,
1364 BACK_RIGHT
1365 ],
1366 channels_3f2_lfe_back, _3F2_LFE_BACK => [
1367 FRONT_LEFT,
1368 FRONT_RIGHT,
1369 FRONT_CENTER,
1370 LOW_FREQUENCY,
1371 BACK_LEFT,
1372 BACK_RIGHT
1373 ],
1374 channels_3f3r_lfe, _3F3R_LFE => [
1375 FRONT_LEFT,
1376 FRONT_RIGHT,
1377 FRONT_CENTER,
1378 LOW_FREQUENCY,
1379 BACK_CENTER,
1380 SIDE_LEFT,
1381 SIDE_RIGHT
1382 ],
1383 channels_3f4_lfe, _3F4_LFE => [
1384 FRONT_LEFT,
1385 FRONT_RIGHT,
1386 FRONT_CENTER,
1387 LOW_FREQUENCY,
1388 BACK_LEFT,
1389 BACK_RIGHT,
1390 SIDE_LEFT,
1391 SIDE_RIGHT
1392 ]
1393 }
1394
1395 #[test]
1396 fn mono_channels_enumerate() {
1397 let layout = ChannelLayout::MONO;
1398 let mut iter = super::channel_layout_iter(layout).enumerate();
1399 assert_eq!(Some((0, ChannelLayout::FRONT_CENTER)), iter.next());
1400 assert_eq!(None, iter.next());
1401 }
1402
1403 #[test]
1404 fn stereo_channels_enumerate() {
1405 let layout = ChannelLayout::STEREO;
1406 let mut iter = super::channel_layout_iter(layout).enumerate();
1407 assert_eq!(Some((0, ChannelLayout::FRONT_LEFT)), iter.next());
1408 assert_eq!(Some((1, ChannelLayout::FRONT_RIGHT)), iter.next());
1409 assert_eq!(None, iter.next());
1410 }
1411
1412 #[test]
1413 fn quad_channels_enumerate() {
1414 let layout = ChannelLayout::QUAD;
1415 let mut iter = super::channel_layout_iter(layout).enumerate();
1416 assert_eq!(Some((0, ChannelLayout::FRONT_LEFT)), iter.next());
1417 assert_eq!(Some((1, ChannelLayout::FRONT_RIGHT)), iter.next());
1418 assert_eq!(Some((2, ChannelLayout::BACK_LEFT)), iter.next());
1419 assert_eq!(Some((3, ChannelLayout::BACK_RIGHT)), iter.next());
1420 assert_eq!(None, iter.next());
1421 }
1422
1423 macro_rules! map_channel_tests {
1424 {$($name: ident, $layout: ident => [ $($channels: ident),* ]),+} => {
1425 $(
1426 #[test]
1427 fn $name() {
1428 let map = layout_to_channel_map(ChannelLayout::$layout);
1429 assert_eq!(map.channels, map_channel_tests!(__COUNT__ $($channels)*));
1430 map_channel_tests!(__EACH__ map, 0, $($channels)*);
1431 }
1432
1433 )*
1434 };
1435 (__COUNT__) => (0u8);
1436 (__COUNT__ $x:ident $($xs: ident)*) => (1u8 + map_channel_tests!(__COUNT__ $($xs)*));
1437 (__EACH__ $map:expr, $i:expr, ) => {};
1438 (__EACH__ $map:expr, $i:expr, $x:ident $($xs: ident)*) => {
1439 assert_eq!($map.map[$i], $x);
1440 map_channel_tests!(__EACH__ $map, $i+1, $($xs)* );
1441 };
1442 }
1443
1444 map_channel_tests! {
1445 map_channel_mono, MONO => [
1446 PA_CHANNEL_POSITION_MONO
1447 ],
1448 map_channel_mono_lfe, MONO_LFE => [
1449 PA_CHANNEL_POSITION_FRONT_CENTER,
1450 PA_CHANNEL_POSITION_LFE
1451 ],
1452 map_channel_stereo, STEREO => [
1453 PA_CHANNEL_POSITION_FRONT_LEFT,
1454 PA_CHANNEL_POSITION_FRONT_RIGHT
1455 ],
1456 map_channel_stereo_lfe, STEREO_LFE => [
1457 PA_CHANNEL_POSITION_FRONT_LEFT,
1458 PA_CHANNEL_POSITION_FRONT_RIGHT,
1459 PA_CHANNEL_POSITION_LFE
1460 ],
1461 map_channel_3f, _3F => [
1462 PA_CHANNEL_POSITION_FRONT_LEFT,
1463 PA_CHANNEL_POSITION_FRONT_RIGHT,
1464 PA_CHANNEL_POSITION_FRONT_CENTER
1465 ],
1466 map_channel_3f_lfe, _3F_LFE => [
1467 PA_CHANNEL_POSITION_FRONT_LEFT,
1468 PA_CHANNEL_POSITION_FRONT_RIGHT,
1469 PA_CHANNEL_POSITION_FRONT_CENTER,
1470 PA_CHANNEL_POSITION_LFE
1471 ],
1472 map_channel_2f1, _2F1 => [
1473 PA_CHANNEL_POSITION_FRONT_LEFT,
1474 PA_CHANNEL_POSITION_FRONT_RIGHT,
1475 PA_CHANNEL_POSITION_REAR_CENTER
1476 ],
1477 map_channel_2f1_lfe, _2F1_LFE => [
1478 PA_CHANNEL_POSITION_FRONT_LEFT,
1479 PA_CHANNEL_POSITION_FRONT_RIGHT,
1480 PA_CHANNEL_POSITION_LFE,
1481 PA_CHANNEL_POSITION_REAR_CENTER
1482 ],
1483 map_channel_3f1, _3F1 => [
1484 PA_CHANNEL_POSITION_FRONT_LEFT,
1485 PA_CHANNEL_POSITION_FRONT_RIGHT,
1486 PA_CHANNEL_POSITION_FRONT_CENTER,
1487 PA_CHANNEL_POSITION_REAR_CENTER
1488 ],
1489 map_channel_3f1_lfe, _3F1_LFE =>[
1490 PA_CHANNEL_POSITION_FRONT_LEFT,
1491 PA_CHANNEL_POSITION_FRONT_RIGHT,
1492 PA_CHANNEL_POSITION_FRONT_CENTER,
1493 PA_CHANNEL_POSITION_LFE,
1494 PA_CHANNEL_POSITION_REAR_CENTER
1495 ],
1496 map_channel_2f2, _2F2 => [
1497 PA_CHANNEL_POSITION_FRONT_LEFT,
1498 PA_CHANNEL_POSITION_FRONT_RIGHT,
1499 PA_CHANNEL_POSITION_SIDE_LEFT,
1500 PA_CHANNEL_POSITION_SIDE_RIGHT
1501 ],
1502 map_channel_2f2_lfe, _2F2_LFE => [
1503 PA_CHANNEL_POSITION_FRONT_LEFT,
1504 PA_CHANNEL_POSITION_FRONT_RIGHT,
1505 PA_CHANNEL_POSITION_LFE,
1506 PA_CHANNEL_POSITION_SIDE_LEFT,
1507 PA_CHANNEL_POSITION_SIDE_RIGHT
1508 ],
1509 map_channel_quad, QUAD => [
1510 PA_CHANNEL_POSITION_FRONT_LEFT,
1511 PA_CHANNEL_POSITION_FRONT_RIGHT,
1512 PA_CHANNEL_POSITION_REAR_LEFT,
1513 PA_CHANNEL_POSITION_REAR_RIGHT
1514 ],
1515 map_channel_quad_lfe, QUAD_LFE => [
1516 PA_CHANNEL_POSITION_FRONT_LEFT,
1517 PA_CHANNEL_POSITION_FRONT_RIGHT,
1518 PA_CHANNEL_POSITION_LFE,
1519 PA_CHANNEL_POSITION_REAR_LEFT,
1520 PA_CHANNEL_POSITION_REAR_RIGHT
1521 ],
1522 map_channel_3f2, _3F2 => [
1523 PA_CHANNEL_POSITION_FRONT_LEFT,
1524 PA_CHANNEL_POSITION_FRONT_RIGHT,
1525 PA_CHANNEL_POSITION_FRONT_CENTER,
1526 PA_CHANNEL_POSITION_SIDE_LEFT,
1527 PA_CHANNEL_POSITION_SIDE_RIGHT
1528 ],
1529 map_channel_3f2_lfe, _3F2_LFE => [
1530 PA_CHANNEL_POSITION_FRONT_LEFT,
1531 PA_CHANNEL_POSITION_FRONT_RIGHT,
1532 PA_CHANNEL_POSITION_FRONT_CENTER,
1533 PA_CHANNEL_POSITION_LFE,
1534 PA_CHANNEL_POSITION_SIDE_LEFT,
1535 PA_CHANNEL_POSITION_SIDE_RIGHT
1536 ],
1537 map_channel_3f2_back, _3F2_BACK => [
1538 PA_CHANNEL_POSITION_FRONT_LEFT,
1539 PA_CHANNEL_POSITION_FRONT_RIGHT,
1540 PA_CHANNEL_POSITION_FRONT_CENTER,
1541 PA_CHANNEL_POSITION_REAR_LEFT,
1542 PA_CHANNEL_POSITION_REAR_RIGHT
1543 ],
1544 map_channel_3f2_lfe_back, _3F2_LFE_BACK => [
1545 PA_CHANNEL_POSITION_FRONT_LEFT,
1546 PA_CHANNEL_POSITION_FRONT_RIGHT,
1547 PA_CHANNEL_POSITION_FRONT_CENTER,
1548 PA_CHANNEL_POSITION_LFE,
1549 PA_CHANNEL_POSITION_REAR_LEFT,
1550 PA_CHANNEL_POSITION_REAR_RIGHT
1551 ],
1552 map_channel_3f3r_lfe, _3F3R_LFE => [
1553 PA_CHANNEL_POSITION_FRONT_LEFT,
1554 PA_CHANNEL_POSITION_FRONT_RIGHT,
1555 PA_CHANNEL_POSITION_FRONT_CENTER,
1556 PA_CHANNEL_POSITION_LFE,
1557 PA_CHANNEL_POSITION_REAR_CENTER,
1558 PA_CHANNEL_POSITION_SIDE_LEFT,
1559 PA_CHANNEL_POSITION_SIDE_RIGHT
1560 ],
1561 map_channel_3f4_lfe, _3F4_LFE => [
1562 PA_CHANNEL_POSITION_FRONT_LEFT,
1563 PA_CHANNEL_POSITION_FRONT_RIGHT,
1564 PA_CHANNEL_POSITION_FRONT_CENTER,
1565 PA_CHANNEL_POSITION_LFE,
1566 PA_CHANNEL_POSITION_REAR_LEFT,
1567 PA_CHANNEL_POSITION_REAR_RIGHT,
1568 PA_CHANNEL_POSITION_SIDE_LEFT,
1569 PA_CHANNEL_POSITION_SIDE_RIGHT
1570 ]
1571 }
1572 }