2 * QEMU OS X CoreAudio audio driver
4 * Copyright (c) 2005 Mike Kronenberg
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include <CoreAudio/CoreAudio.h>
27 #include <pthread.h> /* pthread_X */
29 #include "qemu/main-loop.h"
30 #include "qemu/module.h"
33 #define AUDIO_CAP "coreaudio"
34 #include "audio_int.h"
36 typedef struct coreaudioVoiceOut
{
38 pthread_mutex_t buf_mutex
;
39 AudioDeviceID outputDeviceID
;
42 UInt32 audioDevicePropertyBufferFrameSize
;
43 AudioDeviceIOProcID ioprocid
;
47 static const AudioObjectPropertyAddress voice_addr
= {
48 kAudioHardwarePropertyDefaultOutputDevice
,
49 kAudioObjectPropertyScopeGlobal
,
50 kAudioObjectPropertyElementMaster
53 static OSStatus
coreaudio_get_voice(AudioDeviceID
*id
)
55 UInt32 size
= sizeof(*id
);
57 return AudioObjectGetPropertyData(kAudioObjectSystemObject
,
65 static OSStatus
coreaudio_get_framesizerange(AudioDeviceID id
,
66 AudioValueRange
*framerange
)
68 UInt32 size
= sizeof(*framerange
);
69 AudioObjectPropertyAddress addr
= {
70 kAudioDevicePropertyBufferFrameSizeRange
,
71 kAudioDevicePropertyScopeOutput
,
72 kAudioObjectPropertyElementMaster
75 return AudioObjectGetPropertyData(id
,
83 static OSStatus
coreaudio_get_framesize(AudioDeviceID id
, UInt32
*framesize
)
85 UInt32 size
= sizeof(*framesize
);
86 AudioObjectPropertyAddress addr
= {
87 kAudioDevicePropertyBufferFrameSize
,
88 kAudioDevicePropertyScopeOutput
,
89 kAudioObjectPropertyElementMaster
92 return AudioObjectGetPropertyData(id
,
100 static OSStatus
coreaudio_set_framesize(AudioDeviceID id
, UInt32
*framesize
)
102 UInt32 size
= sizeof(*framesize
);
103 AudioObjectPropertyAddress addr
= {
104 kAudioDevicePropertyBufferFrameSize
,
105 kAudioDevicePropertyScopeOutput
,
106 kAudioObjectPropertyElementMaster
109 return AudioObjectSetPropertyData(id
,
117 static OSStatus
coreaudio_set_streamformat(AudioDeviceID id
,
118 AudioStreamBasicDescription
*d
)
120 UInt32 size
= sizeof(*d
);
121 AudioObjectPropertyAddress addr
= {
122 kAudioDevicePropertyStreamFormat
,
123 kAudioDevicePropertyScopeOutput
,
124 kAudioObjectPropertyElementMaster
127 return AudioObjectSetPropertyData(id
,
135 static OSStatus
coreaudio_get_isrunning(AudioDeviceID id
, UInt32
*result
)
137 UInt32 size
= sizeof(*result
);
138 AudioObjectPropertyAddress addr
= {
139 kAudioDevicePropertyDeviceIsRunning
,
140 kAudioDevicePropertyScopeOutput
,
141 kAudioObjectPropertyElementMaster
144 return AudioObjectGetPropertyData(id
,
152 static void coreaudio_logstatus (OSStatus status
)
154 const char *str
= "BUG";
157 case kAudioHardwareNoError
:
158 str
= "kAudioHardwareNoError";
161 case kAudioHardwareNotRunningError
:
162 str
= "kAudioHardwareNotRunningError";
165 case kAudioHardwareUnspecifiedError
:
166 str
= "kAudioHardwareUnspecifiedError";
169 case kAudioHardwareUnknownPropertyError
:
170 str
= "kAudioHardwareUnknownPropertyError";
173 case kAudioHardwareBadPropertySizeError
:
174 str
= "kAudioHardwareBadPropertySizeError";
177 case kAudioHardwareIllegalOperationError
:
178 str
= "kAudioHardwareIllegalOperationError";
181 case kAudioHardwareBadDeviceError
:
182 str
= "kAudioHardwareBadDeviceError";
185 case kAudioHardwareBadStreamError
:
186 str
= "kAudioHardwareBadStreamError";
189 case kAudioHardwareUnsupportedOperationError
:
190 str
= "kAudioHardwareUnsupportedOperationError";
193 case kAudioDeviceUnsupportedFormatError
:
194 str
= "kAudioDeviceUnsupportedFormatError";
197 case kAudioDevicePermissionsError
:
198 str
= "kAudioDevicePermissionsError";
202 AUD_log (AUDIO_CAP
, "Reason: status code %" PRId32
"\n", (int32_t)status
);
206 AUD_log (AUDIO_CAP
, "Reason: %s\n", str
);
209 static void GCC_FMT_ATTR (2, 3) coreaudio_logerr (
218 AUD_log (AUDIO_CAP
, fmt
, ap
);
221 coreaudio_logstatus (status
);
224 static void GCC_FMT_ATTR (3, 4) coreaudio_logerr2 (
233 AUD_log (AUDIO_CAP
, "Could not initialize %s\n", typ
);
236 AUD_vlog (AUDIO_CAP
, fmt
, ap
);
239 coreaudio_logstatus (status
);
242 #define coreaudio_playback_logerr(status, ...) \
243 coreaudio_logerr2(status, "playback", __VA_ARGS__)
245 static int coreaudio_buf_lock (coreaudioVoiceOut
*core
, const char *fn_name
)
249 err
= pthread_mutex_lock (&core
->buf_mutex
);
251 dolog ("Could not lock voice for %s\nReason: %s\n",
252 fn_name
, strerror (err
));
258 static int coreaudio_buf_unlock (coreaudioVoiceOut
*core
, const char *fn_name
)
262 err
= pthread_mutex_unlock (&core
->buf_mutex
);
264 dolog ("Could not unlock voice for %s\nReason: %s\n",
265 fn_name
, strerror (err
));
271 #define COREAUDIO_WRAPPER_FUNC(name, ret_type, args_decl, args) \
272 static ret_type glue(coreaudio_, name)args_decl \
274 coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw; \
277 if (coreaudio_buf_lock(core, "coreaudio_" #name)) { \
281 ret = glue(audio_generic_, name)args; \
283 coreaudio_buf_unlock(core, "coreaudio_" #name); \
286 COREAUDIO_WRAPPER_FUNC(get_buffer_out
, void *, (HWVoiceOut
*hw
, size_t *size
),
288 COREAUDIO_WRAPPER_FUNC(put_buffer_out
, size_t,
289 (HWVoiceOut
*hw
, void *buf
, size_t size
),
291 COREAUDIO_WRAPPER_FUNC(write
, size_t, (HWVoiceOut
*hw
, void *buf
, size_t size
),
293 #undef COREAUDIO_WRAPPER_FUNC
296 * callback to feed audiooutput buffer. called without iothread lock.
297 * allowed to lock "buf_mutex", but disallowed to have any other locks.
299 static OSStatus
audioDeviceIOProc(
300 AudioDeviceID inDevice
,
301 const AudioTimeStamp
*inNow
,
302 const AudioBufferList
*inInputData
,
303 const AudioTimeStamp
*inInputTime
,
304 AudioBufferList
*outOutputData
,
305 const AudioTimeStamp
*inOutputTime
,
308 UInt32 frameCount
, pending_frames
;
309 void *out
= outOutputData
->mBuffers
[0].mData
;
310 HWVoiceOut
*hw
= hwptr
;
311 coreaudioVoiceOut
*core
= (coreaudioVoiceOut
*) hwptr
;
314 if (coreaudio_buf_lock (core
, "audioDeviceIOProc")) {
319 if (inDevice
!= core
->outputDeviceID
) {
320 coreaudio_buf_unlock (core
, "audioDeviceIOProc(old device)");
324 frameCount
= core
->audioDevicePropertyBufferFrameSize
;
325 pending_frames
= hw
->pending_emul
/ hw
->info
.bytes_per_frame
;
327 /* if there are not enough samples, set signal and return */
328 if (pending_frames
< frameCount
) {
330 coreaudio_buf_unlock (core
, "audioDeviceIOProc(empty)");
334 len
= frameCount
* hw
->info
.bytes_per_frame
;
337 ssize_t start
= ((ssize_t
) hw
->pos_emul
) - hw
->pending_emul
;
339 start
+= hw
->size_emul
;
341 assert(start
>= 0 && start
< hw
->size_emul
);
343 write_len
= MIN(MIN(hw
->pending_emul
, len
),
344 hw
->size_emul
- start
);
346 memcpy(out
, hw
->buf_emul
+ start
, write_len
);
347 hw
->pending_emul
-= write_len
;
352 coreaudio_buf_unlock (core
, "audioDeviceIOProc");
356 static OSStatus
init_out_device(coreaudioVoiceOut
*core
)
359 AudioValueRange frameRange
;
361 AudioStreamBasicDescription streamBasicDescription
= {
362 .mBitsPerChannel
= core
->hw
.info
.bits
,
363 .mBytesPerFrame
= core
->hw
.info
.bytes_per_frame
,
364 .mBytesPerPacket
= core
->hw
.info
.bytes_per_frame
,
365 .mChannelsPerFrame
= core
->hw
.info
.nchannels
,
366 .mFormatFlags
= kLinearPCMFormatFlagIsFloat
,
367 .mFormatID
= kAudioFormatLinearPCM
,
368 .mFramesPerPacket
= 1,
369 .mSampleRate
= core
->hw
.info
.freq
372 status
= coreaudio_get_voice(&core
->outputDeviceID
);
373 if (status
!= kAudioHardwareNoError
) {
374 coreaudio_playback_logerr (status
,
375 "Could not get default output Device\n");
378 if (core
->outputDeviceID
== kAudioDeviceUnknown
) {
379 dolog ("Could not initialize playback - Unknown Audiodevice\n");
383 /* get minimum and maximum buffer frame sizes */
384 status
= coreaudio_get_framesizerange(core
->outputDeviceID
,
386 if (status
== kAudioHardwareBadObjectError
) {
389 if (status
!= kAudioHardwareNoError
) {
390 coreaudio_playback_logerr (status
,
391 "Could not get device buffer frame range\n");
395 if (frameRange
.mMinimum
> core
->frameSizeSetting
) {
396 core
->audioDevicePropertyBufferFrameSize
= (UInt32
) frameRange
.mMinimum
;
397 dolog ("warning: Upsizing Buffer Frames to %f\n", frameRange
.mMinimum
);
398 } else if (frameRange
.mMaximum
< core
->frameSizeSetting
) {
399 core
->audioDevicePropertyBufferFrameSize
= (UInt32
) frameRange
.mMaximum
;
400 dolog ("warning: Downsizing Buffer Frames to %f\n", frameRange
.mMaximum
);
402 core
->audioDevicePropertyBufferFrameSize
= core
->frameSizeSetting
;
405 /* set Buffer Frame Size */
406 status
= coreaudio_set_framesize(core
->outputDeviceID
,
407 &core
->audioDevicePropertyBufferFrameSize
);
408 if (status
== kAudioHardwareBadObjectError
) {
411 if (status
!= kAudioHardwareNoError
) {
412 coreaudio_playback_logerr (status
,
413 "Could not set device buffer frame size %" PRIu32
"\n",
414 (uint32_t)core
->audioDevicePropertyBufferFrameSize
);
418 /* get Buffer Frame Size */
419 status
= coreaudio_get_framesize(core
->outputDeviceID
,
420 &core
->audioDevicePropertyBufferFrameSize
);
421 if (status
== kAudioHardwareBadObjectError
) {
424 if (status
!= kAudioHardwareNoError
) {
425 coreaudio_playback_logerr (status
,
426 "Could not get device buffer frame size\n");
429 core
->hw
.samples
= core
->bufferCount
* core
->audioDevicePropertyBufferFrameSize
;
432 status
= coreaudio_set_streamformat(core
->outputDeviceID
,
433 &streamBasicDescription
);
434 if (status
== kAudioHardwareBadObjectError
) {
437 if (status
!= kAudioHardwareNoError
) {
438 coreaudio_playback_logerr (status
,
439 "Could not set samplerate %lf\n",
440 streamBasicDescription
.mSampleRate
);
441 core
->outputDeviceID
= kAudioDeviceUnknown
;
448 * On macOS 11.3.1, Core Audio calls AudioDeviceIOProc after calling an
449 * internal function named HALB_Mutex::Lock(), which locks a mutex in
450 * HALB_IOThread::Entry(void*). HALB_Mutex::Lock() is also called in
451 * AudioObjectGetPropertyData, which is called by coreaudio driver.
452 * Therefore, the specified callback must be designed to avoid a deadlock
453 * with the callers of AudioObjectGetPropertyData.
455 core
->ioprocid
= NULL
;
456 status
= AudioDeviceCreateIOProcID(core
->outputDeviceID
,
460 if (status
== kAudioHardwareBadDeviceError
) {
463 if (status
!= kAudioHardwareNoError
|| core
->ioprocid
== NULL
) {
464 coreaudio_playback_logerr (status
, "Could not set IOProc\n");
465 core
->outputDeviceID
= kAudioDeviceUnknown
;
472 static void fini_out_device(coreaudioVoiceOut
*core
)
478 status
= coreaudio_get_isrunning(core
->outputDeviceID
, &isrunning
);
479 if (status
!= kAudioHardwareBadObjectError
) {
480 if (status
!= kAudioHardwareNoError
) {
481 coreaudio_logerr(status
,
482 "Could not determine whether Device is playing\n");
486 status
= AudioDeviceStop(core
->outputDeviceID
, core
->ioprocid
);
487 if (status
!= kAudioHardwareBadDeviceError
&& status
!= kAudioHardwareNoError
) {
488 coreaudio_logerr(status
, "Could not stop playback\n");
493 /* remove callback */
494 status
= AudioDeviceDestroyIOProcID(core
->outputDeviceID
,
496 if (status
!= kAudioHardwareBadDeviceError
&& status
!= kAudioHardwareNoError
) {
497 coreaudio_logerr(status
, "Could not remove IOProc\n");
499 core
->outputDeviceID
= kAudioDeviceUnknown
;
502 static void update_device_playback_state(coreaudioVoiceOut
*core
)
507 status
= coreaudio_get_isrunning(core
->outputDeviceID
, &isrunning
);
508 if (status
!= kAudioHardwareNoError
) {
509 if (status
!= kAudioHardwareBadObjectError
) {
510 coreaudio_logerr(status
,
511 "Could not determine whether Device is playing\n");
520 status
= AudioDeviceStart(core
->outputDeviceID
, core
->ioprocid
);
521 if (status
!= kAudioHardwareBadDeviceError
&& status
!= kAudioHardwareNoError
) {
522 coreaudio_logerr (status
, "Could not resume playback\n");
528 status
= AudioDeviceStop(core
->outputDeviceID
,
530 if (status
!= kAudioHardwareBadDeviceError
&& status
!= kAudioHardwareNoError
) {
531 coreaudio_logerr(status
, "Could not pause playback\n");
537 /* called without iothread lock. */
538 static OSStatus
handle_voice_change(
539 AudioObjectID in_object_id
,
540 UInt32 in_number_addresses
,
541 const AudioObjectPropertyAddress
*in_addresses
,
542 void *in_client_data
)
545 coreaudioVoiceOut
*core
= in_client_data
;
547 qemu_mutex_lock_iothread();
549 if (core
->outputDeviceID
) {
550 fini_out_device(core
);
553 status
= init_out_device(core
);
555 update_device_playback_state(core
);
558 qemu_mutex_unlock_iothread();
562 static int coreaudio_init_out(HWVoiceOut
*hw
, struct audsettings
*as
,
566 coreaudioVoiceOut
*core
= (coreaudioVoiceOut
*) hw
;
568 Audiodev
*dev
= drv_opaque
;
569 AudiodevCoreaudioPerDirectionOptions
*cpdo
= dev
->u
.coreaudio
.out
;
570 struct audsettings obt_as
;
573 err
= pthread_mutex_init(&core
->buf_mutex
, NULL
);
575 dolog("Could not create mutex\nReason: %s\n", strerror (err
));
581 as
->fmt
= AUDIO_FORMAT_F32
;
582 audio_pcm_init_info (&hw
->info
, as
);
584 core
->frameSizeSetting
= audio_buffer_frames(
585 qapi_AudiodevCoreaudioPerDirectionOptions_base(cpdo
), as
, 11610);
587 core
->bufferCount
= cpdo
->has_buffer_count
? cpdo
->buffer_count
: 4;
589 status
= AudioObjectAddPropertyListener(kAudioObjectSystemObject
,
590 &voice_addr
, handle_voice_change
,
592 if (status
!= kAudioHardwareNoError
) {
593 coreaudio_playback_logerr (status
,
594 "Could not listen to voice property change\n");
598 if (init_out_device(core
)) {
599 status
= AudioObjectRemovePropertyListener(kAudioObjectSystemObject
,
603 if (status
!= kAudioHardwareNoError
) {
604 coreaudio_playback_logerr(status
,
605 "Could not remove voice property change listener\n");
612 static void coreaudio_fini_out (HWVoiceOut
*hw
)
616 coreaudioVoiceOut
*core
= (coreaudioVoiceOut
*) hw
;
618 status
= AudioObjectRemovePropertyListener(kAudioObjectSystemObject
,
622 if (status
!= kAudioHardwareNoError
) {
623 coreaudio_logerr(status
, "Could not remove voice property change listener\n");
626 fini_out_device(core
);
629 err
= pthread_mutex_destroy(&core
->buf_mutex
);
631 dolog("Could not destroy mutex\nReason: %s\n", strerror (err
));
635 static void coreaudio_enable_out(HWVoiceOut
*hw
, bool enable
)
637 coreaudioVoiceOut
*core
= (coreaudioVoiceOut
*) hw
;
639 core
->enabled
= enable
;
640 update_device_playback_state(core
);
643 static void *coreaudio_audio_init(Audiodev
*dev
)
648 static void coreaudio_audio_fini (void *opaque
)
652 static struct audio_pcm_ops coreaudio_pcm_ops
= {
653 .init_out
= coreaudio_init_out
,
654 .fini_out
= coreaudio_fini_out
,
655 /* wrapper for audio_generic_write */
656 .write
= coreaudio_write
,
657 /* wrapper for audio_generic_get_buffer_out */
658 .get_buffer_out
= coreaudio_get_buffer_out
,
659 /* wrapper for audio_generic_put_buffer_out */
660 .put_buffer_out
= coreaudio_put_buffer_out
,
661 .enable_out
= coreaudio_enable_out
664 static struct audio_driver coreaudio_audio_driver
= {
666 .descr
= "CoreAudio http://developer.apple.com/audio/coreaudio.html",
667 .init
= coreaudio_audio_init
,
668 .fini
= coreaudio_audio_fini
,
669 .pcm_ops
= &coreaudio_pcm_ops
,
673 .voice_size_out
= sizeof (coreaudioVoiceOut
),
677 static void register_audio_coreaudio(void)
679 audio_driver_register(&coreaudio_audio_driver
);
681 type_init(register_audio_coreaudio
);