subs: move text sub loading logic down to find_subfiles.c
[mplayer/greg.git] / libao2 / ao_coreaudio.c
blobcf43800659114f1ae9a02c0e3c3b5f592316efda
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 #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,
78 void *data,
79 AudioDeviceIOProcID *procid)
81 *procid = proc;
82 return AudioDeviceAddIOProc(dev, proc, data);
84 #endif
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 */
95 /* AudioUnit */
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 */
109 int packetSize;
110 int paused;
112 /* Ring-buffer */
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;
117 } ao_coreaudio_t;
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;
136 av_fifo_generic_read(ao->buffer, data, len, NULL);
137 return len;
140 static OSStatus theRenderProc(void *inRefCon,
141 AudioUnitRenderActionFlags *inActionFlags,
142 const AudioTimeStamp *inTimeStamp,
143 UInt32 inBusNumber, UInt32 inNumFrames,
144 AudioBufferList *ioData)
146 int amt=av_fifo_size(ao->buffer);
147 int req=(inNumFrames)*ao->packetSize;
149 if(amt>req)
150 amt=req;
152 if(amt)
153 read_buffer((unsigned char *)ioData->mBuffers[0].mData, amt);
154 else audio_pause();
155 ioData->mBuffers[0].mDataByteSize = amt;
157 return noErr;
160 static int control(int cmd,void *arg){
161 ao_control_vol_t *control_vol;
162 OSStatus err;
163 Float32 vol;
164 switch (cmd) {
165 case AOCONTROL_GET_VOLUME:
166 control_vol = (ao_control_vol_t*)arg;
167 if (ao->b_digital) {
168 // Digital output has no volume adjust.
169 return CONTROL_FALSE;
171 err = AudioUnitGetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, &vol);
173 if(err==0) {
174 // printf("GET VOL=%f\n", vol);
175 control_vol->left=control_vol->right=vol*100.0/4.0;
176 return CONTROL_TRUE;
178 else {
179 ao_msg(MSGT_AO, MSGL_WARN, "could not get HAL output volume: [%4.4s]\n", (char *)&err);
180 return CONTROL_FALSE;
183 case AOCONTROL_SET_VOLUME:
184 control_vol = (ao_control_vol_t*)arg;
186 if (ao->b_digital) {
187 // Digital output can not set volume. Here we have to return true
188 // to make mixer forget it. Else mixer will add a soft filter,
189 // that's not we expected and the filter not support ac3 stream
190 // will cause mplayer die.
192 // Although not support set volume, but at least we support mute.
193 // MPlayer set mute by set volume to zero, we handle it.
194 if (control_vol->left == 0 && control_vol->right == 0)
195 ao->b_muted = 1;
196 else
197 ao->b_muted = 0;
198 return CONTROL_TRUE;
201 vol=(control_vol->left+control_vol->right)*4.0/200.0;
202 err = AudioUnitSetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, vol, 0);
203 if(err==0) {
204 // printf("SET VOL=%f\n", vol);
205 return CONTROL_TRUE;
207 else {
208 ao_msg(MSGT_AO, MSGL_WARN, "could not set HAL output volume: [%4.4s]\n", (char *)&err);
209 return CONTROL_FALSE;
211 /* Everything is currently unimplemented */
212 default:
213 return CONTROL_FALSE;
219 static void print_format(int lev, const char* str, const AudioStreamBasicDescription *f){
220 uint32_t flags=(uint32_t) f->mFormatFlags;
221 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",
222 str, f->mSampleRate, f->mBitsPerChannel,
223 (int)(f->mFormatID & 0xff000000) >> 24,
224 (int)(f->mFormatID & 0x00ff0000) >> 16,
225 (int)(f->mFormatID & 0x0000ff00) >> 8,
226 (int)(f->mFormatID & 0x000000ff) >> 0,
227 f->mFormatFlags, f->mBytesPerPacket,
228 f->mFramesPerPacket, f->mBytesPerFrame,
229 f->mChannelsPerFrame,
230 (flags&kAudioFormatFlagIsFloat) ? "float" : "int",
231 (flags&kAudioFormatFlagIsBigEndian) ? "BE" : "LE",
232 (flags&kAudioFormatFlagIsSignedInteger) ? "S" : "U",
233 (flags&kAudioFormatFlagIsPacked) ? " packed" : "",
234 (flags&kAudioFormatFlagIsAlignedHigh) ? " aligned" : "",
235 (flags&kAudioFormatFlagIsNonInterleaved) ? " ni" : "" );
238 static OSStatus GetAudioProperty(AudioObjectID id,
239 AudioObjectPropertySelector selector,
240 UInt32 outSize, void *outData)
242 AudioObjectPropertyAddress property_address;
244 property_address.mSelector = selector;
245 property_address.mScope = kAudioObjectPropertyScopeGlobal;
246 property_address.mElement = kAudioObjectPropertyElementMaster;
248 return AudioObjectGetPropertyData(id, &property_address, 0, NULL, &outSize, outData);
251 static UInt32 GetAudioPropertyArray(AudioObjectID id,
252 AudioObjectPropertySelector selector,
253 AudioObjectPropertyScope scope,
254 void **outData)
256 OSStatus err;
257 AudioObjectPropertyAddress property_address;
258 UInt32 i_param_size;
260 property_address.mSelector = selector;
261 property_address.mScope = scope;
262 property_address.mElement = kAudioObjectPropertyElementMaster;
264 err = AudioObjectGetPropertyDataSize(id, &property_address, 0, NULL, &i_param_size);
266 if (err != noErr)
267 return 0;
269 *outData = malloc(i_param_size);
272 err = AudioObjectGetPropertyData(id, &property_address, 0, NULL, &i_param_size, *outData);
274 if (err != noErr) {
275 free(*outData);
276 return 0;
279 return i_param_size;
282 static UInt32 GetGlobalAudioPropertyArray(AudioObjectID id,
283 AudioObjectPropertySelector selector,
284 void **outData)
286 return GetAudioPropertyArray(id, selector, kAudioObjectPropertyScopeGlobal, outData);
289 static OSStatus GetAudioPropertyString(AudioObjectID id,
290 AudioObjectPropertySelector selector,
291 char **outData)
293 OSStatus err;
294 AudioObjectPropertyAddress property_address;
295 UInt32 i_param_size;
296 CFStringRef string;
297 CFIndex string_length;
299 property_address.mSelector = selector;
300 property_address.mScope = kAudioObjectPropertyScopeGlobal;
301 property_address.mElement = kAudioObjectPropertyElementMaster;
303 i_param_size = sizeof(CFStringRef);
304 err = AudioObjectGetPropertyData(id, &property_address, 0, NULL, &i_param_size, &string);
305 if (err != noErr)
306 return err;
308 string_length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(string),
309 kCFStringEncodingASCII);
310 *outData = malloc(string_length + 1);
311 CFStringGetCString(string, *outData, string_length + 1, kCFStringEncodingASCII);
313 CFRelease(string);
315 return err;
318 static OSStatus SetAudioProperty(AudioObjectID id,
319 AudioObjectPropertySelector selector,
320 UInt32 inDataSize, void *inData)
322 AudioObjectPropertyAddress property_address;
324 property_address.mSelector = selector;
325 property_address.mScope = kAudioObjectPropertyScopeGlobal;
326 property_address.mElement = kAudioObjectPropertyElementMaster;
328 return AudioObjectSetPropertyData(id, &property_address, 0, NULL, inDataSize, inData);
331 static Boolean IsAudioPropertySettable(AudioObjectID id,
332 AudioObjectPropertySelector selector,
333 Boolean *outData)
335 AudioObjectPropertyAddress property_address;
337 property_address.mSelector = selector;
338 property_address.mScope = kAudioObjectPropertyScopeGlobal;
339 property_address.mElement = kAudioObjectPropertyElementMaster;
341 return AudioObjectIsPropertySettable(id, &property_address, outData);
344 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id );
345 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id );
346 static int OpenSPDIF(void);
347 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format );
348 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
349 const AudioTimeStamp * inNow,
350 const void * inInputData,
351 const AudioTimeStamp * inInputTime,
352 AudioBufferList * outOutputData,
353 const AudioTimeStamp * inOutputTime,
354 void * threadGlobals );
355 static OSStatus StreamListener( AudioObjectID inObjectID,
356 UInt32 inNumberAddresses,
357 const AudioObjectPropertyAddress inAddresses[],
358 void *inClientData );
359 static OSStatus DeviceListener( AudioObjectID inObjectID,
360 UInt32 inNumberAddresses,
361 const AudioObjectPropertyAddress inAddresses[],
362 void *inClientData );
364 static void print_help(void)
366 OSStatus err;
367 UInt32 i_param_size;
368 int num_devices;
369 AudioDeviceID *devids;
370 char *device_name;
372 mp_msg(MSGT_AO, MSGL_FATAL,
373 "\n-ao coreaudio commandline help:\n"
374 "Example: mplayer -ao coreaudio:device_id=266\n"
375 " open Core Audio with output device ID 266.\n"
376 "\nOptions:\n"
377 " device_id\n"
378 " ID of output device to use (0 = default device)\n"
379 " help\n"
380 " This help including list of available devices.\n"
381 "\n"
382 "Available output devices:\n");
384 i_param_size = GetGlobalAudioPropertyArray(kAudioObjectSystemObject, kAudioHardwarePropertyDevices, (void **)&devids);
386 if (!i_param_size) {
387 mp_msg(MSGT_AO, MSGL_FATAL, "Failed to get list of output devices.\n");
388 return;
391 num_devices = i_param_size / sizeof(AudioDeviceID);
393 for (int i = 0; i < num_devices; ++i) {
394 err = GetAudioPropertyString(devids[i], kAudioObjectPropertyName, &device_name);
396 if (err == noErr) {
397 mp_msg(MSGT_AO, MSGL_FATAL, "%s (id: %"PRIu32")\n", device_name, devids[i]);
398 free(device_name);
399 } else
400 mp_msg(MSGT_AO, MSGL_FATAL, "Unknown (id: %"PRIu32")\n", devids[i]);
403 mp_msg(MSGT_AO, MSGL_FATAL, "\n");
405 free(devids);
408 static int init(int rate,int channels,int format,int flags)
410 AudioStreamBasicDescription inDesc;
411 ComponentDescription desc;
412 Component comp;
413 AURenderCallbackStruct renderCallback;
414 OSStatus err;
415 UInt32 size, maxFrames, b_alive;
416 char *psz_name;
417 AudioDeviceID devid_def = 0;
418 int device_id, display_help = 0;
420 const opt_t subopts[] = {
421 {"device_id", OPT_ARG_INT, &device_id, NULL},
422 {"help", OPT_ARG_BOOL, &display_help, NULL},
423 {NULL}
426 // set defaults
427 device_id = 0;
429 if (subopt_parse(ao_subdevice, subopts) != 0 || display_help) {
430 print_help();
431 if (!display_help)
432 return 0;
435 ao_msg(MSGT_AO,MSGL_V, "init([%dHz][%dch][%s][%d])\n", rate, channels, af_fmt2str_short(format), flags);
437 ao = calloc(1, sizeof(ao_coreaudio_t));
439 ao->i_selected_dev = 0;
440 ao->b_supports_digital = 0;
441 ao->b_digital = 0;
442 ao->b_muted = 0;
443 ao->b_stream_format_changed = 0;
444 ao->i_hog_pid = -1;
445 ao->i_stream_id = 0;
446 ao->i_stream_index = -1;
447 ao->b_revert = 0;
448 ao->b_changed_mixing = 0;
450 if (device_id == 0) {
451 /* Find the ID of the default Device. */
452 err = GetAudioProperty(kAudioObjectSystemObject,
453 kAudioHardwarePropertyDefaultOutputDevice,
454 sizeof(UInt32), &devid_def);
455 if (err != noErr)
457 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device: [%4.4s]\n", (char *)&err);
458 goto err_out;
460 } else {
461 devid_def = device_id;
464 /* Retrieve the name of the device. */
465 err = GetAudioPropertyString(devid_def,
466 kAudioObjectPropertyName,
467 &psz_name);
468 if (err != noErr)
470 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name: [%4.4s]\n", (char *)&err);
471 goto err_out;
474 ao_msg(MSGT_AO,MSGL_V, "got audio output device ID: %"PRIu32" Name: %s\n", devid_def, psz_name );
476 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
477 if (AF_FORMAT_IS_AC3(format)) {
478 if (AudioDeviceSupportsDigital(devid_def))
480 ao->b_supports_digital = 1;
482 ao_msg(MSGT_AO, MSGL_V,
483 "probe default audio output device about support for digital s/pdif output: %d\n",
484 ao->b_supports_digital );
487 free(psz_name);
489 // Save selected device id
490 ao->i_selected_dev = devid_def;
492 // Build Description for the input format
493 inDesc.mSampleRate=rate;
494 inDesc.mFormatID=ao->b_supports_digital ? kAudioFormat60958AC3 : kAudioFormatLinearPCM;
495 inDesc.mChannelsPerFrame=channels;
496 inDesc.mBitsPerChannel=af_fmt2bits(format);
498 if((format&AF_FORMAT_POINT_MASK)==AF_FORMAT_F) {
499 // float
500 inDesc.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked;
502 else if((format&AF_FORMAT_SIGN_MASK)==AF_FORMAT_SI) {
503 // signed int
504 inDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger|kAudioFormatFlagIsPacked;
506 else {
507 // unsigned int
508 inDesc.mFormatFlags = kAudioFormatFlagIsPacked;
510 if ((format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
511 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
513 inDesc.mFramesPerPacket = 1;
514 ao->packetSize = inDesc.mBytesPerPacket = inDesc.mBytesPerFrame = inDesc.mFramesPerPacket*channels*(inDesc.mBitsPerChannel/8);
515 print_format(MSGL_V, "source:",&inDesc);
517 if (ao->b_supports_digital)
519 b_alive = 1;
520 err = GetAudioProperty(ao->i_selected_dev,
521 kAudioDevicePropertyDeviceIsAlive,
522 sizeof(UInt32), &b_alive);
523 if (err != noErr)
524 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is alive: [%4.4s]\n", (char *)&err);
525 if (!b_alive)
526 ao_msg(MSGT_AO, MSGL_WARN, "device is not alive\n" );
528 /* S/PDIF output need device in HogMode. */
529 err = GetAudioProperty(ao->i_selected_dev,
530 kAudioDevicePropertyHogMode,
531 sizeof(pid_t), &ao->i_hog_pid);
532 if (err != noErr)
534 /* This is not a fatal error. Some drivers simply don't support this property. */
535 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is hogged: [%4.4s]\n",
536 (char *)&err);
537 ao->i_hog_pid = -1;
540 if (ao->i_hog_pid != -1 && ao->i_hog_pid != getpid())
542 ao_msg(MSGT_AO, MSGL_WARN, "Selected audio device is exclusively in use by another program.\n" );
543 goto err_out;
545 ao->stream_format = inDesc;
546 return OpenSPDIF();
549 /* original analog output code */
550 desc.componentType = kAudioUnitType_Output;
551 desc.componentSubType = (device_id == 0) ? kAudioUnitSubType_DefaultOutput : kAudioUnitSubType_HALOutput;
552 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
553 desc.componentFlags = 0;
554 desc.componentFlagsMask = 0;
556 comp = FindNextComponent(NULL, &desc); //Finds an component that meets the desc spec's
557 if (comp == NULL) {
558 ao_msg(MSGT_AO, MSGL_WARN, "Unable to find Output Unit component\n");
559 goto err_out;
562 err = OpenAComponent(comp, &(ao->theOutputUnit)); //gains access to the services provided by the component
563 if (err) {
564 ao_msg(MSGT_AO, MSGL_WARN, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err);
565 goto err_out;
568 // Initialize AudioUnit
569 err = AudioUnitInitialize(ao->theOutputUnit);
570 if (err) {
571 ao_msg(MSGT_AO, MSGL_WARN, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err);
572 goto err_out1;
575 size = sizeof(AudioStreamBasicDescription);
576 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inDesc, size);
578 if (err) {
579 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the input format: [%4.4s]\n", (char *)&err);
580 goto err_out2;
583 size = sizeof(UInt32);
584 err = AudioUnitGetProperty(ao->theOutputUnit, kAudioDevicePropertyBufferSize, kAudioUnitScope_Input, 0, &maxFrames, &size);
586 if (err)
588 ao_msg(MSGT_AO,MSGL_WARN, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err);
589 goto err_out2;
592 //Set the Current Device to the Default Output Unit.
593 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &ao->i_selected_dev, sizeof(ao->i_selected_dev));
595 ao->chunk_size = maxFrames;//*inDesc.mBytesPerFrame;
597 ao_data.samplerate = inDesc.mSampleRate;
598 ao_data.channels = inDesc.mChannelsPerFrame;
599 ao_data.bps = ao_data.samplerate * inDesc.mBytesPerFrame;
600 ao_data.outburst = ao->chunk_size;
601 ao_data.buffersize = ao_data.bps;
603 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
604 ao->buffer_len = ao->num_chunks * ao->chunk_size;
605 ao->buffer = av_fifo_alloc(ao->buffer_len);
607 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);
609 renderCallback.inputProc = theRenderProc;
610 renderCallback.inputProcRefCon = 0;
611 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
612 if (err) {
613 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the render callback: [%4.4s]\n", (char *)&err);
614 goto err_out2;
617 reset();
619 return CONTROL_OK;
621 err_out2:
622 AudioUnitUninitialize(ao->theOutputUnit);
623 err_out1:
624 CloseComponent(ao->theOutputUnit);
625 err_out:
626 av_fifo_free(ao->buffer);
627 free(ao);
628 ao = NULL;
629 return CONTROL_FALSE;
632 /*****************************************************************************
633 * Setup a encoded digital stream (SPDIF)
634 *****************************************************************************/
635 static int OpenSPDIF(void)
637 OSStatus err = noErr;
638 UInt32 i_param_size, b_mix = 0;
639 Boolean b_writeable = 0;
640 AudioStreamID *p_streams = NULL;
641 int i, i_streams = 0;
642 AudioObjectPropertyAddress property_address;
644 /* Start doing the SPDIF setup process. */
645 ao->b_digital = 1;
647 /* Hog the device. */
648 ao->i_hog_pid = getpid() ;
650 err = SetAudioProperty(ao->i_selected_dev,
651 kAudioDevicePropertyHogMode,
652 sizeof(ao->i_hog_pid), &ao->i_hog_pid);
653 if (err != noErr)
655 ao_msg(MSGT_AO, MSGL_WARN, "failed to set hogmode: [%4.4s]\n", (char *)&err);
656 ao->i_hog_pid = -1;
657 goto err_out;
660 /* Set mixable to false if we are allowed to. */
661 err = IsAudioPropertySettable(ao->i_selected_dev,
662 kAudioDevicePropertySupportsMixing,
663 &b_writeable);
664 err = GetAudioProperty(ao->i_selected_dev,
665 kAudioDevicePropertySupportsMixing,
666 sizeof(UInt32), &b_mix);
667 if (err != noErr && b_writeable)
669 b_mix = 0;
670 err = SetAudioProperty(ao->i_selected_dev,
671 kAudioDevicePropertySupportsMixing,
672 sizeof(UInt32), &b_mix);
673 ao->b_changed_mixing = 1;
675 if (err != noErr)
677 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
678 goto err_out;
681 /* Get a list of all the streams on this device. */
682 i_param_size = GetAudioPropertyArray(ao->i_selected_dev,
683 kAudioDevicePropertyStreams,
684 kAudioDevicePropertyScopeOutput,
685 (void **)&p_streams);
687 if (!i_param_size) {
688 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams.\n");
689 goto err_out;
692 i_streams = i_param_size / sizeof(AudioStreamID);
694 ao_msg(MSGT_AO, MSGL_V, "current device stream number: %d\n", i_streams);
696 for (i = 0; i < i_streams && ao->i_stream_index < 0; ++i)
698 /* Find a stream with a cac3 stream. */
699 AudioStreamBasicDescription *p_format_list = NULL;
700 int i_formats = 0, j = 0, b_digital = 0;
702 i_param_size = GetGlobalAudioPropertyArray(p_streams[i],
703 kAudioStreamPropertyPhysicalFormats,
704 (void **)&p_format_list);
706 if (!i_param_size) {
707 ao_msg(MSGT_AO, MSGL_WARN,
708 "Could not get number of stream formats.\n");
709 continue;
712 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
714 /* Check if one of the supported formats is a digital format. */
715 for (j = 0; j < i_formats; ++j)
717 if (p_format_list[j].mFormatID == 'IAC3' ||
718 p_format_list[j].mFormatID == kAudioFormat60958AC3)
720 b_digital = 1;
721 break;
725 if (b_digital)
727 /* If this stream supports a digital (cac3) format, then set it. */
728 int i_requested_rate_format = -1;
729 int i_current_rate_format = -1;
730 int i_backup_rate_format = -1;
732 ao->i_stream_id = p_streams[i];
733 ao->i_stream_index = i;
735 if (ao->b_revert == 0)
737 /* Retrieve the original format of this stream first if not done so already. */
738 err = GetAudioProperty(ao->i_stream_id,
739 kAudioStreamPropertyPhysicalFormat,
740 sizeof(ao->sfmt_revert), &ao->sfmt_revert);
741 if (err != noErr)
743 ao_msg(MSGT_AO, MSGL_WARN,
744 "Could not retrieve the original stream format: [%4.4s]\n",
745 (char *)&err);
746 free(p_format_list);
747 continue;
749 ao->b_revert = 1;
752 for (j = 0; j < i_formats; ++j)
753 if (p_format_list[j].mFormatID == 'IAC3' ||
754 p_format_list[j].mFormatID == kAudioFormat60958AC3)
756 if (p_format_list[j].mSampleRate == ao->stream_format.mSampleRate)
758 i_requested_rate_format = j;
759 break;
761 if (p_format_list[j].mSampleRate == ao->sfmt_revert.mSampleRate)
762 i_current_rate_format = j;
763 else if (i_backup_rate_format < 0 || p_format_list[j].mSampleRate > p_format_list[i_backup_rate_format].mSampleRate)
764 i_backup_rate_format = j;
767 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio. */
768 ao->stream_format = p_format_list[i_requested_rate_format];
769 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device. */
770 ao->stream_format = p_format_list[i_current_rate_format];
771 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). */
773 free(p_format_list);
775 free(p_streams);
777 if (ao->i_stream_index < 0)
779 ao_msg(MSGT_AO, MSGL_WARN,
780 "Cannot find any digital output stream format when OpenSPDIF().\n");
781 goto err_out;
784 print_format(MSGL_V, "original stream format:", &ao->sfmt_revert);
786 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
787 goto err_out;
789 property_address.mSelector = kAudioDevicePropertyDeviceHasChanged;
790 property_address.mScope = kAudioObjectPropertyScopeGlobal;
791 property_address.mElement = kAudioObjectPropertyElementMaster;
793 err = AudioObjectAddPropertyListener(ao->i_selected_dev,
794 &property_address,
795 DeviceListener,
796 NULL);
797 if (err != noErr)
798 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err);
801 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
802 /* Although there's no such case reported. */
803 #if HAVE_BIGENDIAN
804 if (!(ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian))
805 #else
806 /* tell mplayer that we need a byteswap on AC3 streams, */
807 if (ao->stream_format.mFormatID & kAudioFormat60958AC3)
808 ao_data.format = AF_FORMAT_AC3_LE;
810 if (ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
811 #endif
812 ao_msg(MSGT_AO, MSGL_WARN,
813 "Output stream has non-native byte order, digital output may fail.\n");
815 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
816 ao->chunk_size = ao->stream_format.mBytesPerPacket;
818 ao_data.samplerate = ao->stream_format.mSampleRate;
819 ao_data.channels = ao->stream_format.mChannelsPerFrame;
820 ao_data.bps = ao_data.samplerate * (ao->stream_format.mBytesPerPacket/ao->stream_format.mFramesPerPacket);
821 ao_data.outburst = ao->chunk_size;
822 ao_data.buffersize = ao_data.bps;
824 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
825 ao->buffer_len = ao->num_chunks * ao->chunk_size;
826 ao->buffer = av_fifo_alloc(ao->buffer_len);
828 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);
831 /* Create IOProc callback. */
832 err = AudioDeviceCreateIOProcID(ao->i_selected_dev,
833 (AudioDeviceIOProc)RenderCallbackSPDIF,
834 (void *)ao,
835 &ao->renderCallback);
837 if (err != noErr || ao->renderCallback == NULL)
839 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err);
840 goto err_out1;
843 reset();
845 return CONTROL_TRUE;
847 err_out1:
848 if (ao->b_revert)
849 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
850 err_out:
851 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
853 int b_mix = 1;
854 err = SetAudioProperty(ao->i_selected_dev,
855 kAudioDevicePropertySupportsMixing,
856 sizeof(int), &b_mix);
857 if (err != noErr)
858 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n",
859 (char *)&err);
861 if (ao->i_hog_pid == getpid())
863 ao->i_hog_pid = -1;
864 err = SetAudioProperty(ao->i_selected_dev,
865 kAudioDevicePropertyHogMode,
866 sizeof(ao->i_hog_pid), &ao->i_hog_pid);
867 if (err != noErr)
868 ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n",
869 (char *)&err);
871 av_fifo_free(ao->buffer);
872 free(ao);
873 ao = NULL;
874 return CONTROL_FALSE;
877 /*****************************************************************************
878 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
879 *****************************************************************************/
880 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id )
882 UInt32 i_param_size = 0;
883 AudioStreamID *p_streams = NULL;
884 int i = 0, i_streams = 0;
885 int b_return = CONTROL_FALSE;
887 /* Retrieve all the output streams. */
888 i_param_size = GetAudioPropertyArray(i_dev_id,
889 kAudioDevicePropertyStreams,
890 kAudioDevicePropertyScopeOutput,
891 (void **)&p_streams);
893 if (!i_param_size) {
894 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams.\n");
895 return CONTROL_FALSE;
898 i_streams = i_param_size / sizeof(AudioStreamID);
900 for (i = 0; i < i_streams; ++i)
902 if (AudioStreamSupportsDigital(p_streams[i]))
903 b_return = CONTROL_OK;
906 free(p_streams);
907 return b_return;
910 /*****************************************************************************
911 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
912 *****************************************************************************/
913 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id )
915 UInt32 i_param_size;
916 AudioStreamBasicDescription *p_format_list = NULL;
917 int i, i_formats, b_return = CONTROL_FALSE;
919 /* Retrieve all the stream formats supported by each output stream. */
920 i_param_size = GetGlobalAudioPropertyArray(i_stream_id,
921 kAudioStreamPropertyPhysicalFormats,
922 (void **)&p_format_list);
924 if (!i_param_size) {
925 ao_msg(MSGT_AO, MSGL_WARN, "Could not get number of stream formats.\n");
926 return CONTROL_FALSE;
929 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
931 for (i = 0; i < i_formats; ++i)
933 print_format(MSGL_V, "supported format:", &p_format_list[i]);
935 if (p_format_list[i].mFormatID == 'IAC3' ||
936 p_format_list[i].mFormatID == kAudioFormat60958AC3)
937 b_return = CONTROL_OK;
940 free(p_format_list);
941 return b_return;
944 /*****************************************************************************
945 * AudioStreamChangeFormat: Change i_stream_id to change_format
946 *****************************************************************************/
947 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format )
949 OSStatus err = noErr;
950 int i;
951 AudioObjectPropertyAddress property_address;
953 static volatile int stream_format_changed;
954 stream_format_changed = 0;
956 print_format(MSGL_V, "setting stream format:", &change_format);
958 /* Install the callback. */
959 property_address.mSelector = kAudioStreamPropertyPhysicalFormat;
960 property_address.mScope = kAudioObjectPropertyScopeGlobal;
961 property_address.mElement = kAudioObjectPropertyElementMaster;
963 err = AudioObjectAddPropertyListener(i_stream_id,
964 &property_address,
965 StreamListener,
966 (void *)&stream_format_changed);
967 if (err != noErr)
969 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err);
970 return CONTROL_FALSE;
973 /* Change the format. */
974 err = SetAudioProperty(i_stream_id,
975 kAudioStreamPropertyPhysicalFormat,
976 sizeof(AudioStreamBasicDescription), &change_format);
977 if (err != noErr)
979 ao_msg(MSGT_AO, MSGL_WARN, "could not set the stream format: [%4.4s]\n", (char *)&err);
980 return CONTROL_FALSE;
983 /* The AudioStreamSetProperty is not only asynchronious,
984 * it is also not Atomic, in its behaviour.
985 * Therefore we check 5 times before we really give up.
986 * FIXME: failing isn't actually implemented yet. */
987 for (i = 0; i < 5; ++i)
989 AudioStreamBasicDescription actual_format;
990 int j;
991 for (j = 0; !stream_format_changed && j < 50; ++j)
992 usec_sleep(10000);
993 if (stream_format_changed)
994 stream_format_changed = 0;
995 else
996 ao_msg(MSGT_AO, MSGL_V, "reached timeout\n" );
998 err = GetAudioProperty(i_stream_id,
999 kAudioStreamPropertyPhysicalFormat,
1000 sizeof(AudioStreamBasicDescription), &actual_format);
1002 print_format(MSGL_V, "actual format in use:", &actual_format);
1003 if (actual_format.mSampleRate == change_format.mSampleRate &&
1004 actual_format.mFormatID == change_format.mFormatID &&
1005 actual_format.mFramesPerPacket == change_format.mFramesPerPacket)
1007 /* The right format is now active. */
1008 break;
1010 /* We need to check again. */
1013 /* Removing the property listener. */
1014 err = AudioObjectRemovePropertyListener(i_stream_id,
1015 &property_address,
1016 StreamListener,
1017 (void *)&stream_format_changed);
1018 if (err != noErr)
1020 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err);
1021 return CONTROL_FALSE;
1024 return CONTROL_TRUE;
1027 /*****************************************************************************
1028 * RenderCallbackSPDIF: callback for SPDIF audio output
1029 *****************************************************************************/
1030 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
1031 const AudioTimeStamp * inNow,
1032 const void * inInputData,
1033 const AudioTimeStamp * inInputTime,
1034 AudioBufferList * outOutputData,
1035 const AudioTimeStamp * inOutputTime,
1036 void * threadGlobals )
1038 int amt = av_fifo_size(ao->buffer);
1039 int req = outOutputData->mBuffers[ao->i_stream_index].mDataByteSize;
1041 if (amt > req)
1042 amt = req;
1043 if (amt)
1044 read_buffer(ao->b_muted ? NULL : (unsigned char *)outOutputData->mBuffers[ao->i_stream_index].mData, amt);
1046 return noErr;
1050 static int play(void* output_samples,int num_bytes,int flags)
1052 int wrote, b_digital;
1053 SInt32 exit_reason;
1055 // Check whether we need to reset the digital output stream.
1056 if (ao->b_digital && ao->b_stream_format_changed)
1058 ao->b_stream_format_changed = 0;
1059 b_digital = AudioStreamSupportsDigital(ao->i_stream_id);
1060 if (b_digital)
1062 /* Current stream supports digital format output, let's set it. */
1063 ao_msg(MSGT_AO, MSGL_V,
1064 "Detected current stream supports digital, try to restore digital output...\n");
1066 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
1068 ao_msg(MSGT_AO, MSGL_WARN, "Restoring digital output failed.\n");
1070 else
1072 ao_msg(MSGT_AO, MSGL_WARN, "Restoring digital output succeeded.\n");
1073 reset();
1076 else
1077 ao_msg(MSGT_AO, MSGL_V, "Detected current stream does not support digital.\n");
1080 wrote=write_buffer(output_samples, num_bytes);
1081 audio_resume();
1083 do {
1084 exit_reason = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true);
1085 } while (exit_reason == kCFRunLoopRunHandledSource);
1087 return wrote;
1090 /* set variables and buffer to initial state */
1091 static void reset(void)
1093 audio_pause();
1094 av_fifo_reset(ao->buffer);
1098 /* return available space */
1099 static int get_space(void)
1101 return ao->buffer_len - av_fifo_size(ao->buffer);
1105 /* return delay until audio is played */
1106 static float get_delay(void)
1108 // inaccurate, should also contain the data buffered e.g. by the OS
1109 return (float)av_fifo_size(ao->buffer)/(float)ao_data.bps;
1113 /* unload plugin and deregister from coreaudio */
1114 static void uninit(int immed)
1116 OSStatus err = noErr;
1118 if (!immed) {
1119 long long timeleft=(1000000LL*av_fifo_size(ao->buffer))/ao_data.bps;
1120 ao_msg(MSGT_AO,MSGL_DBG2, "%d bytes left @%d bps (%d usec)\n", av_fifo_size(ao->buffer), ao_data.bps, (int)timeleft);
1121 usec_sleep((int)timeleft);
1124 if (!ao->b_digital) {
1125 AudioOutputUnitStop(ao->theOutputUnit);
1126 AudioUnitUninitialize(ao->theOutputUnit);
1127 CloseComponent(ao->theOutputUnit);
1129 else {
1130 /* Stop device. */
1131 err = AudioDeviceStop(ao->i_selected_dev, ao->renderCallback);
1132 if (err != noErr)
1133 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1135 /* Remove IOProc callback. */
1136 err = AudioDeviceDestroyIOProcID(ao->i_selected_dev, ao->renderCallback);
1137 if (err != noErr)
1138 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err);
1140 if (ao->b_revert)
1141 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
1143 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
1145 UInt32 b_mix;
1146 Boolean b_writeable;
1147 /* Revert mixable to true if we are allowed to. */
1148 err = IsAudioPropertySettable(ao->i_selected_dev,
1149 kAudioDevicePropertySupportsMixing,
1150 &b_writeable);
1151 err = GetAudioProperty(ao->i_selected_dev,
1152 kAudioDevicePropertySupportsMixing,
1153 sizeof(UInt32), &b_mix);
1154 if (err != noErr && b_writeable)
1156 b_mix = 1;
1157 err = SetAudioProperty(ao->i_selected_dev,
1158 kAudioDevicePropertySupportsMixing,
1159 sizeof(UInt32), &b_mix);
1161 if (err != noErr)
1162 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
1164 if (ao->i_hog_pid == getpid())
1166 ao->i_hog_pid = -1;
1167 err = SetAudioProperty(ao->i_selected_dev,
1168 kAudioDevicePropertyHogMode,
1169 sizeof(ao->i_hog_pid), &ao->i_hog_pid);
1170 if (err != noErr) ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n", (char *)&err);
1174 av_fifo_free(ao->buffer);
1175 free(ao);
1176 ao = NULL;
1180 /* stop playing, keep buffers (for pause) */
1181 static void audio_pause(void)
1183 OSErr err=noErr;
1185 /* Stop callback. */
1186 if (!ao->b_digital)
1188 err=AudioOutputUnitStop(ao->theOutputUnit);
1189 if (err != noErr)
1190 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err);
1192 else
1194 err = AudioDeviceStop(ao->i_selected_dev, ao->renderCallback);
1195 if (err != noErr)
1196 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1198 ao->paused = 1;
1202 /* resume playing, after audio_pause() */
1203 static void audio_resume(void)
1205 OSErr err=noErr;
1207 if (!ao->paused)
1208 return;
1210 /* Start callback. */
1211 if (!ao->b_digital)
1213 err = AudioOutputUnitStart(ao->theOutputUnit);
1214 if (err != noErr)
1215 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err);
1217 else
1219 err = AudioDeviceStart(ao->i_selected_dev, ao->renderCallback);
1220 if (err != noErr)
1221 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err);
1223 ao->paused = 0;
1226 /*****************************************************************************
1227 * StreamListener
1228 *****************************************************************************/
1229 static OSStatus StreamListener( AudioObjectID inObjectID,
1230 UInt32 inNumberAddresses,
1231 const AudioObjectPropertyAddress inAddresses[],
1232 void *inClientData )
1234 for (int i=0; i < inNumberAddresses; ++i)
1236 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1237 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1238 if (inClientData)
1239 *(volatile int *)inClientData = 1;
1240 break;
1243 return noErr;
1246 static OSStatus DeviceListener( AudioObjectID inObjectID,
1247 UInt32 inNumberAddresses,
1248 const AudioObjectPropertyAddress inAddresses[],
1249 void *inClientData )
1251 for (int i=0; i < inNumberAddresses; ++i)
1253 if (inAddresses[i].mSelector == kAudioDevicePropertyDeviceHasChanged) {
1254 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1255 ao->b_stream_format_changed = 1;
1256 break;
1259 return noErr;