2 * CoreAudio audio output driver for Mac OS X
4 * original copyright (C) Timothy J. Wood - Aug 2000
5 * ported to MPlayer libao2 by Dan Christiansen
7 * The S/PDIF part of the code is based on the auhal audio output
8 * module from VideoLAN:
9 * Copyright (c) 2006 Derk-Jan Hartman <hartman at videolan dot org>
11 * This file is part of MPlayer.
13 * MPlayer is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * MPlayer is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * along with MPlayer; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 * The MacOS X CoreAudio framework doesn't mesh as simply as some
30 * simpler frameworks do. This is due to the fact that CoreAudio pulls
31 * audio samples rather than having them pushed at it (which is nice
32 * when you are wanting to do good buffering of audio).
34 * AC-3 and MPEG audio passthrough is possible, but has never been tested
35 * due to lack of a soundcard that supports it.
38 #include <CoreServices/CoreServices.h>
39 #include <AudioUnit/AudioUnit.h>
40 #include <AudioToolbox/AudioToolbox.h>
45 #include <sys/types.h>
51 #include "audio_out.h"
52 #include "audio_out_internal.h"
53 #include "libaf/af_format.h"
54 #include "osdep/timer.h"
55 #include "libavutil/fifo.h"
56 #include "subopt-helper.h"
58 static const ao_info_t info
=
60 "Darwin/Mac OS X native audio output",
62 "Timothy J. Wood & Dan Christiansen & Chris Roccati",
66 LIBAO_EXTERN(coreaudio
)
68 /* Prefix for all mp_msg() calls */
69 #define ao_msg(a, b, c...) mp_msg(a, b, "AO: [coreaudio] " c)
71 #if MAC_OS_X_VERSION_MAX_ALLOWED <= 1040
72 /* AudioDeviceIOProcID does not exist in Mac OS X 10.4. We can emulate
73 * this by using AudioDeviceAddIOProc() and AudioDeviceRemoveIOProc(). */
74 #define AudioDeviceIOProcID AudioDeviceIOProc
75 #define AudioDeviceDestroyIOProcID AudioDeviceRemoveIOProc
76 static OSStatus
AudioDeviceCreateIOProcID(AudioDeviceID dev
,
77 AudioDeviceIOProc proc
,
79 AudioDeviceIOProcID
*procid
)
82 return AudioDeviceAddIOProc(dev
, proc
, data
);
86 typedef struct ao_coreaudio_s
88 AudioDeviceID i_selected_dev
; /* Keeps DeviceID of the selected device. */
89 int b_supports_digital
; /* Does the currently selected device support digital mode? */
90 int b_digital
; /* Are we running in digital mode? */
91 int b_muted
; /* Are we muted in digital mode? */
93 AudioDeviceIOProcID renderCallback
; /* Render callback used for SPDIF */
96 AudioUnit theOutputUnit
;
98 /* CoreAudio SPDIF mode specific */
99 pid_t i_hog_pid
; /* Keeps the pid of our hog status. */
100 AudioStreamID i_stream_id
; /* The StreamID that has a cac3 streamformat */
101 int i_stream_index
; /* The index of i_stream_id in an AudioBufferList */
102 AudioStreamBasicDescription stream_format
;/* The format we changed the stream to */
103 AudioStreamBasicDescription sfmt_revert
; /* The original format of the stream */
104 int b_revert
; /* Whether we need to revert the stream format */
105 int b_changed_mixing
; /* Whether we need to set the mixing mode back */
106 int b_stream_format_changed
; /* Flag for main thread to reset stream's format to digital and reset buffer */
108 /* Original common part */
113 AVFifoBuffer
*buffer
;
114 unsigned int buffer_len
; ///< must always be num_chunks * chunk_size
115 unsigned int num_chunks
;
116 unsigned int chunk_size
;
119 static ao_coreaudio_t
*ao
= NULL
;
122 * \brief add data to ringbuffer
124 static int write_buffer(unsigned char* data
, int len
){
125 int free
= ao
->buffer_len
- av_fifo_size(ao
->buffer
);
126 if (len
> free
) len
= free
;
127 return av_fifo_generic_write(ao
->buffer
, data
, len
, NULL
);
131 * \brief remove data from ringbuffer
133 static int read_buffer(unsigned char* data
,int len
){
134 int buffered
= av_fifo_size(ao
->buffer
);
135 if (len
> buffered
) len
= buffered
;
137 av_fifo_generic_read(ao
->buffer
, data
, len
, NULL
);
139 av_fifo_drain(ao
->buffer
, len
);
143 static OSStatus
theRenderProc(void *inRefCon
,
144 AudioUnitRenderActionFlags
*inActionFlags
,
145 const AudioTimeStamp
*inTimeStamp
,
146 UInt32 inBusNumber
, UInt32 inNumFrames
,
147 AudioBufferList
*ioData
)
149 int amt
=av_fifo_size(ao
->buffer
);
150 int req
=(inNumFrames
)*ao
->packetSize
;
156 read_buffer((unsigned char *)ioData
->mBuffers
[0].mData
, amt
);
158 ioData
->mBuffers
[0].mDataByteSize
= amt
;
163 static int control(int cmd
,void *arg
){
164 ao_control_vol_t
*control_vol
;
168 case AOCONTROL_GET_VOLUME
:
169 control_vol
= (ao_control_vol_t
*)arg
;
171 // Digital output has no volume adjust.
172 return CONTROL_FALSE
;
174 err
= AudioUnitGetParameter(ao
->theOutputUnit
, kHALOutputParam_Volume
, kAudioUnitScope_Global
, 0, &vol
);
177 // printf("GET VOL=%f\n", vol);
178 control_vol
->left
=control_vol
->right
=vol
*100.0/4.0;
182 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get HAL output volume: [%4.4s]\n", (char *)&err
);
183 return CONTROL_FALSE
;
186 case AOCONTROL_SET_VOLUME
:
187 control_vol
= (ao_control_vol_t
*)arg
;
190 // Digital output can not set volume. Here we have to return true
191 // to make mixer forget it. Else mixer will add a soft filter,
192 // that's not we expected and the filter not support ac3 stream
193 // will cause mplayer die.
195 // Although not support set volume, but at least we support mute.
196 // MPlayer set mute by set volume to zero, we handle it.
197 if (control_vol
->left
== 0 && control_vol
->right
== 0)
204 vol
=(control_vol
->left
+control_vol
->right
)*4.0/200.0;
205 err
= AudioUnitSetParameter(ao
->theOutputUnit
, kHALOutputParam_Volume
, kAudioUnitScope_Global
, 0, vol
, 0);
207 // printf("SET VOL=%f\n", vol);
211 ao_msg(MSGT_AO
, MSGL_WARN
, "could not set HAL output volume: [%4.4s]\n", (char *)&err
);
212 return CONTROL_FALSE
;
214 /* Everything is currently unimplemented */
216 return CONTROL_FALSE
;
222 static void print_format(int lev
, const char* str
, const AudioStreamBasicDescription
*f
){
223 uint32_t flags
=(uint32_t) f
->mFormatFlags
;
224 ao_msg(MSGT_AO
,lev
, "%s %7.1fHz %"PRIu32
"bit [%c%c%c%c][%"PRIu32
"][%"PRIu32
"][%"PRIu32
"][%"PRIu32
"][%"PRIu32
"] %s %s %s%s%s%s\n",
225 str
, f
->mSampleRate
, f
->mBitsPerChannel
,
226 (int)(f
->mFormatID
& 0xff000000) >> 24,
227 (int)(f
->mFormatID
& 0x00ff0000) >> 16,
228 (int)(f
->mFormatID
& 0x0000ff00) >> 8,
229 (int)(f
->mFormatID
& 0x000000ff) >> 0,
230 f
->mFormatFlags
, f
->mBytesPerPacket
,
231 f
->mFramesPerPacket
, f
->mBytesPerFrame
,
232 f
->mChannelsPerFrame
,
233 (flags
&kAudioFormatFlagIsFloat
) ? "float" : "int",
234 (flags
&kAudioFormatFlagIsBigEndian
) ? "BE" : "LE",
235 (flags
&kAudioFormatFlagIsSignedInteger
) ? "S" : "U",
236 (flags
&kAudioFormatFlagIsPacked
) ? " packed" : "",
237 (flags
&kAudioFormatFlagIsAlignedHigh
) ? " aligned" : "",
238 (flags
&kAudioFormatFlagIsNonInterleaved
) ? " ni" : "" );
241 static OSStatus
GetAudioProperty(AudioObjectID id
,
242 AudioObjectPropertySelector selector
,
243 UInt32 outSize
, void *outData
)
245 AudioObjectPropertyAddress property_address
;
247 property_address
.mSelector
= selector
;
248 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
249 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
251 return AudioObjectGetPropertyData(id
, &property_address
, 0, NULL
, &outSize
, outData
);
254 static UInt32
GetAudioPropertyArray(AudioObjectID id
,
255 AudioObjectPropertySelector selector
,
256 AudioObjectPropertyScope scope
,
260 AudioObjectPropertyAddress property_address
;
263 property_address
.mSelector
= selector
;
264 property_address
.mScope
= scope
;
265 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
267 err
= AudioObjectGetPropertyDataSize(id
, &property_address
, 0, NULL
, &i_param_size
);
272 *outData
= malloc(i_param_size
);
275 err
= AudioObjectGetPropertyData(id
, &property_address
, 0, NULL
, &i_param_size
, *outData
);
285 static UInt32
GetGlobalAudioPropertyArray(AudioObjectID id
,
286 AudioObjectPropertySelector selector
,
289 return GetAudioPropertyArray(id
, selector
, kAudioObjectPropertyScopeGlobal
, outData
);
292 static OSStatus
GetAudioPropertyString(AudioObjectID id
,
293 AudioObjectPropertySelector selector
,
297 AudioObjectPropertyAddress property_address
;
300 CFIndex string_length
;
302 property_address
.mSelector
= selector
;
303 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
304 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
306 i_param_size
= sizeof(CFStringRef
);
307 err
= AudioObjectGetPropertyData(id
, &property_address
, 0, NULL
, &i_param_size
, &string
);
311 string_length
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(string
),
312 kCFStringEncodingASCII
);
313 *outData
= malloc(string_length
+ 1);
314 CFStringGetCString(string
, *outData
, string_length
+ 1, kCFStringEncodingASCII
);
321 static OSStatus
SetAudioProperty(AudioObjectID id
,
322 AudioObjectPropertySelector selector
,
323 UInt32 inDataSize
, void *inData
)
325 AudioObjectPropertyAddress property_address
;
327 property_address
.mSelector
= selector
;
328 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
329 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
331 return AudioObjectSetPropertyData(id
, &property_address
, 0, NULL
, inDataSize
, inData
);
334 static Boolean
IsAudioPropertySettable(AudioObjectID id
,
335 AudioObjectPropertySelector selector
,
338 AudioObjectPropertyAddress property_address
;
340 property_address
.mSelector
= selector
;
341 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
342 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
344 return AudioObjectIsPropertySettable(id
, &property_address
, outData
);
347 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id
);
348 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id
);
349 static int OpenSPDIF(void);
350 static int AudioStreamChangeFormat( AudioStreamID i_stream_id
, AudioStreamBasicDescription change_format
);
351 static OSStatus
RenderCallbackSPDIF( AudioDeviceID inDevice
,
352 const AudioTimeStamp
* inNow
,
353 const void * inInputData
,
354 const AudioTimeStamp
* inInputTime
,
355 AudioBufferList
* outOutputData
,
356 const AudioTimeStamp
* inOutputTime
,
357 void * threadGlobals
);
358 static OSStatus
StreamListener( AudioObjectID inObjectID
,
359 UInt32 inNumberAddresses
,
360 const AudioObjectPropertyAddress inAddresses
[],
361 void *inClientData
);
362 static OSStatus
DeviceListener( AudioObjectID inObjectID
,
363 UInt32 inNumberAddresses
,
364 const AudioObjectPropertyAddress inAddresses
[],
365 void *inClientData
);
367 static void print_help(void)
372 AudioDeviceID
*devids
;
375 mp_msg(MSGT_AO
, MSGL_FATAL
,
376 "\n-ao coreaudio commandline help:\n"
377 "Example: mplayer -ao coreaudio:device_id=266\n"
378 " open Core Audio with output device ID 266.\n"
381 " ID of output device to use (0 = default device)\n"
383 " This help including list of available devices.\n"
385 "Available output devices:\n");
387 i_param_size
= GetGlobalAudioPropertyArray(kAudioObjectSystemObject
, kAudioHardwarePropertyDevices
, (void **)&devids
);
390 mp_msg(MSGT_AO
, MSGL_FATAL
, "Failed to get list of output devices.\n");
394 num_devices
= i_param_size
/ sizeof(AudioDeviceID
);
396 for (int i
= 0; i
< num_devices
; ++i
) {
397 err
= GetAudioPropertyString(devids
[i
], kAudioObjectPropertyName
, &device_name
);
400 mp_msg(MSGT_AO
, MSGL_FATAL
, "%s (id: %"PRIu32
")\n", device_name
, devids
[i
]);
403 mp_msg(MSGT_AO
, MSGL_FATAL
, "Unknown (id: %"PRIu32
")\n", devids
[i
]);
406 mp_msg(MSGT_AO
, MSGL_FATAL
, "\n");
411 static int init(int rate
,int channels
,int format
,int flags
)
413 AudioStreamBasicDescription inDesc
;
414 ComponentDescription desc
;
416 AURenderCallbackStruct renderCallback
;
418 UInt32 size
, maxFrames
, b_alive
;
420 AudioDeviceID devid_def
= 0;
421 int device_id
, display_help
= 0;
423 const opt_t subopts
[] = {
424 {"device_id", OPT_ARG_INT
, &device_id
, NULL
},
425 {"help", OPT_ARG_BOOL
, &display_help
, NULL
},
432 if (subopt_parse(ao_subdevice
, subopts
) != 0 || display_help
) {
438 ao_msg(MSGT_AO
,MSGL_V
, "init([%dHz][%dch][%s][%d])\n", rate
, channels
, af_fmt2str_short(format
), flags
);
440 ao
= calloc(1, sizeof(ao_coreaudio_t
));
442 ao
->i_selected_dev
= 0;
443 ao
->b_supports_digital
= 0;
446 ao
->b_stream_format_changed
= 0;
449 ao
->i_stream_index
= -1;
451 ao
->b_changed_mixing
= 0;
453 global_ao
->no_persistent_volume
= true;
455 if (device_id
== 0) {
456 /* Find the ID of the default Device. */
457 err
= GetAudioProperty(kAudioObjectSystemObject
,
458 kAudioHardwarePropertyDefaultOutputDevice
,
459 sizeof(UInt32
), &devid_def
);
462 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get default audio device: [%4.4s]\n", (char *)&err
);
466 devid_def
= device_id
;
469 /* Retrieve the name of the device. */
470 err
= GetAudioPropertyString(devid_def
,
471 kAudioObjectPropertyName
,
475 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get default audio device name: [%4.4s]\n", (char *)&err
);
479 ao_msg(MSGT_AO
,MSGL_V
, "got audio output device ID: %"PRIu32
" Name: %s\n", devid_def
, psz_name
);
481 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
482 if (AF_FORMAT_IS_AC3(format
)) {
483 if (AudioDeviceSupportsDigital(devid_def
))
485 ao
->b_supports_digital
= 1;
487 ao_msg(MSGT_AO
, MSGL_V
,
488 "probe default audio output device about support for digital s/pdif output: %d\n",
489 ao
->b_supports_digital
);
494 // Save selected device id
495 ao
->i_selected_dev
= devid_def
;
497 // Build Description for the input format
498 inDesc
.mSampleRate
=rate
;
499 inDesc
.mFormatID
=ao
->b_supports_digital
? kAudioFormat60958AC3
: kAudioFormatLinearPCM
;
500 inDesc
.mChannelsPerFrame
=channels
;
501 inDesc
.mBitsPerChannel
=af_fmt2bits(format
);
503 if((format
&AF_FORMAT_POINT_MASK
)==AF_FORMAT_F
) {
505 inDesc
.mFormatFlags
= kAudioFormatFlagIsFloat
|kAudioFormatFlagIsPacked
;
507 else if((format
&AF_FORMAT_SIGN_MASK
)==AF_FORMAT_SI
) {
509 inDesc
.mFormatFlags
= kAudioFormatFlagIsSignedInteger
|kAudioFormatFlagIsPacked
;
513 inDesc
.mFormatFlags
= kAudioFormatFlagIsPacked
;
515 if ((format
& AF_FORMAT_END_MASK
) == AF_FORMAT_BE
)
516 inDesc
.mFormatFlags
|= kAudioFormatFlagIsBigEndian
;
518 inDesc
.mFramesPerPacket
= 1;
519 ao
->packetSize
= inDesc
.mBytesPerPacket
= inDesc
.mBytesPerFrame
= inDesc
.mFramesPerPacket
*channels
*(inDesc
.mBitsPerChannel
/8);
520 print_format(MSGL_V
, "source:",&inDesc
);
522 if (ao
->b_supports_digital
)
525 err
= GetAudioProperty(ao
->i_selected_dev
,
526 kAudioDevicePropertyDeviceIsAlive
,
527 sizeof(UInt32
), &b_alive
);
529 ao_msg(MSGT_AO
, MSGL_WARN
, "could not check whether device is alive: [%4.4s]\n", (char *)&err
);
531 ao_msg(MSGT_AO
, MSGL_WARN
, "device is not alive\n" );
533 /* S/PDIF output need device in HogMode. */
534 err
= GetAudioProperty(ao
->i_selected_dev
,
535 kAudioDevicePropertyHogMode
,
536 sizeof(pid_t
), &ao
->i_hog_pid
);
539 /* This is not a fatal error. Some drivers simply don't support this property. */
540 ao_msg(MSGT_AO
, MSGL_WARN
, "could not check whether device is hogged: [%4.4s]\n",
545 if (ao
->i_hog_pid
!= -1 && ao
->i_hog_pid
!= getpid())
547 ao_msg(MSGT_AO
, MSGL_WARN
, "Selected audio device is exclusively in use by another program.\n" );
550 ao
->stream_format
= inDesc
;
554 /* original analog output code */
555 desc
.componentType
= kAudioUnitType_Output
;
556 desc
.componentSubType
= (device_id
== 0) ? kAudioUnitSubType_DefaultOutput
: kAudioUnitSubType_HALOutput
;
557 desc
.componentManufacturer
= kAudioUnitManufacturer_Apple
;
558 desc
.componentFlags
= 0;
559 desc
.componentFlagsMask
= 0;
561 comp
= FindNextComponent(NULL
, &desc
); //Finds an component that meets the desc spec's
563 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to find Output Unit component\n");
567 err
= OpenAComponent(comp
, &(ao
->theOutputUnit
)); //gains access to the services provided by the component
569 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err
);
573 // Initialize AudioUnit
574 err
= AudioUnitInitialize(ao
->theOutputUnit
);
576 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err
);
580 size
= sizeof(AudioStreamBasicDescription
);
581 err
= AudioUnitSetProperty(ao
->theOutputUnit
, kAudioUnitProperty_StreamFormat
, kAudioUnitScope_Input
, 0, &inDesc
, size
);
584 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to set the input format: [%4.4s]\n", (char *)&err
);
588 size
= sizeof(UInt32
);
589 err
= AudioUnitGetProperty(ao
->theOutputUnit
, kAudioDevicePropertyBufferSize
, kAudioUnitScope_Input
, 0, &maxFrames
, &size
);
593 ao_msg(MSGT_AO
,MSGL_WARN
, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err
);
597 //Set the Current Device to the Default Output Unit.
598 err
= AudioUnitSetProperty(ao
->theOutputUnit
, kAudioOutputUnitProperty_CurrentDevice
, kAudioUnitScope_Global
, 0, &ao
->i_selected_dev
, sizeof(ao
->i_selected_dev
));
600 ao
->chunk_size
= maxFrames
;//*inDesc.mBytesPerFrame;
602 ao_data
.samplerate
= inDesc
.mSampleRate
;
603 ao_data
.channels
= inDesc
.mChannelsPerFrame
;
604 ao_data
.bps
= ao_data
.samplerate
* inDesc
.mBytesPerFrame
;
605 ao_data
.outburst
= ao
->chunk_size
;
606 ao_data
.buffersize
= ao_data
.bps
;
608 ao
->num_chunks
= (ao_data
.bps
+ao
->chunk_size
-1)/ao
->chunk_size
;
609 ao
->buffer_len
= ao
->num_chunks
* ao
->chunk_size
;
610 ao
->buffer
= av_fifo_alloc(ao
->buffer_len
);
612 ao_msg(MSGT_AO
,MSGL_V
, "using %5d chunks of %d bytes (buffer len %d bytes)\n", (int)ao
->num_chunks
, (int)ao
->chunk_size
, (int)ao
->buffer_len
);
614 renderCallback
.inputProc
= theRenderProc
;
615 renderCallback
.inputProcRefCon
= 0;
616 err
= AudioUnitSetProperty(ao
->theOutputUnit
, kAudioUnitProperty_SetRenderCallback
, kAudioUnitScope_Input
, 0, &renderCallback
, sizeof(AURenderCallbackStruct
));
618 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to set the render callback: [%4.4s]\n", (char *)&err
);
627 AudioUnitUninitialize(ao
->theOutputUnit
);
629 CloseComponent(ao
->theOutputUnit
);
631 av_fifo_free(ao
->buffer
);
634 return CONTROL_FALSE
;
637 /*****************************************************************************
638 * Setup a encoded digital stream (SPDIF)
639 *****************************************************************************/
640 static int OpenSPDIF(void)
642 OSStatus err
= noErr
;
643 UInt32 i_param_size
, b_mix
= 0;
644 Boolean b_writeable
= 0;
645 AudioStreamID
*p_streams
= NULL
;
646 int i
, i_streams
= 0;
647 AudioObjectPropertyAddress property_address
;
649 /* Start doing the SPDIF setup process. */
652 /* Hog the device. */
653 ao
->i_hog_pid
= getpid() ;
655 err
= SetAudioProperty(ao
->i_selected_dev
,
656 kAudioDevicePropertyHogMode
,
657 sizeof(ao
->i_hog_pid
), &ao
->i_hog_pid
);
660 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set hogmode: [%4.4s]\n", (char *)&err
);
665 property_address
.mSelector
= kAudioDevicePropertySupportsMixing
;
666 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
667 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
669 /* Set mixable to false if we are allowed to. */
670 if (AudioObjectHasProperty(ao
->i_selected_dev
, &property_address
)) {
671 /* Set mixable to false if we are allowed to. */
672 err
= IsAudioPropertySettable(ao
->i_selected_dev
,
673 kAudioDevicePropertySupportsMixing
,
675 err
= GetAudioProperty(ao
->i_selected_dev
,
676 kAudioDevicePropertySupportsMixing
,
677 sizeof(UInt32
), &b_mix
);
678 if (err
== noErr
&& b_writeable
)
681 err
= SetAudioProperty(ao
->i_selected_dev
,
682 kAudioDevicePropertySupportsMixing
,
683 sizeof(UInt32
), &b_mix
);
684 ao
->b_changed_mixing
= 1;
688 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set mixmode: [%4.4s]\n", (char *)&err
);
693 /* Get a list of all the streams on this device. */
694 i_param_size
= GetAudioPropertyArray(ao
->i_selected_dev
,
695 kAudioDevicePropertyStreams
,
696 kAudioDevicePropertyScopeOutput
,
697 (void **)&p_streams
);
700 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get number of streams.\n");
704 i_streams
= i_param_size
/ sizeof(AudioStreamID
);
706 ao_msg(MSGT_AO
, MSGL_V
, "current device stream number: %d\n", i_streams
);
708 for (i
= 0; i
< i_streams
&& ao
->i_stream_index
< 0; ++i
)
710 /* Find a stream with a cac3 stream. */
711 AudioStreamRangedDescription
*p_format_list
= NULL
;
712 int i_formats
= 0, j
= 0, b_digital
= 0;
714 i_param_size
= GetGlobalAudioPropertyArray(p_streams
[i
],
715 kAudioStreamPropertyAvailablePhysicalFormats
,
716 (void **)&p_format_list
);
719 ao_msg(MSGT_AO
, MSGL_WARN
,
720 "Could not get number of stream formats.\n");
724 i_formats
= i_param_size
/ sizeof(AudioStreamRangedDescription
);
726 /* Check if one of the supported formats is a digital format. */
727 for (j
= 0; j
< i_formats
; ++j
)
729 if (p_format_list
[j
].mFormat
.mFormatID
== 'IAC3' ||
730 p_format_list
[j
].mFormat
.mFormatID
== 'iac3' ||
731 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormat60958AC3
||
732 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormatAC3
)
741 /* If this stream supports a digital (cac3) format, then set it. */
742 int i_requested_rate_format
= -1;
743 int i_current_rate_format
= -1;
744 int i_backup_rate_format
= -1;
746 ao
->i_stream_id
= p_streams
[i
];
747 ao
->i_stream_index
= i
;
749 if (ao
->b_revert
== 0)
751 /* Retrieve the original format of this stream first if not done so already. */
752 err
= GetAudioProperty(ao
->i_stream_id
,
753 kAudioStreamPropertyPhysicalFormat
,
754 sizeof(ao
->sfmt_revert
), &ao
->sfmt_revert
);
757 ao_msg(MSGT_AO
, MSGL_WARN
,
758 "Could not retrieve the original stream format: [%4.4s]\n",
766 for (j
= 0; j
< i_formats
; ++j
)
767 if (p_format_list
[j
].mFormat
.mFormatID
== 'IAC3' ||
768 p_format_list
[j
].mFormat
.mFormatID
== 'iac3' ||
769 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormat60958AC3
||
770 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormatAC3
)
772 if (p_format_list
[j
].mFormat
.mSampleRate
== ao
->stream_format
.mSampleRate
)
774 i_requested_rate_format
= j
;
777 if (p_format_list
[j
].mFormat
.mSampleRate
== ao
->sfmt_revert
.mSampleRate
)
778 i_current_rate_format
= j
;
779 else if (i_backup_rate_format
< 0 || p_format_list
[j
].mFormat
.mSampleRate
> p_format_list
[i_backup_rate_format
].mFormat
.mSampleRate
)
780 i_backup_rate_format
= j
;
783 if (i_requested_rate_format
>= 0) /* We prefer to output at the samplerate of the original audio. */
784 ao
->stream_format
= p_format_list
[i_requested_rate_format
].mFormat
;
785 else if (i_current_rate_format
>= 0) /* If not possible, we will try to use the current samplerate of the device. */
786 ao
->stream_format
= p_format_list
[i_current_rate_format
].mFormat
;
787 else ao
->stream_format
= p_format_list
[i_backup_rate_format
].mFormat
; /* And if we have to, any digital format will be just fine (highest rate possible). */
793 if (ao
->i_stream_index
< 0)
795 ao_msg(MSGT_AO
, MSGL_WARN
,
796 "Cannot find any digital output stream format when OpenSPDIF().\n");
800 print_format(MSGL_V
, "original stream format:", &ao
->sfmt_revert
);
802 if (!AudioStreamChangeFormat(ao
->i_stream_id
, ao
->stream_format
))
805 property_address
.mSelector
= kAudioDevicePropertyDeviceHasChanged
;
806 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
807 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
809 err
= AudioObjectAddPropertyListener(ao
->i_selected_dev
,
814 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err
);
817 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
818 /* Although there's no such case reported. */
820 if (!(ao
->stream_format
.mFormatFlags
& kAudioFormatFlagIsBigEndian
))
822 /* tell mplayer that we need a byteswap on AC3 streams, */
823 if (ao
->stream_format
.mFormatID
& kAudioFormat60958AC3
)
824 ao_data
.format
= AF_FORMAT_AC3_LE
;
826 if (ao
->stream_format
.mFormatFlags
& kAudioFormatFlagIsBigEndian
)
828 ao_msg(MSGT_AO
, MSGL_WARN
,
829 "Output stream has non-native byte order, digital output may fail.\n");
831 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
832 ao
->chunk_size
= ao
->stream_format
.mBytesPerPacket
;
834 ao_data
.samplerate
= ao
->stream_format
.mSampleRate
;
835 ao_data
.channels
= ao
->stream_format
.mChannelsPerFrame
;
836 ao_data
.bps
= ao_data
.samplerate
* (ao
->stream_format
.mBytesPerPacket
/ao
->stream_format
.mFramesPerPacket
);
837 ao_data
.outburst
= ao
->chunk_size
;
838 ao_data
.buffersize
= ao_data
.bps
;
840 ao
->num_chunks
= (ao_data
.bps
+ao
->chunk_size
-1)/ao
->chunk_size
;
841 ao
->buffer_len
= ao
->num_chunks
* ao
->chunk_size
;
842 ao
->buffer
= av_fifo_alloc(ao
->buffer_len
);
844 ao_msg(MSGT_AO
,MSGL_V
, "using %5d chunks of %d bytes (buffer len %d bytes)\n", (int)ao
->num_chunks
, (int)ao
->chunk_size
, (int)ao
->buffer_len
);
847 /* Create IOProc callback. */
848 err
= AudioDeviceCreateIOProcID(ao
->i_selected_dev
,
849 (AudioDeviceIOProc
)RenderCallbackSPDIF
,
851 &ao
->renderCallback
);
853 if (err
!= noErr
|| ao
->renderCallback
== NULL
)
855 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err
);
865 AudioStreamChangeFormat(ao
->i_stream_id
, ao
->sfmt_revert
);
867 if (ao
->b_changed_mixing
&& ao
->sfmt_revert
.mFormatID
!= kAudioFormat60958AC3
)
870 err
= SetAudioProperty(ao
->i_selected_dev
,
871 kAudioDevicePropertySupportsMixing
,
872 sizeof(int), &b_mix
);
874 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set mixmode: [%4.4s]\n",
877 if (ao
->i_hog_pid
== getpid())
880 err
= SetAudioProperty(ao
->i_selected_dev
,
881 kAudioDevicePropertyHogMode
,
882 sizeof(ao
->i_hog_pid
), &ao
->i_hog_pid
);
884 ao_msg(MSGT_AO
, MSGL_WARN
, "Could not release hogmode: [%4.4s]\n",
887 av_fifo_free(ao
->buffer
);
890 return CONTROL_FALSE
;
893 /*****************************************************************************
894 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
895 *****************************************************************************/
896 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id
)
898 UInt32 i_param_size
= 0;
899 AudioStreamID
*p_streams
= NULL
;
900 int i
= 0, i_streams
= 0;
901 int b_return
= CONTROL_FALSE
;
903 /* Retrieve all the output streams. */
904 i_param_size
= GetAudioPropertyArray(i_dev_id
,
905 kAudioDevicePropertyStreams
,
906 kAudioDevicePropertyScopeOutput
,
907 (void **)&p_streams
);
910 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get number of streams.\n");
911 return CONTROL_FALSE
;
914 i_streams
= i_param_size
/ sizeof(AudioStreamID
);
916 for (i
= 0; i
< i_streams
; ++i
)
918 if (AudioStreamSupportsDigital(p_streams
[i
]))
919 b_return
= CONTROL_OK
;
926 /*****************************************************************************
927 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
928 *****************************************************************************/
929 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id
)
932 AudioStreamRangedDescription
*p_format_list
= NULL
;
933 int i
, i_formats
, b_return
= CONTROL_FALSE
;
935 /* Retrieve all the stream formats supported by each output stream. */
936 i_param_size
= GetGlobalAudioPropertyArray(i_stream_id
,
937 kAudioStreamPropertyAvailablePhysicalFormats
,
938 (void **)&p_format_list
);
941 ao_msg(MSGT_AO
, MSGL_WARN
, "Could not get number of stream formats.\n");
942 return CONTROL_FALSE
;
945 i_formats
= i_param_size
/ sizeof(AudioStreamRangedDescription
);
947 for (i
= 0; i
< i_formats
; ++i
)
949 print_format(MSGL_V
, "supported format:", &(p_format_list
[i
].mFormat
));
951 if (p_format_list
[i
].mFormat
.mFormatID
== 'IAC3' ||
952 p_format_list
[i
].mFormat
.mFormatID
== 'iac3' ||
953 p_format_list
[i
].mFormat
.mFormatID
== kAudioFormat60958AC3
||
954 p_format_list
[i
].mFormat
.mFormatID
== kAudioFormatAC3
)
955 b_return
= CONTROL_OK
;
962 /*****************************************************************************
963 * AudioStreamChangeFormat: Change i_stream_id to change_format
964 *****************************************************************************/
965 static int AudioStreamChangeFormat( AudioStreamID i_stream_id
, AudioStreamBasicDescription change_format
)
967 OSStatus err
= noErr
;
969 AudioObjectPropertyAddress property_address
;
971 static volatile int stream_format_changed
;
972 stream_format_changed
= 0;
974 print_format(MSGL_V
, "setting stream format:", &change_format
);
976 /* Install the callback. */
977 property_address
.mSelector
= kAudioStreamPropertyPhysicalFormat
;
978 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
979 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
981 err
= AudioObjectAddPropertyListener(i_stream_id
,
984 (void *)&stream_format_changed
);
987 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err
);
988 return CONTROL_FALSE
;
991 /* Change the format. */
992 err
= SetAudioProperty(i_stream_id
,
993 kAudioStreamPropertyPhysicalFormat
,
994 sizeof(AudioStreamBasicDescription
), &change_format
);
997 ao_msg(MSGT_AO
, MSGL_WARN
, "could not set the stream format: [%4.4s]\n", (char *)&err
);
998 return CONTROL_FALSE
;
1001 /* The AudioStreamSetProperty is not only asynchronious,
1002 * it is also not Atomic, in its behaviour.
1003 * Therefore we check 5 times before we really give up.
1004 * FIXME: failing isn't actually implemented yet. */
1005 for (i
= 0; i
< 5; ++i
)
1007 AudioStreamBasicDescription actual_format
;
1009 for (j
= 0; !stream_format_changed
&& j
< 50; ++j
)
1011 if (stream_format_changed
)
1012 stream_format_changed
= 0;
1014 ao_msg(MSGT_AO
, MSGL_V
, "reached timeout\n" );
1016 err
= GetAudioProperty(i_stream_id
,
1017 kAudioStreamPropertyPhysicalFormat
,
1018 sizeof(AudioStreamBasicDescription
), &actual_format
);
1020 print_format(MSGL_V
, "actual format in use:", &actual_format
);
1021 if (actual_format
.mSampleRate
== change_format
.mSampleRate
&&
1022 actual_format
.mFormatID
== change_format
.mFormatID
&&
1023 actual_format
.mFramesPerPacket
== change_format
.mFramesPerPacket
)
1025 /* The right format is now active. */
1028 /* We need to check again. */
1031 /* Removing the property listener. */
1032 err
= AudioObjectRemovePropertyListener(i_stream_id
,
1035 (void *)&stream_format_changed
);
1038 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err
);
1039 return CONTROL_FALSE
;
1042 return CONTROL_TRUE
;
1045 /*****************************************************************************
1046 * RenderCallbackSPDIF: callback for SPDIF audio output
1047 *****************************************************************************/
1048 static OSStatus
RenderCallbackSPDIF( AudioDeviceID inDevice
,
1049 const AudioTimeStamp
* inNow
,
1050 const void * inInputData
,
1051 const AudioTimeStamp
* inInputTime
,
1052 AudioBufferList
* outOutputData
,
1053 const AudioTimeStamp
* inOutputTime
,
1054 void * threadGlobals
)
1056 int amt
= av_fifo_size(ao
->buffer
);
1057 int req
= outOutputData
->mBuffers
[ao
->i_stream_index
].mDataByteSize
;
1062 read_buffer(ao
->b_muted
? NULL
: (unsigned char *)outOutputData
->mBuffers
[ao
->i_stream_index
].mData
, amt
);
1068 static int play(void* output_samples
,int num_bytes
,int flags
)
1070 int wrote
, b_digital
;
1073 // Check whether we need to reset the digital output stream.
1074 if (ao
->b_digital
&& ao
->b_stream_format_changed
)
1076 ao
->b_stream_format_changed
= 0;
1077 b_digital
= AudioStreamSupportsDigital(ao
->i_stream_id
);
1080 /* Current stream supports digital format output, let's set it. */
1081 ao_msg(MSGT_AO
, MSGL_V
,
1082 "Detected current stream supports digital, try to restore digital output...\n");
1084 if (!AudioStreamChangeFormat(ao
->i_stream_id
, ao
->stream_format
))
1086 ao_msg(MSGT_AO
, MSGL_WARN
, "Restoring digital output failed.\n");
1090 ao_msg(MSGT_AO
, MSGL_WARN
, "Restoring digital output succeeded.\n");
1095 ao_msg(MSGT_AO
, MSGL_V
, "Detected current stream does not support digital.\n");
1098 wrote
=write_buffer(output_samples
, num_bytes
);
1102 exit_reason
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, 0.01, true);
1103 } while (exit_reason
== kCFRunLoopRunHandledSource
);
1108 /* set variables and buffer to initial state */
1109 static void reset(void)
1112 av_fifo_reset(ao
->buffer
);
1116 /* return available space */
1117 static int get_space(void)
1119 return ao
->buffer_len
- av_fifo_size(ao
->buffer
);
1123 /* return delay until audio is played */
1124 static float get_delay(void)
1126 // inaccurate, should also contain the data buffered e.g. by the OS
1127 return (float)av_fifo_size(ao
->buffer
)/(float)ao_data
.bps
;
1131 /* unload plugin and deregister from coreaudio */
1132 static void uninit(int immed
)
1134 OSStatus err
= noErr
;
1137 long long timeleft
=(1000000LL*av_fifo_size(ao
->buffer
))/ao_data
.bps
;
1138 ao_msg(MSGT_AO
,MSGL_DBG2
, "%d bytes left @%d bps (%d usec)\n", av_fifo_size(ao
->buffer
), ao_data
.bps
, (int)timeleft
);
1139 usec_sleep((int)timeleft
);
1142 if (!ao
->b_digital
) {
1143 AudioOutputUnitStop(ao
->theOutputUnit
);
1144 AudioUnitUninitialize(ao
->theOutputUnit
);
1145 CloseComponent(ao
->theOutputUnit
);
1149 err
= AudioDeviceStop(ao
->i_selected_dev
, ao
->renderCallback
);
1151 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err
);
1153 /* Remove IOProc callback. */
1154 err
= AudioDeviceDestroyIOProcID(ao
->i_selected_dev
, ao
->renderCallback
);
1156 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err
);
1159 AudioStreamChangeFormat(ao
->i_stream_id
, ao
->sfmt_revert
);
1161 if (ao
->b_changed_mixing
&& ao
->sfmt_revert
.mFormatID
!= kAudioFormat60958AC3
)
1164 Boolean b_writeable
= 0;
1165 /* Revert mixable to true if we are allowed to. */
1166 err
= IsAudioPropertySettable(ao
->i_selected_dev
,
1167 kAudioDevicePropertySupportsMixing
,
1169 err
= GetAudioProperty(ao
->i_selected_dev
,
1170 kAudioDevicePropertySupportsMixing
,
1171 sizeof(UInt32
), &b_mix
);
1172 if (err
== noErr
&& b_writeable
)
1175 err
= SetAudioProperty(ao
->i_selected_dev
,
1176 kAudioDevicePropertySupportsMixing
,
1177 sizeof(UInt32
), &b_mix
);
1180 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set mixmode: [%4.4s]\n", (char *)&err
);
1182 if (ao
->i_hog_pid
== getpid())
1185 err
= SetAudioProperty(ao
->i_selected_dev
,
1186 kAudioDevicePropertyHogMode
,
1187 sizeof(ao
->i_hog_pid
), &ao
->i_hog_pid
);
1188 if (err
!= noErr
) ao_msg(MSGT_AO
, MSGL_WARN
, "Could not release hogmode: [%4.4s]\n", (char *)&err
);
1192 av_fifo_free(ao
->buffer
);
1198 /* stop playing, keep buffers (for pause) */
1199 static void audio_pause(void)
1203 /* Stop callback. */
1206 err
=AudioOutputUnitStop(ao
->theOutputUnit
);
1208 ao_msg(MSGT_AO
,MSGL_WARN
, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err
);
1212 err
= AudioDeviceStop(ao
->i_selected_dev
, ao
->renderCallback
);
1214 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err
);
1220 /* resume playing, after audio_pause() */
1221 static void audio_resume(void)
1228 /* Start callback. */
1231 err
= AudioOutputUnitStart(ao
->theOutputUnit
);
1233 ao_msg(MSGT_AO
,MSGL_WARN
, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err
);
1237 err
= AudioDeviceStart(ao
->i_selected_dev
, ao
->renderCallback
);
1239 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err
);
1244 /*****************************************************************************
1246 *****************************************************************************/
1247 static OSStatus
StreamListener( AudioObjectID inObjectID
,
1248 UInt32 inNumberAddresses
,
1249 const AudioObjectPropertyAddress inAddresses
[],
1250 void *inClientData
)
1252 for (int i
=0; i
< inNumberAddresses
; ++i
)
1254 if (inAddresses
[i
].mSelector
== kAudioStreamPropertyPhysicalFormat
) {
1255 ao_msg(MSGT_AO
, MSGL_WARN
, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1257 *(volatile int *)inClientData
= 1;
1264 static OSStatus
DeviceListener( AudioObjectID inObjectID
,
1265 UInt32 inNumberAddresses
,
1266 const AudioObjectPropertyAddress inAddresses
[],
1267 void *inClientData
)
1269 for (int i
=0; i
< inNumberAddresses
; ++i
)
1271 if (inAddresses
[i
].mSelector
== kAudioDevicePropertyDeviceHasChanged
) {
1272 ao_msg(MSGT_AO
, MSGL_WARN
, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1273 ao
->b_stream_format_changed
= 1;