Debian Codegraph @

third_party/rust/cubeb-coreaudio/src/backend/mod.rs

raw
1 // Copyright © 2018 Mozilla Foundation
2 //
3 // This program is made available under an ISC-style license. See the
4 // accompanying file LICENSE for details.
5 #![allow(unused_assignments)]
6 #![allow(unused_must_use)]
7 extern crate coreaudio_sys_utils;
8 extern crate libc;
9 extern crate ringbuf;
10
11 mod aggregate_device;
12 mod auto_release;
13 mod buffer_manager;
14 mod device_property;
15 mod mixer;
16 mod resampler;
17 mod utils;
18
19 use self::aggregate_device::*;
20 use self::auto_release::*;
21 use self::buffer_manager::*;
22 use self::coreaudio_sys_utils::aggregate_device::*;
23 use self::coreaudio_sys_utils::audio_device_extensions::*;
24 use self::coreaudio_sys_utils::audio_object::*;
25 use self::coreaudio_sys_utils::audio_unit::*;
26 use self::coreaudio_sys_utils::cf_mutable_dict::*;
27 use self::coreaudio_sys_utils::dispatch::*;
28 use self::coreaudio_sys_utils::string::*;
29 use self::coreaudio_sys_utils::sys::*;
30 use self::device_property::*;
31 use self::mixer::*;
32 use self::resampler::*;
33 use self::utils::*;
34 use backend::ringbuf::RingBuffer;
35 #[cfg(feature = "audio-dump")]
36 use cubeb_backend::ffi::cubeb_audio_dump_stream_t;
37 use cubeb_backend::{
38 ffi, ChannelLayout, Context, ContextOps, DeviceCollectionRef, DeviceId, DeviceRef, DeviceType,
39 Error, InputProcessingParams, Ops, Result, SampleFormat, State, Stream, StreamOps,
40 StreamParams, StreamParamsRef, StreamPrefs,
41 };
42 use mach::mach_time::{mach_absolute_time, mach_timebase_info};
43 use std::cmp;
44 use std::collections::HashSet;
45 use std::ffi::{CStr, CString};
46 use std::fmt;
47 use std::mem;
48 use std::os::raw::{c_uint, c_void};
49 use std::ptr;
50 use std::slice;
51 use std::str::FromStr;
52 use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
53 use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, Weak};
54 use std::time::{Duration, Instant};
55 const NO_ERR: OSStatus = 0;
56
57 const AU_OUT_BUS: AudioUnitElement = 0;
58 const AU_IN_BUS: AudioUnitElement = 1;
59
60 const PRIVATE_AGGREGATE_DEVICE_NAME: &str = "CubebAggregateDevice";
61 const VOICEPROCESSING_AGGREGATE_DEVICE_NAME: &str = "VPAUAggregateAudioDevice";
62
63 const APPLE_STUDIO_DISPLAY_USB_ID: &str = "05AC:1114";
64
65 // Testing empirically, some headsets report a minimal latency that is very low,
66 // but this does not work in practice. Lie and say the minimum is 128 frames.
67 const SAFE_MIN_LATENCY_FRAMES: u32 = 128;
68 const SAFE_MAX_LATENCY_FRAMES: u32 = 512;
69
70 const VPIO_IDLE_TIMEOUT: Duration = Duration::from_secs(10);
71
72 const MACOS_KERNEL_MAJOR_VERSION_MONTEREY: u32 = 21;
73
74 // Global registry for tracking valid sync callback pointers.
75 static SYNC_CALLBACK_REGISTRY: LazyLock<Mutex<HashSet<usize>>> =
76 LazyLock::new(|| Mutex::new(HashSet::new()));
77
78 fn sync_callback_registry_register(ptr: usize) {
79 SYNC_CALLBACK_REGISTRY.lock().unwrap().insert(ptr);
80 }
81
82 fn sync_callback_registry_unregister(ptr: usize) {
83 SYNC_CALLBACK_REGISTRY.lock().unwrap().remove(&ptr);
84 }
85
86 fn with_sync_callback_ptr<F>(ptr: *mut c_void, f: F)
87 where
88 F: FnOnce(),
89 {
90 let guard = SYNC_CALLBACK_REGISTRY.lock().unwrap();
91 if guard.contains(&(ptr as usize)) {
92 f();
93 }
94 }
95
96 #[derive(Debug, PartialEq)]
97 enum ParseMacOSKernelVersionError {
98 SysCtl,
99 Malformed,
100 Parsing,
101 }
102
103 fn macos_kernel_major_version() -> std::result::Result<u32, ParseMacOSKernelVersionError> {
104 let ver = whatsys::kernel_version();
105 if ver.is_none() {
106 return Err(ParseMacOSKernelVersionError::SysCtl);
107 }
108 let ver = ver.unwrap();
109 let major = ver.split('.').next();
110 if major.is_none() {
111 return Err(ParseMacOSKernelVersionError::Malformed);
112 }
113 let parsed_major = u32::from_str(major.unwrap());
114 if parsed_major.is_err() {
115 return Err(ParseMacOSKernelVersionError::Parsing);
116 }
117 Ok(parsed_major.unwrap())
118 }
119
120 bitflags! {
121 #[allow(non_camel_case_types)]
122 #[derive(Clone, Debug, PartialEq, Copy)]
123 struct device_flags: u32 {
124 const DEV_UNKNOWN = 0b0000_0000; // Unknown
125 const DEV_INPUT = 0b0000_0001; // Record device like mic
126 const DEV_OUTPUT = 0b0000_0010; // Playback device like speakers
127 const DEV_SELECTED_DEFAULT = 0b0000_0100; // User selected to use the system default device
128 }
129 }
130
131 #[cfg(feature = "audio-dump")]
132 fn dump_audio(stream: cubeb_audio_dump_stream_t, audio_samples: *mut c_void, count: u32) {
133 unsafe {
134 let rv = ffi::cubeb_audio_dump_write(stream, audio_samples, count);
135 if rv != 0 {
136 cubeb_alog!("Error dumping audio data");
137 }
138 }
139 }
140
141 fn make_sized_audio_channel_layout(sz: usize) -> AutoRelease<AudioChannelLayout> {
142 assert!(sz >= mem::size_of::<AudioChannelLayout>());
143 assert_eq!(
144 (sz - mem::size_of::<AudioChannelLayout>()) % mem::size_of::<AudioChannelDescription>(),
145 0
146 );
147 let acl = unsafe { libc::calloc(1, sz) } as *mut AudioChannelLayout;
148
149 unsafe extern "C" fn free_acl(acl: *mut AudioChannelLayout) {
150 libc::free(acl as *mut libc::c_void);
151 }
152
153 AutoRelease::new(acl, free_acl)
154 }
155
156 #[allow(non_camel_case_types)]
157 #[derive(Clone, Debug)]
158 struct device_info {
159 id: AudioDeviceID,
160 flags: device_flags,
161 }
162
163 impl Default for device_info {
164 fn default() -> Self {
165 Self {
166 id: kAudioObjectUnknown,
167 flags: device_flags::DEV_UNKNOWN,
168 }
169 }
170 }
171
172 #[allow(non_camel_case_types)]
173 #[derive(Debug)]
174 struct device_property_listener {
175 device: AudioDeviceID,
176 property: AudioObjectPropertyAddress,
177 listener: audio_object_property_listener_proc,
178 }
179
180 impl device_property_listener {
181 fn new(
182 device: AudioDeviceID,
183 property: AudioObjectPropertyAddress,
184 listener: audio_object_property_listener_proc,
185 ) -> Self {
186 Self {
187 device,
188 property,
189 listener,
190 }
191 }
192 }
193
194 #[derive(Debug, PartialEq)]
195 struct CAChannelLabel(AudioChannelLabel);
196
197 impl From<CAChannelLabel> for mixer::Channel {
198 fn from(label: CAChannelLabel) -> mixer::Channel {
199 use self::coreaudio_sys_utils::sys;
200 match label.0 {
201 sys::kAudioChannelLabel_Left => mixer::Channel::FrontLeft,
202 sys::kAudioChannelLabel_Right => mixer::Channel::FrontRight,
203 sys::kAudioChannelLabel_Center | sys::kAudioChannelLabel_Mono => {
204 mixer::Channel::FrontCenter
205 }
206 sys::kAudioChannelLabel_LFEScreen => mixer::Channel::LowFrequency,
207 sys::kAudioChannelLabel_LeftSurround => mixer::Channel::BackLeft,
208 sys::kAudioChannelLabel_RightSurround => mixer::Channel::BackRight,
209 sys::kAudioChannelLabel_LeftCenter => mixer::Channel::FrontLeftOfCenter,
210 sys::kAudioChannelLabel_RightCenter => mixer::Channel::FrontRightOfCenter,
211 sys::kAudioChannelLabel_CenterSurround => mixer::Channel::BackCenter,
212 sys::kAudioChannelLabel_LeftSurroundDirect => mixer::Channel::SideLeft,
213 sys::kAudioChannelLabel_RightSurroundDirect => mixer::Channel::SideRight,
214 sys::kAudioChannelLabel_TopCenterSurround => mixer::Channel::TopCenter,
215 sys::kAudioChannelLabel_VerticalHeightLeft => mixer::Channel::TopFrontLeft,
216 sys::kAudioChannelLabel_VerticalHeightCenter => mixer::Channel::TopFrontCenter,
217 sys::kAudioChannelLabel_VerticalHeightRight => mixer::Channel::TopFrontRight,
218 sys::kAudioChannelLabel_TopBackLeft => mixer::Channel::TopBackLeft,
219 sys::kAudioChannelLabel_TopBackCenter => mixer::Channel::TopBackCenter,
220 sys::kAudioChannelLabel_TopBackRight => mixer::Channel::TopBackRight,
221 sys::kAudioChannelLabel_Unknown => mixer::Channel::Discrete,
222 sys::kAudioChannelLabel_Unused => mixer::Channel::Silence,
223 v => {
224 eprintln!("Warning: channel label value {} isn't handled", v);
225 mixer::Channel::Silence
226 }
227 }
228 }
229 }
230
231 fn set_notification_runloop() {
232 let address = AudioObjectPropertyAddress {
233 mSelector: kAudioHardwarePropertyRunLoop,
234 mScope: kAudioObjectPropertyScopeGlobal,
235 mElement: kAudioObjectPropertyElementMaster,
236 };
237
238 // Ask HAL to manage its own thread for notification by setting the run_loop to NULL.
239 // Otherwise HAL may use main thread to fire notifications.
240 let run_loop: CFRunLoopRef = ptr::null_mut();
241 let size = mem::size_of::<CFRunLoopRef>();
242 let status =
243 audio_object_set_property_data(kAudioObjectSystemObject, &address, size, &run_loop);
244 if status != NO_ERR {
245 cubeb_log!("Could not make global CoreAudio notifications use their own thread.");
246 }
247 }
248
249 fn create_device_info(devid: AudioDeviceID, devtype: DeviceType) -> Option<device_info> {
250 assert_ne!(devid, kAudioObjectSystemObject);
251 debug_assert_running_serially();
252
253 let mut flags = match devtype {
254 DeviceType::INPUT => device_flags::DEV_INPUT,
255 DeviceType::OUTPUT => device_flags::DEV_OUTPUT,
256 _ => panic!("Only accept input or output type"),
257 };
258
259 if devid == kAudioObjectUnknown {
260 cubeb_log!("Using the system default device");
261 flags |= device_flags::DEV_SELECTED_DEFAULT;
262 get_default_device(devtype).map(|id| device_info { id, flags })
263 } else {
264 Some(device_info { id: devid, flags })
265 }
266 }
267
268 fn create_stream_description(stream_params: &StreamParams) -> Result<AudioStreamBasicDescription> {
269 assert!(stream_params.rate() > 0);
270 assert!(stream_params.channels() > 0);
271
272 let mut desc = AudioStreamBasicDescription::default();
273
274 match stream_params.format() {
275 SampleFormat::S16LE => {
276 desc.mBitsPerChannel = 16;
277 desc.mFormatFlags = kAudioFormatFlagIsSignedInteger;
278 }
279 SampleFormat::S16BE => {
280 desc.mBitsPerChannel = 16;
281 desc.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsBigEndian;
282 }
283 SampleFormat::Float32LE => {
284 desc.mBitsPerChannel = 32;
285 desc.mFormatFlags = kAudioFormatFlagIsFloat;
286 }
287 SampleFormat::Float32BE => {
288 desc.mBitsPerChannel = 32;
289 desc.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsBigEndian;
290 }
291 _ => {
292 return Err(Error::invalid_format());
293 }
294 }
295
296 desc.mFormatID = kAudioFormatLinearPCM;
297 desc.mFormatFlags |= kLinearPCMFormatFlagIsPacked;
298 desc.mSampleRate = f64::from(stream_params.rate());
299 desc.mChannelsPerFrame = stream_params.channels();
300
301 desc.mBytesPerFrame = (desc.mBitsPerChannel / 8) * desc.mChannelsPerFrame;
302 desc.mFramesPerPacket = 1;
303 desc.mBytesPerPacket = desc.mBytesPerFrame * desc.mFramesPerPacket;
304
305 desc.mReserved = 0;
306
307 Ok(desc)
308 }
309
310 fn set_volume(unit: AudioUnit, volume: f32) -> Result<()> {
311 assert!(!unit.is_null());
312 let r = audio_unit_set_parameter(
313 unit,
314 kHALOutputParam_Volume,
315 kAudioUnitScope_Global,
316 0,
317 volume,
318 0,
319 );
320 if r == NO_ERR {
321 Ok(())
322 } else {
323 cubeb_log!("AudioUnitSetParameter/kHALOutputParam_Volume rv={}", r);
324 Err(Error::error())
325 }
326 }
327
328 fn get_volume(unit: AudioUnit) -> Result<f32> {
329 assert!(!unit.is_null());
330 let mut volume: f32 = 0.0;
331 let r = audio_unit_get_parameter(
332 unit,
333 kHALOutputParam_Volume,
334 kAudioUnitScope_Global,
335 0,
336 &mut volume,
337 );
338 if r == NO_ERR {
339 Ok(volume)
340 } else {
341 cubeb_log!("AudioUnitGetParameter/kHALOutputParam_Volume rv={}", r);
342 Err(Error::error())
343 }
344 }
345
346 fn set_input_mute(unit: AudioUnit, mute: bool) -> Result<()> {
347 assert!(!unit.is_null());
348 let mute: u32 = mute.into();
349 let mut old_mute: u32 = 0;
350 let r = audio_unit_get_property(
351 unit,
352 kAUVoiceIOProperty_MuteOutput,
353 kAudioUnitScope_Global,
354 AU_IN_BUS,
355 &mut old_mute,
356 &mut mem::size_of::<u32>(),
357 );
358 if r != NO_ERR {
359 cubeb_log!(
360 "AudioUnitGetProperty/kAUVoiceIOProperty_MuteOutput rv={}",
361 r
362 );
363 return Err(Error::error());
364 }
365 if old_mute == mute {
366 return Ok(());
367 }
368 let r = audio_unit_set_property(
369 unit,
370 kAUVoiceIOProperty_MuteOutput,
371 kAudioUnitScope_Global,
372 AU_IN_BUS,
373 &mute,
374 mem::size_of::<u32>(),
375 );
376 if r == NO_ERR {
377 Ok(())
378 } else {
379 cubeb_log!(
380 "AudioUnitSetProperty/kAUVoiceIOProperty_MuteOutput rv={}",
381 r
382 );
383 Err(Error::error())
384 }
385 }
386
387 fn set_input_processing_params(unit: AudioUnit, params: InputProcessingParams) -> Result<()> {
388 assert!(!unit.is_null());
389 let aec = params.contains(InputProcessingParams::ECHO_CANCELLATION);
390 let ns = params.contains(InputProcessingParams::NOISE_SUPPRESSION);
391 let agc = params.contains(InputProcessingParams::AUTOMATIC_GAIN_CONTROL);
392 assert_eq!(aec, ns);
393
394 let mut old_agc: u32 = 0;
395 let r = audio_unit_get_property(
396 unit,
397 kAUVoiceIOProperty_VoiceProcessingEnableAGC,
398 kAudioUnitScope_Global,
399 AU_IN_BUS,
400 &mut old_agc,
401 &mut mem::size_of::<u32>(),
402 );
403 if r != NO_ERR {
404 cubeb_log!(
405 "AudioUnitGetProperty/kAUVoiceIOProperty_VoiceProcessingEnableAGC rv={}",
406 r
407 );
408 return Err(Error::error());
409 }
410
411 if (old_agc == 1) != agc {
412 let agc = u32::from(agc);
413 let r = audio_unit_set_property(
414 unit,
415 kAUVoiceIOProperty_VoiceProcessingEnableAGC,
416 kAudioUnitScope_Global,
417 AU_IN_BUS,
418 &agc,
419 mem::size_of::<u32>(),
420 );
421 if r != NO_ERR {
422 cubeb_log!(
423 "AudioUnitSetProperty/kAUVoiceIOProperty_VoiceProcessingEnableAGC rv={}",
424 r
425 );
426 return Err(Error::error());
427 }
428 cubeb_log!(
429 "set_input_processing_params on unit {:p} - set agc: {}",
430 unit,
431 agc
432 );
433 }
434
435 let mut old_bypass: u32 = 0;
436 let r = audio_unit_get_property(
437 unit,
438 kAUVoiceIOProperty_BypassVoiceProcessing,
439 kAudioUnitScope_Global,
440 AU_IN_BUS,
441 &mut old_bypass,
442 &mut mem::size_of::<u32>(),
443 );
444 if r != NO_ERR {
445 cubeb_log!(
446 "AudioUnitGetProperty/kAUVoiceIOProperty_BypassVoiceProcessing rv={}",
447 r
448 );
449 return Err(Error::error());
450 }
451
452 let bypass = u32::from(!aec);
453 if old_bypass != bypass {
454 let r = audio_unit_set_property(
455 unit,
456 kAUVoiceIOProperty_BypassVoiceProcessing,
457 kAudioUnitScope_Global,
458 AU_IN_BUS,
459 &bypass,
460 mem::size_of::<u32>(),
461 );
462 if r != NO_ERR {
463 cubeb_log!(
464 "AudioUnitSetProperty/kAUVoiceIOProperty_BypassVoiceProcessing rv={}",
465 r
466 );
467 return Err(Error::error());
468 }
469 cubeb_log!(
470 "set_input_processing_params on unit {:p} - set bypass: {}",
471 unit,
472 bypass
473 );
474 }
475
476 Ok(())
477 }
478
479 fn minimum_resampling_input_frames(
480 input_rate: f64,
481 output_rate: f64,
482 output_frames: usize,
483 ) -> usize {
484 assert!(!approx_eq!(f64, input_rate, 0_f64));
485 assert!(!approx_eq!(f64, output_rate, 0_f64));
486 if approx_eq!(f64, input_rate, output_rate) {
487 return output_frames;
488 }
489 (input_rate * output_frames as f64 / output_rate).ceil() as usize
490 }
491
492 fn audiounit_make_silent(io_data: &AudioBuffer) {
493 assert!(!io_data.mData.is_null());
494 let bytes = unsafe {
495 let ptr = io_data.mData as *mut u8;
496 let len = io_data.mDataByteSize as usize;
497 slice::from_raw_parts_mut(ptr, len)
498 };
499 for data in bytes.iter_mut() {
500 *data = 0;
501 }
502 }
503
504 extern "C" fn audiounit_input_callback(
505 user_ptr: *mut c_void,
506 flags: *mut AudioUnitRenderActionFlags,
507 tstamp: *const AudioTimeStamp,
508 bus: u32,
509 input_frames: u32,
510 _: *mut AudioBufferList,
511 ) -> OSStatus {
512 enum ErrorHandle {
513 Return(OSStatus),
514 Reinit,
515 }
516
517 assert!(input_frames > 0);
518 assert_eq!(bus, AU_IN_BUS);
519
520 assert!(!user_ptr.is_null());
521 let stm = unsafe { &mut *(user_ptr as *mut AudioUnitStream) };
522
523 if unsafe { *flags | kAudioTimeStampHostTimeValid } != 0 {
524 let now = unsafe { mach_absolute_time() };
525 let input_latency_frames = compute_input_latency(stm, unsafe { (*tstamp).mHostTime }, now);
526 stm.total_input_latency_frames
527 .store(input_latency_frames, Ordering::SeqCst);
528 }
529
530 if stm.stopped.load(Ordering::SeqCst) {
531 cubeb_log!("({:p}) input stopped", stm as *const AudioUnitStream);
532 return NO_ERR;
533 }
534
535 let handler = |stm: &mut AudioUnitStream,
536 flags: *mut AudioUnitRenderActionFlags,
537 tstamp: *const AudioTimeStamp,
538 bus: u32,
539 input_frames: u32|
540 -> ErrorHandle {
541 let input_buffer_manager = stm.core_stream_data.input_buffer_manager.as_mut().unwrap();
542 assert_eq!(
543 stm.core_stream_data.stm_ptr,
544 user_ptr as *const AudioUnitStream
545 );
546
547 // `flags` and `tstamp` must be non-null so they can be casted into the references.
548 assert!(!flags.is_null());
549 let flags = unsafe { &mut (*flags) };
550 assert!(!tstamp.is_null());
551 let tstamp = unsafe { &(*tstamp) };
552
553 // Create the AudioBufferList to store input.
554 let mut input_buffer_list = AudioBufferList::default();
555 input_buffer_list.mBuffers[0].mDataByteSize =
556 stm.core_stream_data.input_dev_desc.mBytesPerFrame * input_frames;
557 input_buffer_list.mBuffers[0].mData = ptr::null_mut();
558 input_buffer_list.mBuffers[0].mNumberChannels =
559 stm.core_stream_data.input_dev_desc.mChannelsPerFrame;
560 input_buffer_list.mNumberBuffers = 1;
561
562 debug_assert!(!stm.core_stream_data.input_unit.is_null());
563 let status = audio_unit_render(
564 stm.core_stream_data.input_unit,
565 flags,
566 tstamp,
567 bus,
568 input_frames,
569 &mut input_buffer_list,
570 );
571 if (status != NO_ERR)
572 && (status != kAudioUnitErr_CannotDoInCurrentContext
573 || stm.core_stream_data.output_unit.is_null())
574 {
575 return ErrorHandle::Return(status);
576 }
577 let handle = if status == kAudioUnitErr_CannotDoInCurrentContext {
578 assert!(!stm.core_stream_data.output_unit.is_null());
579 // kAudioUnitErr_CannotDoInCurrentContext is returned when using a BT
580 // headset and the profile is changed from A2DP to HFP/HSP. The previous
581 // output device is no longer valid and must be reset.
582 // For now state that no error occurred and feed silence, stream will be
583 // resumed once reinit has completed.
584 ErrorHandle::Reinit
585 } else {
586 assert_eq!(status, NO_ERR);
587
588 #[cfg(feature = "audio-dump")]
589 {
590 dump_audio(
591 stm.core_stream_data.audio_dump_input,
592 input_buffer_list.mBuffers[0].mData,
593 input_frames * stm.core_stream_data.input_dev_desc.mChannelsPerFrame,
594 );
595 }
596
597 input_buffer_manager
598 .push_data(input_buffer_list.mBuffers[0].mData, input_frames as usize);
599 ErrorHandle::Return(status)
600 };
601
602 // Full Duplex. We'll call data_callback in the AudioUnit output callback. Record this
603 // callback for logging.
604 if !stm.core_stream_data.output_unit.is_null() {
605 let input_callback_data = InputCallbackData {
606 bytes: input_buffer_list.mBuffers[0].mDataByteSize,
607 rendered_frames: input_frames,
608 total_available: input_buffer_manager.available_frames(),
609 channels: input_buffer_list.mBuffers[0].mNumberChannels,
610 num_buf: input_buffer_list.mNumberBuffers,
611 };
612 stm.core_stream_data
613 .input_logging
614 .as_mut()
615 .unwrap()
616 .push(input_callback_data);
617 return handle;
618 }
619
620 cubeb_alogv!(
621 "({:p}) input: buffers {}, size {}, channels {}, rendered frames {}, total frames {}.",
622 stm.core_stream_data.stm_ptr,
623 input_buffer_list.mNumberBuffers,
624 input_buffer_list.mBuffers[0].mDataByteSize,
625 input_buffer_list.mBuffers[0].mNumberChannels,
626 input_frames,
627 input_buffer_manager.available_frames()
628 );
629
630 // Input only. Call the user callback through resampler.
631 // Resampler will deliver input buffer in the correct rate.
632 assert!(input_frames as usize <= input_buffer_manager.available_frames());
633 stm.frames_read.fetch_add(
634 input_buffer_manager.available_frames(),
635 atomic::Ordering::SeqCst,
636 );
637 let mut total_input_frames = input_buffer_manager.available_frames() as i64;
638 let input_buffer =
639 input_buffer_manager.get_linear_data(input_buffer_manager.available_frames());
640 let outframes = stm.core_stream_data.resampler.fill(
641 input_buffer,
642 &mut total_input_frames,
643 ptr::null_mut(),
644 0,
645 );
646 if outframes < 0 {
647 if !stm.stopped.swap(true, Ordering::SeqCst) {
648 stm.notify_state_changed(State::Error);
649 // Use a new thread, through the queue, to avoid deadlock when calling
650 // AudioOutputUnitStop method from inside render callback
651 stm.queue.clone().run_async(move || {
652 stm.core_stream_data.stop_audiounits();
653 });
654 }
655 return ErrorHandle::Return(status);
656 }
657 if outframes < total_input_frames {
658 stm.draining.store(true, Ordering::SeqCst);
659 }
660
661 handle
662 };
663
664 // If the stream is drained, do nothing.
665 let handle = if !stm.draining.load(Ordering::SeqCst) {
666 handler(stm, flags, tstamp, bus, input_frames)
667 } else {
668 ErrorHandle::Return(NO_ERR)
669 };
670
671 // If the input (input-only stream) is drained, cancel this callback. Whenever an output
672 // is involved, the output callback handles stopping all units and notifying of state.
673 if stm.core_stream_data.output_unit.is_null()
674 && stm.draining.load(Ordering::SeqCst)
675 && !stm.stopped.swap(true, Ordering::SeqCst)
676 {
677 cubeb_alog!("({:p}) Input-only drained.", stm as *const AudioUnitStream);
678 stm.notify_state_changed(State::Drained);
679 // Use a new thread, through the queue, to avoid deadlock when calling
680 // AudioOutputUnitStop method from inside render callback
681 let stm_ptr = user_ptr as usize;
682 stm.queue.clone().run_async(move || {
683 let stm = unsafe { &mut *(stm_ptr as *mut AudioUnitStream) };
684 stm.core_stream_data.stop_audiounits();
685 });
686 }
687
688 match handle {
689 ErrorHandle::Reinit => {
690 stm.reinit_async();
691 NO_ERR
692 }
693 ErrorHandle::Return(s) => s,
694 }
695 }
696
697 fn host_time_to_ns(ctx: &AudioUnitContext, host_time: u64) -> u64 {
698 let mut rv: f64 = host_time as f64;
699 rv *= ctx.host_time_to_ns_ratio.0 as f64;
700 rv /= ctx.host_time_to_ns_ratio.1 as f64;
701 rv as u64
702 }
703
704 fn compute_output_latency(stm: &AudioUnitStream, audio_output_time: u64, now: u64) -> u32 {
705 const NS2S: u64 = 1_000_000_000;
706 let output_hw_rate = stm.core_stream_data.output_dev_desc.mSampleRate as u64;
707 let fixed_latency_ns =
708 (stm.output_device_latency_frames.load(Ordering::SeqCst) as u64 * NS2S) / output_hw_rate;
709 // The total output latency is the timestamp difference + the stream latency + the hardware
710 // latency.
711 let total_output_latency_ns =
712 fixed_latency_ns + host_time_to_ns(stm.context, audio_output_time.saturating_sub(now));
713
714 (total_output_latency_ns * output_hw_rate / NS2S) as u32
715 }
716
717 fn compute_input_latency(stm: &AudioUnitStream, audio_input_time: u64, now: u64) -> u32 {
718 const NS2S: u64 = 1_000_000_000;
719 let input_hw_rate = stm.core_stream_data.input_dev_desc.mSampleRate as u64;
720 let fixed_latency_ns =
721 (stm.input_device_latency_frames.load(Ordering::SeqCst) as u64 * NS2S) / input_hw_rate;
722 // The total input latency is the timestamp difference + the stream latency +
723 // the hardware latency.
724 let total_input_latency_ns =
725 host_time_to_ns(stm.context, now.saturating_sub(audio_input_time)) + fixed_latency_ns;
726
727 (total_input_latency_ns * input_hw_rate / NS2S) as u32
728 }
729
730 extern "C" fn audiounit_output_callback(
731 user_ptr: *mut c_void,
732 flags: *mut AudioUnitRenderActionFlags,
733 tstamp: *const AudioTimeStamp,
734 bus: u32,
735 output_frames: u32,
736 out_buffer_list: *mut AudioBufferList,
737 ) -> OSStatus {
738 assert_eq!(bus, AU_OUT_BUS);
739 assert!(!out_buffer_list.is_null());
740
741 assert!(!user_ptr.is_null());
742 let stm = unsafe { &mut *(user_ptr as *mut AudioUnitStream) };
743
744 if output_frames == 0 {
745 cubeb_alog!(
746 "({:p}) output callback empty.",
747 stm as *const AudioUnitStream
748 );
749 return NO_ERR;
750 }
751
752 let out_buffer_list_ref = unsafe { &mut (*out_buffer_list) };
753 assert_eq!(out_buffer_list_ref.mNumberBuffers, 1);
754 let buffers = unsafe {
755 let ptr = out_buffer_list_ref.mBuffers.as_mut_ptr();
756 let len = out_buffer_list_ref.mNumberBuffers as usize;
757 slice::from_raw_parts_mut(ptr, len)
758 };
759
760 if stm.stopped.load(Ordering::SeqCst) {
761 cubeb_alog!("({:p}) output stopped.", stm as *const AudioUnitStream);
762 audiounit_make_silent(&buffers[0]);
763 #[cfg(feature = "audio-dump")]
764 {
765 dump_audio(
766 stm.core_stream_data.audio_dump_output,
767 buffers[0].mData,
768 output_frames * stm.core_stream_data.output_dev_desc.mChannelsPerFrame,
769 );
770 }
771 return NO_ERR;
772 }
773
774 if stm.draining.load(Ordering::SeqCst) {
775 // Cancel all callbacks. For input-only streams, the input callback handles
776 // cancelling itself.
777 audiounit_make_silent(&buffers[0]);
778 #[cfg(feature = "audio-dump")]
779 {
780 dump_audio(
781 stm.core_stream_data.audio_dump_output,
782 buffers[0].mData,
783 output_frames * stm.core_stream_data.output_dev_desc.mChannelsPerFrame,
784 );
785 }
786 if !stm.stopped.swap(true, Ordering::SeqCst) {
787 cubeb_alog!("({:p}) output drained.", stm as *const AudioUnitStream);
788 stm.notify_state_changed(State::Drained);
789 // Use a new thread, through the queue, to avoid deadlock when calling
790 // AudioOutputUnitStop method from inside render callback
791 stm.queue.clone().run_async(move || {
792 stm.core_stream_data.stop_audiounits();
793 });
794 }
795 return NO_ERR;
796 }
797
798 let now = unsafe { mach_absolute_time() };
799
800 if unsafe { *flags | kAudioTimeStampHostTimeValid } != 0 {
801 let output_latency_frames =
802 compute_output_latency(stm, unsafe { (*tstamp).mHostTime }, now);
803 stm.total_output_latency_frames
804 .store(output_latency_frames, Ordering::SeqCst);
805 }
806 // Get output buffer
807 let output_buffer = match stm.core_stream_data.mixer.as_mut() {
808 None => buffers[0].mData,
809 Some(mixer) => {
810 // If remixing needs to occur, we can't directly work in our final
811 // destination buffer as data may be overwritten or too small to start with.
812 mixer.update_buffer_size(output_frames as usize);
813 mixer.get_buffer_mut_ptr() as *mut c_void
814 }
815 };
816
817 let prev_frames_written = stm.frames_written.load(Ordering::SeqCst);
818
819 stm.frames_written
820 .fetch_add(output_frames as usize, Ordering::SeqCst);
821
822 // Also get the input buffer if the stream is duplex
823 let (input_buffer, mut input_frames) = if !stm.core_stream_data.input_unit.is_null() {
824 let input_logging = &mut stm.core_stream_data.input_logging.as_mut().unwrap();
825 if input_logging.is_empty() {
826 cubeb_alogv!("no audio input data in output callback");
827 } else {
828 while let Some(input_callback_data) = input_logging.pop() {
829 cubeb_alogv!(
830 "input: buffers {}, size {}, channels {}, rendered frames {}, total frames {}.",
831 input_callback_data.num_buf,
832 input_callback_data.bytes,
833 input_callback_data.channels,
834 input_callback_data.rendered_frames,
835 input_callback_data.total_available
836 );
837 }
838 }
839 let input_buffer_manager = stm.core_stream_data.input_buffer_manager.as_mut().unwrap();
840 assert_ne!(stm.core_stream_data.input_dev_desc.mChannelsPerFrame, 0);
841 // If the output callback came first and this is a duplex stream, we need to
842 // fill in some additional silence in the resampler.
843 // Otherwise, if we had more than expected callbacks in a row, or we're
844 // currently switching, we add some silence as well to compensate for the
845 // fact that we're lacking some input data.
846 let input_frames_needed = minimum_resampling_input_frames(
847 stm.core_stream_data.input_dev_desc.mSampleRate,
848 f64::from(stm.core_stream_data.output_stream_params.rate()),
849 output_frames as usize,
850 );
851 let buffered_input_frames = input_buffer_manager.available_frames();
852 // Else if the input has buffered a lot already because the output started late, we
853 // need to trim the input buffer
854 if prev_frames_written == 0 && buffered_input_frames > input_frames_needed {
855 input_buffer_manager.trim(input_frames_needed);
856 let popped_frames = buffered_input_frames - input_frames_needed;
857 cubeb_alog!("Dropping {} frames in input buffer.", popped_frames);
858 }
859
860 let input_frames = if input_frames_needed > buffered_input_frames
861 && (stm.switching_device.load(Ordering::SeqCst)
862 || stm.reinit_pending.load(Ordering::SeqCst)
863 || stm.frames_read.load(Ordering::SeqCst) == 0)
864 {
865 // The silent frames will be inserted in `get_linear_data` below.
866 let silent_frames_to_push = input_frames_needed - buffered_input_frames;
867 cubeb_alog!(
868 "({:p}) Missing Frames: {} will append {} frames of input silence.",
869 stm.core_stream_data.stm_ptr,
870 if stm.frames_read.load(Ordering::SeqCst) == 0 {
871 "input hasn't started,"
872 } else if stm.switching_device.load(Ordering::SeqCst) {
873 "device switching,"
874 } else {
875 "reinit pending,"
876 },
877 silent_frames_to_push
878 );
879 input_frames_needed
880 } else {
881 buffered_input_frames
882 };
883
884 stm.frames_read.fetch_add(input_frames, Ordering::SeqCst);
885 (
886 input_buffer_manager.get_linear_data(input_frames),
887 input_frames as i64,
888 )
889 } else {
890 (ptr::null_mut::<c_void>(), 0)
891 };
892
893 cubeb_alogv!(
894 "({:p}) output: buffers {}, size {}, channels {}, frames {}.",
895 stm as *const AudioUnitStream,
896 buffers.len(),
897 buffers[0].mDataByteSize,
898 buffers[0].mNumberChannels,
899 output_frames
900 );
901
902 assert_ne!(output_frames, 0);
903 let outframes = stm.core_stream_data.resampler.fill(
904 input_buffer,
905 if input_buffer.is_null() {
906 ptr::null_mut()
907 } else {
908 &mut input_frames
909 },
910 output_buffer,
911 i64::from(output_frames),
912 );
913
914 if outframes < 0 || outframes > i64::from(output_frames) {
915 audiounit_make_silent(&buffers[0]);
916
917 #[cfg(feature = "audio-dump")]
918 {
919 dump_audio(
920 stm.core_stream_data.audio_dump_output,
921 buffers[0].mData,
922 output_frames * stm.core_stream_data.output_dev_desc.mChannelsPerFrame,
923 );
924 }
925 if !stm.stopped.swap(true, Ordering::SeqCst) {
926 stm.notify_state_changed(State::Error);
927 // Use a new thread, through the queue, to avoid deadlock when calling
928 // AudioOutputUnitStop method from inside render callback
929 stm.queue.clone().run_async(move || {
930 stm.core_stream_data.stop_audiounits();
931 });
932 }
933 return NO_ERR;
934 }
935
936 stm.draining
937 .store(outframes < i64::from(output_frames), Ordering::SeqCst);
938 stm.output_callback_timing_data_write
939 .write(OutputCallbackTimingData {
940 frames_queued: stm.frames_queued,
941 timestamp: now,
942 buffer_size: outframes as u64,
943 });
944
945 stm.frames_queued += outframes as u64;
946
947 // Post process output samples.
948 if stm.draining.load(Ordering::SeqCst) {
949 // Clear missing frames (silence)
950 let frames_to_bytes = |frames: usize| -> usize {
951 let sample_size = cubeb_sample_size(stm.core_stream_data.output_stream_params.format());
952 let channel_count = stm.core_stream_data.output_stream_params.channels() as usize;
953 frames * sample_size * channel_count
954 };
955 let out_bytes = unsafe {
956 slice::from_raw_parts_mut(
957 output_buffer as *mut u8,
958 frames_to_bytes(output_frames as usize),
959 )
960 };
961 let start = frames_to_bytes(outframes as usize);
962 for byte in out_bytes.iter_mut().skip(start) {
963 *byte = 0;
964 }
965 }
966
967 // Mixing
968 if stm.core_stream_data.mixer.is_some() {
969 assert!(
970 buffers[0].mDataByteSize
971 >= stm.core_stream_data.output_dev_desc.mBytesPerFrame * output_frames
972 );
973 stm.core_stream_data.mixer.as_mut().unwrap().mix(
974 output_frames as usize,
975 buffers[0].mData,
976 buffers[0].mDataByteSize as usize,
977 );
978 }
979
980 #[cfg(feature = "audio-dump")]
981 {
982 dump_audio(
983 stm.core_stream_data.audio_dump_output,
984 buffers[0].mData,
985 output_frames * stm.core_stream_data.output_dev_desc.mChannelsPerFrame,
986 );
987 }
988 NO_ERR
989 }
990
991 #[allow(clippy::cognitive_complexity)]
992 extern "C" fn audiounit_property_listener_callback(
993 id: AudioObjectID,
994 address_count: u32,
995 addresses: *const AudioObjectPropertyAddress,
996 user: *mut c_void,
997 ) -> OSStatus {
998 assert_ne!(address_count, 0);
999
1000 let stm = unsafe { &mut *(user as *mut AudioUnitStream) };
1001 let addrs = unsafe { slice::from_raw_parts(addresses, address_count as usize) };
1002 if stm.switching_device.load(Ordering::SeqCst) {
1003 cubeb_log!(
1004 "Switching is already taking place. Skipping event for device {}",
1005 id
1006 );
1007 return NO_ERR;
1008 }
1009 stm.switching_device.store(true, Ordering::SeqCst);
1010
1011 let mut explicit_device_dead = false;
1012
1013 cubeb_log!(
1014 "({:p}) Handling {} device changed events for device {}",
1015 stm as *const AudioUnitStream,
1016 address_count,
1017 id
1018 );
1019 for (i, addr) in addrs.iter().enumerate() {
1020 let p = PropertySelector::from(addr.mSelector);
1021 cubeb_log!("Event #{}: {}", i, p);
1022 assert_ne!(p, PropertySelector::Unknown);
1023 if p == PropertySelector::DeviceIsAlive {
1024 explicit_device_dead = true;
1025 }
1026 }
1027
1028 // Handle the events
1029 if explicit_device_dead {
1030 if !stm.stopped.swap(true, Ordering::SeqCst) {
1031 cubeb_log!("The user-selected input or output device is dead, entering error state");
1032
1033 // Use a different thread, through the queue, to avoid deadlock when calling
1034 // Get/SetProperties method from inside notify callback
1035 stm.queue.clone().run_async(move || {
1036 stm.core_stream_data.stop_audiounits();
1037 stm.close_on_error();
1038 });
1039 }
1040 return NO_ERR;
1041 }
1042 {
1043 let callback = stm.device_changed_callback.lock().unwrap();
1044 if let Some(device_changed_callback) = *callback {
1045 cubeb_log!("Calling device changed callback");
1046 unsafe {
1047 device_changed_callback(stm.user_ptr);
1048 }
1049 }
1050 }
1051
1052 cubeb_log!("Reinitializing stream with new device because of device change, async");
1053 stm.reinit_async();
1054
1055 NO_ERR
1056 }
1057
1058 fn get_default_device(devtype: DeviceType) -> Option<AudioObjectID> {
1059 debug_assert_running_serially();
1060 match get_default_device_id(devtype) {
1061 Err(e) => {
1062 cubeb_log!("Cannot get default {:?} device. Error: {}", devtype, e);
1063 None
1064 }
1065 Ok(id) if id == kAudioObjectUnknown => {
1066 cubeb_log!("Get an invalid default {:?} device: {}", devtype, id);
1067 None
1068 }
1069 Ok(id) => Some(id),
1070 }
1071 }
1072
1073 fn get_default_device_id(devtype: DeviceType) -> std::result::Result<AudioObjectID, OSStatus> {
1074 debug_assert_running_serially();
1075 let address = get_property_address(
1076 match devtype {
1077 DeviceType::INPUT => Property::HardwareDefaultInputDevice,
1078 DeviceType::OUTPUT => Property::HardwareDefaultOutputDevice,
1079 _ => panic!("Unsupport type"),
1080 },
1081 DeviceType::INPUT | DeviceType::OUTPUT,
1082 );
1083
1084 let mut devid: AudioDeviceID = kAudioObjectUnknown;
1085 let mut size = mem::size_of::<AudioDeviceID>();
1086 let status =
1087 audio_object_get_property_data(kAudioObjectSystemObject, &address, &mut size, &mut devid);
1088 if status == NO_ERR {
1089 Ok(devid)
1090 } else {
1091 Err(status)
1092 }
1093 }
1094
1095 fn audiounit_convert_channel_layout(layout: &AudioChannelLayout) -> Result<Vec<mixer::Channel>> {
1096 if layout.mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions {
1097 // kAudioChannelLayoutTag_UseChannelBitmap
1098 // kAudioChannelLayoutTag_Mono
1099 // kAudioChannelLayoutTag_Stereo
1100 // ....
1101 cubeb_log!("Only handling UseChannelDescriptions for now.\n");
1102 return Err(Error::error());
1103 }
1104
1105 let channel_descriptions = unsafe {
1106 slice::from_raw_parts(
1107 layout.mChannelDescriptions.as_ptr(),
1108 layout.mNumberChannelDescriptions as usize,
1109 )
1110 };
1111
1112 let mut channels = Vec::with_capacity(layout.mNumberChannelDescriptions as usize);
1113 for description in channel_descriptions {
1114 let label = CAChannelLabel(description.mChannelLabel);
1115 channels.push(label.into());
1116 }
1117
1118 Ok(channels)
1119 }
1120
1121 fn audiounit_get_preferred_channel_layout(output_unit: AudioUnit) -> Result<Vec<mixer::Channel>> {
1122 debug_assert_running_serially();
1123 let mut rv = NO_ERR;
1124 let mut size: usize = 0;
1125 rv = audio_unit_get_property_info(
1126 output_unit,
1127 kAudioDevicePropertyPreferredChannelLayout,
1128 kAudioUnitScope_Output,
1129 AU_OUT_BUS,
1130 &mut size,
1131 None,
1132 );
1133 if rv != NO_ERR {
1134 cubeb_log!(
1135 "AudioUnitGetPropertyInfo/kAudioDevicePropertyPreferredChannelLayout rv={}",
1136 rv
1137 );
1138 return Err(Error::error());
1139 }
1140 debug_assert!(size > 0);
1141
1142 let mut layout = make_sized_audio_channel_layout(size);
1143 rv = audio_unit_get_property(
1144 output_unit,
1145 kAudioDevicePropertyPreferredChannelLayout,
1146 kAudioUnitScope_Output,
1147 AU_OUT_BUS,
1148 layout.as_mut(),
1149 &mut size,
1150 );
1151 if rv != NO_ERR {
1152 cubeb_log!(
1153 "AudioUnitGetProperty/kAudioDevicePropertyPreferredChannelLayout rv={}",
1154 rv
1155 );
1156 return Err(Error::error());
1157 }
1158
1159 audiounit_convert_channel_layout(layout.as_ref())
1160 }
1161
1162 // This is for output AudioUnit only. Calling this by input-only AudioUnit is prone
1163 // to crash intermittently.
1164 fn audiounit_get_current_channel_layout(output_unit: AudioUnit) -> Result<Vec<mixer::Channel>> {
1165 debug_assert_running_serially();
1166 let mut rv = NO_ERR;
1167 let mut size: usize = 0;
1168 rv = audio_unit_get_property_info(
1169 output_unit,
1170 kAudioUnitProperty_AudioChannelLayout,
1171 kAudioUnitScope_Output,
1172 AU_OUT_BUS,
1173 &mut size,
1174 None,
1175 );
1176 if rv != NO_ERR {
1177 cubeb_log!(
1178 "AudioUnitGetPropertyInfo/kAudioUnitProperty_AudioChannelLayout rv={}",
1179 rv
1180 );
1181 return Err(Error::error());
1182 }
1183 debug_assert!(size > 0);
1184
1185 let mut layout = make_sized_audio_channel_layout(size);
1186 rv = audio_unit_get_property(
1187 output_unit,
1188 kAudioUnitProperty_AudioChannelLayout,
1189 kAudioUnitScope_Output,
1190 AU_OUT_BUS,
1191 layout.as_mut(),
1192 &mut size,
1193 );
1194 if rv != NO_ERR {
1195 cubeb_log!(
1196 "AudioUnitGetProperty/kAudioUnitProperty_AudioChannelLayout rv={}",
1197 rv
1198 );
1199 return Err(Error::error());
1200 }
1201
1202 audiounit_convert_channel_layout(layout.as_ref())
1203 }
1204
1205 fn get_channel_layout(output_unit: AudioUnit) -> Result<Vec<mixer::Channel>> {
1206 debug_assert_running_serially();
1207 audiounit_get_current_channel_layout(output_unit)
1208 .or_else(|_| {
1209 // The kAudioUnitProperty_AudioChannelLayout property isn't known before
1210 // macOS 10.12, attempt another method.
1211 cubeb_log!(
1212 "Cannot get current channel layout for audiounit @ {:p}. Trying preferred channel layout.",
1213 output_unit
1214 );
1215 audiounit_get_preferred_channel_layout(output_unit)
1216 })
1217 }
1218
1219 fn start_audiounit(unit: AudioUnit) -> Result<()> {
1220 let status = audio_output_unit_start(unit);
1221 if status == NO_ERR {
1222 Ok(())
1223 } else {
1224 cubeb_log!("Cannot start audiounit @ {:p}. Error: {}", unit, status);
1225 Err(Error::error())
1226 }
1227 }
1228
1229 fn stop_audiounit(unit: AudioUnit) -> Result<()> {
1230 let status = audio_output_unit_stop(unit);
1231 if status == NO_ERR {
1232 Ok(())
1233 } else {
1234 cubeb_log!("Cannot stop audiounit @ {:p}. Error: {}", unit, status);
1235 Err(Error::error())
1236 }
1237 }
1238
1239 fn create_audiounit(device: &device_info) -> Result<AudioUnit> {
1240 assert!(device
1241 .flags
1242 .intersects(device_flags::DEV_INPUT | device_flags::DEV_OUTPUT));
1243 assert!(!device
1244 .flags
1245 .contains(device_flags::DEV_INPUT | device_flags::DEV_OUTPUT));
1246 debug_assert_running_serially();
1247
1248 let unit = create_blank_audiounit()?;
1249 let mut bus = AU_OUT_BUS;
1250
1251 if device.flags.contains(device_flags::DEV_INPUT) {
1252 // Input only.
1253 if let Err(e) = enable_audiounit_scope(unit, DeviceType::INPUT, true) {
1254 cubeb_log!("Failed to enable audiounit input scope. Error: {}", e);
1255 dispose_audio_unit(unit);
1256 return Err(Error::error());
1257 }
1258 if let Err(e) = enable_audiounit_scope(unit, DeviceType::OUTPUT, false) {
1259 cubeb_log!("Failed to disable audiounit output scope. Error: {}", e);
1260 dispose_audio_unit(unit);
1261 return Err(Error::error());
1262 }
1263 bus = AU_IN_BUS;
1264 }
1265
1266 if device.flags.contains(device_flags::DEV_OUTPUT) {
1267 // Output only.
1268 if let Err(e) = enable_audiounit_scope(unit, DeviceType::OUTPUT, true) {
1269 cubeb_log!("Failed to enable audiounit output scope. Error: {}", e);
1270 dispose_audio_unit(unit);
1271 return Err(Error::error());
1272 }
1273 if let Err(e) = enable_audiounit_scope(unit, DeviceType::INPUT, false) {
1274 cubeb_log!("Failed to disable audiounit input scope. Error: {}", e);
1275 dispose_audio_unit(unit);
1276 return Err(Error::error());
1277 }
1278 bus = AU_OUT_BUS;
1279 }
1280
1281 if let Err(e) = set_device_to_audiounit(unit, device.id, bus) {
1282 cubeb_log!(
1283 "Failed to set device {} to the created audiounit. Error: {}",
1284 device.id,
1285 e
1286 );
1287 dispose_audio_unit(unit);
1288 return Err(Error::error());
1289 }
1290
1291 Ok(unit)
1292 }
1293
1294 fn get_voiceprocessing_audiounit(
1295 shared_voice_processing_unit: &mut SharedVoiceProcessingUnitManager,
1296 in_device: &device_info,
1297 out_device: &device_info,
1298 ) -> Result<OwningHandle<VoiceProcessingUnit>> {
1299 debug_assert_running_serially();
1300 assert!(in_device.flags.contains(device_flags::DEV_INPUT));
1301 assert!(!in_device.flags.contains(device_flags::DEV_OUTPUT));
1302 assert!(!out_device.flags.contains(device_flags::DEV_INPUT));
1303
1304 let unit_handle = shared_voice_processing_unit.take_or_create();
1305 if let Err(e) = unit_handle {
1306 cubeb_log!(
1307 "Failed to create shared voiceprocessing audiounit. Error: {}",
1308 e
1309 );
1310 return Err(Error::error());
1311 }
1312 let mut unit_handle = unit_handle.unwrap();
1313
1314 if let Err(e) = set_device_to_audiounit(unit_handle.as_mut().unit, in_device.id, AU_IN_BUS) {
1315 cubeb_log!(
1316 "Failed to set in device {} to the created audiounit. Error: {}",
1317 in_device.id,
1318 e
1319 );
1320 return Err(Error::error());
1321 }
1322
1323 let has_output = out_device.id != kAudioObjectUnknown;
1324 if let Err(e) =
1325 enable_audiounit_scope(unit_handle.as_mut().unit, DeviceType::OUTPUT, has_output)
1326 {
1327 cubeb_log!("Failed to enable audiounit input scope. Error: {}", e);
1328 return Err(Error::error());
1329 }
1330 if has_output {
1331 if let Err(e) =
1332 set_device_to_audiounit(unit_handle.as_mut().unit, out_device.id, AU_OUT_BUS)
1333 {
1334 cubeb_log!(
1335 "Failed to set out device {} to the created audiounit. Error: {}",
1336 out_device.id,
1337 e
1338 );
1339 return Err(Error::error());
1340 }
1341 }
1342
1343 Ok(unit_handle)
1344 }
1345
1346 fn enable_audiounit_scope(
1347 unit: AudioUnit,
1348 devtype: DeviceType,
1349 enable_io: bool,
1350 ) -> std::result::Result<(), OSStatus> {
1351 assert!(!unit.is_null());
1352
1353 let enable = u32::from(enable_io);
1354 let (scope, element) = match devtype {
1355 DeviceType::INPUT => (kAudioUnitScope_Input, AU_IN_BUS),
1356 DeviceType::OUTPUT => (kAudioUnitScope_Output, AU_OUT_BUS),
1357 _ => panic!(
1358 "Enable AudioUnit {:?} with unsupported type: {:?}",
1359 unit, devtype
1360 ),
1361 };
1362 let status = audio_unit_set_property(
1363 unit,
1364 kAudioOutputUnitProperty_EnableIO,
1365 scope,
1366 element,
1367 &enable,
1368 mem::size_of::<u32>(),
1369 );
1370 if status == NO_ERR {
1371 Ok(())
1372 } else {
1373 Err(status)
1374 }
1375 }
1376
1377 fn set_device_to_audiounit(
1378 unit: AudioUnit,
1379 device_id: AudioObjectID,
1380 bus: AudioUnitElement,
1381 ) -> std::result::Result<(), OSStatus> {
1382 assert!(!unit.is_null());
1383
1384 let status = audio_unit_set_property(
1385 unit,
1386 kAudioOutputUnitProperty_CurrentDevice,
1387 kAudioUnitScope_Global,
1388 bus,
1389 &device_id,
1390 mem::size_of::<AudioDeviceID>(),
1391 );
1392 if status == NO_ERR {
1393 Ok(())
1394 } else {
1395 Err(status)
1396 }
1397 }
1398
1399 fn create_typed_audiounit(sub_type: c_uint) -> Result<AudioUnit> {
1400 let desc = AudioComponentDescription {
1401 componentType: kAudioUnitType_Output,
1402 componentSubType: sub_type,
1403 componentManufacturer: kAudioUnitManufacturer_Apple,
1404 componentFlags: 0,
1405 componentFlagsMask: 0,
1406 };
1407
1408 let comp = unsafe { AudioComponentFindNext(ptr::null_mut(), &desc) };
1409 if comp.is_null() {
1410 cubeb_log!("Could not find matching audio hardware.");
1411 return Err(Error::error());
1412 }
1413 let mut unit: AudioUnit = ptr::null_mut();
1414 let status = unsafe { AudioComponentInstanceNew(comp, &mut unit) };
1415 if status == NO_ERR {
1416 assert!(!unit.is_null());
1417 Ok(unit)
1418 } else {
1419 cubeb_log!("Fail to get a new AudioUnit. Error: {}", status);
1420 Err(Error::error())
1421 }
1422 }
1423
1424 fn create_blank_audiounit() -> Result<AudioUnit> {
1425 #[cfg(not(target_os = "ios"))]
1426 return create_typed_audiounit(kAudioUnitSubType_HALOutput);
1427 #[cfg(target_os = "ios")]
1428 return create_typed_audiounit(kAudioUnitSubType_RemoteIO);
1429 }
1430
1431 fn create_voiceprocessing_audiounit() -> Result<VoiceProcessingUnit> {
1432 let res = create_typed_audiounit(kAudioUnitSubType_VoiceProcessingIO);
1433 if res.is_err() {
1434 return Err(Error::error());
1435 }
1436
1437 match get_default_device(DeviceType::OUTPUT) {
1438 None => {
1439 cubeb_log!("Could not get default output device in order to undo vpio ducking");
1440 }
1441 Some(id) => {
1442 let r = audio_device_duck(id, 1.0, ptr::null_mut(), 0.5);
1443 if r != NO_ERR {
1444 cubeb_log!(
1445 "Failed to undo ducking of voiceprocessing on output device {}. Proceeding... Error: {}",
1446 id,
1447 r
1448 );
1449 }
1450 }
1451 };
1452
1453 res.map(|unit| VoiceProcessingUnit { unit })
1454 }
1455
1456 fn get_buffer_size(unit: AudioUnit, devtype: DeviceType) -> std::result::Result<u32, OSStatus> {
1457 assert!(!unit.is_null());
1458 let (scope, element) = match devtype {
1459 DeviceType::INPUT => (kAudioUnitScope_Output, AU_IN_BUS),
1460 DeviceType::OUTPUT => (kAudioUnitScope_Input, AU_OUT_BUS),
1461 _ => panic!(
1462 "Get buffer size of AudioUnit {:?} with unsupported type: {:?}",
1463 unit, devtype
1464 ),
1465 };
1466 let mut frames: u32 = 0;
1467 let mut size = mem::size_of::<u32>();
1468 let status = audio_unit_get_property(
1469 unit,
1470 kAudioDevicePropertyBufferFrameSize,
1471 scope,
1472 element,
1473 &mut frames,
1474 &mut size,
1475 );
1476 if status == NO_ERR {
1477 Ok(frames)
1478 } else {
1479 Err(status)
1480 }
1481 }
1482
1483 fn set_buffer_size(
1484 unit: AudioUnit,
1485 devtype: DeviceType,
1486 frames: u32,
1487 ) -> std::result::Result<(), OSStatus> {
1488 assert!(!unit.is_null());
1489 let (scope, element) = match devtype {
1490 DeviceType::INPUT => (kAudioUnitScope_Output, AU_IN_BUS),
1491 DeviceType::OUTPUT => (kAudioUnitScope_Input, AU_OUT_BUS),
1492 _ => panic!(
1493 "Set buffer size of AudioUnit {:?} with unsupported type: {:?}",
1494 unit, devtype
1495 ),
1496 };
1497 let status = audio_unit_set_property(
1498 unit,
1499 kAudioDevicePropertyBufferFrameSize,
1500 scope,
1501 element,
1502 &frames,
1503 mem::size_of_val(&frames),
1504 );
1505 if status == NO_ERR {
1506 Ok(())
1507 } else {
1508 Err(status)
1509 }
1510 }
1511
1512 #[allow(clippy::mutex_atomic)] // The mutex needs to be fed into Condvar::wait_timeout.
1513 fn set_buffer_size_sync(unit: AudioUnit, devtype: DeviceType, frames: u32) -> Result<()> {
1514 let current_frames = get_buffer_size(unit, devtype).map_err(|e| {
1515 cubeb_log!(
1516 "Cannot get buffer size of AudioUnit {:?} for {:?}. Error: {}",
1517 unit,
1518 devtype,
1519 e
1520 );
1521 Error::error()
1522 })?;
1523 if frames == current_frames {
1524 cubeb_log!(
1525 "The buffer frame size of AudioUnit {:?} for {:?} is already {}",
1526 unit,
1527 devtype,
1528 frames
1529 );
1530 return Ok(());
1531 }
1532
1533 let waiting_time = Duration::from_millis(100);
1534 let pair = Box::new((Mutex::new(false), Condvar::new()));
1535 let pair_ptr = Box::into_raw(pair);
1536 sync_callback_registry_register(pair_ptr as usize);
1537
1538 assert_eq!(
1539 audio_unit_add_property_listener(
1540 unit,
1541 kAudioDevicePropertyBufferFrameSize,
1542 buffer_size_changed_callback,
1543 pair_ptr as *mut c_void,
1544 ),
1545 NO_ERR
1546 );
1547
1548 let _teardown = finally(|| {
1549 assert_eq!(
1550 audio_unit_remove_property_listener_with_user_data(
1551 unit,
1552 kAudioDevicePropertyBufferFrameSize,
1553 buffer_size_changed_callback,
1554 pair_ptr as *mut c_void,
1555 ),
1556 NO_ERR
1557 );
1558 // Unregister blocks if callback is in-flight (holds registry lock)
1559 sync_callback_registry_unregister(pair_ptr as usize);
1560 // Safe to drop: callback has either completed or will exit early
1561 unsafe { drop(Box::from_raw(pair_ptr)) };
1562 });
1563
1564 set_buffer_size(unit, devtype, frames).map_err(|e| {
1565 cubeb_log!(
1566 "Failed to set buffer size for AudioUnit {:?} for {:?}. Error: {}",
1567 unit,
1568 devtype,
1569 e
1570 );
1571 Error::error()
1572 })?;
1573
1574 let (lock, cvar) = unsafe { &*pair_ptr };
1575 let changed = lock.lock().unwrap();
1576 if !*changed {
1577 let (chg, timeout_res) = cvar.wait_timeout(changed, waiting_time).unwrap();
1578 if timeout_res.timed_out() {
1579 cubeb_log!(
1580 "Timed out for waiting the buffer frame size setting of AudioUnit {:?} for {:?}",
1581 unit,
1582 devtype
1583 );
1584 }
1585 if !*chg {
1586 return Err(Error::error());
1587 }
1588 }
1589
1590 let new_frames = get_buffer_size(unit, devtype).map_err(|e| {
1591 cubeb_log!(
1592 "Cannot get new buffer size of AudioUnit {:?} for {:?}. Error: {}",
1593 unit,
1594 devtype,
1595 e
1596 );
1597 Error::error()
1598 })?;
1599 cubeb_log!(
1600 "The new buffer frames size of AudioUnit {:?} for {:?} is {}",
1601 unit,
1602 devtype,
1603 new_frames
1604 );
1605
1606 extern "C" fn buffer_size_changed_callback(
1607 in_client_data: *mut c_void,
1608 _in_unit: AudioUnit,
1609 in_property_id: AudioUnitPropertyID,
1610 in_scope: AudioUnitScope,
1611 in_element: AudioUnitElement,
1612 ) {
1613 if in_scope == 0 {
1614 return;
1615 }
1616 with_sync_callback_ptr(in_client_data, || {
1617 assert!(in_element == AU_IN_BUS || in_element == AU_OUT_BUS);
1618 assert_eq!(in_property_id, kAudioDevicePropertyBufferFrameSize);
1619 let pair = unsafe { &*(in_client_data as *const (Mutex<bool>, Condvar)) };
1620 let (lock, cvar) = pair;
1621 let mut changed = lock.lock().unwrap();
1622 *changed = true;
1623 cvar.notify_one();
1624 });
1625 }
1626
1627 Ok(())
1628 }
1629
1630 fn convert_uint32_into_string(data: u32) -> CString {
1631 let empty = CString::default();
1632 if data == 0 {
1633 return empty;
1634 }
1635
1636 // Reverse 0xWXYZ into 0xZYXW.
1637 let mut buffer = vec![b'\x00'; 4]; // 4 bytes for uint32.
1638 buffer[0] = (data >> 24) as u8;
1639 buffer[1] = (data >> 16) as u8;
1640 buffer[2] = (data >> 8) as u8;
1641 buffer[3] = (data) as u8;
1642
1643 // CString::new() will consume the input bytes vec and add a '\0' at the
1644 // end of the bytes. The input bytes vec must not contain any 0 bytes in
1645 // it in case causing memory leaks.
1646 CString::new(buffer).unwrap_or(empty)
1647 }
1648
1649 fn get_channel_count(
1650 devid: AudioObjectID,
1651 devtype: DeviceType,
1652 ) -> std::result::Result<u32, OSStatus> {
1653 assert_ne!(devid, kAudioObjectUnknown);
1654 debug_assert_running_serially();
1655
1656 let devstreams = get_device_streams(devid, devtype)?;
1657 let mut count: u32 = 0;
1658 for ds in devstreams {
1659 if devtype == DeviceType::INPUT
1660 && CoreStreamData::should_force_vpio_for_input_device(ds.device)
1661 {
1662 count += 1;
1663 } else {
1664 count += get_stream_virtual_format(ds.stream)
1665 .map(|f| f.mChannelsPerFrame)
1666 .unwrap_or(0);
1667 }
1668 }
1669 Ok(count)
1670 }
1671
1672 fn get_range_of_sample_rates(
1673 devid: AudioObjectID,
1674 devtype: DeviceType,
1675 ) -> std::result::Result<(f64, f64), String> {
1676 debug_assert_running_serially();
1677 let result = get_ranges_of_device_sample_rate(devid, devtype);
1678 if let Err(e) = result {
1679 return Err(format!("status {}", e));
1680 }
1681 let rates = result.unwrap();
1682 if rates.is_empty() {
1683 return Err(String::from("No data"));
1684 }
1685 let (mut min, mut max) = (f64::MAX, f64::MIN);
1686 for rate in rates {
1687 if rate.mMaximum > max {
1688 max = rate.mMaximum;
1689 }
1690 if rate.mMinimum < min {
1691 min = rate.mMinimum;
1692 }
1693 }
1694 Ok((min, max))
1695 }
1696
1697 fn get_fixed_latency(devid: AudioObjectID, devtype: DeviceType) -> u32 {
1698 debug_assert_running_serially();
1699 let device_latency = match get_device_latency(devid, devtype) {
1700 Ok(latency) => latency,
1701 Err(e) => {
1702 cubeb_log!(
1703 "Cannot get the device latency for device {} in {:?} scope. Error: {}",
1704 devid,
1705 devtype,
1706 e
1707 );
1708 0 // default device latency
1709 }
1710 };
1711
1712 let stream_latency = get_device_streams(devid, devtype).and_then(|devstreams| {
1713 if devstreams.is_empty() {
1714 cubeb_log!(
1715 "No stream on device {} in {:?} scope!",
1716 devid,
1717 devtype
1718 );
1719 Ok(0) // default stream latency
1720 } else {
1721 get_stream_latency(devstreams[0].stream)
1722 }
1723 }).inspect_err(|e| {
1724 cubeb_log!(
1725 "Cannot get the stream, or the latency of the first stream on device {} in {:?} scope. Error: {}",
1726 devid,
1727 devtype,
1728 e
1729 );
1730 }).unwrap_or(0); // default stream latency
1731
1732 device_latency + stream_latency
1733 }
1734
1735 #[allow(non_upper_case_globals)]
1736 fn get_device_group_id(
1737 id: AudioDeviceID,
1738 devtype: DeviceType,
1739 ) -> std::result::Result<CString, OSStatus> {
1740 debug_assert_running_serially();
1741 match get_device_transport_type(id, devtype) {
1742 Ok(kAudioDeviceTransportTypeBuiltIn) => {
1743 cubeb_log!(
1744 "The transport type is {:?}",
1745 convert_uint32_into_string(kAudioDeviceTransportTypeBuiltIn)
1746 );
1747 match get_custom_group_id(id, devtype) {
1748 Some(id) => return Ok(id),
1749 None => {
1750 cubeb_log!("Getting model UID instead.");
1751 }
1752 };
1753 }
1754 Ok(trans_type) => {
1755 cubeb_log!(
1756 "The transport type is {:?}. Getting model UID instead.",
1757 convert_uint32_into_string(trans_type)
1758 );
1759 }
1760 Err(e) => {
1761 cubeb_log!(
1762 "Error: {} when getting transport type. Get model uid instead.",
1763 e
1764 );
1765 }
1766 }
1767
1768 // Some devices (e.g. AirPods) might only set the model-uid in the global scope.
1769 // The query might fail if the scope is input-only or output-only.
1770 get_device_model_uid(id, devtype)
1771 .or_else(|_| get_device_model_uid(id, DeviceType::INPUT | DeviceType::OUTPUT))
1772 .map(|uid| uid.into_cstring())
1773 }
1774
1775 fn get_custom_group_id(id: AudioDeviceID, devtype: DeviceType) -> Option<CString> {
1776 debug_assert_running_serially();
1777
1778 const IMIC: u32 = 0x696D_6963; // "imic" (internal microphone)
1779 const ISPK: u32 = 0x6973_706B; // "ispk" (internal speaker)
1780 const EMIC: u32 = 0x656D_6963; // "emic" (external microphone)
1781 const HDPN: u32 = 0x6864_706E; // "hdpn" (headphone)
1782
1783 match get_device_source(id, devtype) {
1784 s @ Ok(IMIC) | s @ Ok(ISPK) => {
1785 const GROUP_ID: &str = "builtin-internal-mic|spk";
1786 cubeb_log!(
1787 "Using hardcode group id: {} when source is: {:?}.",
1788 GROUP_ID,
1789 convert_uint32_into_string(s.unwrap())
1790 );
1791 return Some(CString::new(GROUP_ID).unwrap());
1792 }
1793 s @ Ok(EMIC) | s @ Ok(HDPN) => {
1794 const GROUP_ID: &str = "builtin-external-mic|hdpn";
1795 cubeb_log!(
1796 "Using hardcode group id: {} when source is: {:?}.",
1797 GROUP_ID,
1798 convert_uint32_into_string(s.unwrap())
1799 );
1800 return Some(CString::new(GROUP_ID).unwrap());
1801 }
1802 Ok(s) => {
1803 cubeb_log!(
1804 "No custom group id when source is: {:?}.",
1805 convert_uint32_into_string(s)
1806 );
1807 }
1808 Err(e) => {
1809 cubeb_log!("Error: {} when getting device source. ", e);
1810 }
1811 }
1812 None
1813 }
1814
1815 fn get_device_label(
1816 id: AudioDeviceID,
1817 devtype: DeviceType,
1818 ) -> std::result::Result<StringRef, OSStatus> {
1819 debug_assert_running_serially();
1820 get_device_source_name(id, devtype).or_else(|_| get_device_name(id, devtype))
1821 }
1822
1823 fn get_device_global_uid(id: AudioDeviceID) -> std::result::Result<StringRef, OSStatus> {
1824 debug_assert_running_serially();
1825 get_device_uid(id, DeviceType::INPUT | DeviceType::OUTPUT)
1826 }
1827
1828 #[allow(clippy::cognitive_complexity)]
1829 fn create_cubeb_device_info(
1830 devid: AudioObjectID,
1831 devtype: DeviceType,
1832 ) -> Result<ffi::cubeb_device_info> {
1833 if devtype != DeviceType::INPUT && devtype != DeviceType::OUTPUT {
1834 return Err(Error::error());
1835 }
1836 let channels = get_channel_count(devid, devtype).map_err(|e| {
1837 cubeb_log!("Cannot get the channel count. Error: {}", e);
1838 Error::error()
1839 })?;
1840 if channels == 0 {
1841 // Invalid type for this device.
1842 return Err(Error::error());
1843 }
1844
1845 let mut dev_info = ffi::cubeb_device_info {
1846 max_channels: channels,
1847 ..Default::default()
1848 };
1849
1850 assert!(
1851 mem::size_of::<ffi::cubeb_devid>() >= mem::size_of_val(&devid),
1852 "cubeb_devid can't represent devid"
1853 );
1854 dev_info.devid = devid as ffi::cubeb_devid;
1855
1856 match get_device_uid(devid, devtype) {
1857 Ok(uid) => {
1858 let c_string = uid.into_cstring();
1859 dev_info.device_id = c_string.into_raw();
1860 }
1861 Err(e) => {
1862 cubeb_log!(
1863 "Cannot get the UID for device {} in {:?} scope. Error: {}",
1864 devid,
1865 devtype,
1866 e
1867 );
1868 }
1869 }
1870
1871 match get_device_group_id(devid, devtype) {
1872 Ok(group_id) => {
1873 dev_info.group_id = group_id.into_raw();
1874 }
1875 Err(e) => {
1876 cubeb_log!(
1877 "Cannot get the model UID for device {} in {:?} scope. Error: {}",
1878 devid,
1879 devtype,
1880 e
1881 );
1882 }
1883 }
1884
1885 let label = match get_device_label(devid, devtype) {
1886 Ok(label) => label.into_cstring(),
1887 Err(e) => {
1888 cubeb_log!(
1889 "Cannot get the label for device {} in {:?} scope. Error: {}",
1890 devid,
1891 devtype,
1892 e
1893 );
1894 CString::default()
1895 }
1896 };
1897 dev_info.friendly_name = label.into_raw();
1898
1899 match get_device_manufacturer(devid, devtype) {
1900 Ok(vendor) => {
1901 let vendor = vendor.into_cstring();
1902 dev_info.vendor_name = vendor.into_raw();
1903 }
1904 Err(e) => {
1905 cubeb_log!(
1906 "Cannot get the manufacturer for device {} in {:?} scope. Error: {}",
1907 devid,
1908 devtype,
1909 e
1910 );
1911 }
1912 }
1913
1914 dev_info.device_type = match devtype {
1915 DeviceType::INPUT => ffi::CUBEB_DEVICE_TYPE_INPUT,
1916 DeviceType::OUTPUT => ffi::CUBEB_DEVICE_TYPE_OUTPUT,
1917 _ => panic!("invalid type"),
1918 };
1919
1920 dev_info.state = ffi::CUBEB_DEVICE_STATE_ENABLED;
1921 dev_info.preferred = match get_default_device(devtype) {
1922 Some(id) if id == devid => ffi::CUBEB_DEVICE_PREF_ALL,
1923 _ => ffi::CUBEB_DEVICE_PREF_NONE,
1924 };
1925
1926 dev_info.format = ffi::CUBEB_DEVICE_FMT_ALL;
1927 dev_info.default_format = ffi::CUBEB_DEVICE_FMT_F32NE;
1928
1929 match get_device_sample_rate(devid, devtype) {
1930 Ok(rate) => {
1931 dev_info.default_rate = rate as u32;
1932 }
1933 Err(e) => {
1934 cubeb_log!(
1935 "Cannot get the sample rate for device {} in {:?} scope. Error: {}",
1936 devid,
1937 devtype,
1938 e
1939 );
1940 }
1941 }
1942
1943 match get_range_of_sample_rates(devid, devtype) {
1944 Ok((min, max)) => {
1945 dev_info.min_rate = min as u32;
1946 dev_info.max_rate = max as u32;
1947 }
1948 Err(e) => {
1949 cubeb_log!(
1950 "Cannot get the range of sample rate for device {} in {:?} scope. Error: {}",
1951 devid,
1952 devtype,
1953 e
1954 );
1955 }
1956 }
1957
1958 let latency = get_fixed_latency(devid, devtype);
1959
1960 let (latency_low, latency_high) = match get_device_buffer_frame_size_range(devid, devtype) {
1961 Ok(range) => (
1962 latency + range.mMinimum as u32,
1963 latency + range.mMaximum as u32,
1964 ),
1965 Err(e) => {
1966 cubeb_log!("Cannot get the buffer frame size for device {} in {:?} scope. Using default value instead. Error: {}", devid, devtype, e);
1967 (
1968 10 * dev_info.default_rate / 1000,
1969 100 * dev_info.default_rate / 1000,
1970 )
1971 }
1972 };
1973 dev_info.latency_lo = latency_low;
1974 dev_info.latency_hi = latency_high;
1975
1976 Ok(dev_info)
1977 }
1978
1979 fn destroy_cubeb_device_info(device: &mut ffi::cubeb_device_info) {
1980 // This should be mapped to the memory allocation in `create_cubeb_device_info`.
1981 // The `device_id`, `group_id`, `vendor_name` can be null pointer if the queries
1982 // failed, while `friendly_name` will be assigned to a default empty "" string.
1983 // Set the pointers to null in case it points to some released memory.
1984 unsafe {
1985 if !device.device_id.is_null() {
1986 let _ = CString::from_raw(device.device_id as *mut _);
1987 device.device_id = ptr::null();
1988 }
1989
1990 if !device.group_id.is_null() {
1991 let _ = CString::from_raw(device.group_id as *mut _);
1992 device.group_id = ptr::null();
1993 }
1994
1995 assert!(!device.friendly_name.is_null());
1996 let _ = CString::from_raw(device.friendly_name as *mut _);
1997 device.friendly_name = ptr::null();
1998
1999 if !device.vendor_name.is_null() {
2000 let _ = CString::from_raw(device.vendor_name as *mut _);
2001 device.vendor_name = ptr::null();
2002 }
2003 }
2004 }
2005
2006 fn audiounit_get_devices_of_type(devtype: DeviceType) -> Vec<AudioObjectID> {
2007 assert!(devtype.intersects(DeviceType::INPUT | DeviceType::OUTPUT));
2008 debug_assert_running_serially();
2009
2010 let mut devices = get_devices();
2011
2012 // Remove the aggregate device from the list of devices (if any).
2013 devices.retain(|&device| {
2014 // TODO: (bug 1628411) Figure out when `device` is `kAudioObjectUnknown`.
2015 if device == kAudioObjectUnknown {
2016 false
2017 } else if let Ok(uid) = get_device_global_uid(device) {
2018 let uid = uid.into_string();
2019 !uid.contains(PRIVATE_AGGREGATE_DEVICE_NAME)
2020 && !uid.contains(VOICEPROCESSING_AGGREGATE_DEVICE_NAME)
2021 } else {
2022 // Fail to get device uid.
2023 true
2024 }
2025 });
2026
2027 // Expected sorted but did not find anything in the docs.
2028 devices.sort_unstable();
2029 if devtype.contains(DeviceType::INPUT | DeviceType::OUTPUT) {
2030 return devices;
2031 }
2032
2033 let mut devices_in_scope = Vec::new();
2034 for device in devices {
2035 let label = match get_device_label(device, DeviceType::OUTPUT | DeviceType::INPUT) {
2036 Ok(label) => label.into_string(),
2037 Err(e) => format!("Unknown(error: {})", e),
2038 };
2039 let info = format!("{} ({})", device, label);
2040
2041 if let Ok(channels) = get_channel_count(device, devtype) {
2042 cubeb_log!("Device {} has {} {:?}-channels", info, channels, devtype);
2043 if channels > 0 {
2044 devices_in_scope.push(device);
2045 }
2046 } else {
2047 cubeb_log!("Cannot get the channel count for device {}. Ignored.", info);
2048 }
2049 }
2050
2051 devices_in_scope
2052 }
2053
2054 extern "C" fn audiounit_collection_changed_callback(
2055 _in_object_id: AudioObjectID,
2056 _in_number_addresses: u32,
2057 _in_addresses: *const AudioObjectPropertyAddress,
2058 in_client_data: *mut c_void,
2059 ) -> OSStatus {
2060 let context = unsafe { &mut *(in_client_data as *mut AudioUnitContext) };
2061
2062 let queue = context.serial_queue.clone();
2063
2064 // This can be called from inside an AudioUnit function, dispatch to another queue.
2065 queue.run_async(move || {
2066 let ctx_ptr = context as *const AudioUnitContext;
2067
2068 let mut devices = context.devices.lock().unwrap();
2069
2070 if devices.input.changed_callback.is_none() && devices.output.changed_callback.is_none() {
2071 return;
2072 }
2073 if devices.input.changed_callback.is_some() {
2074 let input_devices = audiounit_get_devices_of_type(DeviceType::INPUT);
2075 if devices.input.update_devices(input_devices) {
2076 unsafe {
2077 devices.input.changed_callback.unwrap()(
2078 ctx_ptr as *mut ffi::cubeb,
2079 devices.input.callback_user_ptr,
2080 );
2081 }
2082 }
2083 }
2084 if devices.output.changed_callback.is_some() {
2085 let output_devices = audiounit_get_devices_of_type(DeviceType::OUTPUT);
2086 if devices.output.update_devices(output_devices) {
2087 unsafe {
2088 devices.output.changed_callback.unwrap()(
2089 ctx_ptr as *mut ffi::cubeb,
2090 devices.output.callback_user_ptr,
2091 );
2092 }
2093 }
2094 }
2095 });
2096
2097 NO_ERR
2098 }
2099
2100 #[derive(Debug)]
2101 struct DevicesData {
2102 changed_callback: ffi::cubeb_device_collection_changed_callback,
2103 callback_user_ptr: *mut c_void,
2104 devices: Vec<AudioObjectID>,
2105 }
2106
2107 impl DevicesData {
2108 fn set(
2109 &mut self,
2110 changed_callback: ffi::cubeb_device_collection_changed_callback,
2111 callback_user_ptr: *mut c_void,
2112 devices: Vec<AudioObjectID>,
2113 ) {
2114 self.changed_callback = changed_callback;
2115 self.callback_user_ptr = callback_user_ptr;
2116 self.devices = devices;
2117 }
2118
2119 fn update_devices(&mut self, devices: Vec<AudioObjectID>) -> bool {
2120 // Elements in the vector expected sorted.
2121 if self.devices == devices {
2122 return false;
2123 }
2124 self.devices = devices;
2125 true
2126 }
2127
2128 fn clear(&mut self) {
2129 self.changed_callback = None;
2130 self.callback_user_ptr = ptr::null_mut();
2131 self.devices.clear();
2132 }
2133
2134 fn is_empty(&self) -> bool {
2135 self.changed_callback.is_none()
2136 && self.callback_user_ptr.is_null()
2137 && self.devices.is_empty()
2138 }
2139 }
2140
2141 impl Default for DevicesData {
2142 fn default() -> Self {
2143 Self {
2144 changed_callback: None,
2145 callback_user_ptr: ptr::null_mut(),
2146 devices: Vec::new(),
2147 }
2148 }
2149 }
2150
2151 #[derive(Debug, Default)]
2152 struct SharedDevices {
2153 input: DevicesData,
2154 output: DevicesData,
2155 }
2156
2157 #[derive(Debug, Default)]
2158 struct LatencyController {
2159 streams: u32,
2160 latency: Option<u32>,
2161 }
2162
2163 impl LatencyController {
2164 fn add_stream(&mut self, latency: u32) -> u32 {
2165 self.streams += 1;
2166 // For the 1st stream set anything within safe min-max
2167 if self.streams == 1 {
2168 assert!(self.latency.is_none());
2169 // Silently clamp the latency down to the platform default, because we
2170 // synthetize the clock from the callbacks, and we want the clock to update often.
2171 self.latency = Some(latency.clamp(SAFE_MIN_LATENCY_FRAMES, SAFE_MAX_LATENCY_FRAMES));
2172 }
2173 self.latency.unwrap_or(latency)
2174 }
2175
2176 fn subtract_stream(&mut self) {
2177 self.streams -= 1;
2178 if self.streams == 0 {
2179 assert!(self.latency.is_some());
2180 self.latency = None;
2181 }
2182 }
2183 }
2184
2185 // SharedStorage<T> below looks generic but has evolved to be pretty tailored
2186 // the observed behavior of VoiceProcessingIO audio units on macOS 14.
2187 // Some key points are:
2188 // - Creating the first VoiceProcessingIO unit in a process takes a long time, often > 3s.
2189 // - Creating a second VoiceProcessingIO unit in a process is significantly faster, < 1s.
2190 // - Disposing of a VoiceProcessingIO unit when all other VoiceProcessingIO units are
2191 // uninitialized will take significantly longer than disposing the remaining
2192 // VoiceProcessingIO units, and will have other side effects: starting another
2193 // VoiceProcessingIO unit after this is on par with creating the first one in the
2194 // process, bluetooth devices will move away from the handsfree profile, etc.
2195 // The takeaway is that there is something internal to the VoiceProcessingIO audio unit
2196 // that is costly to create and dispose of and its creation is triggered by creation of
2197 // the first VoiceProcessingIO unit, and its disposal is triggered by the disposal of
2198 // the first VoiceProcessingIO unit when no other VoiceProcessingIO units are initialized.
2199 //
2200 // The intended behavior of SharedStorage<T> and SharedVoiceProcessingUnitManager is therefore:
2201 // - Retain ideally just one VoiceProcessingIO unit after stream destruction, so device
2202 // switching is fast. The benefit of retaining more than one is unclear.
2203 // - Dispose of either all VoiceProcessingIO units, or none at all, such that the retained
2204 // VoiceProcessingIO unit really helps speed up creating and starting the next. In practice
2205 // this means we retain all VoiceProcessingIO units until they can all be disposed of.
2206
2207 #[derive(Debug)]
2208 struct SharedStorageInternal<T> {
2209 // Storage for shared elements.
2210 elements: Vec<T>,
2211 // Number of elements in use, i.e. all elements created/taken and not recycled.
2212 outstanding_element_count: usize,
2213 // Used for invalidation of in-flight tasks to clear elements.
2214 // Incremented when something takes a shared element.
2215 generation: usize,
2216 }
2217
2218 #[derive(Debug)]
2219 struct SharedStorage<T> {
2220 queue: Queue,
2221 idle_timeout: Duration,
2222 storage: Mutex<SharedStorageInternal<T>>,
2223 }
2224
2225 impl<T: Send> SharedStorage<T> {
2226 fn with_idle_timeout(queue: Queue, idle_timeout: Duration) -> Self {
2227 Self {
2228 queue,
2229 idle_timeout,
2230 storage: Mutex::new(SharedStorageInternal::<T> {
2231 elements: Vec::default(),
2232 outstanding_element_count: 0,
2233 generation: 0,
2234 }),
2235 }
2236 }
2237
2238 fn take_locked(guard: &mut MutexGuard<'_, SharedStorageInternal<T>>) -> Result<T> {
2239 if let Some(e) = guard.elements.pop() {
2240 cubeb_log!("Taking shared element #{}.", guard.elements.len());
2241 guard.outstanding_element_count += 1;
2242 guard.generation += 1;
2243 return Ok(e);
2244 }
2245
2246 Err(Error::not_supported())
2247 }
2248
2249 fn create_with_locked<F>(
2250 guard: &mut MutexGuard<'_, SharedStorageInternal<T>>,
2251 f: F,
2252 ) -> Result<T>
2253 where
2254 F: FnOnce() -> Result<T>,
2255 {
2256 let start = Instant::now();
2257 match f() {
2258 Ok(obj) => {
2259 cubeb_log!(
2260 "Just created shared element #{}. Took {}s.",
2261 guard.outstanding_element_count,
2262 (Instant::now() - start).as_secs_f32()
2263 );
2264 guard.outstanding_element_count += 1;
2265 guard.generation += 1;
2266 Ok(obj)
2267 }
2268 Err(_) => {
2269 cubeb_log!("Creating shared element failed");
2270 Err(Error::error())
2271 }
2272 }
2273 }
2274
2275 #[cfg(test)]
2276 fn take(&self) -> Result<T> {
2277 let mut guard = self.storage.lock().unwrap();
2278 SharedStorage::take_locked(&mut guard)
2279 }
2280
2281 fn take_or_create_with<F>(&self, f: F) -> Result<T>
2282 where
2283 F: FnOnce() -> Result<T>,
2284 {
2285 let mut guard = self.storage.lock().unwrap();
2286 SharedStorage::take_locked(&mut guard)
2287 .or_else(|_| SharedStorage::create_with_locked(&mut guard, f))
2288 }
2289
2290 fn recycle(&self, obj: T) {
2291 let mut guard = self.storage.lock().unwrap();
2292 guard.outstanding_element_count -= 1;
2293 cubeb_log!(
2294 "Recycling shared element #{}. Nr of live elements now {}.",
2295 guard.elements.len(),
2296 guard.outstanding_element_count
2297 );
2298 guard.elements.push(obj);
2299 }
2300
2301 fn clear_locked(guard: &mut MutexGuard<'_, SharedStorageInternal<T>>) {
2302 let count = guard.elements.len();
2303 let start = Instant::now();
2304 guard.elements.clear();
2305 cubeb_log!(
2306 "Cleared {} shared element{}. Took {}s.",
2307 count,
2308 if count == 1 { "" } else { "s" },
2309 (Instant::now() - start).as_secs_f32()
2310 );
2311 }
2312
2313 fn clear(&self) {
2314 debug_assert_running_serially();
2315 let mut guard = self.storage.lock().unwrap();
2316 SharedStorage::clear_locked(&mut guard);
2317 }
2318
2319 fn clear_if_all_idle_async(storage: &Arc<SharedStorage<T>>) {
2320 let (queue, outstanding_element_count, generation) = {
2321 let guard = storage.storage.lock().unwrap();
2322 (
2323 storage.queue.clone(),
2324 guard.outstanding_element_count,
2325 guard.generation,
2326 )
2327 };
2328 if outstanding_element_count > 0 {
2329 cubeb_log!(
2330 "Not clearing shared voiceprocessing unit storage because {} elements are in use. Generation={}.",
2331 outstanding_element_count,
2332 generation
2333 );
2334 return;
2335 }
2336 cubeb_log!(
2337 "Clearing shared voiceprocessing unit storage in {}s if still at generation {}.",
2338 storage.idle_timeout.as_secs_f32(),
2339 generation
2340 );
2341 let storage = storage.clone();
2342 queue.run_after(Instant::now() + storage.idle_timeout, move || {
2343 let mut guard = storage.storage.lock().unwrap();
2344 if generation != guard.generation {
2345 cubeb_log!(
2346 "Not clearing shared voiceprocessing unit storage for generation {} as we're now at {}.",
2347 generation,
2348 guard.generation
2349 );
2350 return;
2351 }
2352 SharedStorage::clear_locked(&mut guard);
2353 });
2354 }
2355 }
2356
2357 #[derive(Debug)]
2358 struct OwningHandle<T>
2359 where
2360 T: Send,
2361 {
2362 storage: Weak<SharedStorage<T>>,
2363 obj: Option<T>,
2364 }
2365
2366 impl<T: Send> OwningHandle<T> {
2367 fn new(storage: Weak<SharedStorage<T>>, obj: T) -> Self {
2368 Self {
2369 storage,
2370 obj: Some(obj),
2371 }
2372 }
2373 }
2374
2375 impl<T: Send> AsRef<T> for OwningHandle<T> {
2376 fn as_ref(&self) -> &T {
2377 self.obj.as_ref().unwrap()
2378 }
2379 }
2380
2381 impl<T: Send> AsMut<T> for OwningHandle<T> {
2382 fn as_mut(&mut self) -> &mut T {
2383 self.obj.as_mut().unwrap()
2384 }
2385 }
2386
2387 impl<T: Send> Drop for OwningHandle<T> {
2388 fn drop(&mut self) {
2389 let storage = self.storage.upgrade();
2390 assert!(
2391 storage.is_some(),
2392 "Storage must outlive the handle, but didn't"
2393 );
2394 let storage = storage.unwrap();
2395 if self.obj.is_none() {
2396 return;
2397 }
2398 let obj = self.obj.take().unwrap();
2399 storage.recycle(obj);
2400 SharedStorage::clear_if_all_idle_async(&storage);
2401 }
2402 }
2403
2404 #[derive(Debug)]
2405 struct VoiceProcessingUnit {
2406 unit: AudioUnit,
2407 }
2408
2409 impl Drop for VoiceProcessingUnit {
2410 fn drop(&mut self) {
2411 assert!(!self.unit.is_null());
2412 dispose_audio_unit(self.unit);
2413 }
2414 }
2415
2416 unsafe impl Send for VoiceProcessingUnit {}
2417
2418 #[derive(Debug)]
2419 struct SharedVoiceProcessingUnitManager {
2420 sync_storage: Mutex<Option<Arc<SharedStorage<VoiceProcessingUnit>>>>,
2421 queue: Queue,
2422 idle_timeout: Duration,
2423 }
2424
2425 impl SharedVoiceProcessingUnitManager {
2426 fn with_idle_timeout(queue: Queue, idle_timeout: Duration) -> Self {
2427 Self {
2428 sync_storage: Mutex::new(None),
2429 queue,
2430 idle_timeout,
2431 }
2432 }
2433
2434 fn new(queue: Queue) -> Self {
2435 SharedVoiceProcessingUnitManager::with_idle_timeout(queue, VPIO_IDLE_TIMEOUT)
2436 }
2437
2438 fn ensure_storage_locked(
2439 &self,
2440 guard: &mut MutexGuard<Option<Arc<SharedStorage<VoiceProcessingUnit>>>>,
2441 ) {
2442 if guard.is_some() {
2443 return;
2444 }
2445 cubeb_log!("Creating shared voiceprocessing storage.");
2446 let storage = SharedStorage::<VoiceProcessingUnit>::with_idle_timeout(
2447 self.queue.clone(),
2448 self.idle_timeout,
2449 );
2450 let old_storage = guard.replace(Arc::from(storage));
2451 assert!(old_storage.is_none());
2452 }
2453
2454 // Take an already existing, shared, vpio unit, if one is available.
2455 #[cfg(test)]
2456 fn take(&mut self) -> Result<OwningHandle<VoiceProcessingUnit>> {
2457 debug_assert_running_serially();
2458 let mut guard = self.sync_storage.lock().unwrap();
2459 self.ensure_storage_locked(&mut guard);
2460 let storage = guard.as_mut().unwrap();
2461 let res = storage.take();
2462 res.map(|u| OwningHandle::new(Arc::downgrade(storage), u))
2463 }
2464
2465 // Take an already existing, shared, vpio unit, or create one if none are available.
2466 fn take_or_create(&mut self) -> Result<OwningHandle<VoiceProcessingUnit>> {
2467 debug_assert_running_serially();
2468 let mut guard = self.sync_storage.lock().unwrap();
2469 self.ensure_storage_locked(&mut guard);
2470 let storage = guard.as_mut().unwrap();
2471 let res = storage.take_or_create_with(create_voiceprocessing_audiounit);
2472 res.map(|u| OwningHandle::new(Arc::downgrade(storage), u))
2473 }
2474 }
2475
2476 unsafe impl Send for SharedVoiceProcessingUnitManager {}
2477 unsafe impl Sync for SharedVoiceProcessingUnitManager {}
2478
2479 impl Drop for SharedVoiceProcessingUnitManager {
2480 fn drop(&mut self) {
2481 debug_assert_not_running_serially();
2482 self.queue.run_final(|| {
2483 let mut guard = self.sync_storage.lock().unwrap();
2484 if guard.is_none() {
2485 return;
2486 }
2487 guard.as_mut().unwrap().clear();
2488 });
2489 }
2490 }
2491
2492 pub const OPS: Ops = capi_new!(AudioUnitContext, AudioUnitStream);
2493
2494 // The fisrt member of the Cubeb context must be a pointer to a Ops struct. The Ops struct is an
2495 // interface to link to all the Cubeb APIs, and the Cubeb interface use this assumption to operate
2496 // the Cubeb APIs on different implementation.
2497 // #[repr(C)] is used to prevent any padding from being added in the beginning of the AudioUnitContext.
2498 #[repr(C)]
2499 #[derive(Debug)]
2500 pub struct AudioUnitContext {
2501 _ops: *const Ops,
2502 serial_queue: Queue,
2503 latency_controller: Mutex<LatencyController>,
2504 devices: Mutex<SharedDevices>,
2505 host_time_to_ns_ratio: (u32, u32),
2506 // Storage for a context-global vpio unit. Duplex streams that need one will take this
2507 // and return it when done.
2508 shared_voice_processing_unit: SharedVoiceProcessingUnitManager,
2509 }
2510
2511 impl AudioUnitContext {
2512 fn new() -> Self {
2513 let queue_label = format!("{}.context", DISPATCH_QUEUE_LABEL);
2514 let serial_queue =
2515 Queue::new_with_target(queue_label.as_str(), get_serial_queue_singleton());
2516 let shared_vp_queue = Queue::new_with_target(
2517 format!("{}.context.shared_vpio", DISPATCH_QUEUE_LABEL).as_str(),
2518 &serial_queue,
2519 );
2520 let host_time_to_ns_ratio = {
2521 let mut timebase_info = mach_timebase_info { numer: 0, denom: 0 };
2522 unsafe {
2523 mach_timebase_info(&mut timebase_info);
2524 }
2525 (timebase_info.numer, timebase_info.denom)
2526 };
2527 Self {
2528 _ops: &OPS as *const _,
2529 serial_queue,
2530 latency_controller: Mutex::new(LatencyController::default()),
2531 devices: Mutex::new(SharedDevices::default()),
2532 host_time_to_ns_ratio,
2533 shared_voice_processing_unit: SharedVoiceProcessingUnitManager::new(shared_vp_queue),
2534 }
2535 }
2536
2537 fn active_streams(&self) -> u32 {
2538 let controller = self.latency_controller.lock().unwrap();
2539 controller.streams
2540 }
2541
2542 fn update_latency_by_adding_stream(&self, latency_frames: u32) -> u32 {
2543 let mut controller = self.latency_controller.lock().unwrap();
2544 controller.add_stream(latency_frames)
2545 }
2546
2547 fn update_latency_by_removing_stream(&self) {
2548 let mut controller = self.latency_controller.lock().unwrap();
2549 controller.subtract_stream();
2550 }
2551
2552 fn add_devices_changed_listener(
2553 &mut self,
2554 devtype: DeviceType,
2555 collection_changed_callback: ffi::cubeb_device_collection_changed_callback,
2556 user_ptr: *mut c_void,
2557 ) -> Result<()> {
2558 assert!(devtype.intersects(DeviceType::INPUT | DeviceType::OUTPUT));
2559 assert!(collection_changed_callback.is_some());
2560
2561 let context_ptr = self as *mut AudioUnitContext;
2562 let mut devices = self.devices.lock().unwrap();
2563
2564 // Note: second register without unregister first causes 'nope' error.
2565 // Current implementation requires unregister before register a new cb.
2566 if devtype.contains(DeviceType::INPUT) && devices.input.changed_callback.is_some()
2567 || devtype.contains(DeviceType::OUTPUT) && devices.output.changed_callback.is_some()
2568 {
2569 return Err(Error::invalid_parameter());
2570 }
2571
2572 if devices.input.changed_callback.is_none() && devices.output.changed_callback.is_none() {
2573 let address = get_property_address(
2574 Property::HardwareDevices,
2575 DeviceType::INPUT | DeviceType::OUTPUT,
2576 );
2577 let ret = audio_object_add_property_listener(
2578 kAudioObjectSystemObject,
2579 &address,
2580 audiounit_collection_changed_callback,
2581 context_ptr,
2582 );
2583 if ret != NO_ERR {
2584 cubeb_log!(
2585 "Cannot add devices-changed listener for {:?}, Error: {}",
2586 devtype,
2587 ret
2588 );
2589 return Err(Error::error());
2590 }
2591 }
2592
2593 if devtype.contains(DeviceType::INPUT) {
2594 // Expected empty after unregister.
2595 assert!(devices.input.is_empty());
2596 devices.input.set(
2597 collection_changed_callback,
2598 user_ptr,
2599 audiounit_get_devices_of_type(DeviceType::INPUT),
2600 );
2601 }
2602
2603 if devtype.contains(DeviceType::OUTPUT) {
2604 // Expected empty after unregister.
2605 assert!(devices.output.is_empty());
2606 devices.output.set(
2607 collection_changed_callback,
2608 user_ptr,
2609 audiounit_get_devices_of_type(DeviceType::OUTPUT),
2610 );
2611 }
2612
2613 Ok(())
2614 }
2615
2616 fn remove_devices_changed_listener(&mut self, devtype: DeviceType) -> Result<()> {
2617 if !devtype.intersects(DeviceType::INPUT | DeviceType::OUTPUT) {
2618 return Err(Error::invalid_parameter());
2619 }
2620
2621 let context_ptr = self as *mut AudioUnitContext;
2622 let mut devices = self.devices.lock().unwrap();
2623
2624 if devtype.contains(DeviceType::INPUT) {
2625 devices.input.clear();
2626 }
2627
2628 if devtype.contains(DeviceType::OUTPUT) {
2629 devices.output.clear();
2630 }
2631
2632 if devices.input.changed_callback.is_some() || devices.output.changed_callback.is_some() {
2633 return Ok(());
2634 }
2635
2636 let address = get_property_address(
2637 Property::HardwareDevices,
2638 DeviceType::INPUT | DeviceType::OUTPUT,
2639 );
2640 // Note: unregister a non registered cb is not a problem, not checking.
2641 let r = audio_object_remove_property_listener(
2642 kAudioObjectSystemObject,
2643 &address,
2644 audiounit_collection_changed_callback,
2645 context_ptr,
2646 );
2647 if r == NO_ERR {
2648 Ok(())
2649 } else {
2650 cubeb_log!(
2651 "Cannot remove devices-changed listener for {:?}, Error: {}",
2652 devtype,
2653 r
2654 );
2655 Err(Error::error())
2656 }
2657 }
2658 }
2659
2660 impl ContextOps for AudioUnitContext {
2661 fn init(_context_name: Option<&CStr>) -> Result<Context> {
2662 run_serially(set_notification_runloop);
2663 let mut ctx = Box::new(AudioUnitContext::new());
2664 let queue_label = format!("{}.context.{:p}", DISPATCH_QUEUE_LABEL, ctx.as_ref());
2665 ctx.serial_queue =
2666 Queue::new_with_target(queue_label.as_str(), get_serial_queue_singleton());
2667 let shared_vp_queue = Queue::new_with_target(
2668 format!("{}.shared_vpio", queue_label).as_str(),
2669 &ctx.serial_queue,
2670 );
2671 ctx.shared_voice_processing_unit = SharedVoiceProcessingUnitManager::new(shared_vp_queue);
2672 Ok(unsafe { Context::from_ptr(Box::into_raw(ctx) as *mut _) })
2673 }
2674
2675 fn backend_id(&mut self) -> &'static CStr {
2676 unsafe { CStr::from_ptr(b"audiounit-rust\0".as_ptr() as *const _) }
2677 }
2678 #[cfg(target_os = "ios")]
2679 fn max_channel_count(&mut self) -> Result<u32> {
2680 Ok(2u32)
2681 }
2682 #[cfg(not(target_os = "ios"))]
2683 fn max_channel_count(&mut self) -> Result<u32> {
2684 self.serial_queue
2685 .run_sync(|| {
2686 let device = match get_default_device(DeviceType::OUTPUT) {
2687 None => {
2688 cubeb_log!("Could not get default output device");
2689 return Err(Error::error());
2690 }
2691 Some(id) => id,
2692 };
2693 get_channel_count(device, DeviceType::OUTPUT).map_err(|e| {
2694 cubeb_log!("Cannot get the channel count. Error: {}", e);
2695 Error::error()
2696 })
2697 })
2698 .unwrap()
2699 }
2700 #[cfg(target_os = "ios")]
2701 fn min_latency(&mut self, _params: StreamParams) -> Result<u32> {
2702 Err(not_supported());
2703 }
2704 #[cfg(not(target_os = "ios"))]
2705 fn min_latency(&mut self, _params: StreamParams) -> Result<u32> {
2706 self.serial_queue
2707 .run_sync(|| {
2708 let device = match get_default_device(DeviceType::OUTPUT) {
2709 None => {
2710 cubeb_log!("Could not get default output device");
2711 return Err(Error::error());
2712 }
2713 Some(id) => id,
2714 };
2715
2716 let range = get_device_buffer_frame_size_range(device, DeviceType::OUTPUT)
2717 .map_err(|e| {
2718 cubeb_log!("Could not get acceptable latency range. Error: {}", e);
2719 Error::error()
2720 })?;
2721
2722 Ok(cmp::max(range.mMinimum as u32, SAFE_MIN_LATENCY_FRAMES))
2723 })
2724 .unwrap()
2725 }
2726 #[cfg(target_os = "ios")]
2727 fn preferred_sample_rate(&mut self) -> Result<u32> {
2728 Err(not_supported());
2729 }
2730 #[cfg(not(target_os = "ios"))]
2731 fn preferred_sample_rate(&mut self) -> Result<u32> {
2732 self.serial_queue
2733 .run_sync(|| {
2734 let device = match get_default_device(DeviceType::OUTPUT) {
2735 None => {
2736 cubeb_log!("Could not get default output device");
2737 return Err(Error::error());
2738 }
2739 Some(id) => id,
2740 };
2741 let rate = get_device_sample_rate(device, DeviceType::OUTPUT).map_err(|e| {
2742 cubeb_log!(
2743 "Cannot get the sample rate of the default output device. Error: {}",
2744 e
2745 );
2746 Error::error()
2747 })?;
2748 Ok(rate as u32)
2749 })
2750 .unwrap()
2751 }
2752 fn supported_input_processing_params(&mut self) -> Result<InputProcessingParams> {
2753 Ok(InputProcessingParams::ECHO_CANCELLATION
2754 | InputProcessingParams::NOISE_SUPPRESSION
2755 | InputProcessingParams::AUTOMATIC_GAIN_CONTROL)
2756 }
2757 fn enumerate_devices(
2758 &mut self,
2759 devtype: DeviceType,
2760 collection: &DeviceCollectionRef,
2761 ) -> Result<()> {
2762 let device_infos = self
2763 .serial_queue
2764 .run_sync(|| {
2765 let mut dev_types = vec![DeviceType::INPUT, DeviceType::OUTPUT];
2766 dev_types.retain(|&dt| devtype.contains(dt));
2767 let device_ids: Vec<(DeviceType, Vec<AudioObjectID>)> = dev_types
2768 .iter()
2769 .map(|&dt| (dt, audiounit_get_devices_of_type(dt)))
2770 .collect();
2771 let count = device_ids.iter().map(|(_dt, ids)| ids.len()).sum();
2772 let mut device_infos = Vec::with_capacity(count);
2773 for (dt, dev_ids) in device_ids {
2774 for dev_id in dev_ids {
2775 if let Ok(info) = create_cubeb_device_info(dev_id, dt) {
2776 device_infos.push(info);
2777 }
2778 }
2779 }
2780 device_infos
2781 })
2782 .unwrap();
2783 let (ptr, len) = if device_infos.is_empty() {
2784 (ptr::null_mut(), 0)
2785 } else {
2786 forget_vec(device_infos)
2787 };
2788 let coll = unsafe { &mut *collection.as_ptr() };
2789 coll.device = ptr;
2790 coll.count = len;
2791 Ok(())
2792 }
2793 fn device_collection_destroy(&mut self, collection: &mut DeviceCollectionRef) -> Result<()> {
2794 assert!(!collection.as_ptr().is_null());
2795 let coll = unsafe { &mut *collection.as_ptr() };
2796 if coll.device.is_null() {
2797 return Ok(());
2798 }
2799
2800 let mut devices = retake_forgotten_vec(coll.device, coll.count);
2801 for device in &mut devices {
2802 destroy_cubeb_device_info(device);
2803 }
2804 drop(devices); // Release the memory.
2805 coll.device = ptr::null_mut();
2806 coll.count = 0;
2807 Ok(())
2808 }
2809 fn stream_init(
2810 &mut self,
2811 _stream_name: Option<&CStr>,
2812 input_device: DeviceId,
2813 input_stream_params: Option<&StreamParamsRef>,
2814 output_device: DeviceId,
2815 output_stream_params: Option<&StreamParamsRef>,
2816 latency_frames: u32,
2817 data_callback: ffi::cubeb_data_callback,
2818 state_callback: ffi::cubeb_state_callback,
2819 user_ptr: *mut c_void,
2820 ) -> Result<Stream> {
2821 if !input_device.is_null() && input_stream_params.is_none() {
2822 cubeb_log!("Cannot init an input device without input stream params");
2823 return Err(Error::invalid_parameter());
2824 }
2825
2826 if !output_device.is_null() && output_stream_params.is_none() {
2827 cubeb_log!("Cannot init an output device without output stream params");
2828 return Err(Error::invalid_parameter());
2829 }
2830
2831 if input_stream_params.is_none() && output_stream_params.is_none() {
2832 cubeb_log!("Cannot init a stream without any stream params");
2833 return Err(Error::invalid_parameter());
2834 }
2835
2836 if data_callback.is_none() {
2837 cubeb_log!("Cannot init a stream without a data callback");
2838 return Err(Error::invalid_parameter());
2839 }
2840
2841 let in_stm_settings = if let Some(params) = input_stream_params {
2842 let in_device = match self
2843 .serial_queue
2844 .run_sync(|| create_device_info(input_device as AudioDeviceID, DeviceType::INPUT))
2845 .unwrap()
2846 {
2847 None => {
2848 cubeb_log!("Fail to create device info for input");
2849 return Err(Error::error());
2850 }
2851 Some(d) => d,
2852 };
2853 let stm_params = StreamParams::from(unsafe { *params.as_ptr() });
2854 Some((stm_params, in_device))
2855 } else {
2856 None
2857 };
2858
2859 let out_stm_settings = if let Some(params) = output_stream_params {
2860 let out_device = match self
2861 .serial_queue
2862 .run_sync(|| create_device_info(output_device as AudioDeviceID, DeviceType::OUTPUT))
2863 .unwrap()
2864 {
2865 None => {
2866 cubeb_log!("Fail to create device info for output");
2867 return Err(Error::error());
2868 }
2869 Some(d) => d,
2870 };
2871 let stm_params = StreamParams::from(unsafe { *params.as_ptr() });
2872 Some((stm_params, out_device))
2873 } else {
2874 None
2875 };
2876
2877 // Latency cannot change if another stream is operating in parallel. In this case
2878 // latency is set to the other stream value.
2879 let global_latency_frames = self.update_latency_by_adding_stream(latency_frames);
2880 if global_latency_frames != latency_frames {
2881 cubeb_log!(
2882 "Use global latency {} instead of the requested latency {}.",
2883 global_latency_frames,
2884 latency_frames
2885 );
2886 }
2887
2888 let mut boxed_stream = Box::new(AudioUnitStream::new(
2889 self,
2890 user_ptr,
2891 data_callback,
2892 state_callback,
2893 global_latency_frames,
2894 ));
2895
2896 // Rename the task queue to be an unique label.
2897 let queue_label = format!(
2898 "{}.stream.{:p}",
2899 DISPATCH_QUEUE_LABEL,
2900 boxed_stream.as_ref()
2901 );
2902 boxed_stream.queue = Queue::new_with_target(queue_label.as_str(), &boxed_stream.queue);
2903
2904 boxed_stream.core_stream_data =
2905 CoreStreamData::new(boxed_stream.as_ref(), in_stm_settings, out_stm_settings);
2906
2907 let result = boxed_stream
2908 .queue
2909 .clone()
2910 .run_sync(|| {
2911 boxed_stream
2912 .core_stream_data
2913 .setup(&mut boxed_stream.context.shared_voice_processing_unit)
2914 })
2915 .unwrap();
2916 if let Err(r) = result {
2917 cubeb_log!(
2918 "({:p}) Could not setup the audiounit stream.",
2919 boxed_stream.as_ref()
2920 );
2921 return Err(r);
2922 }
2923
2924 let cubeb_stream = unsafe { Stream::from_ptr(Box::into_raw(boxed_stream) as *mut _) };
2925 cubeb_log!(
2926 "({:p}) Cubeb stream init successful.",
2927 cubeb_stream.as_ref()
2928 );
2929 Ok(cubeb_stream)
2930 }
2931 fn register_device_collection_changed(
2932 &mut self,
2933 devtype: DeviceType,
2934 collection_changed_callback: ffi::cubeb_device_collection_changed_callback,
2935 user_ptr: *mut c_void,
2936 ) -> Result<()> {
2937 if devtype == DeviceType::UNKNOWN {
2938 return Err(Error::invalid_parameter());
2939 }
2940 self.serial_queue
2941 .clone()
2942 .run_sync(|| {
2943 if collection_changed_callback.is_some() {
2944 self.add_devices_changed_listener(
2945 devtype,
2946 collection_changed_callback,
2947 user_ptr,
2948 )
2949 } else {
2950 self.remove_devices_changed_listener(devtype)
2951 }
2952 })
2953 .unwrap()
2954 }
2955 }
2956
2957 impl Drop for AudioUnitContext {
2958 fn drop(&mut self) {
2959 assert!({
2960 let devices = self.devices.lock().unwrap();
2961 devices.input.changed_callback.is_none() && devices.output.changed_callback.is_none()
2962 });
2963
2964 self.shared_voice_processing_unit =
2965 SharedVoiceProcessingUnitManager::new(self.serial_queue.clone());
2966
2967 // Make sure all the pending (device-collection-changed-callback) tasks
2968 // in queue are done, and cancel all the tasks appended after `drop` is executed.
2969 let queue = self.serial_queue.clone();
2970 queue.run_final(|| {});
2971
2972 {
2973 let controller = self.latency_controller.lock().unwrap();
2974 // Disabling this assert in release for bug 1083664 -- we seem to leak a stream
2975 // assert(controller.streams == 0);
2976 debug_assert!(controller.streams == 0);
2977 if controller.streams > 0 {
2978 cubeb_log!(
2979 "({:p}) API misuse, {} streams active when context destroyed!",
2980 self as *const AudioUnitContext,
2981 controller.streams
2982 );
2983 }
2984 }
2985 }
2986 }
2987
2988 #[allow(clippy::non_send_fields_in_send_ty)]
2989 unsafe impl Send for AudioUnitContext {}
2990 unsafe impl Sync for AudioUnitContext {}
2991
2992 // Holds the information for an audio input callback call, for debugging purposes.
2993 struct InputCallbackData {
2994 bytes: u32,
2995 rendered_frames: u32,
2996 total_available: usize,
2997 channels: u32,
2998 num_buf: u32,
2999 }
3000 struct InputCallbackLogger {
3001 prod: ringbuf::Producer<InputCallbackData>,
3002 cons: ringbuf::Consumer<InputCallbackData>,
3003 }
3004
3005 impl InputCallbackLogger {
3006 fn new() -> Self {
3007 let ring = RingBuffer::<InputCallbackData>::new(16);
3008 let (prod, cons) = ring.split();
3009 Self { prod, cons }
3010 }
3011
3012 fn push(&mut self, data: InputCallbackData) {
3013 self.prod.push(data);
3014 }
3015
3016 fn pop(&mut self) -> Option<InputCallbackData> {
3017 self.cons.pop()
3018 }
3019
3020 fn is_empty(&self) -> bool {
3021 self.cons.is_empty()
3022 }
3023 }
3024
3025 impl fmt::Debug for InputCallbackLogger {
3026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3027 write!(
3028 f,
3029 "InputCallbackLogger {{ prod: {}, cons: {} }}",
3030 self.prod.len(),
3031 self.cons.len()
3032 )
3033 }
3034 }
3035
3036 #[derive(Debug)]
3037 struct CoreStreamData<'ctx> {
3038 stm_ptr: *const AudioUnitStream<'ctx>,
3039 aggregate_device: Option<AggregateDevice>,
3040 mixer: Option<Mixer>,
3041 resampler: Resampler,
3042 // Stream creation parameters.
3043 input_stream_params: StreamParams,
3044 output_stream_params: StreamParams,
3045 // Device settings for AudioUnits.
3046 input_dev_desc: AudioStreamBasicDescription,
3047 output_dev_desc: AudioStreamBasicDescription,
3048 // I/O AudioUnits.
3049 input_unit: AudioUnit,
3050 output_unit: AudioUnit,
3051 // Handle to shared voiceprocessing AudioUnit, if in use.
3052 voiceprocessing_unit_handle: Option<OwningHandle<VoiceProcessingUnit>>,
3053 // Info of the I/O devices.
3054 input_device: device_info,
3055 output_device: device_info,
3056 input_processing_params: InputProcessingParams,
3057 input_mute: bool,
3058 input_buffer_manager: Option<BufferManager>,
3059 units_running: bool,
3060 // Listeners indicating what system events are monitored.
3061 default_input_listener: Option<device_property_listener>,
3062 default_output_listener: Option<device_property_listener>,
3063 input_alive_listener: Option<device_property_listener>,
3064 input_source_listener: Option<device_property_listener>,
3065 output_alive_listener: Option<device_property_listener>,
3066 output_source_listener: Option<device_property_listener>,
3067 input_logging: Option<InputCallbackLogger>,
3068 #[cfg(feature = "audio-dump")]
3069 audio_dump_session: ffi::cubeb_audio_dump_session_t,
3070 #[cfg(feature = "audio-dump")]
3071 audio_dump_session_running: bool,
3072 #[cfg(feature = "audio-dump")]
3073 audio_dump_input: ffi::cubeb_audio_dump_stream_t,
3074 #[cfg(feature = "audio-dump")]
3075 audio_dump_output: ffi::cubeb_audio_dump_stream_t,
3076 }
3077
3078 impl<'ctx> Default for CoreStreamData<'ctx> {
3079 fn default() -> Self {
3080 Self {
3081 stm_ptr: ptr::null(),
3082 aggregate_device: None,
3083 mixer: None,
3084 resampler: Resampler::default(),
3085 input_stream_params: StreamParams::from(ffi::cubeb_stream_params {
3086 format: ffi::CUBEB_SAMPLE_FLOAT32NE,
3087 rate: 0,
3088 channels: 0,
3089 layout: ffi::CUBEB_LAYOUT_UNDEFINED,
3090 prefs: ffi::CUBEB_STREAM_PREF_NONE,
3091 }),
3092 output_stream_params: StreamParams::from(ffi::cubeb_stream_params {
3093 format: ffi::CUBEB_SAMPLE_FLOAT32NE,
3094 rate: 0,
3095 channels: 0,
3096 layout: ffi::CUBEB_LAYOUT_UNDEFINED,
3097 prefs: ffi::CUBEB_STREAM_PREF_NONE,
3098 }),
3099 input_dev_desc: AudioStreamBasicDescription::default(),
3100 output_dev_desc: AudioStreamBasicDescription::default(),
3101 input_unit: ptr::null_mut(),
3102 output_unit: ptr::null_mut(),
3103 voiceprocessing_unit_handle: None,
3104 input_device: device_info::default(),
3105 output_device: device_info::default(),
3106 input_processing_params: InputProcessingParams::NONE,
3107 input_mute: false,
3108 input_buffer_manager: None,
3109 units_running: false,
3110 default_input_listener: None,
3111 default_output_listener: None,
3112 input_alive_listener: None,
3113 input_source_listener: None,
3114 output_alive_listener: None,
3115 output_source_listener: None,
3116 input_logging: None,
3117 #[cfg(feature = "audio-dump")]
3118 audio_dump_session: ptr::null_mut(),
3119 #[cfg(feature = "audio-dump")]
3120 audio_dump_session_running: false,
3121 #[cfg(feature = "audio-dump")]
3122 audio_dump_input: ptr::null_mut(),
3123 #[cfg(feature = "audio-dump")]
3124 audio_dump_output: ptr::null_mut(),
3125 }
3126 }
3127 }
3128
3129 impl<'ctx> CoreStreamData<'ctx> {
3130 fn new(
3131 stm: &AudioUnitStream<'ctx>,
3132 input_stream_settings: Option<(StreamParams, device_info)>,
3133 output_stream_settings: Option<(StreamParams, device_info)>,
3134 ) -> Self {
3135 fn get_default_sttream_params() -> StreamParams {
3136 StreamParams::from(ffi::cubeb_stream_params {
3137 format: ffi::CUBEB_SAMPLE_FLOAT32NE,
3138 rate: 0,
3139 channels: 0,
3140 layout: ffi::CUBEB_LAYOUT_UNDEFINED,
3141 prefs: ffi::CUBEB_STREAM_PREF_NONE,
3142 })
3143 }
3144 let (in_stm_params, in_dev) =
3145 input_stream_settings.unwrap_or((get_default_sttream_params(), device_info::default()));
3146 let (out_stm_params, out_dev) = output_stream_settings
3147 .unwrap_or((get_default_sttream_params(), device_info::default()));
3148 Self {
3149 stm_ptr: stm,
3150 aggregate_device: None,
3151 mixer: None,
3152 resampler: Resampler::default(),
3153 input_stream_params: in_stm_params,
3154 output_stream_params: out_stm_params,
3155 input_dev_desc: AudioStreamBasicDescription::default(),
3156 output_dev_desc: AudioStreamBasicDescription::default(),
3157 input_unit: ptr::null_mut(),
3158 output_unit: ptr::null_mut(),
3159 voiceprocessing_unit_handle: None,
3160 input_device: in_dev,
3161 output_device: out_dev,
3162 input_processing_params: InputProcessingParams::NONE,
3163 input_mute: false,
3164 input_buffer_manager: None,
3165 units_running: false,
3166 default_input_listener: None,
3167 default_output_listener: None,
3168 input_alive_listener: None,
3169 input_source_listener: None,
3170 output_alive_listener: None,
3171 output_source_listener: None,
3172 input_logging: None,
3173 #[cfg(feature = "audio-dump")]
3174 audio_dump_session: ptr::null_mut(),
3175 #[cfg(feature = "audio-dump")]
3176 audio_dump_session_running: false,
3177 #[cfg(feature = "audio-dump")]
3178 audio_dump_input: ptr::null_mut(),
3179 #[cfg(feature = "audio-dump")]
3180 audio_dump_output: ptr::null_mut(),
3181 }
3182 }
3183
3184 fn debug_assert_is_on_stream_queue(&self) {
3185 if self.stm_ptr.is_null() {
3186 return;
3187 }
3188 let stm = unsafe { &*self.stm_ptr };
3189 stm.queue.debug_assert_is_current();
3190 }
3191
3192 fn start_audiounits(&mut self) -> Result<()> {
3193 self.debug_assert_is_on_stream_queue();
3194 // Only allowed to be called after the stream is initialized
3195 // and before the stream is destroyed.
3196 debug_assert!(!self.input_unit.is_null() || !self.output_unit.is_null());
3197
3198 if !self.input_unit.is_null() {
3199 start_audiounit(self.input_unit)?;
3200 }
3201 if self.using_voice_processing_unit() {
3202 // Handle the VoiceProcessIO case where there is a single unit.
3203
3204 // Always try to remember the applied input processing params. If they cannot
3205 // be applied in the new device pair, we notify the client of an error and it
3206 // will have to open a new stream.
3207 if let Err(r) =
3208 set_input_processing_params(self.input_unit, self.input_processing_params)
3209 {
3210 cubeb_log!(
3211 "({:p}) Failed to set params of voiceprocessing. Error: {}",
3212 self.stm_ptr,
3213 r
3214 );
3215 return Err(r);
3216 }
3217 return Ok(());
3218 }
3219 if !self.output_unit.is_null() {
3220 start_audiounit(self.output_unit)?;
3221 }
3222 self.units_running = true;
3223 Ok(())
3224 }
3225
3226 fn stop_audiounits(&mut self) {
3227 self.debug_assert_is_on_stream_queue();
3228 self.units_running = false;
3229 if !self.input_unit.is_null() {
3230 let r = stop_audiounit(self.input_unit);
3231 assert!(r.is_ok());
3232 }
3233 if self.using_voice_processing_unit() {
3234 // Handle the VoiceProcessIO case where there is a single unit.
3235
3236 // Always reset input processing params to VPIO defaults in case VPIO is reused later.
3237 let vpio_defaults = InputProcessingParams::ECHO_CANCELLATION
3238 | InputProcessingParams::AUTOMATIC_GAIN_CONTROL
3239 | InputProcessingParams::NOISE_SUPPRESSION;
3240 if let Err(r) = set_input_processing_params(self.input_unit, vpio_defaults) {
3241 cubeb_log!(
3242 "({:p}) Failed to reset params of voiceprocessing. Error: {}",
3243 self.stm_ptr,
3244 r
3245 );
3246 }
3247 return;
3248 }
3249 if !self.output_unit.is_null() {
3250 let r = stop_audiounit(self.output_unit);
3251 assert!(r.is_ok());
3252 }
3253 }
3254
3255 fn has_input(&self) -> bool {
3256 self.input_stream_params.rate() > 0
3257 }
3258
3259 fn has_output(&self) -> bool {
3260 self.output_stream_params.rate() > 0
3261 }
3262
3263 fn using_voice_processing_unit(&self) -> bool {
3264 self.voiceprocessing_unit_handle.is_some()
3265 }
3266
3267 fn same_clock_domain(&self) -> bool {
3268 self.debug_assert_is_on_stream_queue();
3269 // If not setting up a duplex stream, there is only one device,
3270 // no reclocking necessary.
3271 if !(self.has_input() && self.has_output()) {
3272 return true;
3273 }
3274 let input_domain = match get_clock_domain(self.input_device.id, DeviceType::INPUT) {
3275 Ok(clock_domain) => clock_domain,
3276 Err(_) => {
3277 cubeb_log!("Coudn't determine clock domains for input.");
3278 return false;
3279 }
3280 };
3281
3282 let output_domain = match get_clock_domain(self.output_device.id, DeviceType::OUTPUT) {
3283 Ok(clock_domain) => clock_domain,
3284 Err(_) => {
3285 cubeb_log!("Coudn't determine clock domains for input.");
3286 return false;
3287 }
3288 };
3289 input_domain == output_domain
3290 }
3291
3292 #[allow(non_upper_case_globals)]
3293 fn should_force_vpio_for_input_device(id: AudioDeviceID) -> bool {
3294 assert!(id != kAudioObjectUnknown);
3295 debug_assert_running_serially();
3296 match get_device_transport_type(id, DeviceType::INPUT) {
3297 Ok(kAudioDeviceTransportTypeBuiltIn) => {
3298 cubeb_log!(
3299 "Input device {} is on the VPIO force list because it is built in, \
3300 and its volume is known to be very low without VPIO whenever VPIO \
3301 is hooked up to it elsewhere.",
3302 id
3303 );
3304 true
3305 }
3306 _ => false,
3307 }
3308 }
3309
3310 fn should_block_vpio_for_device_pair(
3311 &self,
3312 in_device: &device_info,
3313 out_device: &device_info,
3314 ) -> bool {
3315 self.debug_assert_is_on_stream_queue();
3316 cubeb_log!("Evaluating device pair against VPIO block list");
3317 let log_device_and_get_model_uid = |id, devtype| -> String {
3318 let device_model_uid = get_device_model_uid(id, devtype)
3319 .map(|s| s.into_string())
3320 .unwrap_or_default();
3321 cubeb_log!("{} uid=\"{}\", model_uid=\"{}\", transport_type={:?}, source={:?}, source_name=\"{}\", name=\"{}\", manufacturer=\"{}\"",
3322 if devtype == DeviceType::INPUT {
3323 "Input"
3324 } else {
3325 debug_assert_eq!(devtype, DeviceType::OUTPUT);
3326 "Output"
3327 },
3328 get_device_uid(id, devtype).map(|s| s.into_string()).unwrap_or_default(),
3329 device_model_uid,
3330 convert_uint32_into_string(get_device_transport_type(id, devtype).unwrap_or(0)),
3331 convert_uint32_into_string(get_device_source(id, devtype).unwrap_or(0)),
3332 get_device_source_name(id, devtype).map(|s| s.into_string()).unwrap_or_default(),
3333 get_device_name(id, devtype).map(|s| s.into_string()).unwrap_or_default(),
3334 get_device_manufacturer(id, devtype).map(|s| s.into_string()).unwrap_or_default());
3335 device_model_uid
3336 };
3337
3338 #[allow(non_upper_case_globals)]
3339 let in_id = match in_device.id {
3340 kAudioObjectUnknown => None,
3341 id => Some(id),
3342 };
3343 #[allow(non_upper_case_globals)]
3344 let out_id = match out_device.id {
3345 kAudioObjectUnknown => None,
3346 id => Some(id),
3347 };
3348
3349 let (in_model_uid, out_model_uid) = (
3350 in_id
3351 .map(|id| log_device_and_get_model_uid(id, DeviceType::INPUT))
3352 .unwrap_or_default(),
3353 out_id
3354 .or_else(|| get_default_device(DeviceType::OUTPUT))
3355 .map(|id| log_device_and_get_model_uid(id, DeviceType::OUTPUT))
3356 .unwrap_or_default(),
3357 );
3358
3359 if in_model_uid.contains(APPLE_STUDIO_DISPLAY_USB_ID)
3360 && out_model_uid.contains(APPLE_STUDIO_DISPLAY_USB_ID)
3361 {
3362 cubeb_log!("Both input and output device is an Apple Studio Display. BLOCKED");
3363 return true;
3364 }
3365
3366 cubeb_log!("Device pair is not blocked");
3367 false
3368 }
3369
3370 fn create_audiounits(
3371 &mut self,
3372 shared_voice_processing_unit: &mut SharedVoiceProcessingUnitManager,
3373 ) -> Result<(device_info, device_info)> {
3374 self.debug_assert_is_on_stream_queue();
3375 let should_use_voice_processing_unit = self.has_input()
3376 && (self
3377 .input_stream_params
3378 .prefs()
3379 .contains(StreamPrefs::VOICE)
3380 || CoreStreamData::should_force_vpio_for_input_device(self.input_device.id))
3381 && !self.should_block_vpio_for_device_pair(&self.input_device, &self.output_device)
3382 && macos_kernel_major_version() != Ok(MACOS_KERNEL_MAJOR_VERSION_MONTEREY);
3383
3384 let should_use_aggregate_device = {
3385 // It's impossible to create an aggregate device from an aggregate device, and it's
3386 // unnecessary to create an aggregate device when opening the same device input/output. In
3387 // all other cases, use an aggregate device.
3388 let mut either_already_aggregate = false;
3389 if self.has_input() {
3390 let input_is_aggregate =
3391 get_device_transport_type(self.input_device.id, DeviceType::INPUT).unwrap_or(0)
3392 == kAudioDeviceTransportTypeAggregate;
3393 if input_is_aggregate {
3394 either_already_aggregate = true;
3395 }
3396 cubeb_log!(
3397 "Input device ID: {} (aggregate: {:?})",
3398 self.input_device.id,
3399 input_is_aggregate
3400 );
3401 }
3402 if self.has_output() {
3403 let output_is_aggregate =
3404 get_device_transport_type(self.output_device.id, DeviceType::OUTPUT)
3405 .unwrap_or(0)
3406 == kAudioDeviceTransportTypeAggregate;
3407 if output_is_aggregate {
3408 either_already_aggregate = true;
3409 }
3410 cubeb_log!(
3411 "Output device ID: {} (aggregate: {:?})",
3412 self.output_device.id,
3413 output_is_aggregate
3414 );
3415 }
3416 // Only use an aggregate device when the device are different.
3417 self.has_input()
3418 && self.has_output()
3419 && self.input_device.id != self.output_device.id
3420 && !either_already_aggregate
3421 };
3422
3423 // Create an AudioUnit:
3424 // - If we're eligible to use voice processing, try creating a VoiceProcessingIO AudioUnit.
3425 // - If we should use an aggregate device, try creating one and input and output AudioUnits next.
3426 // - As last resort, create regular AudioUnits. This is also the normal non-duplex path.
3427
3428 if should_use_voice_processing_unit {
3429 if let Ok(mut au_handle) = get_voiceprocessing_audiounit(
3430 shared_voice_processing_unit,
3431 &self.input_device,
3432 &self.output_device,
3433 ) {
3434 self.input_unit = au_handle.as_mut().unit;
3435 if self.has_output() {
3436 self.output_unit = au_handle.as_mut().unit;
3437 }
3438 self.voiceprocessing_unit_handle = Some(au_handle);
3439 return Ok((self.input_device.clone(), self.output_device.clone()));
3440 }
3441 cubeb_log!(
3442 "({:p}) Failed to get VoiceProcessingIO AudioUnit. Trying a regular one.",
3443 self.stm_ptr
3444 );
3445 }
3446
3447 if should_use_aggregate_device {
3448 if let Ok(device) = AggregateDevice::new(self.input_device.id, self.output_device.id) {
3449 let in_dev_info = {
3450 device_info {
3451 id: device.get_device_id(),
3452 ..self.input_device
3453 }
3454 };
3455 let out_dev_info = {
3456 device_info {
3457 id: device.get_device_id(),
3458 ..self.output_device
3459 }
3460 };
3461
3462 match (
3463 create_audiounit(&in_dev_info),
3464 create_audiounit(&out_dev_info),
3465 ) {
3466 (Ok(in_au), Ok(out_au)) => {
3467 cubeb_log!(
3468 "({:p}) Using an aggregate device {} for input and output.",
3469 self.stm_ptr,
3470 device.get_device_id()
3471 );
3472 self.aggregate_device = Some(device);
3473 self.input_unit = in_au;
3474 self.output_unit = out_au;
3475 return Ok((in_dev_info, out_dev_info));
3476 }
3477 (Err(e), Ok(au)) => {
3478 cubeb_log!(
3479 "({:p}) Failed to create input AudioUnit for aggregate device. Error: {}.",
3480 self.stm_ptr,
3481 e
3482 );
3483 dispose_audio_unit(au);
3484 }
3485 (Ok(au), Err(e)) => {
3486 cubeb_log!(
3487 "({:p}) Failed to create output AudioUnit for aggregate device. Error: {}.",
3488 self.stm_ptr,
3489 e
3490 );
3491 dispose_audio_unit(au);
3492 }
3493 (Err(e), _) => {
3494 cubeb_log!(
3495 "({:p}) Failed to create AudioUnits for aggregate device. Error: {}.",
3496 self.stm_ptr,
3497 e
3498 );
3499 }
3500 }
3501 }
3502 cubeb_log!(
3503 "({:p}) Failed to set up aggregate device. Using regular AudioUnits.",
3504 self.stm_ptr
3505 );
3506 }
3507
3508 if self.has_input() {
3509 match create_audiounit(&self.input_device) {
3510 Ok(in_au) => self.input_unit = in_au,
3511 Err(e) => {
3512 cubeb_log!(
3513 "({:p}) Failed to create regular AudioUnit for input. Error: {}",
3514 self.stm_ptr,
3515 e
3516 );
3517 return Err(e);
3518 }
3519 }
3520 }
3521
3522 if self.has_output() {
3523 match create_audiounit(&self.output_device) {
3524 Ok(out_au) => self.output_unit = out_au,
3525 Err(e) => {
3526 cubeb_log!(
3527 "({:p}) Failed to create regular AudioUnit for output. Error: {}",
3528 self.stm_ptr,
3529 e
3530 );
3531 if !self.input_unit.is_null() {
3532 dispose_audio_unit(self.input_unit);
3533 self.input_unit = ptr::null_mut();
3534 }
3535 return Err(e);
3536 }
3537 }
3538 }
3539
3540 Ok((self.input_device.clone(), self.output_device.clone()))
3541 }
3542
3543 #[allow(clippy::cognitive_complexity)] // TODO: Refactoring.
3544 fn setup(
3545 &mut self,
3546 shared_voice_processing_unit: &mut SharedVoiceProcessingUnitManager,
3547 ) -> Result<()> {
3548 self.debug_assert_is_on_stream_queue();
3549 if self
3550 .input_stream_params
3551 .prefs()
3552 .contains(StreamPrefs::LOOPBACK)
3553 || self
3554 .output_stream_params
3555 .prefs()
3556 .contains(StreamPrefs::LOOPBACK)
3557 {
3558 cubeb_log!("({:p}) Loopback not supported for audiounit.", self.stm_ptr);
3559 return Err(Error::not_supported());
3560 }
3561
3562 let same_clock_domain = self.same_clock_domain();
3563 let (in_dev_info, out_dev_info) = self.create_audiounits(shared_voice_processing_unit)?;
3564 let using_voice_processing_unit = self.using_voice_processing_unit();
3565
3566 assert!(!self.stm_ptr.is_null());
3567 let stream = unsafe { &(*self.stm_ptr) };
3568
3569 #[cfg(feature = "audio-dump")]
3570 unsafe {
3571 ffi::cubeb_audio_dump_init(&mut self.audio_dump_session);
3572 }
3573
3574 // Configure I/O stream
3575 if self.has_input() {
3576 assert!(!self.input_unit.is_null());
3577
3578 cubeb_log!(
3579 "({:p}) Initializing input by device info: {:?}",
3580 self.stm_ptr,
3581 in_dev_info
3582 );
3583
3584 let device_channel_count =
3585 get_channel_count(self.input_device.id, DeviceType::INPUT).unwrap_or(0);
3586 if device_channel_count < self.input_stream_params.channels() {
3587 cubeb_log!(
3588 "({:p}) Invalid input channel count; device={}, params={}",
3589 self.stm_ptr,
3590 device_channel_count,
3591 self.input_stream_params.channels()
3592 );
3593 return Err(Error::invalid_parameter());
3594 }
3595
3596 cubeb_log!(
3597 "({:p}) Opening input side: rate {}, channels {}, format {:?}, layout {:?}, prefs {:?}, latency in frames {}, voice processing {}.",
3598 self.stm_ptr,
3599 self.input_stream_params.rate(),
3600 self.input_stream_params.channels(),
3601 self.input_stream_params.format(),
3602 self.input_stream_params.layout(),
3603 self.input_stream_params.prefs(),
3604 stream.latency_frames,
3605 using_voice_processing_unit
3606 );
3607
3608 // Get input device hardware information.
3609 let mut input_hw_desc = AudioStreamBasicDescription::default();
3610 let mut size = mem::size_of::<AudioStreamBasicDescription>();
3611 let r = audio_unit_get_property(
3612 self.input_unit,
3613 kAudioUnitProperty_StreamFormat,
3614 if using_voice_processing_unit {
3615 // With a VPIO unit the input scope includes AEC reference channels.
3616 // We need to use the output scope of the input bus.
3617 kAudioUnitScope_Output
3618 } else {
3619 // With a HAL unit the output scope for the input bus returns the number of
3620 // output channels of the output device, i.e. it seems the bus is ignored.
3621 kAudioUnitScope_Input
3622 },
3623 AU_IN_BUS,
3624 &mut input_hw_desc,
3625 &mut size,
3626 );
3627 if r != NO_ERR {
3628 cubeb_log!(
3629 "AudioUnitGetProperty/input/kAudioUnitProperty_StreamFormat rv={}",
3630 r
3631 );
3632 return Err(Error::error());
3633 }
3634 cubeb_log!(
3635 "({:p}) Input hardware description: {:?}",
3636 self.stm_ptr,
3637 input_hw_desc
3638 );
3639 // Notice: when we are using aggregate device, the input_hw_desc.mChannelsPerFrame is
3640 // the total of all the input channel count of the devices added in the aggregate device.
3641 // Due to our aggregate device settings, the data captured by the output device's input
3642 // channels will be put in the beginning of the raw data given by the input callback.
3643
3644 // Always request all the input channels of the device, and only pass the correct
3645 // channels to the audio callback.
3646 let params = unsafe {
3647 let mut p = *self.input_stream_params.as_ptr();
3648 p.channels = input_hw_desc.mChannelsPerFrame;
3649 // Input AudioUnit must be configured with device's sample rate.
3650 // we will resample inside input callback.
3651 p.rate = input_hw_desc.mSampleRate as _;
3652 StreamParams::from(p)
3653 };
3654
3655 self.input_dev_desc = create_stream_description(&params).inspect_err(|_| {
3656 cubeb_log!(
3657 "({:p}) Setting format description for input failed.",
3658 self.stm_ptr
3659 );
3660 })?;
3661
3662 #[cfg(feature = "audio-dump")]
3663 {
3664 let name = format!("input-{:p}.wav", self.stm_ptr);
3665 let cname = CString::new(name).expect("OK");
3666 let rv = unsafe {
3667 ffi::cubeb_audio_dump_stream_init(
3668 self.audio_dump_session,
3669 &mut self.audio_dump_input,
3670 *params.as_ptr(),
3671 cname.as_ptr(),
3672 )
3673 };
3674 if rv == 0 {
3675 assert_ne!(self.audio_dump_input, ptr::null_mut(),);
3676 cubeb_log!("Successfully inited audio dump for input");
3677 } else {
3678 cubeb_log!("Failed to init audio dump for input");
3679 }
3680 }
3681
3682 assert_eq!(self.input_dev_desc.mSampleRate, input_hw_desc.mSampleRate);
3683
3684 // Use latency to set buffer size
3685 assert_ne!(stream.latency_frames, 0);
3686 if let Err(r) =
3687 set_buffer_size_sync(self.input_unit, DeviceType::INPUT, stream.latency_frames)
3688 {
3689 cubeb_log!("({:p}) Error in change input buffer size.", self.stm_ptr);
3690 return Err(r);
3691 }
3692
3693 let r = audio_unit_set_property(
3694 self.input_unit,
3695 kAudioUnitProperty_StreamFormat,
3696 kAudioUnitScope_Output,
3697 AU_IN_BUS,
3698 &self.input_dev_desc,
3699 mem::size_of::<AudioStreamBasicDescription>(),
3700 );
3701 if r != NO_ERR {
3702 cubeb_log!(
3703 "AudioUnitSetProperty/input/kAudioUnitProperty_StreamFormat rv={}",
3704 r
3705 );
3706 return Err(Error::error());
3707 }
3708
3709 // Frames per buffer in the input callback.
3710 let r = audio_unit_set_property(
3711 self.input_unit,
3712 kAudioUnitProperty_MaximumFramesPerSlice,
3713 kAudioUnitScope_Global,
3714 AU_IN_BUS,
3715 &stream.latency_frames,
3716 mem::size_of::<u32>(),
3717 );
3718 if r != NO_ERR {
3719 cubeb_log!(
3720 "AudioUnitSetProperty/input/kAudioUnitProperty_MaximumFramesPerSlice rv={}",
3721 r
3722 );
3723 return Err(Error::error());
3724 }
3725
3726 // When we use the aggregate device, the self.input_dev_desc.mChannelsPerFrame is the
3727 // total input channel count of all the device added in the aggregate device. However,
3728 // we only need the audio data captured by the requested input device, so we need to
3729 // ignore some data captured by the audio input of the requested output device (e.g.,
3730 // the requested output device is a USB headset with built-in mic), in the beginning of
3731 // the raw data taken from input callback.
3732 self.input_buffer_manager = Some(BufferManager::new(
3733 self.input_stream_params.format(),
3734 SAFE_MAX_LATENCY_FRAMES as usize,
3735 self.input_dev_desc.mChannelsPerFrame as usize,
3736 self.input_dev_desc
3737 .mChannelsPerFrame
3738 .saturating_sub(device_channel_count) as usize,
3739 self.input_stream_params.channels() as usize,
3740 ));
3741
3742 let aurcbs_in = AURenderCallbackStruct {
3743 inputProc: Some(audiounit_input_callback),
3744 inputProcRefCon: self.stm_ptr as *mut c_void,
3745 };
3746
3747 let r = audio_unit_set_property(
3748 self.input_unit,
3749 kAudioOutputUnitProperty_SetInputCallback,
3750 kAudioUnitScope_Global,
3751 AU_OUT_BUS,
3752 &aurcbs_in,
3753 mem::size_of_val(&aurcbs_in),
3754 );
3755 if r != NO_ERR {
3756 cubeb_log!(
3757 "AudioUnitSetProperty/input/kAudioOutputUnitProperty_SetInputCallback rv={}",
3758 r
3759 );
3760 return Err(Error::error());
3761 }
3762
3763 stream.frames_read.store(0, Ordering::SeqCst);
3764
3765 cubeb_log!(
3766 "({:p}) Input audiounit init with device {} successfully.",
3767 self.stm_ptr,
3768 in_dev_info.id
3769 );
3770 }
3771
3772 if self.has_input() && !self.has_output() && using_voice_processing_unit {
3773 // We must configure the output side of VPIO to match the input side, even if we don't use it.
3774 let r = audio_unit_set_property(
3775 self.input_unit,
3776 kAudioUnitProperty_StreamFormat,
3777 kAudioUnitScope_Input,
3778 AU_OUT_BUS,
3779 &self.input_dev_desc,
3780 mem::size_of::<AudioStreamBasicDescription>(),
3781 );
3782 if r != NO_ERR {
3783 cubeb_log!(
3784 "AudioUnitSetProperty/output/kAudioUnitProperty_StreamFormat rv={}",
3785 r
3786 );
3787 return Err(Error::error());
3788 }
3789 }
3790
3791 if self.has_output() {
3792 assert!(!self.output_unit.is_null());
3793
3794 cubeb_log!(
3795 "({:p}) Initialize output by device info: {:?}",
3796 self.stm_ptr,
3797 out_dev_info
3798 );
3799
3800 cubeb_log!(
3801 "({:p}) Opening output side: rate {}, channels {}, format {:?}, layout {:?}, prefs {:?}, latency in frames {}, voice processing {}.",
3802 self.stm_ptr,
3803 self.output_stream_params.rate(),
3804 self.output_stream_params.channels(),
3805 self.output_stream_params.format(),
3806 self.output_stream_params.layout(),
3807 self.output_stream_params.prefs(),
3808 stream.latency_frames,
3809 using_voice_processing_unit
3810 );
3811
3812 // Get output device hardware information.
3813 let mut output_hw_desc = AudioStreamBasicDescription::default();
3814 let mut size = mem::size_of::<AudioStreamBasicDescription>();
3815 let r = audio_unit_get_property(
3816 self.output_unit,
3817 kAudioUnitProperty_StreamFormat,
3818 if using_voice_processing_unit {
3819 // With a VPIO unit the output scope includes all channels in the hw.
3820 // The VPIO unit however is only MONO which the input scope reflects.
3821 kAudioUnitScope_Input
3822 } else {
3823 // With a HAL unit the output scope for the output bus returns the number of
3824 // output channels of the hw, as we want. The input scope seems limited to
3825 // two channels.
3826 kAudioUnitScope_Output
3827 },
3828 AU_OUT_BUS,
3829 &mut output_hw_desc,
3830 &mut size,
3831 );
3832 if r != NO_ERR {
3833 cubeb_log!(
3834 "AudioUnitGetProperty/output/kAudioUnitProperty_StreamFormat rv={}",
3835 r
3836 );
3837 return Err(Error::error());
3838 }
3839 cubeb_log!(
3840 "({:p}) Output hardware description: {:?}",
3841 self.stm_ptr,
3842 output_hw_desc
3843 );
3844
3845 // This has been observed in the wild.
3846 if output_hw_desc.mChannelsPerFrame == 0 {
3847 cubeb_log!(
3848 "({:p}) Output hardware description channel count is zero",
3849 self.stm_ptr
3850 );
3851 return Err(Error::error());
3852 }
3853
3854 // Simple case of stereo output, map to the stereo pair (that might not be the first
3855 // two channels). Fall back to regular mixing if this fails.
3856 let mut maybe_need_mixer = true;
3857 if self.output_stream_params.channels() == 2
3858 && self.output_stream_params.layout() == ChannelLayout::STEREO
3859 {
3860 let layout = AudioChannelLayout {
3861 mChannelLayoutTag: kAudioChannelLayoutTag_Stereo,
3862 ..Default::default()
3863 };
3864 let r = audio_unit_set_property(
3865 self.output_unit,
3866 kAudioUnitProperty_AudioChannelLayout,
3867 kAudioUnitScope_Input,
3868 AU_OUT_BUS,
3869 &layout,
3870 mem::size_of::<AudioChannelLayout>(),
3871 );
3872 if r != NO_ERR {
3873 cubeb_log!(
3874 "AudioUnitSetProperty/output/kAudioUnitProperty_AudioChannelLayout rv={}",
3875 r
3876 );
3877 }
3878 maybe_need_mixer = r != NO_ERR;
3879 }
3880
3881 // Notice: when we are using aggregate device, the output_hw_desc.mChannelsPerFrame is
3882 // the total of all the output channel count of the devices added in the aggregate device.
3883 // Due to our aggregate device settings, the data recorded by the input device's output
3884 // channels will be appended at the end of the raw data given by the output callback.
3885 let params = unsafe {
3886 let mut p = *self.output_stream_params.as_ptr();
3887 p.channels = if maybe_need_mixer {
3888 output_hw_desc.mChannelsPerFrame
3889 } else {
3890 self.output_stream_params.channels()
3891 };
3892 if using_voice_processing_unit {
3893 // VPIO will always use the sample rate of the input hw for both input and output,
3894 // as reported to us. (We can override it but we cannot improve quality this way).
3895 p.rate = self.input_dev_desc.mSampleRate as _;
3896 }
3897 StreamParams::from(p)
3898 };
3899
3900 self.output_dev_desc = create_stream_description(&params).inspect_err(|_| {
3901 cubeb_log!(
3902 "({:p}) Could not initialize the audio stream description.",
3903 self.stm_ptr
3904 );
3905 })?;
3906
3907 #[cfg(feature = "audio-dump")]
3908 {
3909 let name = format!("output-{:p}.wav", self.stm_ptr);
3910 let cname = CString::new(name).expect("OK");
3911 let rv = unsafe {
3912 ffi::cubeb_audio_dump_stream_init(
3913 self.audio_dump_session,
3914 &mut self.audio_dump_output,
3915 *params.as_ptr(),
3916 cname.as_ptr(),
3917 )
3918 };
3919 if rv == 0 {
3920 assert_ne!(self.audio_dump_output, ptr::null_mut(),);
3921 cubeb_log!("Successfully inited audio dump for output");
3922 } else {
3923 cubeb_log!("Failed to init audio dump for output");
3924 }
3925 }
3926
3927 let device_layout = self
3928 .get_output_channel_layout()
3929 .inspect_err(|_| {
3930 cubeb_log!(
3931 "({:p}) Could not get any channel layout. Defaulting to no channels.",
3932 self.stm_ptr
3933 );
3934 })
3935 .unwrap_or_default();
3936
3937 cubeb_log!(
3938 "({:p} Using output device channel layout {:?}",
3939 self.stm_ptr,
3940 device_layout
3941 );
3942
3943 if maybe_need_mixer {
3944 // The mixer will be set up when
3945 // 0. not playing simply stereo, or failing to set the channel layout to the stereo
3946 // pair
3947 // 1. using aggregate device whose input device has output channels
3948 // 2. output device has more channels than we need, and stream isn't simply stereo
3949 // 3. output device has different layout than the one we have
3950 self.mixer = if self.output_dev_desc.mChannelsPerFrame
3951 != self.output_stream_params.channels()
3952 || device_layout != mixer::get_channel_order(self.output_stream_params.layout())
3953 {
3954 cubeb_log!("Incompatible channel layouts detected, setting up remixer");
3955 // We will be remixing the data before it reaches the output device.
3956 Some(Mixer::new(
3957 self.output_stream_params.format(),
3958 self.output_stream_params.channels() as usize,
3959 self.output_stream_params.layout(),
3960 self.output_dev_desc.mChannelsPerFrame as usize,
3961 device_layout,
3962 ))
3963 } else {
3964 None
3965 };
3966 }
3967
3968 let r = audio_unit_set_property(
3969 self.output_unit,
3970 kAudioUnitProperty_StreamFormat,
3971 kAudioUnitScope_Input,
3972 AU_OUT_BUS,
3973 &self.output_dev_desc,
3974 mem::size_of::<AudioStreamBasicDescription>(),
3975 );
3976 if r != NO_ERR {
3977 cubeb_log!(
3978 "AudioUnitSetProperty/output/kAudioUnitProperty_StreamFormat rv={}",
3979 r
3980 );
3981 return Err(Error::error());
3982 }
3983
3984 // Use latency to set buffer size
3985 assert_ne!(stream.latency_frames, 0);
3986 if let Err(r) =
3987 set_buffer_size_sync(self.output_unit, DeviceType::OUTPUT, stream.latency_frames)
3988 {
3989 cubeb_log!("({:p}) Error in change output buffer size.", self.stm_ptr);
3990 return Err(r);
3991 }
3992
3993 // Frames per buffer in the input callback.
3994 let r = audio_unit_set_property(
3995 self.output_unit,
3996 kAudioUnitProperty_MaximumFramesPerSlice,
3997 kAudioUnitScope_Global,
3998 AU_OUT_BUS,
3999 &stream.latency_frames,
4000 mem::size_of::<u32>(),
4001 );
4002 if r != NO_ERR {
4003 cubeb_log!(
4004 "AudioUnitSetProperty/output/kAudioUnitProperty_MaximumFramesPerSlice rv={}",
4005 r
4006 );
4007 return Err(Error::error());
4008 }
4009
4010 let aurcbs_out = AURenderCallbackStruct {
4011 inputProc: Some(audiounit_output_callback),
4012 inputProcRefCon: self.stm_ptr as *mut c_void,
4013 };
4014 let r = audio_unit_set_property(
4015 self.output_unit,
4016 kAudioUnitProperty_SetRenderCallback,
4017 kAudioUnitScope_Global,
4018 AU_OUT_BUS,
4019 &aurcbs_out,
4020 mem::size_of_val(&aurcbs_out),
4021 );
4022 if r != NO_ERR {
4023 cubeb_log!(
4024 "AudioUnitSetProperty/output/kAudioUnitProperty_SetRenderCallback rv={}",
4025 r
4026 );
4027 return Err(Error::error());
4028 }
4029
4030 stream.frames_written.store(0, Ordering::SeqCst);
4031
4032 cubeb_log!(
4033 "({:p}) Output audiounit init with device {} successfully.",
4034 self.stm_ptr,
4035 out_dev_info.id
4036 );
4037 }
4038
4039 // We use a resampler because input AudioUnit operates
4040 // reliable only in the capture device sample rate.
4041 // Resampler will convert it to the user sample rate
4042 // and deliver it to the callback.
4043 let target_sample_rate = if self.has_input() {
4044 self.input_stream_params.rate()
4045 } else {
4046 assert!(self.has_output());
4047 self.output_stream_params.rate()
4048 };
4049
4050 let resampler_input_params = if self.has_input() {
4051 let mut p = unsafe { *(self.input_stream_params.as_ptr()) };
4052 p.rate = self.input_dev_desc.mSampleRate as u32;
4053 Some(p)
4054 } else {
4055 None
4056 };
4057 let resampler_output_params = if self.has_output() {
4058 let mut p = unsafe { *(self.output_stream_params.as_ptr()) };
4059 p.rate = self.output_dev_desc.mSampleRate as u32;
4060 Some(p)
4061 } else {
4062 None
4063 };
4064
4065 // Only reclock if there is an input and we couldn't use an aggregate device, and the
4066 // devices are not part of the same clock domain.
4067 let reclock_policy = if self.aggregate_device.is_none()
4068 && !using_voice_processing_unit
4069 && !same_clock_domain
4070 {
4071 cubeb_log!(
4072 "Reclocking duplex steam using_aggregate_device={} same_clock_domain={}",
4073 self.aggregate_device.is_some(),
4074 same_clock_domain
4075 );
4076 ffi::CUBEB_RESAMPLER_RECLOCK_INPUT
4077 } else {
4078 ffi::CUBEB_RESAMPLER_RECLOCK_NONE
4079 };
4080
4081 self.resampler = Resampler::new(
4082 self.stm_ptr as *mut ffi::cubeb_stream,
4083 resampler_input_params,
4084 resampler_output_params,
4085 target_sample_rate,
4086 stream.data_callback,
4087 stream.user_ptr,
4088 ffi::CUBEB_RESAMPLER_QUALITY_DESKTOP,
4089 reclock_policy,
4090 );
4091
4092 // In duplex, the input thread might be different from the output thread, and we're logging
4093 // everything from the output thread: relay the audio input callback information using a
4094 // ring buffer to diagnose issues.
4095 if self.has_input() && self.has_output() {
4096 self.input_logging = Some(InputCallbackLogger::new());
4097 }
4098
4099 #[cfg(feature = "audio-dump")]
4100 {
4101 unsafe { ffi::cubeb_audio_dump_start(self.audio_dump_session) };
4102 self.audio_dump_session_running = true;
4103 }
4104
4105 if !self.input_unit.is_null() {
4106 let r = audio_unit_initialize(self.input_unit);
4107 if r != NO_ERR {
4108 cubeb_log!("AudioUnitInitialize/input rv={}", r);
4109 return Err(Error::error());
4110 }
4111
4112 stream.input_device_latency_frames.store(
4113 get_fixed_latency(self.input_device.id, DeviceType::INPUT),
4114 Ordering::SeqCst,
4115 );
4116 }
4117
4118 if !self.output_unit.is_null() {
4119 if self.input_unit != self.output_unit {
4120 let r = audio_unit_initialize(self.output_unit);
4121 if r != NO_ERR {
4122 cubeb_log!("AudioUnitInitialize/output rv={}", r);
4123 return Err(Error::error());
4124 }
4125 }
4126
4127 stream.output_device_latency_frames.store(
4128 get_fixed_latency(self.output_device.id, DeviceType::OUTPUT),
4129 Ordering::SeqCst,
4130 );
4131
4132 let mut unit_s: f64 = 0.0;
4133 let mut size = mem::size_of_val(&unit_s);
4134 if audio_unit_get_property(
4135 self.output_unit,
4136 kAudioUnitProperty_Latency,
4137 kAudioUnitScope_Global,
4138 0,
4139 &mut unit_s,
4140 &mut size,
4141 ) == NO_ERR
4142 {
4143 stream.output_device_latency_frames.fetch_add(
4144 (unit_s * self.output_dev_desc.mSampleRate) as u32,
4145 Ordering::SeqCst,
4146 );
4147 }
4148 }
4149
4150 if using_voice_processing_unit {
4151 // The VPIO AudioUnit automatically ducks other audio streams on the VPIO
4152 // output device. Its ramp duration is 0.5s when ducking, so unduck similarly
4153 // now.
4154 // NOTE: On MacOS 14 the ducking happens on creation of the VPIO AudioUnit.
4155 // On MacOS 10.15 it happens on both creation and initialization, which
4156 // is why we defer the unducking until now.
4157 #[allow(non_upper_case_globals)]
4158 let mut device = match self.output_device.id {
4159 kAudioObjectUnknown => None,
4160 id => Some(id),
4161 };
4162 device = device.or_else(|| get_default_device(DeviceType::OUTPUT));
4163 match device {
4164 None => {
4165 cubeb_log!(
4166 "({:p}) No output device to undo vpio ducking on",
4167 self.stm_ptr
4168 );
4169 }
4170 Some(id) => {
4171 let r = audio_device_duck(id, 1.0, ptr::null_mut(), 0.5);
4172 if r != NO_ERR {
4173 cubeb_log!(
4174 "({:p}) Failed to undo ducking of voiceprocessing on output device {}. Proceeding... Error: {}",
4175 self.stm_ptr,
4176 id,
4177 r
4178 );
4179 }
4180 }
4181 };
4182
4183 // Always try to remember the applied input mute state. If it cannot be applied
4184 // to the new device pair, we notify the client of an error and it will have to
4185 // open a new stream.
4186 if let Err(r) = set_input_mute(self.input_unit, self.input_mute) {
4187 cubeb_log!(
4188 "({:p}) Failed to set mute state of voiceprocessing. Error: {}",
4189 self.stm_ptr,
4190 r
4191 );
4192 return Err(r);
4193 }
4194 }
4195
4196 if let Err(r) = self.install_system_changed_callback() {
4197 cubeb_log!(
4198 "({:p}) Could not install the device change callback.",
4199 self.stm_ptr
4200 );
4201 return Err(r);
4202 }
4203
4204 if let Err(r) = self.install_device_changed_callback() {
4205 cubeb_log!(
4206 "({:p}) Could not install all device change callback.",
4207 self.stm_ptr
4208 );
4209 return Err(r);
4210 }
4211
4212 // We have either default_input_listener or input_alive_listener.
4213 // We cannot have both of them at the same time.
4214 assert!(
4215 !self.has_input()
4216 || ((self.default_input_listener.is_some() != self.input_alive_listener.is_some())
4217 && (self.default_input_listener.is_some()
4218 || self.input_alive_listener.is_some()))
4219 );
4220
4221 // We have either default_output_listener or output_alive_listener.
4222 // We cannot have both of them at the same time.
4223 assert!(
4224 !self.has_output()
4225 || ((self.default_output_listener.is_some()
4226 != self.output_alive_listener.is_some())
4227 && (self.default_output_listener.is_some()
4228 || self.output_alive_listener.is_some()))
4229 );
4230
4231 Ok(())
4232 }
4233
4234 fn close(&mut self) {
4235 self.debug_assert_is_on_stream_queue();
4236 if !self.input_unit.is_null() {
4237 audio_unit_uninitialize(self.input_unit);
4238 if self.using_voice_processing_unit() {
4239 // Handle the VoiceProcessIO case where there is a single unit.
4240 self.output_unit = ptr::null_mut();
4241 }
4242
4243 // Cannot unset self.input_unit yet, since the output callback might be live
4244 // and reading it.
4245 }
4246
4247 if !self.output_unit.is_null() {
4248 audio_unit_uninitialize(self.output_unit);
4249 dispose_audio_unit(self.output_unit);
4250 self.output_unit = ptr::null_mut();
4251 }
4252
4253 if !self.input_unit.is_null() {
4254 if !self.using_voice_processing_unit() {
4255 // The VPIO unit is shared and must not be disposed.
4256 dispose_audio_unit(self.input_unit);
4257 }
4258 self.input_unit = ptr::null_mut();
4259 }
4260
4261 // Return the VPIO unit if present.
4262 self.voiceprocessing_unit_handle = None;
4263
4264 #[cfg(feature = "audio-dump")]
4265 {
4266 if !self.audio_dump_session.is_null() {
4267 unsafe {
4268 ffi::cubeb_audio_dump_stop(self.audio_dump_session);
4269 if !self.audio_dump_input.is_null() {
4270 let rv = ffi::cubeb_audio_dump_stream_shutdown(
4271 self.audio_dump_session,
4272 self.audio_dump_input,
4273 );
4274 if rv != 0 {
4275 cubeb_log!("Failed to shutdown audio dump for input");
4276 }
4277 }
4278 if !self.audio_dump_output.is_null() {
4279 let rv = ffi::cubeb_audio_dump_stream_shutdown(
4280 self.audio_dump_session,
4281 self.audio_dump_output,
4282 );
4283 if rv != 0 {
4284 cubeb_log!("Failed to shutdown audio dump for output");
4285 }
4286 }
4287 ffi::cubeb_audio_dump_shutdown(self.audio_dump_session);
4288 self.audio_dump_session = ptr::null_mut();
4289 self.audio_dump_session_running = false;
4290 }
4291 }
4292 }
4293
4294 self.resampler.destroy();
4295 self.mixer = None;
4296 self.aggregate_device = None;
4297
4298 if self.uninstall_system_changed_callback().is_err() {
4299 cubeb_log!(
4300 "({:p}) Could not uninstall the system changed callback",
4301 self.stm_ptr
4302 );
4303 }
4304
4305 if self.uninstall_device_changed_callback().is_err() {
4306 cubeb_log!(
4307 "({:p}) Could not uninstall all device change listeners",
4308 self.stm_ptr
4309 );
4310 }
4311 }
4312
4313 fn install_device_changed_callback(&mut self) -> Result<()> {
4314 self.debug_assert_is_on_stream_queue();
4315 assert!(!self.stm_ptr.is_null());
4316 let stm = unsafe { &(*self.stm_ptr) };
4317
4318 if !self.output_unit.is_null() {
4319 assert_ne!(self.output_device.id, kAudioObjectUnknown);
4320 assert_ne!(self.output_device.id, kAudioObjectSystemObject);
4321 assert!(
4322 self.output_source_listener.is_none(),
4323 "register output_source_listener without unregistering the one in use"
4324 );
4325 assert!(
4326 self.output_alive_listener.is_none(),
4327 "register output_alive_listener without unregistering the one in use"
4328 );
4329
4330 // Get the notification when the data source on the same device changes,
4331 // e.g., when the user plugs in a TRRS headset into the headphone jack.
4332 self.output_source_listener = Some(device_property_listener::new(
4333 self.output_device.id,
4334 get_property_address(Property::DeviceSource, DeviceType::OUTPUT),
4335 audiounit_property_listener_callback,
4336 ));
4337 let rv = stm.add_device_listener(self.output_source_listener.as_ref().unwrap());
4338 if rv != NO_ERR {
4339 self.output_source_listener = None;
4340 cubeb_log!("AudioObjectAddPropertyListener/output/kAudioDevicePropertyDataSource rv={}, device id={}", rv, self.output_device.id);
4341 return Err(Error::error());
4342 }
4343
4344 // Get the notification when the output device is going away
4345 // if the output doesn't follow the system default.
4346 if !self
4347 .output_device
4348 .flags
4349 .contains(device_flags::DEV_SELECTED_DEFAULT)
4350 {
4351 self.output_alive_listener = Some(device_property_listener::new(
4352 self.output_device.id,
4353 get_property_address(
4354 Property::DeviceIsAlive,
4355 DeviceType::INPUT | DeviceType::OUTPUT,
4356 ),
4357 audiounit_property_listener_callback,
4358 ));
4359 let rv = stm.add_device_listener(self.output_alive_listener.as_ref().unwrap());
4360 if rv != NO_ERR {
4361 self.output_alive_listener = None;
4362 cubeb_log!("AudioObjectAddPropertyListener/output/kAudioDevicePropertyDeviceIsAlive rv={}, device id ={}", rv, self.output_device.id);
4363 return Err(Error::error());
4364 }
4365 }
4366 }
4367
4368 if !self.input_unit.is_null() {
4369 assert_ne!(self.input_device.id, kAudioObjectUnknown);
4370 assert_ne!(self.input_device.id, kAudioObjectSystemObject);
4371 assert!(
4372 self.input_source_listener.is_none(),
4373 "register input_source_listener without unregistering the one in use"
4374 );
4375 assert!(
4376 self.input_alive_listener.is_none(),
4377 "register input_alive_listener without unregistering the one in use"
4378 );
4379
4380 // Get the notification when the data source on the same device changes,
4381 // e.g., when the user plugs in a TRRS mic into the headphone jack.
4382 self.input_source_listener = Some(device_property_listener::new(
4383 self.input_device.id,
4384 get_property_address(Property::DeviceSource, DeviceType::INPUT),
4385 audiounit_property_listener_callback,
4386 ));
4387 let rv = stm.add_device_listener(self.input_source_listener.as_ref().unwrap());
4388 if rv != NO_ERR {
4389 self.input_source_listener = None;
4390 cubeb_log!("AudioObjectAddPropertyListener/input/kAudioDevicePropertyDataSource rv={}, device id={}", rv, self.input_device.id);
4391 return Err(Error::error());
4392 }
4393
4394 // Get the notification when the input device is going away
4395 // if the input doesn't follow the system default.
4396 if !self
4397 .input_device
4398 .flags
4399 .contains(device_flags::DEV_SELECTED_DEFAULT)
4400 {
4401 self.input_alive_listener = Some(device_property_listener::new(
4402 self.input_device.id,
4403 get_property_address(
4404 Property::DeviceIsAlive,
4405 DeviceType::INPUT | DeviceType::OUTPUT,
4406 ),
4407 audiounit_property_listener_callback,
4408 ));
4409 let rv = stm.add_device_listener(self.input_alive_listener.as_ref().unwrap());
4410 if rv != NO_ERR {
4411 self.input_alive_listener = None;
4412 cubeb_log!("AudioObjectAddPropertyListener/input/kAudioDevicePropertyDeviceIsAlive rv={}, device id ={}", rv, self.input_device.id);
4413 return Err(Error::error());
4414 }
4415 }
4416 }
4417
4418 Ok(())
4419 }
4420
4421 fn install_system_changed_callback(&mut self) -> Result<()> {
4422 self.debug_assert_is_on_stream_queue();
4423 assert!(!self.stm_ptr.is_null());
4424 let stm = unsafe { &(*self.stm_ptr) };
4425
4426 if !self.output_unit.is_null()
4427 && self
4428 .output_device
4429 .flags
4430 .contains(device_flags::DEV_SELECTED_DEFAULT)
4431 {
4432 assert!(
4433 self.default_output_listener.is_none(),
4434 "register default_output_listener without unregistering the one in use"
4435 );
4436
4437 // Get the notification when the default output audio changes, e.g.,
4438 // when the user plugs in a USB headset and the system chooses it automatically as the default,
4439 // or when another device is chosen in the dropdown list.
4440 self.default_output_listener = Some(device_property_listener::new(
4441 kAudioObjectSystemObject,
4442 get_property_address(
4443 Property::HardwareDefaultOutputDevice,
4444 DeviceType::INPUT | DeviceType::OUTPUT,
4445 ),
4446 audiounit_property_listener_callback,
4447 ));
4448 let r = stm.add_device_listener(self.default_output_listener.as_ref().unwrap());
4449 if r != NO_ERR {
4450 self.default_output_listener = None;
4451 cubeb_log!("AudioObjectAddPropertyListener/output/kAudioHardwarePropertyDefaultOutputDevice rv={}", r);
4452 return Err(Error::error());
4453 }
4454 }
4455
4456 if !self.input_unit.is_null()
4457 && self
4458 .input_device
4459 .flags
4460 .contains(device_flags::DEV_SELECTED_DEFAULT)
4461 {
4462 assert!(
4463 self.default_input_listener.is_none(),
4464 "register default_input_listener without unregistering the one in use"
4465 );
4466
4467 // Get the notification when the default intput audio changes, e.g.,
4468 // when the user plugs in a USB mic and the system chooses it automatically as the default,
4469 // or when another device is chosen in the system preference.
4470 self.default_input_listener = Some(device_property_listener::new(
4471 kAudioObjectSystemObject,
4472 get_property_address(
4473 Property::HardwareDefaultInputDevice,
4474 DeviceType::INPUT | DeviceType::OUTPUT,
4475 ),
4476 audiounit_property_listener_callback,
4477 ));
4478 let r = stm.add_device_listener(self.default_input_listener.as_ref().unwrap());
4479 if r != NO_ERR {
4480 self.default_input_listener = None;
4481 cubeb_log!("AudioObjectAddPropertyListener/input/kAudioHardwarePropertyDefaultInputDevice rv={}", r);
4482 return Err(Error::error());
4483 }
4484 }
4485
4486 Ok(())
4487 }
4488
4489 fn uninstall_device_changed_callback(&mut self) -> Result<()> {
4490 self.debug_assert_is_on_stream_queue();
4491 if self.stm_ptr.is_null() {
4492 assert!(
4493 self.output_source_listener.is_none()
4494 && self.output_alive_listener.is_none()
4495 && self.input_source_listener.is_none()
4496 && self.input_alive_listener.is_none()
4497 );
4498 return Ok(());
4499 }
4500
4501 let stm = unsafe { &(*self.stm_ptr) };
4502
4503 // Failing to uninstall listeners is not a fatal error.
4504 let mut r = Ok(());
4505
4506 if self.output_source_listener.is_some() {
4507 let rv = stm.remove_device_listener(self.output_source_listener.as_ref().unwrap());
4508 if rv != NO_ERR {
4509 cubeb_log!("AudioObjectRemovePropertyListener/output/kAudioDevicePropertyDataSource rv={}, device id={}", rv, self.output_device.id);
4510 r = Err(Error::error());
4511 }
4512 self.output_source_listener = None;
4513 }
4514
4515 if self.output_alive_listener.is_some() {
4516 let rv = stm.remove_device_listener(self.output_alive_listener.as_ref().unwrap());
4517 if rv != NO_ERR {
4518 cubeb_log!("AudioObjectRemovePropertyListener/output/kAudioDevicePropertyDeviceIsAlive rv={}, device id={}", rv, self.output_device.id);
4519 r = Err(Error::error());
4520 }
4521 self.output_alive_listener = None;
4522 }
4523
4524 if self.input_source_listener.is_some() {
4525 let rv = stm.remove_device_listener(self.input_source_listener.as_ref().unwrap());
4526 if rv != NO_ERR {
4527 cubeb_log!("AudioObjectRemovePropertyListener/input/kAudioDevicePropertyDataSource rv={}, device id={}", rv, self.input_device.id);
4528 r = Err(Error::error());
4529 }
4530 self.input_source_listener = None;
4531 }
4532
4533 if self.input_alive_listener.is_some() {
4534 let rv = stm.remove_device_listener(self.input_alive_listener.as_ref().unwrap());
4535 if rv != NO_ERR {
4536 cubeb_log!("AudioObjectRemovePropertyListener/input/kAudioDevicePropertyDeviceIsAlive rv={}, device id={}", rv, self.input_device.id);
4537 r = Err(Error::error());
4538 }
4539 self.input_alive_listener = None;
4540 }
4541
4542 r
4543 }
4544
4545 fn uninstall_system_changed_callback(&mut self) -> Result<()> {
4546 self.debug_assert_is_on_stream_queue();
4547 if self.stm_ptr.is_null() {
4548 assert!(
4549 self.default_output_listener.is_none() && self.default_input_listener.is_none()
4550 );
4551 return Ok(());
4552 }
4553
4554 let stm = unsafe { &(*self.stm_ptr) };
4555
4556 if self.default_output_listener.is_some() {
4557 let r = stm.remove_device_listener(self.default_output_listener.as_ref().unwrap());
4558 if r != NO_ERR {
4559 return Err(Error::error());
4560 }
4561 self.default_output_listener = None;
4562 }
4563
4564 if self.default_input_listener.is_some() {
4565 let r = stm.remove_device_listener(self.default_input_listener.as_ref().unwrap());
4566 if r != NO_ERR {
4567 return Err(Error::error());
4568 }
4569 self.default_input_listener = None;
4570 }
4571
4572 Ok(())
4573 }
4574
4575 fn get_output_channel_layout(&self) -> Result<Vec<mixer::Channel>> {
4576 self.debug_assert_is_on_stream_queue();
4577 assert!(!self.output_unit.is_null());
4578 if self.using_voice_processing_unit() {
4579 return Ok(get_channel_order(ChannelLayout::MONO));
4580 }
4581 get_channel_layout(self.output_unit)
4582 }
4583 }
4584
4585 impl<'ctx> Drop for CoreStreamData<'ctx> {
4586 fn drop(&mut self) {
4587 self.debug_assert_is_on_stream_queue();
4588 self.stop_audiounits();
4589 self.close();
4590 }
4591 }
4592
4593 #[derive(Debug, Clone)]
4594 struct OutputCallbackTimingData {
4595 frames_queued: u64,
4596 timestamp: u64,
4597 buffer_size: u64,
4598 }
4599
4600 // The fisrt two members of the Cubeb stream must be a pointer to its Cubeb context and a void user
4601 // defined pointer. The Cubeb interface use this assumption to operate the Cubeb APIs.
4602 // #[repr(C)] is used to prevent any padding from being added in the beginning of the AudioUnitStream.
4603 #[repr(C)]
4604 #[derive(Debug)]
4605 struct AudioUnitStream<'ctx> {
4606 context: &'ctx mut AudioUnitContext,
4607 user_ptr: *mut c_void,
4608 // Task queue for the stream.
4609 queue: Queue,
4610
4611 data_callback: ffi::cubeb_data_callback,
4612 state_callback: ffi::cubeb_state_callback,
4613 device_changed_callback: Mutex<ffi::cubeb_device_changed_callback>,
4614 // Frame counters
4615 frames_queued: u64,
4616 // How many frames got read from the input since the stream started (includes
4617 // padded silence)
4618 frames_read: AtomicUsize,
4619 // How many frames got written to the output device since the stream started
4620 frames_written: AtomicUsize,
4621 stopped: AtomicBool,
4622 draining: AtomicBool,
4623 reinit_pending: AtomicBool,
4624 delayed_reinit: bool,
4625 destroy_pending: AtomicBool,
4626 // Latency requested by the user.
4627 latency_frames: u32,
4628 // Fixed latency, characteristic of the device.
4629 output_device_latency_frames: AtomicU32,
4630 input_device_latency_frames: AtomicU32,
4631 // Total latency: the latency of the device + the OS latency
4632 total_output_latency_frames: AtomicU32,
4633 total_input_latency_frames: AtomicU32,
4634 output_callback_timing_data_read: triple_buffer::Output<OutputCallbackTimingData>,
4635 output_callback_timing_data_write: triple_buffer::Input<OutputCallbackTimingData>,
4636 prev_position: u64,
4637 // This is true if a device change callback is currently running.
4638 switching_device: AtomicBool,
4639 core_stream_data: CoreStreamData<'ctx>,
4640 }
4641
4642 impl<'ctx> AudioUnitStream<'ctx> {
4643 fn new(
4644 context: &'ctx mut AudioUnitContext,
4645 user_ptr: *mut c_void,
4646 data_callback: ffi::cubeb_data_callback,
4647 state_callback: ffi::cubeb_state_callback,
4648 latency_frames: u32,
4649 ) -> Self {
4650 let output_callback_timing_data =
4651 triple_buffer::TripleBuffer::new(OutputCallbackTimingData {
4652 frames_queued: 0,
4653 timestamp: 0,
4654 buffer_size: 0,
4655 });
4656 let (output_callback_timing_data_write, output_callback_timing_data_read) =
4657 output_callback_timing_data.split();
4658 let queue = context.serial_queue.clone();
4659 AudioUnitStream {
4660 context,
4661 user_ptr,
4662 queue,
4663 data_callback,
4664 state_callback,
4665 device_changed_callback: Mutex::new(None),
4666 frames_queued: 0,
4667 frames_read: AtomicUsize::new(0),
4668 frames_written: AtomicUsize::new(0),
4669 stopped: AtomicBool::new(true),
4670 draining: AtomicBool::new(false),
4671 reinit_pending: AtomicBool::new(false),
4672 delayed_reinit: false,
4673 destroy_pending: AtomicBool::new(false),
4674 latency_frames,
4675 output_device_latency_frames: AtomicU32::new(0),
4676 input_device_latency_frames: AtomicU32::new(0),
4677 total_output_latency_frames: AtomicU32::new(0),
4678 total_input_latency_frames: AtomicU32::new(0),
4679 output_callback_timing_data_write,
4680 output_callback_timing_data_read,
4681 prev_position: 0,
4682 switching_device: AtomicBool::new(false),
4683 core_stream_data: CoreStreamData::default(),
4684 }
4685 }
4686
4687 fn add_device_listener(&self, listener: &device_property_listener) -> OSStatus {
4688 self.queue.debug_assert_is_current();
4689 audio_object_add_property_listener(
4690 listener.device,
4691 &listener.property,
4692 listener.listener,
4693 self as *const Self as *mut c_void,
4694 )
4695 }
4696
4697 fn remove_device_listener(&self, listener: &device_property_listener) -> OSStatus {
4698 self.queue.debug_assert_is_current();
4699 audio_object_remove_property_listener(
4700 listener.device,
4701 &listener.property,
4702 listener.listener,
4703 self as *const Self as *mut c_void,
4704 )
4705 }
4706
4707 fn notify_state_changed(&self, state: State) {
4708 if self.state_callback.is_none() {
4709 return;
4710 }
4711 let callback = self.state_callback.unwrap();
4712 unsafe {
4713 callback(
4714 self as *const AudioUnitStream as *mut ffi::cubeb_stream,
4715 self.user_ptr,
4716 state.into(),
4717 );
4718 }
4719 }
4720
4721 fn reinit(&mut self) -> Result<()> {
4722 self.queue.debug_assert_is_current();
4723 // Call stop_audiounits to avoid potential data race. If there is a running data callback,
4724 // which locks a mutex inside CoreAudio framework, then this call will block the current
4725 // thread until the callback is finished since this call asks to lock a mutex inside
4726 // CoreAudio framework that is used by the data callback.
4727 if !self.stopped.load(Ordering::SeqCst) {
4728 self.core_stream_data.stop_audiounits();
4729 }
4730
4731 if self.stopped.load(Ordering::SeqCst) {
4732 // Something stopped the stream, reinit on next start
4733 self.delayed_reinit = true;
4734 return Ok(());
4735 }
4736
4737 debug_assert!(
4738 !self.core_stream_data.input_unit.is_null()
4739 || !self.core_stream_data.output_unit.is_null()
4740 );
4741 let vol_rv = if self.core_stream_data.output_unit.is_null() {
4742 Err(Error::error())
4743 } else {
4744 get_volume(self.core_stream_data.output_unit)
4745 };
4746
4747 self.core_stream_data.close();
4748
4749 // Use the new default device if this stream was set to follow the output device.
4750 if self.core_stream_data.has_output()
4751 && self
4752 .core_stream_data
4753 .output_device
4754 .flags
4755 .contains(device_flags::DEV_SELECTED_DEFAULT)
4756 {
4757 cubeb_log!("Using new default output device");
4758 self.core_stream_data.output_device =
4759 match create_device_info(kAudioObjectUnknown, DeviceType::OUTPUT) {
4760 None => {
4761 cubeb_log!("Fail to create device info for output");
4762 return Err(Error::error());
4763 }
4764 Some(d) => d,
4765 };
4766 }
4767
4768 // Likewise, for the input side
4769 if self.core_stream_data.has_input()
4770 && self
4771 .core_stream_data
4772 .input_device
4773 .flags
4774 .contains(device_flags::DEV_SELECTED_DEFAULT)
4775 {
4776 cubeb_log!("Using new default input device");
4777 self.core_stream_data.input_device =
4778 match create_device_info(kAudioObjectUnknown, DeviceType::INPUT) {
4779 None => {
4780 cubeb_log!("Fail to create device info for input");
4781 return Err(Error::error());
4782 }
4783 Some(d) => d,
4784 }
4785 }
4786
4787 cubeb_log!("Reinit: setup");
4788 self.core_stream_data
4789 .setup(&mut self.context.shared_voice_processing_unit)
4790 .inspect_err(|_| {
4791 cubeb_log!("({:p}) Setup failed.", self.core_stream_data.stm_ptr);
4792 })?;
4793
4794 if let Ok(volume) = vol_rv {
4795 set_volume(self.core_stream_data.output_unit, volume);
4796 }
4797
4798 // If the stream was running, start it again.
4799 if !self.stopped.load(Ordering::SeqCst) {
4800 self.core_stream_data.start_audiounits().inspect_err(|_| {
4801 cubeb_log!(
4802 "({:p}) Start audiounit failed.",
4803 self.core_stream_data.stm_ptr
4804 );
4805 })?;
4806 }
4807
4808 Ok(())
4809 }
4810
4811 fn reinit_async(&mut self) {
4812 if self.reinit_pending.swap(true, Ordering::SeqCst) {
4813 // A reinit task is already pending, nothing more to do.
4814 cubeb_log!(
4815 "({:p}) re-init stream task already pending, cancelling request",
4816 self as *const AudioUnitStream
4817 );
4818 return;
4819 }
4820
4821 let queue = self.queue.clone();
4822 // Use a new thread, through the queue, to avoid deadlock when calling
4823 // Get/SetProperties method from inside notify callback
4824 queue.run_async(move || {
4825 cubeb_log!("Reinitialization of stream");
4826 let stm_ptr = self as *const AudioUnitStream;
4827 if self.destroy_pending.load(Ordering::SeqCst) {
4828 cubeb_log!(
4829 "({:p}) stream pending destroy, cancelling reinit task",
4830 stm_ptr
4831 );
4832 return;
4833 }
4834
4835 if self.reinit().is_err() {
4836 self.core_stream_data.close();
4837 self.notify_state_changed(State::Error);
4838 cubeb_log!(
4839 "({:p}) Could not reopen the stream after switching.",
4840 stm_ptr
4841 );
4842 }
4843 self.switching_device.store(false, Ordering::SeqCst);
4844 self.reinit_pending.store(false, Ordering::SeqCst);
4845 });
4846 }
4847
4848 fn close_on_error(&mut self) {
4849 self.queue.debug_assert_is_current();
4850 let stm_ptr = self as *const AudioUnitStream;
4851
4852 self.core_stream_data.close();
4853 self.notify_state_changed(State::Error);
4854 cubeb_log!("({:p}) Close the stream due to an error.", stm_ptr);
4855
4856 self.switching_device.store(false, Ordering::SeqCst);
4857 }
4858
4859 fn destroy_internal(&mut self) {
4860 self.queue.debug_assert_is_current();
4861 self.core_stream_data.close();
4862 assert!(self.context.active_streams() >= 1);
4863 self.context.update_latency_by_removing_stream();
4864 }
4865
4866 fn destroy(&mut self) {
4867 self.queue.debug_assert_is_current();
4868 if self
4869 .core_stream_data
4870 .uninstall_system_changed_callback()
4871 .is_err()
4872 {
4873 cubeb_log!(
4874 "({:p}) Could not uninstall the system changed callback",
4875 self as *const AudioUnitStream
4876 );
4877 }
4878
4879 if self
4880 .core_stream_data
4881 .uninstall_device_changed_callback()
4882 .is_err()
4883 {
4884 cubeb_log!(
4885 "({:p}) Could not uninstall all device change listeners",
4886 self as *const AudioUnitStream
4887 );
4888 }
4889
4890 // Execute the stream destroy work.
4891 self.destroy_pending.store(true, Ordering::SeqCst);
4892
4893 // Call stop_audiounits to avoid potential data race. If there is a running data callback,
4894 // which locks a mutex inside CoreAudio framework, then this call will block the current
4895 // thread until the callback is finished since this call asks to lock a mutex inside
4896 // CoreAudio framework that is used by the data callback.
4897 if !self.stopped.swap(true, Ordering::SeqCst) {
4898 self.core_stream_data.stop_audiounits();
4899 }
4900
4901 self.destroy_internal();
4902
4903 cubeb_log!(
4904 "Cubeb stream ({:p}) destroyed successful.",
4905 self as *const AudioUnitStream
4906 );
4907 }
4908 }
4909
4910 impl<'ctx> Drop for AudioUnitStream<'ctx> {
4911 fn drop(&mut self) {
4912 // Execute destroy in serial queue to avoid collision with reinit when un/plug devices
4913 self.queue.clone().run_final(|| {
4914 self.destroy();
4915 self.core_stream_data = CoreStreamData::default();
4916 });
4917 }
4918 }
4919
4920 impl<'ctx> StreamOps for AudioUnitStream<'ctx> {
4921 fn start(&mut self) -> Result<()> {
4922 let was_stopped = self.stopped.load(Ordering::SeqCst);
4923 let was_draining = self.draining.load(Ordering::SeqCst);
4924 self.stopped.store(false, Ordering::SeqCst);
4925 self.draining.store(false, Ordering::SeqCst);
4926
4927 self.queue
4928 .clone()
4929 .run_sync(|| -> Result<()> {
4930 // Need reinitialization: device was changed when paused. It will be started after
4931 // reinit because self.stopped is false.
4932 if self.delayed_reinit {
4933 let rv = self.reinit().inspect_err(|_| {
4934 cubeb_log!(
4935 "({:p}) delayed reinit during start failed.",
4936 self.core_stream_data.stm_ptr
4937 );
4938 });
4939 // In case of failure, restore the state
4940 if rv.is_err() {
4941 self.stopped.store(was_stopped, Ordering::SeqCst);
4942 self.draining.store(was_draining, Ordering::SeqCst);
4943 return rv;
4944 }
4945 self.delayed_reinit = false;
4946 Ok(())
4947 } else {
4948 // Execute start in serial queue to avoid racing with destroy or reinit.
4949 let rv = self.core_stream_data.start_audiounits();
4950 if rv.is_err() {
4951 cubeb_log!("({:p}) start failed.", self.core_stream_data.stm_ptr);
4952 self.stopped.store(was_stopped, Ordering::SeqCst);
4953 self.draining.store(was_draining, Ordering::SeqCst);
4954 return rv;
4955 }
4956 Ok(())
4957 }
4958 })
4959 .unwrap()?;
4960
4961 self.notify_state_changed(State::Started);
4962
4963 cubeb_log!(
4964 "Cubeb stream ({:p}) started successfully.",
4965 self as *const AudioUnitStream
4966 );
4967 Ok(())
4968 }
4969 fn stop(&mut self) -> Result<()> {
4970 if !self.stopped.swap(true, Ordering::SeqCst) {
4971 // Execute stop in serial queue to avoid racing with destroy or reinit.
4972 self.queue
4973 .clone()
4974 .run_sync(|| self.core_stream_data.stop_audiounits());
4975
4976 self.notify_state_changed(State::Stopped);
4977
4978 cubeb_log!(
4979 "Cubeb stream ({:p}) stopped successfully.",
4980 self as *const AudioUnitStream
4981 );
4982 }
4983 Ok(())
4984 }
4985 fn position(&mut self) -> Result<u64> {
4986 let OutputCallbackTimingData {
4987 frames_queued,
4988 timestamp,
4989 buffer_size,
4990 } = self.output_callback_timing_data_read.read().clone();
4991 let total_output_latency_frames =
4992 u64::from(self.total_output_latency_frames.load(Ordering::SeqCst));
4993 // If output latency is available, take it into account. Otherwise, use the number of
4994 // frames played.
4995 let position = if total_output_latency_frames != 0 {
4996 if total_output_latency_frames > frames_queued {
4997 0
4998 } else {
4999 // Interpolate here to match other cubeb backends. Only return an interpolated time
5000 // if we've played enough frames. If the stream is paused, clamp the interpolated
5001 // number of frames to the buffer size.
5002 const NS2S: u64 = 1_000_000_000;
5003 let now = unsafe { mach_absolute_time() };
5004 let diff = now - timestamp;
5005 let interpolated_frames = cmp::min(
5006 host_time_to_ns(self.context, diff)
5007 * self.core_stream_data.output_stream_params.rate() as u64
5008 / NS2S,
5009 buffer_size,
5010 );
5011 (frames_queued - total_output_latency_frames) + interpolated_frames
5012 }
5013 } else {
5014 frames_queued
5015 };
5016
5017 // Ensure mononicity of the clock even when changing output device.
5018 if position > self.prev_position {
5019 self.prev_position = position;
5020 }
5021 Ok(self.prev_position)
5022 }
5023 #[cfg(target_os = "ios")]
5024 fn latency(&mut self) -> Result<u32> {
5025 Err(not_supported())
5026 }
5027 #[cfg(not(target_os = "ios"))]
5028 fn latency(&mut self) -> Result<u32> {
5029 Ok(self.total_output_latency_frames.load(Ordering::SeqCst))
5030 }
5031 #[cfg(target_os = "ios")]
5032 fn input_latency(&mut self) -> Result<u32> {
5033 Err(not_supported())
5034 }
5035 #[cfg(not(target_os = "ios"))]
5036 fn input_latency(&mut self) -> Result<u32> {
5037 let user_rate = self.core_stream_data.input_stream_params.rate();
5038 let hw_rate = self.core_stream_data.input_dev_desc.mSampleRate as u32;
5039 let frames = self.total_input_latency_frames.load(Ordering::SeqCst);
5040 if frames != 0 {
5041 if hw_rate == user_rate {
5042 Ok(frames)
5043 } else {
5044 Ok((frames * user_rate) / hw_rate)
5045 }
5046 } else {
5047 Err(Error::error())
5048 }
5049 }
5050 fn set_volume(&mut self, volume: f32) -> Result<()> {
5051 // Execute set_volume in serial queue to avoid racing with destroy or reinit.
5052 let result = self
5053 .queue
5054 .run_sync(|| set_volume(self.core_stream_data.output_unit, volume))
5055 .unwrap();
5056
5057 result?;
5058
5059 cubeb_log!(
5060 "Cubeb stream ({:p}) set volume to {}.",
5061 self as *const AudioUnitStream,
5062 volume
5063 );
5064 Ok(())
5065 }
5066 fn set_name(&mut self, _: &CStr) -> Result<()> {
5067 Err(Error::not_supported())
5068 }
5069 fn current_device(&mut self) -> Result<&DeviceRef> {
5070 Err(Error::not_supported())
5071 }
5072 fn set_input_mute(&mut self, mute: bool) -> Result<()> {
5073 if self.core_stream_data.input_unit.is_null() {
5074 return Err(Error::invalid_parameter());
5075 }
5076
5077 if !self.core_stream_data.using_voice_processing_unit() {
5078 return Err(Error::error());
5079 }
5080
5081 // Execute set_input_mute in serial queue to avoid racing with destroy or reinit.
5082 let mut result = Err(Error::error());
5083 let set = &mut result;
5084 let stream = &self;
5085 self.queue.run_sync(move || {
5086 *set = set_input_mute(stream.core_stream_data.input_unit, mute);
5087 });
5088
5089 result?;
5090
5091 cubeb_log!(
5092 "Cubeb stream ({:p}) set input mute to {}.",
5093 self as *const AudioUnitStream,
5094 mute
5095 );
5096 self.core_stream_data.input_mute = mute;
5097 Ok(())
5098 }
5099 fn set_input_processing_params(&mut self, params: InputProcessingParams) -> Result<()> {
5100 // CUBEB_ERROR_INVALID_PARAMETER if a given param is not supported by
5101 // this backend, or if this stream does not have an input device
5102 if self.core_stream_data.input_unit.is_null() {
5103 return Err(Error::invalid_parameter());
5104 }
5105
5106 if self
5107 .context
5108 .supported_input_processing_params()
5109 .unwrap()
5110 .intersection(params)
5111 != params
5112 {
5113 return Err(Error::invalid_parameter());
5114 }
5115
5116 // AEC and NS are active as soon as VPIO is not bypassed, therefore the only combinations
5117 // of those we can explicitly support are {} and {aec, ns}.
5118 let aec = params.contains(InputProcessingParams::ECHO_CANCELLATION);
5119 let ns = params.contains(InputProcessingParams::NOISE_SUPPRESSION);
5120 if aec != ns {
5121 // No control to turn on AEC without NS or vice versa.
5122 cubeb_log!(
5123 "Cubeb stream ({:p}) couldn't set input processing params {:?}. AEC != NS.",
5124 self as *const AudioUnitStream,
5125 params
5126 );
5127 return Err(Error::error());
5128 }
5129
5130 // CUBEB_ERROR if params could not be applied
5131 // note: only works with VoiceProcessingIO
5132 if !self.core_stream_data.using_voice_processing_unit() {
5133 return Err(Error::error());
5134 }
5135
5136 // Execute set_input_processing_params in serial queue to avoid racing with destroy or reinit.
5137 let mut result = Err(Error::error());
5138 let result_ = &mut result;
5139 let mut deferred = false;
5140 let deferred_ = &mut deferred;
5141 let stream = &self;
5142 self.queue.run_sync(move || {
5143 if stream.core_stream_data.units_running {
5144 *deferred_ = true;
5145 *result_ = Ok(());
5146 } else {
5147 *deferred_ = false;
5148 *result_ = set_input_processing_params(stream.core_stream_data.input_unit, params);
5149 }
5150 });
5151
5152 result?;
5153
5154 cubeb_log!(
5155 "Cubeb stream ({:p}) {} input processing params {:?}.",
5156 self as *const AudioUnitStream,
5157 if deferred { "deferred" } else { "set" },
5158 params
5159 );
5160 self.core_stream_data.input_processing_params = params;
5161 Ok(())
5162 }
5163 #[cfg(target_os = "ios")]
5164 fn device_destroy(&mut self, device: &DeviceRef) -> Result<()> {
5165 Err(not_supported())
5166 }
5167 #[cfg(not(target_os = "ios"))]
5168 fn device_destroy(&mut self, device: &DeviceRef) -> Result<()> {
5169 if device.as_ptr().is_null() {
5170 Err(Error::error())
5171 } else {
5172 unsafe {
5173 let mut dev: Box<ffi::cubeb_device> = Box::from_raw(device.as_ptr() as *mut _);
5174 if !dev.output_name.is_null() {
5175 let _ = CString::from_raw(dev.output_name as *mut _);
5176 dev.output_name = ptr::null_mut();
5177 }
5178 if !dev.input_name.is_null() {
5179 let _ = CString::from_raw(dev.input_name as *mut _);
5180 dev.input_name = ptr::null_mut();
5181 }
5182 drop(dev);
5183 }
5184 Ok(())
5185 }
5186 }
5187 fn register_device_changed_callback(
5188 &mut self,
5189 device_changed_callback: ffi::cubeb_device_changed_callback,
5190 ) -> Result<()> {
5191 let mut callback = self.device_changed_callback.lock().unwrap();
5192 // Note: second register without unregister first causes 'nope' error.
5193 // Current implementation requires unregister before register a new cb.
5194 if device_changed_callback.is_some() && callback.is_some() {
5195 Err(Error::invalid_parameter())
5196 } else {
5197 *callback = device_changed_callback;
5198 Ok(())
5199 }
5200 }
5201 }
5202
5203 #[allow(clippy::non_send_fields_in_send_ty)]
5204 unsafe impl<'ctx> Send for AudioUnitStream<'ctx> {}
5205 unsafe impl<'ctx> Sync for AudioUnitStream<'ctx> {}
5206
5207 #[cfg(test)]
5208 mod tests;