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 int vol
= ao
->b_muted
? 0 : 100;
173 *control_vol
= (ao_control_vol_t
) {
174 .left
= vol
, .right
= vol
,
178 err
= AudioUnitGetParameter(ao
->theOutputUnit
, kHALOutputParam_Volume
, kAudioUnitScope_Global
, 0, &vol
);
181 // printf("GET VOL=%f\n", vol);
182 control_vol
->left
=control_vol
->right
=vol
*100.0/4.0;
186 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get HAL output volume: [%4.4s]\n", (char *)&err
);
187 return CONTROL_FALSE
;
190 case AOCONTROL_SET_VOLUME
:
191 control_vol
= (ao_control_vol_t
*)arg
;
194 // Digital output can not set volume. Here we have to return true
195 // to make mixer forget it. Else mixer will add a soft filter,
196 // that's not we expected and the filter not support ac3 stream
197 // will cause mplayer die.
199 // Although not support set volume, but at least we support mute.
200 // MPlayer set mute by set volume to zero, we handle it.
201 if (control_vol
->left
== 0 && control_vol
->right
== 0)
208 vol
=(control_vol
->left
+control_vol
->right
)*4.0/200.0;
209 err
= AudioUnitSetParameter(ao
->theOutputUnit
, kHALOutputParam_Volume
, kAudioUnitScope_Global
, 0, vol
, 0);
211 // printf("SET VOL=%f\n", vol);
215 ao_msg(MSGT_AO
, MSGL_WARN
, "could not set HAL output volume: [%4.4s]\n", (char *)&err
);
216 return CONTROL_FALSE
;
218 /* Everything is currently unimplemented */
220 return CONTROL_FALSE
;
226 static void print_format(int lev
, const char* str
, const AudioStreamBasicDescription
*f
){
227 uint32_t flags
=(uint32_t) f
->mFormatFlags
;
228 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",
229 str
, f
->mSampleRate
, f
->mBitsPerChannel
,
230 (int)(f
->mFormatID
& 0xff000000) >> 24,
231 (int)(f
->mFormatID
& 0x00ff0000) >> 16,
232 (int)(f
->mFormatID
& 0x0000ff00) >> 8,
233 (int)(f
->mFormatID
& 0x000000ff) >> 0,
234 f
->mFormatFlags
, f
->mBytesPerPacket
,
235 f
->mFramesPerPacket
, f
->mBytesPerFrame
,
236 f
->mChannelsPerFrame
,
237 (flags
&kAudioFormatFlagIsFloat
) ? "float" : "int",
238 (flags
&kAudioFormatFlagIsBigEndian
) ? "BE" : "LE",
239 (flags
&kAudioFormatFlagIsSignedInteger
) ? "S" : "U",
240 (flags
&kAudioFormatFlagIsPacked
) ? " packed" : "",
241 (flags
&kAudioFormatFlagIsAlignedHigh
) ? " aligned" : "",
242 (flags
&kAudioFormatFlagIsNonInterleaved
) ? " ni" : "" );
245 static OSStatus
GetAudioProperty(AudioObjectID id
,
246 AudioObjectPropertySelector selector
,
247 UInt32 outSize
, void *outData
)
249 AudioObjectPropertyAddress property_address
;
251 property_address
.mSelector
= selector
;
252 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
253 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
255 return AudioObjectGetPropertyData(id
, &property_address
, 0, NULL
, &outSize
, outData
);
258 static UInt32
GetAudioPropertyArray(AudioObjectID id
,
259 AudioObjectPropertySelector selector
,
260 AudioObjectPropertyScope scope
,
264 AudioObjectPropertyAddress property_address
;
267 property_address
.mSelector
= selector
;
268 property_address
.mScope
= scope
;
269 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
271 err
= AudioObjectGetPropertyDataSize(id
, &property_address
, 0, NULL
, &i_param_size
);
276 *outData
= malloc(i_param_size
);
279 err
= AudioObjectGetPropertyData(id
, &property_address
, 0, NULL
, &i_param_size
, *outData
);
289 static UInt32
GetGlobalAudioPropertyArray(AudioObjectID id
,
290 AudioObjectPropertySelector selector
,
293 return GetAudioPropertyArray(id
, selector
, kAudioObjectPropertyScopeGlobal
, outData
);
296 static OSStatus
GetAudioPropertyString(AudioObjectID id
,
297 AudioObjectPropertySelector selector
,
301 AudioObjectPropertyAddress property_address
;
304 CFIndex string_length
;
306 property_address
.mSelector
= selector
;
307 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
308 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
310 i_param_size
= sizeof(CFStringRef
);
311 err
= AudioObjectGetPropertyData(id
, &property_address
, 0, NULL
, &i_param_size
, &string
);
315 string_length
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(string
),
316 kCFStringEncodingASCII
);
317 *outData
= malloc(string_length
+ 1);
318 CFStringGetCString(string
, *outData
, string_length
+ 1, kCFStringEncodingASCII
);
325 static OSStatus
SetAudioProperty(AudioObjectID id
,
326 AudioObjectPropertySelector selector
,
327 UInt32 inDataSize
, void *inData
)
329 AudioObjectPropertyAddress property_address
;
331 property_address
.mSelector
= selector
;
332 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
333 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
335 return AudioObjectSetPropertyData(id
, &property_address
, 0, NULL
, inDataSize
, inData
);
338 static Boolean
IsAudioPropertySettable(AudioObjectID id
,
339 AudioObjectPropertySelector selector
,
342 AudioObjectPropertyAddress property_address
;
344 property_address
.mSelector
= selector
;
345 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
346 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
348 return AudioObjectIsPropertySettable(id
, &property_address
, outData
);
351 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id
);
352 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id
);
353 static int OpenSPDIF(void);
354 static int AudioStreamChangeFormat( AudioStreamID i_stream_id
, AudioStreamBasicDescription change_format
);
355 static OSStatus
RenderCallbackSPDIF( AudioDeviceID inDevice
,
356 const AudioTimeStamp
* inNow
,
357 const void * inInputData
,
358 const AudioTimeStamp
* inInputTime
,
359 AudioBufferList
* outOutputData
,
360 const AudioTimeStamp
* inOutputTime
,
361 void * threadGlobals
);
362 static OSStatus
StreamListener( AudioObjectID inObjectID
,
363 UInt32 inNumberAddresses
,
364 const AudioObjectPropertyAddress inAddresses
[],
365 void *inClientData
);
366 static OSStatus
DeviceListener( AudioObjectID inObjectID
,
367 UInt32 inNumberAddresses
,
368 const AudioObjectPropertyAddress inAddresses
[],
369 void *inClientData
);
371 static void print_help(void)
376 AudioDeviceID
*devids
;
379 mp_msg(MSGT_AO
, MSGL_FATAL
,
380 "\n-ao coreaudio commandline help:\n"
381 "Example: mplayer -ao coreaudio:device_id=266\n"
382 " open Core Audio with output device ID 266.\n"
385 " ID of output device to use (0 = default device)\n"
387 " This help including list of available devices.\n"
389 "Available output devices:\n");
391 i_param_size
= GetGlobalAudioPropertyArray(kAudioObjectSystemObject
, kAudioHardwarePropertyDevices
, (void **)&devids
);
394 mp_msg(MSGT_AO
, MSGL_FATAL
, "Failed to get list of output devices.\n");
398 num_devices
= i_param_size
/ sizeof(AudioDeviceID
);
400 for (int i
= 0; i
< num_devices
; ++i
) {
401 err
= GetAudioPropertyString(devids
[i
], kAudioObjectPropertyName
, &device_name
);
404 mp_msg(MSGT_AO
, MSGL_FATAL
, "%s (id: %"PRIu32
")\n", device_name
, devids
[i
]);
407 mp_msg(MSGT_AO
, MSGL_FATAL
, "Unknown (id: %"PRIu32
")\n", devids
[i
]);
410 mp_msg(MSGT_AO
, MSGL_FATAL
, "\n");
415 static int init(int rate
,int channels
,int format
,int flags
)
417 AudioStreamBasicDescription inDesc
;
418 ComponentDescription desc
;
420 AURenderCallbackStruct renderCallback
;
422 UInt32 size
, maxFrames
, b_alive
;
424 AudioDeviceID devid_def
= 0;
425 int device_id
, display_help
= 0;
427 const opt_t subopts
[] = {
428 {"device_id", OPT_ARG_INT
, &device_id
, NULL
},
429 {"help", OPT_ARG_BOOL
, &display_help
, NULL
},
436 if (subopt_parse(ao_subdevice
, subopts
) != 0 || display_help
) {
442 ao_msg(MSGT_AO
,MSGL_V
, "init([%dHz][%dch][%s][%d])\n", rate
, channels
, af_fmt2str_short(format
), flags
);
444 ao
= calloc(1, sizeof(ao_coreaudio_t
));
446 ao
->i_selected_dev
= 0;
447 ao
->b_supports_digital
= 0;
450 ao
->b_stream_format_changed
= 0;
453 ao
->i_stream_index
= -1;
455 ao
->b_changed_mixing
= 0;
457 global_ao
->no_persistent_volume
= true;
459 if (device_id
== 0) {
460 /* Find the ID of the default Device. */
461 err
= GetAudioProperty(kAudioObjectSystemObject
,
462 kAudioHardwarePropertyDefaultOutputDevice
,
463 sizeof(UInt32
), &devid_def
);
466 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get default audio device: [%4.4s]\n", (char *)&err
);
470 devid_def
= device_id
;
473 /* Retrieve the name of the device. */
474 err
= GetAudioPropertyString(devid_def
,
475 kAudioObjectPropertyName
,
479 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get default audio device name: [%4.4s]\n", (char *)&err
);
483 ao_msg(MSGT_AO
,MSGL_V
, "got audio output device ID: %"PRIu32
" Name: %s\n", devid_def
, psz_name
);
485 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
486 if (AF_FORMAT_IS_AC3(format
)) {
487 if (AudioDeviceSupportsDigital(devid_def
))
489 ao
->b_supports_digital
= 1;
491 ao_msg(MSGT_AO
, MSGL_V
,
492 "probe default audio output device about support for digital s/pdif output: %d\n",
493 ao
->b_supports_digital
);
498 // Save selected device id
499 ao
->i_selected_dev
= devid_def
;
501 // Build Description for the input format
502 inDesc
.mSampleRate
=rate
;
503 inDesc
.mFormatID
=ao
->b_supports_digital
? kAudioFormat60958AC3
: kAudioFormatLinearPCM
;
504 inDesc
.mChannelsPerFrame
=channels
;
505 inDesc
.mBitsPerChannel
=af_fmt2bits(format
);
507 if((format
&AF_FORMAT_POINT_MASK
)==AF_FORMAT_F
) {
509 inDesc
.mFormatFlags
= kAudioFormatFlagIsFloat
|kAudioFormatFlagIsPacked
;
511 else if((format
&AF_FORMAT_SIGN_MASK
)==AF_FORMAT_SI
) {
513 inDesc
.mFormatFlags
= kAudioFormatFlagIsSignedInteger
|kAudioFormatFlagIsPacked
;
517 inDesc
.mFormatFlags
= kAudioFormatFlagIsPacked
;
519 if ((format
& AF_FORMAT_END_MASK
) == AF_FORMAT_BE
)
520 inDesc
.mFormatFlags
|= kAudioFormatFlagIsBigEndian
;
522 inDesc
.mFramesPerPacket
= 1;
523 ao
->packetSize
= inDesc
.mBytesPerPacket
= inDesc
.mBytesPerFrame
= inDesc
.mFramesPerPacket
*channels
*(inDesc
.mBitsPerChannel
/8);
524 print_format(MSGL_V
, "source:",&inDesc
);
526 if (ao
->b_supports_digital
)
529 err
= GetAudioProperty(ao
->i_selected_dev
,
530 kAudioDevicePropertyDeviceIsAlive
,
531 sizeof(UInt32
), &b_alive
);
533 ao_msg(MSGT_AO
, MSGL_WARN
, "could not check whether device is alive: [%4.4s]\n", (char *)&err
);
535 ao_msg(MSGT_AO
, MSGL_WARN
, "device is not alive\n" );
537 /* S/PDIF output need device in HogMode. */
538 err
= GetAudioProperty(ao
->i_selected_dev
,
539 kAudioDevicePropertyHogMode
,
540 sizeof(pid_t
), &ao
->i_hog_pid
);
543 /* This is not a fatal error. Some drivers simply don't support this property. */
544 ao_msg(MSGT_AO
, MSGL_WARN
, "could not check whether device is hogged: [%4.4s]\n",
549 if (ao
->i_hog_pid
!= -1 && ao
->i_hog_pid
!= getpid())
551 ao_msg(MSGT_AO
, MSGL_WARN
, "Selected audio device is exclusively in use by another program.\n" );
554 ao
->stream_format
= inDesc
;
558 /* original analog output code */
559 desc
.componentType
= kAudioUnitType_Output
;
560 desc
.componentSubType
= (device_id
== 0) ? kAudioUnitSubType_DefaultOutput
: kAudioUnitSubType_HALOutput
;
561 desc
.componentManufacturer
= kAudioUnitManufacturer_Apple
;
562 desc
.componentFlags
= 0;
563 desc
.componentFlagsMask
= 0;
565 comp
= FindNextComponent(NULL
, &desc
); //Finds an component that meets the desc spec's
567 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to find Output Unit component\n");
571 err
= OpenAComponent(comp
, &(ao
->theOutputUnit
)); //gains access to the services provided by the component
573 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err
);
577 // Initialize AudioUnit
578 err
= AudioUnitInitialize(ao
->theOutputUnit
);
580 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err
);
584 size
= sizeof(AudioStreamBasicDescription
);
585 err
= AudioUnitSetProperty(ao
->theOutputUnit
, kAudioUnitProperty_StreamFormat
, kAudioUnitScope_Input
, 0, &inDesc
, size
);
588 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to set the input format: [%4.4s]\n", (char *)&err
);
592 size
= sizeof(UInt32
);
593 err
= AudioUnitGetProperty(ao
->theOutputUnit
, kAudioDevicePropertyBufferSize
, kAudioUnitScope_Input
, 0, &maxFrames
, &size
);
597 ao_msg(MSGT_AO
,MSGL_WARN
, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err
);
601 //Set the Current Device to the Default Output Unit.
602 err
= AudioUnitSetProperty(ao
->theOutputUnit
, kAudioOutputUnitProperty_CurrentDevice
, kAudioUnitScope_Global
, 0, &ao
->i_selected_dev
, sizeof(ao
->i_selected_dev
));
604 ao
->chunk_size
= maxFrames
;//*inDesc.mBytesPerFrame;
606 ao_data
.samplerate
= inDesc
.mSampleRate
;
607 ao_data
.channels
= inDesc
.mChannelsPerFrame
;
608 ao_data
.bps
= ao_data
.samplerate
* inDesc
.mBytesPerFrame
;
609 ao_data
.outburst
= ao
->chunk_size
;
610 ao_data
.buffersize
= ao_data
.bps
;
612 ao
->num_chunks
= (ao_data
.bps
+ao
->chunk_size
-1)/ao
->chunk_size
;
613 ao
->buffer_len
= ao
->num_chunks
* ao
->chunk_size
;
614 ao
->buffer
= av_fifo_alloc(ao
->buffer_len
);
616 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
);
618 renderCallback
.inputProc
= theRenderProc
;
619 renderCallback
.inputProcRefCon
= 0;
620 err
= AudioUnitSetProperty(ao
->theOutputUnit
, kAudioUnitProperty_SetRenderCallback
, kAudioUnitScope_Input
, 0, &renderCallback
, sizeof(AURenderCallbackStruct
));
622 ao_msg(MSGT_AO
, MSGL_WARN
, "Unable to set the render callback: [%4.4s]\n", (char *)&err
);
631 AudioUnitUninitialize(ao
->theOutputUnit
);
633 CloseComponent(ao
->theOutputUnit
);
635 av_fifo_free(ao
->buffer
);
638 return CONTROL_FALSE
;
641 /*****************************************************************************
642 * Setup a encoded digital stream (SPDIF)
643 *****************************************************************************/
644 static int OpenSPDIF(void)
646 OSStatus err
= noErr
;
647 UInt32 i_param_size
, b_mix
= 0;
648 Boolean b_writeable
= 0;
649 AudioStreamID
*p_streams
= NULL
;
650 int i
, i_streams
= 0;
651 AudioObjectPropertyAddress property_address
;
653 /* Start doing the SPDIF setup process. */
656 /* Hog the device. */
657 ao
->i_hog_pid
= getpid() ;
659 err
= SetAudioProperty(ao
->i_selected_dev
,
660 kAudioDevicePropertyHogMode
,
661 sizeof(ao
->i_hog_pid
), &ao
->i_hog_pid
);
664 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set hogmode: [%4.4s]\n", (char *)&err
);
669 property_address
.mSelector
= kAudioDevicePropertySupportsMixing
;
670 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
671 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
673 /* Set mixable to false if we are allowed to. */
674 if (AudioObjectHasProperty(ao
->i_selected_dev
, &property_address
)) {
675 /* Set mixable to false if we are allowed to. */
676 err
= IsAudioPropertySettable(ao
->i_selected_dev
,
677 kAudioDevicePropertySupportsMixing
,
679 err
= GetAudioProperty(ao
->i_selected_dev
,
680 kAudioDevicePropertySupportsMixing
,
681 sizeof(UInt32
), &b_mix
);
682 if (err
== noErr
&& b_writeable
)
685 err
= SetAudioProperty(ao
->i_selected_dev
,
686 kAudioDevicePropertySupportsMixing
,
687 sizeof(UInt32
), &b_mix
);
688 ao
->b_changed_mixing
= 1;
692 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set mixmode: [%4.4s]\n", (char *)&err
);
697 /* Get a list of all the streams on this device. */
698 i_param_size
= GetAudioPropertyArray(ao
->i_selected_dev
,
699 kAudioDevicePropertyStreams
,
700 kAudioDevicePropertyScopeOutput
,
701 (void **)&p_streams
);
704 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get number of streams.\n");
708 i_streams
= i_param_size
/ sizeof(AudioStreamID
);
710 ao_msg(MSGT_AO
, MSGL_V
, "current device stream number: %d\n", i_streams
);
712 for (i
= 0; i
< i_streams
&& ao
->i_stream_index
< 0; ++i
)
714 /* Find a stream with a cac3 stream. */
715 AudioStreamRangedDescription
*p_format_list
= NULL
;
716 int i_formats
= 0, j
= 0, b_digital
= 0;
718 i_param_size
= GetGlobalAudioPropertyArray(p_streams
[i
],
719 kAudioStreamPropertyAvailablePhysicalFormats
,
720 (void **)&p_format_list
);
723 ao_msg(MSGT_AO
, MSGL_WARN
,
724 "Could not get number of stream formats.\n");
728 i_formats
= i_param_size
/ sizeof(AudioStreamRangedDescription
);
730 /* Check if one of the supported formats is a digital format. */
731 for (j
= 0; j
< i_formats
; ++j
)
733 if (p_format_list
[j
].mFormat
.mFormatID
== 'IAC3' ||
734 p_format_list
[j
].mFormat
.mFormatID
== 'iac3' ||
735 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormat60958AC3
||
736 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormatAC3
)
745 /* If this stream supports a digital (cac3) format, then set it. */
746 int i_requested_rate_format
= -1;
747 int i_current_rate_format
= -1;
748 int i_backup_rate_format
= -1;
750 ao
->i_stream_id
= p_streams
[i
];
751 ao
->i_stream_index
= i
;
753 if (ao
->b_revert
== 0)
755 /* Retrieve the original format of this stream first if not done so already. */
756 err
= GetAudioProperty(ao
->i_stream_id
,
757 kAudioStreamPropertyPhysicalFormat
,
758 sizeof(ao
->sfmt_revert
), &ao
->sfmt_revert
);
761 ao_msg(MSGT_AO
, MSGL_WARN
,
762 "Could not retrieve the original stream format: [%4.4s]\n",
770 for (j
= 0; j
< i_formats
; ++j
)
771 if (p_format_list
[j
].mFormat
.mFormatID
== 'IAC3' ||
772 p_format_list
[j
].mFormat
.mFormatID
== 'iac3' ||
773 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormat60958AC3
||
774 p_format_list
[j
].mFormat
.mFormatID
== kAudioFormatAC3
)
776 if (p_format_list
[j
].mFormat
.mSampleRate
== ao
->stream_format
.mSampleRate
)
778 i_requested_rate_format
= j
;
781 if (p_format_list
[j
].mFormat
.mSampleRate
== ao
->sfmt_revert
.mSampleRate
)
782 i_current_rate_format
= j
;
783 else if (i_backup_rate_format
< 0 || p_format_list
[j
].mFormat
.mSampleRate
> p_format_list
[i_backup_rate_format
].mFormat
.mSampleRate
)
784 i_backup_rate_format
= j
;
787 if (i_requested_rate_format
>= 0) /* We prefer to output at the samplerate of the original audio. */
788 ao
->stream_format
= p_format_list
[i_requested_rate_format
].mFormat
;
789 else if (i_current_rate_format
>= 0) /* If not possible, we will try to use the current samplerate of the device. */
790 ao
->stream_format
= p_format_list
[i_current_rate_format
].mFormat
;
791 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). */
797 if (ao
->i_stream_index
< 0)
799 ao_msg(MSGT_AO
, MSGL_WARN
,
800 "Cannot find any digital output stream format when OpenSPDIF().\n");
804 print_format(MSGL_V
, "original stream format:", &ao
->sfmt_revert
);
806 if (!AudioStreamChangeFormat(ao
->i_stream_id
, ao
->stream_format
))
809 property_address
.mSelector
= kAudioDevicePropertyDeviceHasChanged
;
810 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
811 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
813 err
= AudioObjectAddPropertyListener(ao
->i_selected_dev
,
818 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err
);
821 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
822 /* Although there's no such case reported. */
824 if (!(ao
->stream_format
.mFormatFlags
& kAudioFormatFlagIsBigEndian
))
826 /* tell mplayer that we need a byteswap on AC3 streams, */
827 if (ao
->stream_format
.mFormatID
& kAudioFormat60958AC3
)
828 ao_data
.format
= AF_FORMAT_AC3_LE
;
830 if (ao
->stream_format
.mFormatFlags
& kAudioFormatFlagIsBigEndian
)
832 ao_msg(MSGT_AO
, MSGL_WARN
,
833 "Output stream has non-native byte order, digital output may fail.\n");
835 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
836 ao
->chunk_size
= ao
->stream_format
.mBytesPerPacket
;
838 ao_data
.samplerate
= ao
->stream_format
.mSampleRate
;
839 ao_data
.channels
= ao
->stream_format
.mChannelsPerFrame
;
840 ao_data
.bps
= ao_data
.samplerate
* (ao
->stream_format
.mBytesPerPacket
/ao
->stream_format
.mFramesPerPacket
);
841 ao_data
.outburst
= ao
->chunk_size
;
842 ao_data
.buffersize
= ao_data
.bps
;
844 ao
->num_chunks
= (ao_data
.bps
+ao
->chunk_size
-1)/ao
->chunk_size
;
845 ao
->buffer_len
= ao
->num_chunks
* ao
->chunk_size
;
846 ao
->buffer
= av_fifo_alloc(ao
->buffer_len
);
848 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
);
851 /* Create IOProc callback. */
852 err
= AudioDeviceCreateIOProcID(ao
->i_selected_dev
,
853 (AudioDeviceIOProc
)RenderCallbackSPDIF
,
855 &ao
->renderCallback
);
857 if (err
!= noErr
|| ao
->renderCallback
== NULL
)
859 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err
);
869 AudioStreamChangeFormat(ao
->i_stream_id
, ao
->sfmt_revert
);
871 if (ao
->b_changed_mixing
&& ao
->sfmt_revert
.mFormatID
!= kAudioFormat60958AC3
)
874 err
= SetAudioProperty(ao
->i_selected_dev
,
875 kAudioDevicePropertySupportsMixing
,
876 sizeof(int), &b_mix
);
878 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set mixmode: [%4.4s]\n",
881 if (ao
->i_hog_pid
== getpid())
884 err
= SetAudioProperty(ao
->i_selected_dev
,
885 kAudioDevicePropertyHogMode
,
886 sizeof(ao
->i_hog_pid
), &ao
->i_hog_pid
);
888 ao_msg(MSGT_AO
, MSGL_WARN
, "Could not release hogmode: [%4.4s]\n",
891 av_fifo_free(ao
->buffer
);
894 return CONTROL_FALSE
;
897 /*****************************************************************************
898 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
899 *****************************************************************************/
900 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id
)
902 UInt32 i_param_size
= 0;
903 AudioStreamID
*p_streams
= NULL
;
904 int i
= 0, i_streams
= 0;
905 int b_return
= CONTROL_FALSE
;
907 /* Retrieve all the output streams. */
908 i_param_size
= GetAudioPropertyArray(i_dev_id
,
909 kAudioDevicePropertyStreams
,
910 kAudioDevicePropertyScopeOutput
,
911 (void **)&p_streams
);
914 ao_msg(MSGT_AO
, MSGL_WARN
, "could not get number of streams.\n");
915 return CONTROL_FALSE
;
918 i_streams
= i_param_size
/ sizeof(AudioStreamID
);
920 for (i
= 0; i
< i_streams
; ++i
)
922 if (AudioStreamSupportsDigital(p_streams
[i
]))
923 b_return
= CONTROL_OK
;
930 /*****************************************************************************
931 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
932 *****************************************************************************/
933 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id
)
936 AudioStreamRangedDescription
*p_format_list
= NULL
;
937 int i
, i_formats
, b_return
= CONTROL_FALSE
;
939 /* Retrieve all the stream formats supported by each output stream. */
940 i_param_size
= GetGlobalAudioPropertyArray(i_stream_id
,
941 kAudioStreamPropertyAvailablePhysicalFormats
,
942 (void **)&p_format_list
);
945 ao_msg(MSGT_AO
, MSGL_WARN
, "Could not get number of stream formats.\n");
946 return CONTROL_FALSE
;
949 i_formats
= i_param_size
/ sizeof(AudioStreamRangedDescription
);
951 for (i
= 0; i
< i_formats
; ++i
)
953 print_format(MSGL_V
, "supported format:", &(p_format_list
[i
].mFormat
));
955 if (p_format_list
[i
].mFormat
.mFormatID
== 'IAC3' ||
956 p_format_list
[i
].mFormat
.mFormatID
== 'iac3' ||
957 p_format_list
[i
].mFormat
.mFormatID
== kAudioFormat60958AC3
||
958 p_format_list
[i
].mFormat
.mFormatID
== kAudioFormatAC3
)
959 b_return
= CONTROL_OK
;
966 /*****************************************************************************
967 * AudioStreamChangeFormat: Change i_stream_id to change_format
968 *****************************************************************************/
969 static int AudioStreamChangeFormat( AudioStreamID i_stream_id
, AudioStreamBasicDescription change_format
)
971 OSStatus err
= noErr
;
973 AudioObjectPropertyAddress property_address
;
975 static volatile int stream_format_changed
;
976 stream_format_changed
= 0;
978 print_format(MSGL_V
, "setting stream format:", &change_format
);
980 /* Install the callback. */
981 property_address
.mSelector
= kAudioStreamPropertyPhysicalFormat
;
982 property_address
.mScope
= kAudioObjectPropertyScopeGlobal
;
983 property_address
.mElement
= kAudioObjectPropertyElementMaster
;
985 err
= AudioObjectAddPropertyListener(i_stream_id
,
988 (void *)&stream_format_changed
);
991 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err
);
992 return CONTROL_FALSE
;
995 /* Change the format. */
996 err
= SetAudioProperty(i_stream_id
,
997 kAudioStreamPropertyPhysicalFormat
,
998 sizeof(AudioStreamBasicDescription
), &change_format
);
1001 ao_msg(MSGT_AO
, MSGL_WARN
, "could not set the stream format: [%4.4s]\n", (char *)&err
);
1002 return CONTROL_FALSE
;
1005 /* The AudioStreamSetProperty is not only asynchronious,
1006 * it is also not Atomic, in its behaviour.
1007 * Therefore we check 5 times before we really give up.
1008 * FIXME: failing isn't actually implemented yet. */
1009 for (i
= 0; i
< 5; ++i
)
1011 AudioStreamBasicDescription actual_format
;
1013 for (j
= 0; !stream_format_changed
&& j
< 50; ++j
)
1015 if (stream_format_changed
)
1016 stream_format_changed
= 0;
1018 ao_msg(MSGT_AO
, MSGL_V
, "reached timeout\n" );
1020 err
= GetAudioProperty(i_stream_id
,
1021 kAudioStreamPropertyPhysicalFormat
,
1022 sizeof(AudioStreamBasicDescription
), &actual_format
);
1024 print_format(MSGL_V
, "actual format in use:", &actual_format
);
1025 if (actual_format
.mSampleRate
== change_format
.mSampleRate
&&
1026 actual_format
.mFormatID
== change_format
.mFormatID
&&
1027 actual_format
.mFramesPerPacket
== change_format
.mFramesPerPacket
)
1029 /* The right format is now active. */
1032 /* We need to check again. */
1035 /* Removing the property listener. */
1036 err
= AudioObjectRemovePropertyListener(i_stream_id
,
1039 (void *)&stream_format_changed
);
1042 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err
);
1043 return CONTROL_FALSE
;
1046 return CONTROL_TRUE
;
1049 /*****************************************************************************
1050 * RenderCallbackSPDIF: callback for SPDIF audio output
1051 *****************************************************************************/
1052 static OSStatus
RenderCallbackSPDIF( AudioDeviceID inDevice
,
1053 const AudioTimeStamp
* inNow
,
1054 const void * inInputData
,
1055 const AudioTimeStamp
* inInputTime
,
1056 AudioBufferList
* outOutputData
,
1057 const AudioTimeStamp
* inOutputTime
,
1058 void * threadGlobals
)
1060 int amt
= av_fifo_size(ao
->buffer
);
1061 int req
= outOutputData
->mBuffers
[ao
->i_stream_index
].mDataByteSize
;
1066 read_buffer(ao
->b_muted
? NULL
: (unsigned char *)outOutputData
->mBuffers
[ao
->i_stream_index
].mData
, amt
);
1072 static int play(void* output_samples
,int num_bytes
,int flags
)
1074 int wrote
, b_digital
;
1077 // Check whether we need to reset the digital output stream.
1078 if (ao
->b_digital
&& ao
->b_stream_format_changed
)
1080 ao
->b_stream_format_changed
= 0;
1081 b_digital
= AudioStreamSupportsDigital(ao
->i_stream_id
);
1084 /* Current stream supports digital format output, let's set it. */
1085 ao_msg(MSGT_AO
, MSGL_V
,
1086 "Detected current stream supports digital, try to restore digital output...\n");
1088 if (!AudioStreamChangeFormat(ao
->i_stream_id
, ao
->stream_format
))
1090 ao_msg(MSGT_AO
, MSGL_WARN
, "Restoring digital output failed.\n");
1094 ao_msg(MSGT_AO
, MSGL_WARN
, "Restoring digital output succeeded.\n");
1099 ao_msg(MSGT_AO
, MSGL_V
, "Detected current stream does not support digital.\n");
1102 wrote
=write_buffer(output_samples
, num_bytes
);
1106 exit_reason
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, 0.01, true);
1107 } while (exit_reason
== kCFRunLoopRunHandledSource
);
1112 /* set variables and buffer to initial state */
1113 static void reset(void)
1116 av_fifo_reset(ao
->buffer
);
1120 /* return available space */
1121 static int get_space(void)
1123 return ao
->buffer_len
- av_fifo_size(ao
->buffer
);
1127 /* return delay until audio is played */
1128 static float get_delay(void)
1130 // inaccurate, should also contain the data buffered e.g. by the OS
1131 return (float)av_fifo_size(ao
->buffer
)/(float)ao_data
.bps
;
1135 /* unload plugin and deregister from coreaudio */
1136 static void uninit(int immed
)
1138 OSStatus err
= noErr
;
1141 long long timeleft
=(1000000LL*av_fifo_size(ao
->buffer
))/ao_data
.bps
;
1142 ao_msg(MSGT_AO
,MSGL_DBG2
, "%d bytes left @%d bps (%d usec)\n", av_fifo_size(ao
->buffer
), ao_data
.bps
, (int)timeleft
);
1143 usec_sleep((int)timeleft
);
1146 if (!ao
->b_digital
) {
1147 AudioOutputUnitStop(ao
->theOutputUnit
);
1148 AudioUnitUninitialize(ao
->theOutputUnit
);
1149 CloseComponent(ao
->theOutputUnit
);
1153 err
= AudioDeviceStop(ao
->i_selected_dev
, ao
->renderCallback
);
1155 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err
);
1157 /* Remove IOProc callback. */
1158 err
= AudioDeviceDestroyIOProcID(ao
->i_selected_dev
, ao
->renderCallback
);
1160 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err
);
1163 AudioStreamChangeFormat(ao
->i_stream_id
, ao
->sfmt_revert
);
1165 if (ao
->b_changed_mixing
&& ao
->sfmt_revert
.mFormatID
!= kAudioFormat60958AC3
)
1168 Boolean b_writeable
= 0;
1169 /* Revert mixable to true if we are allowed to. */
1170 err
= IsAudioPropertySettable(ao
->i_selected_dev
,
1171 kAudioDevicePropertySupportsMixing
,
1173 err
= GetAudioProperty(ao
->i_selected_dev
,
1174 kAudioDevicePropertySupportsMixing
,
1175 sizeof(UInt32
), &b_mix
);
1176 if (err
== noErr
&& b_writeable
)
1179 err
= SetAudioProperty(ao
->i_selected_dev
,
1180 kAudioDevicePropertySupportsMixing
,
1181 sizeof(UInt32
), &b_mix
);
1184 ao_msg(MSGT_AO
, MSGL_WARN
, "failed to set mixmode: [%4.4s]\n", (char *)&err
);
1186 if (ao
->i_hog_pid
== getpid())
1189 err
= SetAudioProperty(ao
->i_selected_dev
,
1190 kAudioDevicePropertyHogMode
,
1191 sizeof(ao
->i_hog_pid
), &ao
->i_hog_pid
);
1192 if (err
!= noErr
) ao_msg(MSGT_AO
, MSGL_WARN
, "Could not release hogmode: [%4.4s]\n", (char *)&err
);
1196 av_fifo_free(ao
->buffer
);
1202 /* stop playing, keep buffers (for pause) */
1203 static void audio_pause(void)
1207 /* Stop callback. */
1210 err
=AudioOutputUnitStop(ao
->theOutputUnit
);
1212 ao_msg(MSGT_AO
,MSGL_WARN
, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err
);
1216 err
= AudioDeviceStop(ao
->i_selected_dev
, ao
->renderCallback
);
1218 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err
);
1224 /* resume playing, after audio_pause() */
1225 static void audio_resume(void)
1232 /* Start callback. */
1235 err
= AudioOutputUnitStart(ao
->theOutputUnit
);
1237 ao_msg(MSGT_AO
,MSGL_WARN
, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err
);
1241 err
= AudioDeviceStart(ao
->i_selected_dev
, ao
->renderCallback
);
1243 ao_msg(MSGT_AO
, MSGL_WARN
, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err
);
1248 /*****************************************************************************
1250 *****************************************************************************/
1251 static OSStatus
StreamListener( AudioObjectID inObjectID
,
1252 UInt32 inNumberAddresses
,
1253 const AudioObjectPropertyAddress inAddresses
[],
1254 void *inClientData
)
1256 for (int i
=0; i
< inNumberAddresses
; ++i
)
1258 if (inAddresses
[i
].mSelector
== kAudioStreamPropertyPhysicalFormat
) {
1259 ao_msg(MSGT_AO
, MSGL_WARN
, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1261 *(volatile int *)inClientData
= 1;
1268 static OSStatus
DeviceListener( AudioObjectID inObjectID
,
1269 UInt32 inNumberAddresses
,
1270 const AudioObjectPropertyAddress inAddresses
[],
1271 void *inClientData
)
1273 for (int i
=0; i
< inNumberAddresses
; ++i
)
1275 if (inAddresses
[i
].mSelector
== kAudioDevicePropertyDeviceHasChanged
) {
1276 ao_msg(MSGT_AO
, MSGL_WARN
, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1277 ao
->b_stream_format_changed
= 1;