Simplify code: make open_stream() accept NULL file_format argument
[mplayer/glamo.git] / libao2 / ao_coreaudio.c
blob8a8387bed6e63fd4ca3188657d8bb83471a92356
1 /*
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>
41 #include <stdio.h>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <inttypes.h>
45 #include <sys/types.h>
46 #include <unistd.h>
48 #include "config.h"
49 #include "mp_msg.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",
61 "coreaudio",
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 typedef struct ao_coreaudio_s
73 AudioDeviceID i_selected_dev; /* Keeps DeviceID of the selected device. */
74 int b_supports_digital; /* Does the currently selected device support digital mode? */
75 int b_digital; /* Are we running in digital mode? */
76 int b_muted; /* Are we muted in digital mode? */
78 AudioDeviceIOProcID renderCallback; /* Render callback used for SPDIF */
80 /* AudioUnit */
81 AudioUnit theOutputUnit;
83 /* CoreAudio SPDIF mode specific */
84 pid_t i_hog_pid; /* Keeps the pid of our hog status. */
85 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
86 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
87 AudioStreamBasicDescription stream_format;/* The format we changed the stream to */
88 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
89 int b_revert; /* Whether we need to revert the stream format */
90 int b_changed_mixing; /* Whether we need to set the mixing mode back */
91 int b_stream_format_changed; /* Flag for main thread to reset stream's format to digital and reset buffer */
93 /* Original common part */
94 int packetSize;
95 int paused;
97 /* Ring-buffer */
98 AVFifoBuffer *buffer;
99 unsigned int buffer_len; ///< must always be num_chunks * chunk_size
100 unsigned int num_chunks;
101 unsigned int chunk_size;
102 } ao_coreaudio_t;
104 static ao_coreaudio_t *ao = NULL;
107 * \brief add data to ringbuffer
109 static int write_buffer(unsigned char* data, int len){
110 int free = ao->buffer_len - av_fifo_size(ao->buffer);
111 if (len > free) len = free;
112 return av_fifo_generic_write(ao->buffer, data, len, NULL);
116 * \brief remove data from ringbuffer
118 static int read_buffer(unsigned char* data,int len){
119 int buffered = av_fifo_size(ao->buffer);
120 if (len > buffered) len = buffered;
121 av_fifo_generic_read(ao->buffer, data, len, NULL);
122 return len;
125 static OSStatus theRenderProc(void *inRefCon,
126 AudioUnitRenderActionFlags *inActionFlags,
127 const AudioTimeStamp *inTimeStamp,
128 UInt32 inBusNumber, UInt32 inNumFrames,
129 AudioBufferList *ioData)
131 int amt=av_fifo_size(ao->buffer);
132 int req=(inNumFrames)*ao->packetSize;
134 if(amt>req)
135 amt=req;
137 if(amt)
138 read_buffer((unsigned char *)ioData->mBuffers[0].mData, amt);
139 else audio_pause();
140 ioData->mBuffers[0].mDataByteSize = amt;
142 return noErr;
145 static int control(int cmd,void *arg){
146 ao_control_vol_t *control_vol;
147 OSStatus err;
148 Float32 vol;
149 switch (cmd) {
150 case AOCONTROL_GET_VOLUME:
151 control_vol = (ao_control_vol_t*)arg;
152 if (ao->b_digital) {
153 // Digital output has no volume adjust.
154 return CONTROL_FALSE;
156 err = AudioUnitGetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, &vol);
158 if(err==0) {
159 // printf("GET VOL=%f\n", vol);
160 control_vol->left=control_vol->right=vol*100.0/4.0;
161 return CONTROL_TRUE;
163 else {
164 ao_msg(MSGT_AO, MSGL_WARN, "could not get HAL output volume: [%4.4s]\n", (char *)&err);
165 return CONTROL_FALSE;
168 case AOCONTROL_SET_VOLUME:
169 control_vol = (ao_control_vol_t*)arg;
171 if (ao->b_digital) {
172 // Digital output can not set volume. Here we have to return true
173 // to make mixer forget it. Else mixer will add a soft filter,
174 // that's not we expected and the filter not support ac3 stream
175 // will cause mplayer die.
177 // Although not support set volume, but at least we support mute.
178 // MPlayer set mute by set volume to zero, we handle it.
179 if (control_vol->left == 0 && control_vol->right == 0)
180 ao->b_muted = 1;
181 else
182 ao->b_muted = 0;
183 return CONTROL_TRUE;
186 vol=(control_vol->left+control_vol->right)*4.0/200.0;
187 err = AudioUnitSetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, vol, 0);
188 if(err==0) {
189 // printf("SET VOL=%f\n", vol);
190 return CONTROL_TRUE;
192 else {
193 ao_msg(MSGT_AO, MSGL_WARN, "could not set HAL output volume: [%4.4s]\n", (char *)&err);
194 return CONTROL_FALSE;
196 /* Everything is currently unimplemented */
197 default:
198 return CONTROL_FALSE;
204 static void print_format(int lev, const char* str, const AudioStreamBasicDescription *f){
205 uint32_t flags=(uint32_t) f->mFormatFlags;
206 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",
207 str, f->mSampleRate, f->mBitsPerChannel,
208 (int)(f->mFormatID & 0xff000000) >> 24,
209 (int)(f->mFormatID & 0x00ff0000) >> 16,
210 (int)(f->mFormatID & 0x0000ff00) >> 8,
211 (int)(f->mFormatID & 0x000000ff) >> 0,
212 f->mFormatFlags, f->mBytesPerPacket,
213 f->mFramesPerPacket, f->mBytesPerFrame,
214 f->mChannelsPerFrame,
215 (flags&kAudioFormatFlagIsFloat) ? "float" : "int",
216 (flags&kAudioFormatFlagIsBigEndian) ? "BE" : "LE",
217 (flags&kAudioFormatFlagIsSignedInteger) ? "S" : "U",
218 (flags&kAudioFormatFlagIsPacked) ? " packed" : "",
219 (flags&kAudioFormatFlagIsAlignedHigh) ? " aligned" : "",
220 (flags&kAudioFormatFlagIsNonInterleaved) ? " ni" : "" );
223 static OSStatus GetAudioProperty(AudioObjectID id,
224 AudioObjectPropertySelector selector,
225 UInt32 outSize, void *outData)
227 AudioObjectPropertyAddress property_address;
229 property_address.mSelector = selector;
230 property_address.mScope = kAudioObjectPropertyScopeGlobal;
231 property_address.mElement = kAudioObjectPropertyElementMaster;
233 return AudioObjectGetPropertyData(id, &property_address, 0, NULL, &outSize, outData);
236 static UInt32 GetAudioPropertyArray(AudioObjectID id,
237 AudioObjectPropertySelector selector,
238 AudioObjectPropertyScope scope,
239 void **outData)
241 OSStatus err;
242 AudioObjectPropertyAddress property_address;
243 UInt32 i_param_size;
245 property_address.mSelector = selector;
246 property_address.mScope = scope;
247 property_address.mElement = kAudioObjectPropertyElementMaster;
249 err = AudioObjectGetPropertyDataSize(id, &property_address, 0, NULL, &i_param_size);
251 if (err != noErr)
252 return 0;
254 *outData = malloc(i_param_size);
257 err = AudioObjectGetPropertyData(id, &property_address, 0, NULL, &i_param_size, *outData);
259 if (err != noErr) {
260 free(*outData);
261 return 0;
264 return i_param_size;
267 static UInt32 GetGlobalAudioPropertyArray(AudioObjectID id,
268 AudioObjectPropertySelector selector,
269 void **outData)
271 return GetAudioPropertyArray(id, selector, kAudioObjectPropertyScopeGlobal, outData);
274 static OSStatus GetAudioPropertyString(AudioObjectID id,
275 AudioObjectPropertySelector selector,
276 char **outData)
278 OSStatus err;
279 AudioObjectPropertyAddress property_address;
280 UInt32 i_param_size;
281 CFStringRef string;
282 CFIndex string_length;
284 property_address.mSelector = selector;
285 property_address.mScope = kAudioObjectPropertyScopeGlobal;
286 property_address.mElement = kAudioObjectPropertyElementMaster;
288 i_param_size = sizeof(CFStringRef);
289 err = AudioObjectGetPropertyData(id, &property_address, 0, NULL, &i_param_size, &string);
290 if (err != noErr)
291 return err;
293 string_length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(string),
294 kCFStringEncodingASCII);
295 *outData = malloc(string_length + 1);
296 CFStringGetCString(string, *outData, string_length + 1, kCFStringEncodingASCII);
298 CFRelease(string);
300 return err;
303 static OSStatus SetAudioProperty(AudioObjectID id,
304 AudioObjectPropertySelector selector,
305 UInt32 inDataSize, void *inData)
307 AudioObjectPropertyAddress property_address;
309 property_address.mSelector = selector;
310 property_address.mScope = kAudioObjectPropertyScopeGlobal;
311 property_address.mElement = kAudioObjectPropertyElementMaster;
313 return AudioObjectSetPropertyData(id, &property_address, 0, NULL, inDataSize, inData);
316 static Boolean IsAudioPropertySettable(AudioObjectID id,
317 AudioObjectPropertySelector selector,
318 Boolean *outData)
320 AudioObjectPropertyAddress property_address;
322 property_address.mSelector = selector;
323 property_address.mScope = kAudioObjectPropertyScopeGlobal;
324 property_address.mElement = kAudioObjectPropertyElementMaster;
326 return AudioObjectIsPropertySettable(id, &property_address, outData);
329 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id );
330 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id );
331 static int OpenSPDIF(void);
332 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format );
333 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
334 const AudioTimeStamp * inNow,
335 const void * inInputData,
336 const AudioTimeStamp * inInputTime,
337 AudioBufferList * outOutputData,
338 const AudioTimeStamp * inOutputTime,
339 void * threadGlobals );
340 static OSStatus StreamListener( AudioObjectID inObjectID,
341 UInt32 inNumberAddresses,
342 const AudioObjectPropertyAddress inAddresses[],
343 void *inClientData );
344 static OSStatus DeviceListener( AudioObjectID inObjectID,
345 UInt32 inNumberAddresses,
346 const AudioObjectPropertyAddress inAddresses[],
347 void *inClientData );
349 static void print_help(void)
351 OSStatus err;
352 UInt32 i_param_size;
353 int num_devices;
354 AudioDeviceID *devids;
355 char *device_name;
357 mp_msg(MSGT_AO, MSGL_FATAL,
358 "\n-ao coreaudio commandline help:\n"
359 "Example: mplayer -ao coreaudio:device_id=266\n"
360 " open Core Audio with output device ID 266.\n"
361 "\nOptions:\n"
362 " device_id\n"
363 " ID of output device to use (0 = default device)\n"
364 " help\n"
365 " This help including list of available devices.\n"
366 "\n"
367 "Available output devices:\n");
369 i_param_size = GetGlobalAudioPropertyArray(kAudioObjectSystemObject, kAudioHardwarePropertyDevices, (void **)&devids);
371 if (!i_param_size) {
372 mp_msg(MSGT_AO, MSGL_FATAL, "Failed to get list of output devices.\n");
373 return;
376 num_devices = i_param_size / sizeof(AudioDeviceID);
378 for (int i = 0; i < num_devices; ++i) {
379 err = GetAudioPropertyString(devids[i], kAudioObjectPropertyName, &device_name);
381 if (err == noErr) {
382 mp_msg(MSGT_AO, MSGL_FATAL, "%s (id: %"PRIu32")\n", device_name, devids[i]);
383 free(device_name);
384 } else
385 mp_msg(MSGT_AO, MSGL_FATAL, "Unknown (id: %"PRIu32")\n", devids[i]);
388 mp_msg(MSGT_AO, MSGL_FATAL, "\n");
390 free(devids);
393 static int init(int rate,int channels,int format,int flags)
395 AudioStreamBasicDescription inDesc;
396 ComponentDescription desc;
397 Component comp;
398 AURenderCallbackStruct renderCallback;
399 OSStatus err;
400 UInt32 size, maxFrames, b_alive;
401 char *psz_name;
402 AudioDeviceID devid_def = 0;
403 int device_id, display_help = 0;
405 const opt_t subopts[] = {
406 {"device_id", OPT_ARG_INT, &device_id, NULL},
407 {"help", OPT_ARG_BOOL, &display_help, NULL},
408 {NULL}
411 // set defaults
412 device_id = 0;
414 if (subopt_parse(ao_subdevice, subopts) != 0 || display_help) {
415 print_help();
416 if (!display_help)
417 return 0;
420 ao_msg(MSGT_AO,MSGL_V, "init([%dHz][%dch][%s][%d])\n", rate, channels, af_fmt2str_short(format), flags);
422 ao = calloc(1, sizeof(ao_coreaudio_t));
424 ao->i_selected_dev = 0;
425 ao->b_supports_digital = 0;
426 ao->b_digital = 0;
427 ao->b_muted = 0;
428 ao->b_stream_format_changed = 0;
429 ao->i_hog_pid = -1;
430 ao->i_stream_id = 0;
431 ao->i_stream_index = -1;
432 ao->b_revert = 0;
433 ao->b_changed_mixing = 0;
435 if (device_id == 0) {
436 /* Find the ID of the default Device. */
437 err = GetAudioProperty(kAudioObjectSystemObject,
438 kAudioHardwarePropertyDefaultOutputDevice,
439 sizeof(UInt32), &devid_def);
440 if (err != noErr)
442 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device: [%4.4s]\n", (char *)&err);
443 goto err_out;
445 } else {
446 devid_def = device_id;
449 /* Retrieve the name of the device. */
450 err = GetAudioPropertyString(devid_def,
451 kAudioObjectPropertyName,
452 &psz_name);
453 if (err != noErr)
455 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name: [%4.4s]\n", (char *)&err);
456 goto err_out;
459 ao_msg(MSGT_AO,MSGL_V, "got audio output device ID: %"PRIu32" Name: %s\n", devid_def, psz_name );
461 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
462 if (AF_FORMAT_IS_AC3(format)) {
463 if (AudioDeviceSupportsDigital(devid_def))
465 ao->b_supports_digital = 1;
467 ao_msg(MSGT_AO,MSGL_V, "probe default audio output device whether support digital s/pdif output:%d\n", ao->b_supports_digital );
470 free(psz_name);
472 // Save selected device id
473 ao->i_selected_dev = devid_def;
475 // Build Description for the input format
476 inDesc.mSampleRate=rate;
477 inDesc.mFormatID=ao->b_supports_digital ? kAudioFormat60958AC3 : kAudioFormatLinearPCM;
478 inDesc.mChannelsPerFrame=channels;
479 inDesc.mBitsPerChannel=af_fmt2bits(format);
481 if((format&AF_FORMAT_POINT_MASK)==AF_FORMAT_F) {
482 // float
483 inDesc.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked;
485 else if((format&AF_FORMAT_SIGN_MASK)==AF_FORMAT_SI) {
486 // signed int
487 inDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger|kAudioFormatFlagIsPacked;
489 else {
490 // unsigned int
491 inDesc.mFormatFlags = kAudioFormatFlagIsPacked;
493 if ((format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
494 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
496 inDesc.mFramesPerPacket = 1;
497 ao->packetSize = inDesc.mBytesPerPacket = inDesc.mBytesPerFrame = inDesc.mFramesPerPacket*channels*(inDesc.mBitsPerChannel/8);
498 print_format(MSGL_V, "source:",&inDesc);
500 if (ao->b_supports_digital)
502 b_alive = 1;
503 err = GetAudioProperty(ao->i_selected_dev,
504 kAudioDevicePropertyDeviceIsAlive,
505 sizeof(UInt32), &b_alive);
506 if (err != noErr)
507 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is alive: [%4.4s]\n", (char *)&err);
508 if (!b_alive)
509 ao_msg(MSGT_AO, MSGL_WARN, "device is not alive\n" );
511 /* S/PDIF output need device in HogMode. */
512 err = GetAudioProperty(ao->i_selected_dev,
513 kAudioDevicePropertyHogMode,
514 sizeof(pid_t), &ao->i_hog_pid);
515 if (err != noErr)
517 /* This is not a fatal error. Some drivers simply don't support this property. */
518 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is hogged: [%4.4s]\n",
519 (char *)&err);
520 ao->i_hog_pid = -1;
523 if (ao->i_hog_pid != -1 && ao->i_hog_pid != getpid())
525 ao_msg(MSGT_AO, MSGL_WARN, "Selected audio device is exclusively in use by another program.\n" );
526 goto err_out;
528 ao->stream_format = inDesc;
529 return OpenSPDIF();
532 /* original analog output code */
533 desc.componentType = kAudioUnitType_Output;
534 desc.componentSubType = (device_id == 0) ? kAudioUnitSubType_DefaultOutput : kAudioUnitSubType_HALOutput;
535 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
536 desc.componentFlags = 0;
537 desc.componentFlagsMask = 0;
539 comp = FindNextComponent(NULL, &desc); //Finds an component that meets the desc spec's
540 if (comp == NULL) {
541 ao_msg(MSGT_AO, MSGL_WARN, "Unable to find Output Unit component\n");
542 goto err_out;
545 err = OpenAComponent(comp, &(ao->theOutputUnit)); //gains access to the services provided by the component
546 if (err) {
547 ao_msg(MSGT_AO, MSGL_WARN, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err);
548 goto err_out;
551 // Initialize AudioUnit
552 err = AudioUnitInitialize(ao->theOutputUnit);
553 if (err) {
554 ao_msg(MSGT_AO, MSGL_WARN, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err);
555 goto err_out1;
558 size = sizeof(AudioStreamBasicDescription);
559 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inDesc, size);
561 if (err) {
562 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the input format: [%4.4s]\n", (char *)&err);
563 goto err_out2;
566 size = sizeof(UInt32);
567 err = AudioUnitGetProperty(ao->theOutputUnit, kAudioDevicePropertyBufferSize, kAudioUnitScope_Input, 0, &maxFrames, &size);
569 if (err)
571 ao_msg(MSGT_AO,MSGL_WARN, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err);
572 goto err_out2;
575 //Set the Current Device to the Default Output Unit.
576 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &ao->i_selected_dev, sizeof(ao->i_selected_dev));
578 ao->chunk_size = maxFrames;//*inDesc.mBytesPerFrame;
580 ao_data.samplerate = inDesc.mSampleRate;
581 ao_data.channels = inDesc.mChannelsPerFrame;
582 ao_data.bps = ao_data.samplerate * inDesc.mBytesPerFrame;
583 ao_data.outburst = ao->chunk_size;
584 ao_data.buffersize = ao_data.bps;
586 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
587 ao->buffer_len = ao->num_chunks * ao->chunk_size;
588 ao->buffer = av_fifo_alloc(ao->buffer_len);
590 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);
592 renderCallback.inputProc = theRenderProc;
593 renderCallback.inputProcRefCon = 0;
594 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
595 if (err) {
596 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the render callback: [%4.4s]\n", (char *)&err);
597 goto err_out2;
600 reset();
602 return CONTROL_OK;
604 err_out2:
605 AudioUnitUninitialize(ao->theOutputUnit);
606 err_out1:
607 CloseComponent(ao->theOutputUnit);
608 err_out:
609 av_fifo_free(ao->buffer);
610 free(ao);
611 ao = NULL;
612 return CONTROL_FALSE;
615 /*****************************************************************************
616 * Setup a encoded digital stream (SPDIF)
617 *****************************************************************************/
618 static int OpenSPDIF(void)
620 OSStatus err = noErr;
621 UInt32 i_param_size, b_mix = 0;
622 Boolean b_writeable = 0;
623 AudioStreamID *p_streams = NULL;
624 int i, i_streams = 0;
625 AudioObjectPropertyAddress property_address;
627 /* Start doing the SPDIF setup process. */
628 ao->b_digital = 1;
630 /* Hog the device. */
631 ao->i_hog_pid = getpid() ;
633 err = SetAudioProperty(ao->i_selected_dev,
634 kAudioDevicePropertyHogMode,
635 sizeof(ao->i_hog_pid), &ao->i_hog_pid);
636 if (err != noErr)
638 ao_msg(MSGT_AO, MSGL_WARN, "failed to set hogmode: [%4.4s]\n", (char *)&err);
639 ao->i_hog_pid = -1;
640 goto err_out;
643 /* Set mixable to false if we are allowed to. */
644 err = IsAudioPropertySettable(ao->i_selected_dev,
645 kAudioDevicePropertySupportsMixing,
646 &b_writeable);
647 err = GetAudioProperty(ao->i_selected_dev,
648 kAudioDevicePropertySupportsMixing,
649 sizeof(UInt32), &b_mix);
650 if (err != noErr && b_writeable)
652 b_mix = 0;
653 err = SetAudioProperty(ao->i_selected_dev,
654 kAudioDevicePropertySupportsMixing,
655 sizeof(UInt32), &b_mix);
656 ao->b_changed_mixing = 1;
658 if (err != noErr)
660 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
661 goto err_out;
664 /* Get a list of all the streams on this device. */
665 i_param_size = GetAudioPropertyArray(ao->i_selected_dev,
666 kAudioDevicePropertyStreams,
667 kAudioDevicePropertyScopeOutput,
668 (void **)&p_streams);
670 if (!i_param_size) {
671 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams.\n");
672 goto err_out;
675 i_streams = i_param_size / sizeof(AudioStreamID);
677 ao_msg(MSGT_AO, MSGL_V, "current device stream number: %d\n", i_streams);
679 for (i = 0; i < i_streams && ao->i_stream_index < 0; ++i)
681 /* Find a stream with a cac3 stream. */
682 AudioStreamBasicDescription *p_format_list = NULL;
683 int i_formats = 0, j = 0, b_digital = 0;
685 i_param_size = GetGlobalAudioPropertyArray(p_streams[i],
686 kAudioStreamPropertyPhysicalFormats,
687 (void **)&p_format_list);
689 if (!i_param_size) {
690 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streamformats.\n");
691 continue;
694 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
696 /* Check if one of the supported formats is a digital format. */
697 for (j = 0; j < i_formats; ++j)
699 if (p_format_list[j].mFormatID == 'IAC3' ||
700 p_format_list[j].mFormatID == kAudioFormat60958AC3)
702 b_digital = 1;
703 break;
707 if (b_digital)
709 /* If this stream supports a digital (cac3) format, then set it. */
710 int i_requested_rate_format = -1;
711 int i_current_rate_format = -1;
712 int i_backup_rate_format = -1;
714 ao->i_stream_id = p_streams[i];
715 ao->i_stream_index = i;
717 if (ao->b_revert == 0)
719 /* Retrieve the original format of this stream first if not done so already. */
720 err = GetAudioProperty(ao->i_stream_id,
721 kAudioStreamPropertyPhysicalFormat,
722 sizeof(ao->sfmt_revert), &ao->sfmt_revert);
723 if (err != noErr)
725 ao_msg(MSGT_AO, MSGL_WARN, "could not retrieve the original streamformat: [%4.4s]\n", (char *)&err);
726 if (p_format_list) free(p_format_list);
727 continue;
729 ao->b_revert = 1;
732 for (j = 0; j < i_formats; ++j)
733 if (p_format_list[j].mFormatID == 'IAC3' ||
734 p_format_list[j].mFormatID == kAudioFormat60958AC3)
736 if (p_format_list[j].mSampleRate == ao->stream_format.mSampleRate)
738 i_requested_rate_format = j;
739 break;
741 if (p_format_list[j].mSampleRate == ao->sfmt_revert.mSampleRate)
742 i_current_rate_format = j;
743 else if (i_backup_rate_format < 0 || p_format_list[j].mSampleRate > p_format_list[i_backup_rate_format].mSampleRate)
744 i_backup_rate_format = j;
747 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio. */
748 ao->stream_format = p_format_list[i_requested_rate_format];
749 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device. */
750 ao->stream_format = p_format_list[i_current_rate_format];
751 else ao->stream_format = p_format_list[i_backup_rate_format]; /* And if we have to, any digital format will be just fine (highest rate possible). */
753 if (p_format_list) free(p_format_list);
755 if (p_streams) free(p_streams);
757 if (ao->i_stream_index < 0)
759 ao_msg(MSGT_AO, MSGL_WARN, "can not find any digital output stream format when OpenSPDIF().\n");
760 goto err_out;
763 print_format(MSGL_V, "original stream format:", &ao->sfmt_revert);
765 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
766 goto err_out;
768 property_address.mSelector = kAudioDevicePropertyDeviceHasChanged;
769 property_address.mScope = kAudioObjectPropertyScopeGlobal;
770 property_address.mElement = kAudioObjectPropertyElementMaster;
772 err = AudioObjectAddPropertyListener(ao->i_selected_dev,
773 &property_address,
774 DeviceListener,
775 NULL);
776 if (err != noErr)
777 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err);
780 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
781 /* Although there's no such case reported. */
782 #if HAVE_BIGENDIAN
783 if (!(ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian))
784 #else
785 if (ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
786 #endif
787 ao_msg(MSGT_AO, MSGL_WARN, "output stream has a no-native byte-order, digital output may failed.\n");
789 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
790 ao->chunk_size = ao->stream_format.mBytesPerPacket;
792 ao_data.samplerate = ao->stream_format.mSampleRate;
793 ao_data.channels = ao->stream_format.mChannelsPerFrame;
794 ao_data.bps = ao_data.samplerate * (ao->stream_format.mBytesPerPacket/ao->stream_format.mFramesPerPacket);
795 ao_data.outburst = ao->chunk_size;
796 ao_data.buffersize = ao_data.bps;
798 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
799 ao->buffer_len = ao->num_chunks * ao->chunk_size;
800 ao->buffer = av_fifo_alloc(ao->buffer_len);
802 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);
805 /* Create IOProc callback. */
806 err = AudioDeviceCreateIOProcID(ao->i_selected_dev,
807 (AudioDeviceIOProc)RenderCallbackSPDIF,
808 (void *)ao,
809 &ao->renderCallback);
811 if (err != noErr || ao->renderCallback == NULL)
813 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err);
814 goto err_out1;
817 reset();
819 return CONTROL_TRUE;
821 err_out1:
822 if (ao->b_revert)
823 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
824 err_out:
825 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
827 int b_mix = 1;
828 err = SetAudioProperty(ao->i_selected_dev,
829 kAudioDevicePropertySupportsMixing,
830 sizeof(int), &b_mix);
831 if (err != noErr)
832 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n",
833 (char *)&err);
835 if (ao->i_hog_pid == getpid())
837 ao->i_hog_pid = -1;
838 err = SetAudioProperty(ao->i_selected_dev,
839 kAudioDevicePropertyHogMode,
840 sizeof(ao->i_hog_pid), &ao->i_hog_pid);
841 if (err != noErr)
842 ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n",
843 (char *)&err);
845 av_fifo_free(ao->buffer);
846 free(ao);
847 ao = NULL;
848 return CONTROL_FALSE;
851 /*****************************************************************************
852 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
853 *****************************************************************************/
854 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id )
856 UInt32 i_param_size = 0;
857 AudioStreamID *p_streams = NULL;
858 int i = 0, i_streams = 0;
859 int b_return = CONTROL_FALSE;
861 /* Retrieve all the output streams. */
862 i_param_size = GetAudioPropertyArray(i_dev_id,
863 kAudioDevicePropertyStreams,
864 kAudioDevicePropertyScopeOutput,
865 (void **)&p_streams);
867 if (!i_param_size) {
868 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams.\n");
869 return CONTROL_FALSE;
872 i_streams = i_param_size / sizeof(AudioStreamID);
874 for (i = 0; i < i_streams; ++i)
876 if (AudioStreamSupportsDigital(p_streams[i]))
877 b_return = CONTROL_OK;
880 free(p_streams);
881 return b_return;
884 /*****************************************************************************
885 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
886 *****************************************************************************/
887 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id )
889 UInt32 i_param_size;
890 AudioStreamBasicDescription *p_format_list = NULL;
891 int i, i_formats, b_return = CONTROL_FALSE;
893 /* Retrieve all the stream formats supported by each output stream. */
894 i_param_size = GetGlobalAudioPropertyArray(i_stream_id,
895 kAudioStreamPropertyPhysicalFormats,
896 (void **)&p_format_list);
898 if (!i_param_size) {
899 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streamformats.\n");
900 return CONTROL_FALSE;
903 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
905 for (i = 0; i < i_formats; ++i)
907 print_format(MSGL_V, "supported format:", &p_format_list[i]);
909 if (p_format_list[i].mFormatID == 'IAC3' ||
910 p_format_list[i].mFormatID == kAudioFormat60958AC3)
911 b_return = CONTROL_OK;
914 free(p_format_list);
915 return b_return;
918 /*****************************************************************************
919 * AudioStreamChangeFormat: Change i_stream_id to change_format
920 *****************************************************************************/
921 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format )
923 OSStatus err = noErr;
924 int i;
925 AudioObjectPropertyAddress property_address;
927 static volatile int stream_format_changed;
928 stream_format_changed = 0;
930 print_format(MSGL_V, "setting stream format:", &change_format);
932 /* Install the callback. */
933 property_address.mSelector = kAudioStreamPropertyPhysicalFormat;
934 property_address.mScope = kAudioObjectPropertyScopeGlobal;
935 property_address.mElement = kAudioObjectPropertyElementMaster;
937 err = AudioObjectAddPropertyListener(i_stream_id,
938 &property_address,
939 StreamListener,
940 (void *)&stream_format_changed);
941 if (err != noErr)
943 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err);
944 return CONTROL_FALSE;
947 /* Change the format. */
948 err = SetAudioProperty(i_stream_id,
949 kAudioStreamPropertyPhysicalFormat,
950 sizeof(AudioStreamBasicDescription), &change_format);
951 if (err != noErr)
953 ao_msg(MSGT_AO, MSGL_WARN, "could not set the stream format: [%4.4s]\n", (char *)&err);
954 return CONTROL_FALSE;
957 /* The AudioStreamSetProperty is not only asynchronious,
958 * it is also not Atomic, in its behaviour.
959 * Therefore we check 5 times before we really give up.
960 * FIXME: failing isn't actually implemented yet. */
961 for (i = 0; i < 5; ++i)
963 AudioStreamBasicDescription actual_format;
964 int j;
965 for (j = 0; !stream_format_changed && j < 50; ++j)
966 usec_sleep(10000);
967 if (stream_format_changed)
968 stream_format_changed = 0;
969 else
970 ao_msg(MSGT_AO, MSGL_V, "reached timeout\n" );
972 err = GetAudioProperty(i_stream_id,
973 kAudioStreamPropertyPhysicalFormat,
974 sizeof(AudioStreamBasicDescription), &actual_format);
976 print_format(MSGL_V, "actual format in use:", &actual_format);
977 if (actual_format.mSampleRate == change_format.mSampleRate &&
978 actual_format.mFormatID == change_format.mFormatID &&
979 actual_format.mFramesPerPacket == change_format.mFramesPerPacket)
981 /* The right format is now active. */
982 break;
984 /* We need to check again. */
987 /* Removing the property listener. */
988 err = AudioObjectRemovePropertyListener(i_stream_id,
989 &property_address,
990 StreamListener,
991 (void *)&stream_format_changed);
992 if (err != noErr)
994 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err);
995 return CONTROL_FALSE;
998 return CONTROL_TRUE;
1001 /*****************************************************************************
1002 * RenderCallbackSPDIF: callback for SPDIF audio output
1003 *****************************************************************************/
1004 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
1005 const AudioTimeStamp * inNow,
1006 const void * inInputData,
1007 const AudioTimeStamp * inInputTime,
1008 AudioBufferList * outOutputData,
1009 const AudioTimeStamp * inOutputTime,
1010 void * threadGlobals )
1012 int amt = av_fifo_size(ao->buffer);
1013 int req = outOutputData->mBuffers[ao->i_stream_index].mDataByteSize;
1015 if (amt > req)
1016 amt = req;
1017 if (amt)
1018 read_buffer(ao->b_muted ? NULL : (unsigned char *)outOutputData->mBuffers[ao->i_stream_index].mData, amt);
1020 return noErr;
1024 static int play(void* output_samples,int num_bytes,int flags)
1026 int wrote, b_digital;
1027 SInt32 exit_reason;
1029 // Check whether we need to reset the digital output stream.
1030 if (ao->b_digital && ao->b_stream_format_changed)
1032 ao->b_stream_format_changed = 0;
1033 b_digital = AudioStreamSupportsDigital(ao->i_stream_id);
1034 if (b_digital)
1036 /* Current stream support digital format output, let's set it. */
1037 ao_msg(MSGT_AO, MSGL_V, "detected current stream support digital, try to restore digital output...\n");
1039 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
1041 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output failed.\n");
1043 else
1045 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output succeed.\n");
1046 reset();
1049 else
1050 ao_msg(MSGT_AO, MSGL_V, "detected current stream do not support digital.\n");
1053 wrote=write_buffer(output_samples, num_bytes);
1054 audio_resume();
1056 do {
1057 exit_reason = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true);
1058 } while (exit_reason == kCFRunLoopRunHandledSource);
1060 return wrote;
1063 /* set variables and buffer to initial state */
1064 static void reset(void)
1066 audio_pause();
1067 av_fifo_reset(ao->buffer);
1071 /* return available space */
1072 static int get_space(void)
1074 return ao->buffer_len - av_fifo_size(ao->buffer);
1078 /* return delay until audio is played */
1079 static float get_delay(void)
1081 // inaccurate, should also contain the data buffered e.g. by the OS
1082 return (float)av_fifo_size(ao->buffer)/(float)ao_data.bps;
1086 /* unload plugin and deregister from coreaudio */
1087 static void uninit(int immed)
1089 OSStatus err = noErr;
1091 if (!immed) {
1092 long long timeleft=(1000000LL*av_fifo_size(ao->buffer))/ao_data.bps;
1093 ao_msg(MSGT_AO,MSGL_DBG2, "%d bytes left @%d bps (%d usec)\n", av_fifo_size(ao->buffer), ao_data.bps, (int)timeleft);
1094 usec_sleep((int)timeleft);
1097 if (!ao->b_digital) {
1098 AudioOutputUnitStop(ao->theOutputUnit);
1099 AudioUnitUninitialize(ao->theOutputUnit);
1100 CloseComponent(ao->theOutputUnit);
1102 else {
1103 /* Stop device. */
1104 err = AudioDeviceStop(ao->i_selected_dev, ao->renderCallback);
1105 if (err != noErr)
1106 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1108 /* Remove IOProc callback. */
1109 err = AudioDeviceDestroyIOProcID(ao->i_selected_dev, ao->renderCallback);
1110 if (err != noErr)
1111 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err);
1113 if (ao->b_revert)
1114 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
1116 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
1118 UInt32 b_mix;
1119 Boolean b_writeable;
1120 /* Revert mixable to true if we are allowed to. */
1121 err = IsAudioPropertySettable(ao->i_selected_dev,
1122 kAudioDevicePropertySupportsMixing,
1123 &b_writeable);
1124 err = GetAudioProperty(ao->i_selected_dev,
1125 kAudioDevicePropertySupportsMixing,
1126 sizeof(UInt32), &b_mix);
1127 if (err != noErr && b_writeable)
1129 b_mix = 1;
1130 err = SetAudioProperty(ao->i_selected_dev,
1131 kAudioDevicePropertySupportsMixing,
1132 sizeof(UInt32), &b_mix);
1134 if (err != noErr)
1135 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
1137 if (ao->i_hog_pid == getpid())
1139 ao->i_hog_pid = -1;
1140 err = SetAudioProperty(ao->i_selected_dev,
1141 kAudioDevicePropertyHogMode,
1142 sizeof(ao->i_hog_pid), &ao->i_hog_pid);
1143 if (err != noErr) ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n", (char *)&err);
1147 av_fifo_free(ao->buffer);
1148 free(ao);
1149 ao = NULL;
1153 /* stop playing, keep buffers (for pause) */
1154 static void audio_pause(void)
1156 OSErr err=noErr;
1158 /* Stop callback. */
1159 if (!ao->b_digital)
1161 err=AudioOutputUnitStop(ao->theOutputUnit);
1162 if (err != noErr)
1163 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err);
1165 else
1167 err = AudioDeviceStop(ao->i_selected_dev, ao->renderCallback);
1168 if (err != noErr)
1169 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1171 ao->paused = 1;
1175 /* resume playing, after audio_pause() */
1176 static void audio_resume(void)
1178 OSErr err=noErr;
1180 if (!ao->paused)
1181 return;
1183 /* Start callback. */
1184 if (!ao->b_digital)
1186 err = AudioOutputUnitStart(ao->theOutputUnit);
1187 if (err != noErr)
1188 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err);
1190 else
1192 err = AudioDeviceStart(ao->i_selected_dev, ao->renderCallback);
1193 if (err != noErr)
1194 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err);
1196 ao->paused = 0;
1199 /*****************************************************************************
1200 * StreamListener
1201 *****************************************************************************/
1202 static OSStatus StreamListener( AudioObjectID inObjectID,
1203 UInt32 inNumberAddresses,
1204 const AudioObjectPropertyAddress inAddresses[],
1205 void *inClientData )
1207 for (int i=0; i < inNumberAddresses; ++i)
1209 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1210 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1211 if (inClientData)
1212 *(volatile int *)inClientData = 1;
1213 break;
1216 return noErr;
1219 static OSStatus DeviceListener( AudioObjectID inObjectID,
1220 UInt32 inNumberAddresses,
1221 const AudioObjectPropertyAddress inAddresses[],
1222 void *inClientData )
1224 for (int i=0; i < inNumberAddresses; ++i)
1226 if (inAddresses[i].mSelector == kAudioDevicePropertyDeviceHasChanged) {
1227 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1228 ao->b_stream_format_changed = 1;
1229 break;
1232 return noErr;