Debian Codegraph @

third_party/rust/cubeb-coreaudio/src/backend/tests/manual.rs

raw
1 use super::utils::{
2 test_get_devices_in_scope, test_ops_context_operation, test_ops_stream_operation, Scope,
3 StreamType, TestDeviceInfo, TestDeviceSwitcher,
4 };
5 use super::*;
6 use std::io;
7
8 #[ignore]
9 #[test]
10 fn test_switch_output_device() {
11 use std::f32::consts::PI;
12
13 const SAMPLE_FREQUENCY: u32 = 48_000;
14
15 // Do nothing if there is no 2 available output devices at least.
16 let devices = test_get_devices_in_scope(Scope::Output);
17 if devices.len() < 2 {
18 println!("Need 2 output devices at least.");
19 return;
20 }
21
22 let mut output_device_switcher = TestDeviceSwitcher::new(Scope::Output);
23
24 // Make sure the parameters meet the requirements of AudioUnitContext::stream_init
25 // (in the comments).
26 let mut output_params = ffi::cubeb_stream_params::default();
27 output_params.format = ffi::CUBEB_SAMPLE_S16NE;
28 output_params.rate = SAMPLE_FREQUENCY;
29 output_params.channels = 1;
30 output_params.layout = ffi::CUBEB_LAYOUT_MONO;
31 output_params.prefs = ffi::CUBEB_STREAM_PREF_NONE;
32
33 // Used to calculate the tone's wave.
34 let mut position: i64 = 0; // TODO: Use Atomic instead.
35
36 test_ops_stream_operation(
37 "stream: North American dial tone",
38 ptr::null_mut(), // Use default input device.
39 ptr::null_mut(), // No input parameters.
40 ptr::null_mut(), // Use default output device.
41 &mut output_params,
42 4096, // TODO: Get latency by get_min_latency instead ?
43 Some(data_callback),
44 Some(state_callback),
45 &mut position as *mut i64 as *mut c_void,
46 |stream| {
47 assert_eq!(unsafe { OPS.stream_start.unwrap()(stream) }, ffi::CUBEB_OK);
48 println!("Start playing! Enter 's' to switch device. Enter 'q' to quit.");
49 loop {
50 let mut input = String::new();
51 let _ = io::stdin().read_line(&mut input);
52 assert_eq!(input.pop().unwrap(), '\n');
53 match input.as_str() {
54 "s" => {
55 output_device_switcher.next();
56 }
57 "q" => {
58 println!("Quit.");
59 break;
60 }
61 x => {
62 println!("Unknown command: {}", x);
63 }
64 }
65 }
66 assert_eq!(unsafe { OPS.stream_stop.unwrap()(stream) }, ffi::CUBEB_OK);
67 },
68 );
69
70 extern "C" fn state_callback(
71 stream: *mut ffi::cubeb_stream,
72 user_ptr: *mut c_void,
73 state: ffi::cubeb_state,
74 ) {
75 assert!(!stream.is_null());
76 assert!(!user_ptr.is_null());
77 assert_ne!(state, ffi::CUBEB_STATE_ERROR);
78 }
79
80 extern "C" fn data_callback(
81 stream: *mut ffi::cubeb_stream,
82 user_ptr: *mut c_void,
83 _input_buffer: *const c_void,
84 output_buffer: *mut c_void,
85 nframes: i64,
86 ) -> i64 {
87 assert!(!stream.is_null());
88 assert!(!user_ptr.is_null());
89 assert!(!output_buffer.is_null());
90
91 let buffer = unsafe {
92 let ptr = output_buffer as *mut i16;
93 let len = nframes as usize;
94 slice::from_raw_parts_mut(ptr, len)
95 };
96
97 let position = unsafe { &mut *(user_ptr as *mut i64) };
98
99 // Generate tone on the fly.
100 for data in buffer.iter_mut() {
101 let t1 = (2.0 * PI * 350.0 * (*position) as f32 / SAMPLE_FREQUENCY as f32).sin();
102 let t2 = (2.0 * PI * 440.0 * (*position) as f32 / SAMPLE_FREQUENCY as f32).sin();
103 *data = f32_to_i16_sample(0.5 * (t1 + t2));
104 *position += 1;
105 }
106
107 nframes
108 }
109
110 fn f32_to_i16_sample(x: f32) -> i16 {
111 (x * f32::from(i16::max_value())) as i16
112 }
113 }
114
115 #[ignore]
116 #[test]
117 fn test_device_collection_change() {
118 const DUMMY_PTR: *mut c_void = 0xDEAD_BEEF as *mut c_void;
119 let mut context = AudioUnitContext::new();
120 println!("Context allocated @ {:p}", &context);
121
122 extern "C" fn input_changed_callback(context: *mut ffi::cubeb, data: *mut c_void) {
123 println!(
124 "Input device collection @ {:p} is changed. Data @ {:p}",
125 context, data
126 );
127 assert_eq!(data, DUMMY_PTR);
128 }
129
130 extern "C" fn output_changed_callback(context: *mut ffi::cubeb, data: *mut c_void) {
131 println!(
132 "output device collection @ {:p} is changed. Data @ {:p}",
133 context, data
134 );
135 assert_eq!(data, DUMMY_PTR);
136 }
137
138 context.register_device_collection_changed(
139 DeviceType::INPUT,
140 Some(input_changed_callback),
141 DUMMY_PTR,
142 );
143
144 context.register_device_collection_changed(
145 DeviceType::OUTPUT,
146 Some(output_changed_callback),
147 DUMMY_PTR,
148 );
149
150 println!("Unplug/Plug device to see the event log.\nEnter anything to finish.");
151 let mut input = String::new();
152 let _ = std::io::stdin().read_line(&mut input);
153 }
154
155 struct StreamData {
156 stream_ptr: *mut ffi::cubeb_stream,
157 enable_loopback: AtomicBool,
158 }
159
160 impl StreamData {
161 fn new() -> Self {
162 Self {
163 stream_ptr: ptr::null_mut(),
164 enable_loopback: AtomicBool::new(false),
165 }
166 }
167 }
168
169 struct StreamsData {
170 streams: Vec<StreamData>,
171 current_idx: Option<usize>,
172 }
173
174 impl StreamsData {
175 fn new() -> Self {
176 Self {
177 streams: Vec::new(),
178 current_idx: None,
179 }
180 }
181
182 fn len(&self) -> usize {
183 self.streams.len()
184 }
185
186 fn current_mut(&mut self) -> &mut StreamData {
187 &mut self.streams[self.current_idx.unwrap()]
188 }
189
190 fn current(&self) -> &StreamData {
191 &self.streams[self.current_idx.unwrap()]
192 }
193
194 fn select(&mut self, idx: usize) {
195 assert!(idx < self.len());
196 self.current_idx = Some(idx);
197 }
198
199 fn push(&mut self, stream: StreamData) {
200 self.streams.push(stream)
201 }
202 }
203
204 #[ignore]
205 #[test]
206 fn test_stream_tester() {
207 test_ops_context_operation("context: stream tester", |context_ptr| {
208 let mut input_prefs = StreamPrefs::NONE;
209 let mut output_prefs = StreamPrefs::NONE;
210 let mut streams = StreamsData::new();
211 loop {
212 println!(
213 "Current stream: {} (of {}). Commands:\n\
214 \t'q': quit\n\
215 \t'b': change current stream\n\
216 \t'i': set input stream prefs to be used for creating streams\n\
217 \t'o': set output stream prefs to be used for creating streams\n\
218 \t'c': create a stream\n\
219 Commands on the current stream:\n\
220 \t'd': destroy\n\
221 \t's': start\n\
222 \t't': stop\n\
223 \t'r': register a device changed callback\n\
224 \t'l': set loopback (DUPLEX-only)\n\
225 \t'v': set volume\n\
226 \t'm': set input mute\n\
227 \t'p': set input processing",
228 streams
229 .current_idx
230 .map(|i| format!("{}", i + 1 as usize))
231 .unwrap_or(String::from("N/A")),
232 streams.len(),
233 );
234
235 let mut command = String::new();
236 let _ = io::stdin().read_line(&mut command);
237 assert_eq!(command.pop().unwrap(), '\n');
238
239 match command.as_str() {
240 "q" => {
241 println!("Quit.");
242 for mut stream in streams.streams {
243 if !stream.stream_ptr.is_null() {
244 destroy_stream(&mut stream);
245 }
246 }
247 break;
248 }
249 "i" => set_prefs(&mut input_prefs),
250 "o" => set_prefs(&mut output_prefs),
251 "c" => create_stream(context_ptr, &mut streams, input_prefs, output_prefs),
252 _ if streams.current_idx.is_none() => {
253 println!("There are no streams! Create a stream first.")
254 }
255 cmd => match cmd {
256 "b" => select_stream(&mut streams),
257 "d" => destroy_stream(streams.current_mut()),
258 "s" => start_stream(streams.current()),
259 "t" => stop_stream(streams.current()),
260 "r" => register_device_change_callback(streams.current()),
261 "l" => set_loopback(streams.current()),
262 "v" => set_volume(streams.current()),
263 "m" => set_input_mute(streams.current()),
264 "p" => set_input_processing(streams.current()),
265 x => println!("Unknown command: {}", x),
266 },
267 }
268 }
269 });
270
271 fn set_prefs(prefs: &mut StreamPrefs) {
272 let mut done = false;
273 while !done {
274 println!(
275 "Current prefs: {:?}\nSelect action:\n\
276 \t1) Set None\n\
277 \t2) Toggle Loopback\n\
278 \t3) Toggle Disable Device Switching\n\
279 \t4) Toggle Voice\n\
280 \t5) Set All\n\
281 \t0) Done",
282 prefs
283 );
284 let mut input = String::new();
285 let _ = io::stdin().read_line(&mut input);
286 assert_eq!(input.pop().unwrap(), '\n');
287 match input.as_str() {
288 "1" => *prefs = StreamPrefs::NONE,
289 "2" => prefs.toggle(StreamPrefs::LOOPBACK),
290 "3" => prefs.toggle(StreamPrefs::DISABLE_DEVICE_SWITCHING),
291 "4" => prefs.toggle(StreamPrefs::VOICE),
292 "5" => *prefs = StreamPrefs::all(),
293 "0" => done = true,
294 _ => println!("Invalid action. Select again.\n"),
295 }
296 }
297 }
298
299 fn select_stream(streams: &mut StreamsData) {
300 let num_streams = streams.len();
301 let current_idx = streams.current_idx.unwrap();
302 println!(
303 "Current stream is {}. Select stream 1 to {} on which to apply commands:",
304 current_idx + 1 as usize,
305 num_streams
306 );
307 let mut selection: Option<usize> = None;
308 while selection.is_none() {
309 let mut input = String::new();
310 let _ = io::stdin().read_line(&mut input);
311 assert_eq!(input.pop().unwrap(), '\n');
312 selection = match input.parse::<usize>() {
313 Ok(i) if (1..=num_streams).contains((&i).into()) => Some(i),
314 _ => {
315 println!("Invalid stream. Select again.\n");
316 None
317 }
318 }
319 }
320 streams.select(selection.unwrap() - 1)
321 }
322
323 fn start_stream(stream: &StreamData) {
324 if stream.stream_ptr.is_null() {
325 println!("No stream can start.");
326 return;
327 }
328 assert_eq!(
329 unsafe { OPS.stream_start.unwrap()(stream.stream_ptr) },
330 ffi::CUBEB_OK
331 );
332 println!("Stream {:p} started.", stream.stream_ptr);
333 }
334
335 fn stop_stream(stream: &StreamData) {
336 if stream.stream_ptr.is_null() {
337 println!("No stream can stop.");
338 return;
339 }
340 assert_eq!(
341 unsafe { OPS.stream_stop.unwrap()(stream.stream_ptr) },
342 ffi::CUBEB_OK
343 );
344 println!("Stream {:p} stopped.", stream.stream_ptr);
345 }
346
347 fn set_volume(stream: &StreamData) {
348 if stream.stream_ptr.is_null() {
349 println!("No stream can set volume.");
350 return;
351 }
352 const VOL: f32 = 0.5;
353 assert_eq!(
354 unsafe { OPS.stream_set_volume.unwrap()(stream.stream_ptr, VOL) },
355 ffi::CUBEB_OK
356 );
357 println!("Set stream {:p} volume to {}", stream.stream_ptr, VOL);
358 }
359
360 fn set_loopback(stream: &StreamData) {
361 if stream.stream_ptr.is_null() {
362 println!("No stream can set loopback.");
363 return;
364 }
365 let stm = unsafe { &mut *(stream.stream_ptr as *mut AudioUnitStream) };
366 if !stm.core_stream_data.has_input() || !stm.core_stream_data.has_output() {
367 println!("Duplex stream needed to set loopback");
368 return;
369 }
370 let mut loopback: Option<bool> = None;
371 while loopback.is_none() {
372 println!("Select action:\n1) Enable loopback, 2) Disable loopback");
373 let mut input = String::new();
374 let _ = io::stdin().read_line(&mut input);
375 assert_eq!(input.pop().unwrap(), '\n');
376 loopback = match input.as_str() {
377 "1" => Some(true),
378 "2" => Some(false),
379 _ => {
380 println!("Invalid action. Select again.\n");
381 None
382 }
383 }
384 }
385 let loopback = loopback.unwrap();
386 stream.enable_loopback.store(loopback, Ordering::SeqCst);
387 println!(
388 "Loopback {} for stream {:p}",
389 if loopback { "enabled" } else { "disabled" },
390 stream.stream_ptr
391 );
392 }
393
394 fn set_input_mute(stream: &StreamData) {
395 if stream.stream_ptr.is_null() {
396 println!("No stream can set input mute.");
397 return;
398 }
399 let stm = unsafe { &mut *(stream.stream_ptr as *mut AudioUnitStream) };
400 if !stm.core_stream_data.has_input() {
401 println!("Input stream needed to set loopback");
402 return;
403 }
404 let mut mute: Option<bool> = None;
405 while mute.is_none() {
406 println!("Select action:\n1) Mute, 2) Unmute");
407 let mut input = String::new();
408 let _ = io::stdin().read_line(&mut input);
409 assert_eq!(input.pop().unwrap(), '\n');
410 mute = match input.as_str() {
411 "1" => Some(true),
412 "2" => Some(false),
413 _ => {
414 println!("Invalid action. Select again.\n");
415 None
416 }
417 }
418 }
419 let mute = mute.unwrap();
420 let res = unsafe { OPS.stream_set_input_mute.unwrap()(stream.stream_ptr, mute.into()) };
421 println!(
422 "{} set stream {:p} input {}",
423 if res == ffi::CUBEB_OK {
424 "Successfully"
425 } else {
426 "Failed to"
427 },
428 stream.stream_ptr,
429 if mute { "mute" } else { "unmute" }
430 );
431 }
432
433 fn set_input_processing(stream: &StreamData) {
434 if stream.stream_ptr.is_null() {
435 println!("No stream can set input processing.");
436 return;
437 }
438 let stm = unsafe { &mut *(stream.stream_ptr as *mut AudioUnitStream) };
439 if !stm.core_stream_data.using_voice_processing_unit() {
440 println!("Duplex stream with voice processing needed to set input processing params");
441 return;
442 }
443 let mut params = InputProcessingParams::NONE;
444 run_serially(|| {
445 let mut bypass = u32::from(true);
446 let mut size: usize = mem::size_of::<u32>();
447 assert_eq!(
448 audio_unit_get_property(
449 stm.core_stream_data.input_unit,
450 kAudioUnitProperty_BypassEffect,
451 kAudioUnitScope_Global,
452 AU_IN_BUS,
453 &mut bypass,
454 &mut size,
455 ),
456 NO_ERR
457 );
458 assert_eq!(size, mem::size_of::<u32>());
459 if bypass == 0 {
460 params.set(InputProcessingParams::ECHO_CANCELLATION, true);
461 params.set(InputProcessingParams::NOISE_SUPPRESSION, true);
462 }
463 let mut agc = u32::from(false);
464 let mut size: usize = mem::size_of::<u32>();
465 assert_eq!(
466 audio_unit_get_property(
467 stm.core_stream_data.input_unit,
468 kAUVoiceIOProperty_VoiceProcessingEnableAGC,
469 kAudioUnitScope_Global,
470 AU_IN_BUS,
471 &mut agc,
472 &mut size,
473 ),
474 NO_ERR
475 );
476 assert_eq!(size, mem::size_of::<u32>());
477 if agc == 1 {
478 params.set(InputProcessingParams::AUTOMATIC_GAIN_CONTROL, true);
479 }
480 });
481 let mut done = false;
482 while !done {
483 println!(
484 "Supported params: {:?}\nCurrent params: {:?}\nSelect action:\n\
485 \t1) Set None\n\
486 \t2) Toggle Echo Cancellation\n\
487 \t3) Toggle Noise Suppression\n\
488 \t4) Toggle Automatic Gain Control\n\
489 \t5) Toggle Voice Isolation\n\
490 \t6) Set All\n\
491 \t0) Done",
492 stm.context.supported_input_processing_params().unwrap(),
493 params
494 );
495 let mut input = String::new();
496 let _ = io::stdin().read_line(&mut input);
497 assert_eq!(input.pop().unwrap(), '\n');
498 match input.as_str() {
499 "1" => params = InputProcessingParams::NONE,
500 "2" => params.toggle(InputProcessingParams::ECHO_CANCELLATION),
501 "3" => params.toggle(InputProcessingParams::NOISE_SUPPRESSION),
502 "4" => params.toggle(InputProcessingParams::AUTOMATIC_GAIN_CONTROL),
503 "5" => params.toggle(InputProcessingParams::VOICE_ISOLATION),
504 "6" => params = InputProcessingParams::all(),
505 "0" => done = true,
506 _ => println!("Invalid action. Select again.\n"),
507 }
508 }
509 let res = unsafe {
510 OPS.stream_set_input_processing_params.unwrap()(stream.stream_ptr, params.bits())
511 };
512 println!(
513 "{} set stream {:p} input processing params to {:?}",
514 if res == ffi::CUBEB_OK {
515 "Successfully"
516 } else {
517 "Failed to"
518 },
519 stream.stream_ptr,
520 params,
521 );
522 }
523
524 fn register_device_change_callback(stream: &StreamData) {
525 extern "C" fn callback(user_ptr: *mut c_void) {
526 println!("user pointer @ {:p}", user_ptr);
527 assert!(user_ptr.is_null());
528 }
529
530 if stream.stream_ptr.is_null() {
531 println!("No stream for registering the callback.");
532 return;
533 }
534 assert_eq!(
535 unsafe {
536 OPS.stream_register_device_changed_callback.unwrap()(
537 stream.stream_ptr,
538 Some(callback),
539 )
540 },
541 ffi::CUBEB_OK
542 );
543 println!(
544 "Stream {:p} now has a device change callback.",
545 stream.stream_ptr
546 );
547 }
548
549 fn destroy_stream(stream: &mut StreamData) {
550 if stream.stream_ptr.is_null() {
551 println!("No need to destroy stream.");
552 return;
553 }
554 unsafe {
555 OPS.stream_destroy.unwrap()((*stream).stream_ptr);
556 }
557 println!("Stream {:p} destroyed.", stream.stream_ptr);
558 stream.stream_ptr = ptr::null_mut();
559 }
560
561 fn create_stream(
562 context_ptr: *mut ffi::cubeb,
563 streams: &mut StreamsData,
564 input_prefs: StreamPrefs,
565 output_prefs: StreamPrefs,
566 ) {
567 if streams.len() == 0 || !streams.current().stream_ptr.is_null() {
568 println!("Allocating stream {}.", streams.len() + 1);
569 streams.push(StreamData::new());
570 streams.select(streams.len() - 1);
571 }
572
573 let stream = streams.current_mut();
574 if !stream.stream_ptr.is_null() {
575 println!("Stream has been created.");
576 return;
577 }
578
579 let mut stream_type = StreamType::empty();
580 while stream_type.is_empty() {
581 println!("Select stream type:\n1) Input 2) Output 3) In-Out Duplex 4) Back");
582 let mut input = String::new();
583 let _ = io::stdin().read_line(&mut input);
584 assert_eq!(input.pop().unwrap(), '\n');
585 stream_type = match input.as_str() {
586 "1" => StreamType::INPUT,
587 "2" => StreamType::OUTPUT,
588 "3" => StreamType::DUPLEX,
589 "4" => {
590 println!("Do nothing.");
591 return;
592 }
593 _ => {
594 println!("Invalid type. Select again.\n");
595 StreamType::empty()
596 }
597 }
598 }
599
600 let device_selector = |scope: Scope| -> AudioObjectID {
601 loop {
602 println!(
603 "Select {} device:\n",
604 if scope == Scope::Input {
605 "input"
606 } else {
607 "output"
608 }
609 );
610 let mut list = vec![];
611 list.push(kAudioObjectUnknown);
612 println!("{:>4}: System default", 0);
613 let devices = test_get_devices_in_scope(scope.clone());
614 for (idx, device) in devices.iter().enumerate() {
615 list.push(*device);
616 let info = TestDeviceInfo::new(*device, scope.clone());
617 println!(
618 "{:>4}: {}\n\tAudioObjectID: {}\n\tuid: {}",
619 idx + 1,
620 info.label,
621 device,
622 info.uid
623 );
624 }
625
626 let mut input = String::new();
627 io::stdin().read_line(&mut input).unwrap();
628 let n: usize = match input.trim().parse() {
629 Err(_) => {
630 println!("Invalid option. Try again.\n");
631 continue;
632 }
633 Ok(n) => n,
634 };
635 if n >= list.len() {
636 println!("Invalid option. Try again.\n");
637 continue;
638 }
639 return list[n];
640 }
641 };
642
643 let mut input_params = get_dummy_stream_params(Scope::Input, input_prefs);
644 let mut output_params = get_dummy_stream_params(Scope::Output, output_prefs);
645
646 let (input_device, input_stream_params) = if stream_type.contains(StreamType::INPUT) {
647 (
648 device_selector(Scope::Input),
649 &mut input_params as *mut ffi::cubeb_stream_params,
650 )
651 } else {
652 (
653 kAudioObjectUnknown, /* default input device */
654 ptr::null_mut(),
655 )
656 };
657
658 let (output_device, output_stream_params) = if stream_type.contains(StreamType::OUTPUT) {
659 (
660 device_selector(Scope::Output),
661 &mut output_params as *mut ffi::cubeb_stream_params,
662 )
663 } else {
664 (
665 kAudioObjectUnknown, /* default output device */
666 ptr::null_mut(),
667 )
668 };
669
670 let stream_name = CString::new("stream tester").unwrap();
671
672 assert_eq!(
673 unsafe {
674 OPS.stream_init.unwrap()(
675 context_ptr,
676 &mut stream.stream_ptr,
677 stream_name.as_ptr(),
678 input_device as ffi::cubeb_devid,
679 input_stream_params,
680 output_device as ffi::cubeb_devid,
681 output_stream_params,
682 4096, // latency
683 Some(data_callback),
684 Some(state_callback),
685 &stream.enable_loopback as *const AtomicBool as *mut c_void, // user pointer
686 )
687 },
688 ffi::CUBEB_OK
689 );
690 assert!(!stream.stream_ptr.is_null());
691 println!("Stream {:p} created.", stream.stream_ptr);
692
693 extern "C" fn state_callback(
694 stream: *mut ffi::cubeb_stream,
695 _user_ptr: *mut c_void,
696 state: ffi::cubeb_state,
697 ) {
698 assert!(!stream.is_null());
699 let s = State::from(state);
700 println!("state: {:?}", s);
701 }
702
703 extern "C" fn data_callback(
704 stream: *mut ffi::cubeb_stream,
705 user_ptr: *mut c_void,
706 input_buffer: *const c_void,
707 output_buffer: *mut c_void,
708 nframes: i64,
709 ) -> i64 {
710 assert!(!stream.is_null());
711
712 let enable_loopback = unsafe { &mut *(user_ptr as *mut AtomicBool) };
713 let loopback = enable_loopback.load(Ordering::SeqCst);
714 if loopback && !input_buffer.is_null() && !output_buffer.is_null() {
715 // Dupe the mono input to stereo
716 let stm = unsafe { &mut *(stream as *mut AudioUnitStream) };
717 assert_eq!(stm.core_stream_data.input_stream_params.channels(), 1);
718 let channels = stm.core_stream_data.output_stream_params.channels() as usize;
719 let sample_size =
720 cubeb_sample_size(stm.core_stream_data.output_stream_params.format());
721 for f in 0..(nframes as usize) {
722 let input_offset = f * sample_size;
723 let output_offset = input_offset * channels;
724 for c in 0..channels {
725 unsafe {
726 ptr::copy(
727 input_buffer.add(input_offset) as *const u8,
728 output_buffer.add(output_offset + (sample_size * c)) as *mut u8,
729 sample_size,
730 )
731 };
732 }
733 }
734 } else if !output_buffer.is_null() {
735 // Feed silence data to output buffer
736 let stm = unsafe { &mut *(stream as *mut AudioUnitStream) };
737 let channels = stm.core_stream_data.output_stream_params.channels();
738 let samples = nframes as usize * channels as usize;
739 let sample_size =
740 cubeb_sample_size(stm.core_stream_data.output_stream_params.format());
741 unsafe {
742 ptr::write_bytes(output_buffer, 0, samples * sample_size);
743 }
744 }
745
746 nframes
747 }
748
749 fn get_dummy_stream_params(scope: Scope, prefs: StreamPrefs) -> ffi::cubeb_stream_params {
750 // The stream format for input and output must be same.
751 const STREAM_FORMAT: u32 = ffi::CUBEB_SAMPLE_FLOAT32NE;
752
753 // Make sure the parameters meet the requirements of AudioUnitContext::stream_init
754 // (in the comments).
755 let mut stream_params = ffi::cubeb_stream_params::default();
756 stream_params.prefs = prefs.bits();
757 let (format, rate, channels, layout) = match scope {
758 Scope::Input => (STREAM_FORMAT, 48000, 1, ffi::CUBEB_LAYOUT_MONO),
759 Scope::Output => (STREAM_FORMAT, 44100, 2, ffi::CUBEB_LAYOUT_STEREO),
760 };
761 stream_params.format = format;
762 stream_params.rate = rate;
763 stream_params.channels = channels;
764 stream_params.layout = layout;
765 stream_params
766 }
767 }
768 }
769
770 // Simple stereo tone test
771 #[ignore]
772 #[test]
773 fn test_tone() {
774 let devices = test_get_devices_in_scope(Scope::Output);
775 for (_, device) in devices.iter().enumerate() {
776 let info = TestDeviceInfo::new(*device, Scope::Output);
777 let mut pa = AudioObjectPropertyAddress::default();
778 pa.mSelector = kAudioDevicePropertyPreferredChannelsForStereo;
779 pa.mScope = kAudioDevicePropertyScopeOutput;
780 pa.mElement = kAudioObjectPropertyElementMaster;
781 get_serial_queue_singleton().run_sync(|| {
782 let mut ssize: usize = 8;
783 let mut value = [0 as u32; 2];
784 let r = audio_object_get_property_data(*device, &pa, &mut ssize, &mut value);
785 if r != 0 {
786 eprintln!("Error getting prop data");
787 }
788 println!(
789 "{}: Channels for the stereo pair are [{}, {}]",
790 info.label, value[0], value[1]
791 );
792 });
793 }
794 fn test_impl(ch_count: usize) {
795 use std::f32::consts::PI;
796 use std::thread;
797 use std::time::Duration;
798
799 const SAMPLE_FREQUENCY: u32 = 48000;
800
801 // Make sure the parameters meet the requirements of AudioUnitContext::stream_init
802 // (in the comments).
803 let mut output_params = ffi::cubeb_stream_params::default();
804 output_params.format = ffi::CUBEB_SAMPLE_FLOAT32NE;
805 output_params.rate = SAMPLE_FREQUENCY;
806 output_params.channels = ch_count as u32;
807 output_params.layout = if ch_count == 1 {
808 ffi::CUBEB_LAYOUT_MONO
809 } else {
810 ffi::CUBEB_LAYOUT_STEREO
811 };
812 output_params.prefs = ffi::CUBEB_STREAM_PREF_NONE;
813
814 struct Closure {
815 phase: i64,
816 channel_count: usize,
817 }
818 let mut closure = Closure {
819 phase: 0,
820 channel_count: ch_count,
821 };
822 let closure_ptr = &mut closure as *mut Closure as *mut c_void;
823
824 test_ops_stream_operation(
825 "tone",
826 ptr::null_mut(),
827 ptr::null_mut(),
828 ptr::null_mut(),
829 &mut output_params,
830 4096, // TODO: Get latency by get_min_latency instead ?
831 Some(data_callback),
832 Some(state_callback),
833 closure_ptr,
834 |stream| {
835 assert_eq!(unsafe { OPS.stream_start.unwrap()(stream) }, ffi::CUBEB_OK);
836 thread::sleep(Duration::from_millis(1000));
837 assert_eq!(unsafe { OPS.stream_stop.unwrap()(stream) }, ffi::CUBEB_OK);
838 },
839 );
840
841 extern "C" fn state_callback(
842 stream: *mut ffi::cubeb_stream,
843 user_ptr: *mut c_void,
844 state: ffi::cubeb_state,
845 ) {
846 assert!(!stream.is_null());
847 assert!(!user_ptr.is_null());
848 assert_ne!(state, ffi::CUBEB_STATE_ERROR);
849 }
850
851 extern "C" fn data_callback(
852 stream: *mut ffi::cubeb_stream,
853 user_ptr: *mut c_void,
854 _input_buffer: *const c_void,
855 output_buffer: *mut c_void,
856 nframes: i64,
857 ) -> i64 {
858 assert!(!stream.is_null());
859 assert!(!user_ptr.is_null());
860 assert!(!output_buffer.is_null());
861
862 let closure = unsafe { &mut *(user_ptr as *mut Closure) };
863
864 let buffer = unsafe {
865 let ptr = output_buffer as *mut f32;
866 let len = closure.channel_count * nframes as usize;
867 slice::from_raw_parts_mut(ptr, len)
868 };
869
870 for (i, e) in buffer.iter_mut().enumerate() {
871 // If stereo, L is 220Hz, R is 440Hz. If mono, 220Hz
872 let tone = (2.0
873 * PI
874 * (if i % closure.channel_count == 0 {
875 220.0
876 } else {
877 440.0
878 })
879 * (closure.phase) as f32
880 / SAMPLE_FREQUENCY as f32)
881 .sin();
882 *e = tone;
883 if closure.channel_count > 1 {
884 closure.phase += (i % closure.channel_count) as i64;
885 } else {
886 closure.phase += 1;
887 }
888 }
889
890 nframes
891 }
892 }
893 test_impl(2);
894 test_impl(1);
895 }