Remove an useless conditional suggested by Emanuele Giaquinta.
[mplayer/greg.git] / libao2 / ao_macosx.c
blob9b73c36be0d038a45db1edaa8dd6d5f10600ab3c
1 /*
3 * ao_macosx.c
5 * Original Copyright (C) Timothy J. Wood - Aug 2000
7 * This file is part of libao, a cross-platform library. See
8 * README for a history of this source code.
10 * libao is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2, or (at your option)
13 * any later version.
15 * libao is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with libao; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * The MacOS X CoreAudio framework doesn't mesh as simply as some
27 * simpler frameworks do. This is due to the fact that CoreAudio pulls
28 * audio samples rather than having them pushed at it (which is nice
29 * when you are wanting to do good buffering of audio).
32 /* Change log:
34 * 14/5-2003: Ported to MPlayer libao2 by Dan Christiansen
36 * AC-3 and MPEG audio passthrough is possible, but I don't have
37 * access to a sound card that supports it.
40 #include <CoreServices/CoreServices.h>
41 #include <AudioUnit/AudioUnit.h>
42 #include <AudioToolbox/AudioToolbox.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <stdlib.h>
46 #include <inttypes.h>
47 #include <sys/types.h>
48 #include <unistd.h>
50 #include "config.h"
51 #include "mp_msg.h"
53 #include "audio_out.h"
54 #include "audio_out_internal.h"
55 #include "libaf/af_format.h"
56 #include "osdep/timer.h"
58 static ao_info_t info =
60 "Darwin/Mac OS X native audio output",
61 "macosx",
62 "Timothy J. Wood & Dan Christiansen & Chris Roccati",
66 LIBAO_EXTERN(macosx)
68 /* Prefix for all mp_msg() calls */
69 #define ao_msg(a, b, c...) mp_msg(a, b, "AO: [macosx] " c)
71 typedef struct ao_macosx_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 /* AudioUnit */
79 AudioUnit theOutputUnit;
81 /* CoreAudio SPDIF mode specific */
82 pid_t i_hog_pid; /* Keeps the pid of our hog status. */
83 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
84 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
85 AudioStreamBasicDescription stream_format;/* The format we changed the stream to */
86 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
87 int b_revert; /* Whether we need to revert the stream format */
88 int b_changed_mixing; /* Whether we need to set the mixing mode back */
89 int b_stream_format_changed; /* Flag for main thread to reset stream's format to digital and reset buffer */
91 /* Original common part */
92 int packetSize;
93 int paused;
95 /* Ring-buffer */
96 /* does not need explicit synchronization, but needs to allocate
97 * (num_chunks + 1) * chunk_size memory to store num_chunks * chunk_size
98 * data */
99 unsigned char *buffer;
100 unsigned int buffer_len; ///< must always be (num_chunks + 1) * chunk_size
101 unsigned int num_chunks;
102 unsigned int chunk_size;
104 unsigned int buf_read_pos;
105 unsigned int buf_write_pos;
106 } ao_macosx_t;
108 static ao_macosx_t *ao = NULL;
111 * \brief return number of free bytes in the buffer
112 * may only be called by mplayer's thread
113 * \return minimum number of free bytes in buffer, value may change between
114 * two immediately following calls, and the real number of free bytes
115 * might actually be larger!
117 static int buf_free(void) {
118 int free = ao->buf_read_pos - ao->buf_write_pos - ao->chunk_size;
119 if (free < 0) free += ao->buffer_len;
120 return free;
124 * \brief return number of buffered bytes
125 * may only be called by playback thread
126 * \return minimum number of buffered bytes, value may change between
127 * two immediately following calls, and the real number of buffered bytes
128 * might actually be larger!
130 static int buf_used(void) {
131 int used = ao->buf_write_pos - ao->buf_read_pos;
132 if (used < 0) used += ao->buffer_len;
133 return used;
137 * \brief add data to ringbuffer
139 static int write_buffer(unsigned char* data, int len){
140 int first_len = ao->buffer_len - ao->buf_write_pos;
141 int free = buf_free();
142 if (len > free) len = free;
143 if (first_len > len) first_len = len;
144 // till end of buffer
145 memcpy (&ao->buffer[ao->buf_write_pos], data, first_len);
146 if (len > first_len) { // we have to wrap around
147 // remaining part from beginning of buffer
148 memcpy (ao->buffer, &data[first_len], len - first_len);
150 ao->buf_write_pos = (ao->buf_write_pos + len) % ao->buffer_len;
151 return len;
155 * \brief remove data from ringbuffer
157 static int read_buffer(unsigned char* data,int len){
158 int first_len = ao->buffer_len - ao->buf_read_pos;
159 int buffered = buf_used();
160 if (len > buffered) len = buffered;
161 if (first_len > len) first_len = len;
162 // till end of buffer
163 if (data) {
164 memcpy (data, &ao->buffer[ao->buf_read_pos], first_len);
165 if (len > first_len) { // we have to wrap around
166 // remaining part from beginning of buffer
167 memcpy (&data[first_len], ao->buffer, len - first_len);
170 ao->buf_read_pos = (ao->buf_read_pos + len) % ao->buffer_len;
171 return len;
174 OSStatus theRenderProc(void *inRefCon, AudioUnitRenderActionFlags *inActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumFrames, AudioBufferList *ioData)
176 int amt=buf_used();
177 int req=(inNumFrames)*ao->packetSize;
179 if(amt>req)
180 amt=req;
182 if(amt)
183 read_buffer((unsigned char *)ioData->mBuffers[0].mData, amt);
184 else audio_pause();
185 ioData->mBuffers[0].mDataByteSize = amt;
187 return noErr;
190 static int control(int cmd,void *arg){
191 ao_control_vol_t *control_vol;
192 OSStatus err;
193 Float32 vol;
194 switch (cmd) {
195 case AOCONTROL_GET_VOLUME:
196 control_vol = (ao_control_vol_t*)arg;
197 if (ao->b_digital) {
198 // Digital output has no volume adjust.
199 return CONTROL_FALSE;
201 err = AudioUnitGetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, &vol);
203 if(err==0) {
204 // printf("GET VOL=%f\n", vol);
205 control_vol->left=control_vol->right=vol*100.0/4.0;
206 return CONTROL_TRUE;
208 else {
209 ao_msg(MSGT_AO, MSGL_WARN, "could not get HAL output volume: [%4.4s]\n", (char *)&err);
210 return CONTROL_FALSE;
213 case AOCONTROL_SET_VOLUME:
214 control_vol = (ao_control_vol_t*)arg;
216 if (ao->b_digital) {
217 // Digital output can not set volume. Here we have to return true
218 // to make mixer forget it. Else mixer will add a soft filter,
219 // that's not we expected and the filter not support ac3 stream
220 // will cause mplayer die.
222 // Although not support set volume, but at least we support mute.
223 // MPlayer set mute by set volume to zero, we handle it.
224 if (control_vol->left == 0 && control_vol->right == 0)
225 ao->b_muted = 1;
226 else
227 ao->b_muted = 0;
228 return CONTROL_TRUE;
231 vol=(control_vol->left+control_vol->right)*4.0/200.0;
232 err = AudioUnitSetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, vol, 0);
233 if(err==0) {
234 // printf("SET VOL=%f\n", vol);
235 return CONTROL_TRUE;
237 else {
238 ao_msg(MSGT_AO, MSGL_WARN, "could not set HAL output volume: [%4.4s]\n", (char *)&err);
239 return CONTROL_FALSE;
241 /* Everything is currently unimplemented */
242 default:
243 return CONTROL_FALSE;
249 static void print_format(int lev, const char* str, const AudioStreamBasicDescription *f){
250 uint32_t flags=(uint32_t) f->mFormatFlags;
251 ao_msg(MSGT_AO,lev, "%s %7.1fHz %lubit [%c%c%c%c][%lu][%lu][%lu][%lu][%lu] %s %s %s%s%s%s\n",
252 str, f->mSampleRate, f->mBitsPerChannel,
253 (int)(f->mFormatID & 0xff000000) >> 24,
254 (int)(f->mFormatID & 0x00ff0000) >> 16,
255 (int)(f->mFormatID & 0x0000ff00) >> 8,
256 (int)(f->mFormatID & 0x000000ff) >> 0,
257 f->mFormatFlags, f->mBytesPerPacket,
258 f->mFramesPerPacket, f->mBytesPerFrame,
259 f->mChannelsPerFrame,
260 (flags&kAudioFormatFlagIsFloat) ? "float" : "int",
261 (flags&kAudioFormatFlagIsBigEndian) ? "BE" : "LE",
262 (flags&kAudioFormatFlagIsSignedInteger) ? "S" : "U",
263 (flags&kAudioFormatFlagIsPacked) ? " packed" : "",
264 (flags&kAudioFormatFlagIsAlignedHigh) ? " aligned" : "",
265 (flags&kAudioFormatFlagIsNonInterleaved) ? " ni" : "" );
269 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id );
270 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id );
271 static int OpenSPDIF();
272 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format );
273 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
274 const AudioTimeStamp * inNow,
275 const void * inInputData,
276 const AudioTimeStamp * inInputTime,
277 AudioBufferList * outOutputData,
278 const AudioTimeStamp * inOutputTime,
279 void * threadGlobals );
280 static OSStatus StreamListener( AudioStreamID inStream,
281 UInt32 inChannel,
282 AudioDevicePropertyID inPropertyID,
283 void * inClientData );
284 static OSStatus DeviceListener( AudioDeviceID inDevice,
285 UInt32 inChannel,
286 Boolean isInput,
287 AudioDevicePropertyID inPropertyID,
288 void* inClientData );
290 static int init(int rate,int channels,int format,int flags)
292 AudioStreamBasicDescription inDesc;
293 ComponentDescription desc;
294 Component comp;
295 AURenderCallbackStruct renderCallback;
296 OSStatus err;
297 UInt32 size, maxFrames, i_param_size;
298 char *psz_name;
299 int aoIsCreated = ao != NULL;
300 AudioDeviceID devid_def = 0;
301 int b_alive;
303 ao_msg(MSGT_AO,MSGL_V, "init([%dHz][%dch][%s][%d])\n", rate, channels, af_fmt2str_short(format), flags);
305 if (!aoIsCreated) { ao = malloc(sizeof(ao_macosx_t)); ao->buffer = NULL;}
307 ao->i_selected_dev = 0;
308 ao->b_supports_digital = 0;
309 ao->b_digital = 0;
310 ao->b_muted = 0;
311 ao->b_stream_format_changed = 0;
312 ao->i_hog_pid = -1;
313 ao->i_stream_id = 0;
314 ao->i_stream_index = -1;
315 ao->b_revert = 0;
316 ao->b_changed_mixing = 0;
318 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
319 if ((format & AF_FORMAT_SPECIAL_MASK) == AF_FORMAT_AC3)
321 /* Find the ID of the default Device. */
322 i_param_size = sizeof(AudioDeviceID);
323 err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
324 &i_param_size, &devid_def);
325 if (err != noErr)
327 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device: [%4.4s]\n", (char *)&err);
328 return CONTROL_FALSE;
331 /* Retrieve the length of the device name. */
332 i_param_size = 0;
333 err = AudioDeviceGetPropertyInfo(devid_def, 0, 0,
334 kAudioDevicePropertyDeviceName,
335 &i_param_size, NULL);
336 if (err != noErr)
338 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name length: [%4.4s]\n", (char *)&err);
339 return CONTROL_FALSE;
342 /* Retrieve the name of the device. */
343 psz_name = (char *)malloc(i_param_size);
344 err = AudioDeviceGetProperty(devid_def, 0, 0,
345 kAudioDevicePropertyDeviceName,
346 &i_param_size, psz_name);
347 if (err != noErr)
349 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name: [%4.4s]\n", (char *)&err);
350 return CONTROL_FALSE;
353 ao_msg(MSGT_AO,MSGL_V, "got default audio output device ID: %#lx Name: %s\n", devid_def, psz_name );
355 if (AudioDeviceSupportsDigital(devid_def))
357 ao->b_supports_digital = 1;
358 ao->i_selected_dev = devid_def;
360 ao_msg(MSGT_AO,MSGL_V, "probe default audio output device whether support digital s/pdif output:%d\n", ao->b_supports_digital );
362 free( psz_name);
365 // Build Description for the input format
366 inDesc.mSampleRate=rate;
367 inDesc.mFormatID=ao->b_supports_digital ? kAudioFormat60958AC3 : kAudioFormatLinearPCM;
368 inDesc.mChannelsPerFrame=channels;
369 switch(format&AF_FORMAT_BITS_MASK){
370 case AF_FORMAT_8BIT:
371 inDesc.mBitsPerChannel=8;
372 break;
373 case AF_FORMAT_16BIT:
374 inDesc.mBitsPerChannel=16;
375 break;
376 case AF_FORMAT_24BIT:
377 inDesc.mBitsPerChannel=24;
378 break;
379 case AF_FORMAT_32BIT:
380 inDesc.mBitsPerChannel=32;
381 break;
382 default:
383 ao_msg(MSGT_AO, MSGL_WARN, "Unsupported format (0x%08x)\n", format);
384 return CONTROL_FALSE;
385 break;
388 if((format&AF_FORMAT_POINT_MASK)==AF_FORMAT_F) {
389 // float
390 inDesc.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked;
392 else if((format&AF_FORMAT_SIGN_MASK)==AF_FORMAT_SI) {
393 // signed int
394 inDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger|kAudioFormatFlagIsPacked;
396 else {
397 // unsigned int
398 inDesc.mFormatFlags = kAudioFormatFlagIsPacked;
400 if ((format & AF_FORMAT_SPECIAL_MASK) == AF_FORMAT_AC3) {
401 // Currently ac3 input (comes from hwac3) is always in native byte-order.
402 #ifdef WORDS_BIGENDIAN
403 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
404 #endif
406 else if ((format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
407 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
409 inDesc.mFramesPerPacket = 1;
410 ao->packetSize = inDesc.mBytesPerPacket = inDesc.mBytesPerFrame = inDesc.mFramesPerPacket*channels*(inDesc.mBitsPerChannel/8);
411 print_format(MSGL_V, "source:",&inDesc);
413 if (ao->b_supports_digital)
415 b_alive = 1;
416 i_param_size = sizeof(b_alive);
417 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
418 kAudioDevicePropertyDeviceIsAlive,
419 &i_param_size, &b_alive);
420 if (err != noErr)
421 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is alive: [%4.4s]\n", (char *)&err);
422 if (!b_alive)
423 ao_msg(MSGT_AO, MSGL_WARN, "device is not alive\n" );
424 /* S/PDIF output need device in HogMode. */
425 i_param_size = sizeof(ao->i_hog_pid);
426 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
427 kAudioDevicePropertyHogMode,
428 &i_param_size, &ao->i_hog_pid);
430 if (err != noErr)
432 /* This is not a fatal error. Some drivers simply don't support this property. */
433 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is hogged: [%4.4s]\n",
434 (char *)&err);
435 ao->i_hog_pid = -1;
438 if (ao->i_hog_pid != -1 && ao->i_hog_pid != getpid())
440 ao_msg(MSGT_AO, MSGL_WARN, "Selected audio device is exclusively in use by another program.\n" );
441 return CONTROL_FALSE;
443 ao->stream_format = inDesc;
444 return OpenSPDIF();
447 /* original analog output code */
448 desc.componentType = kAudioUnitType_Output;
449 desc.componentSubType = kAudioUnitSubType_DefaultOutput;
450 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
451 desc.componentFlags = 0;
452 desc.componentFlagsMask = 0;
454 comp = FindNextComponent(NULL, &desc); //Finds an component that meets the desc spec's
455 if (comp == NULL) {
456 ao_msg(MSGT_AO, MSGL_WARN, "Unable to find Output Unit component\n");
457 return CONTROL_FALSE;
460 err = OpenAComponent(comp, &(ao->theOutputUnit)); //gains access to the services provided by the component
461 if (err) {
462 ao_msg(MSGT_AO, MSGL_WARN, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err);
463 return CONTROL_FALSE;
466 // Initialize AudioUnit
467 err = AudioUnitInitialize(ao->theOutputUnit);
468 if (err) {
469 ao_msg(MSGT_AO, MSGL_WARN, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err);
470 return CONTROL_FALSE;
473 size = sizeof(AudioStreamBasicDescription);
474 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inDesc, size);
476 if (err) {
477 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the input format: [%4.4s]\n", (char *)&err);
478 return CONTROL_FALSE;
481 size = sizeof(UInt32);
482 err = AudioUnitGetProperty(ao->theOutputUnit, kAudioDevicePropertyBufferSize, kAudioUnitScope_Input, 0, &maxFrames, &size);
484 if (err)
486 ao_msg(MSGT_AO,MSGL_WARN, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err);
487 return CONTROL_FALSE;
490 ao->chunk_size = maxFrames;//*inDesc.mBytesPerFrame;
492 ao_data.samplerate = inDesc.mSampleRate;
493 ao_data.channels = inDesc.mChannelsPerFrame;
494 ao_data.bps = ao_data.samplerate * inDesc.mBytesPerFrame;
495 ao_data.outburst = ao->chunk_size;
496 ao_data.buffersize = ao_data.bps;
498 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
499 ao->buffer_len = (ao->num_chunks + 1) * ao->chunk_size;
500 ao->buffer = aoIsCreated ? realloc(ao->buffer,(ao->num_chunks + 1)*ao->chunk_size)
501 : calloc(ao->num_chunks + 1, ao->chunk_size);
503 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);
505 renderCallback.inputProc = theRenderProc;
506 renderCallback.inputProcRefCon = 0;
507 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
508 if (err) {
509 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the render callback: [%4.4s]\n", (char *)&err);
510 return CONTROL_FALSE;
513 reset();
515 return CONTROL_OK;
518 /*****************************************************************************
519 * Setup a encoded digital stream (SPDIF)
520 *****************************************************************************/
521 static int OpenSPDIF()
523 OSStatus err = noErr;
524 UInt32 i_param_size, b_mix = 0;
525 Boolean b_writeable = 0;
526 AudioStreamID *p_streams = NULL;
527 int i, i_streams = 0;
529 /* Start doing the SPDIF setup process. */
530 ao->b_digital = 1;
532 /* Hog the device. */
533 i_param_size = sizeof(ao->i_hog_pid);
534 ao->i_hog_pid = getpid() ;
536 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
537 kAudioDevicePropertyHogMode, i_param_size, &ao->i_hog_pid);
539 if (err != noErr)
541 ao_msg(MSGT_AO, MSGL_WARN, "failed to set hogmode: [%4.4s]\n", (char *)&err);
542 return CONTROL_FALSE;
545 /* Set mixable to false if we are allowed to. */
546 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE,
547 kAudioDevicePropertySupportsMixing,
548 &i_param_size, &b_writeable);
549 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
550 kAudioDevicePropertySupportsMixing,
551 &i_param_size, &b_mix);
552 if (err != noErr && b_writeable)
554 b_mix = 0;
555 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
556 kAudioDevicePropertySupportsMixing,
557 i_param_size, &b_mix);
558 ao->b_changed_mixing = 1;
560 if (err != noErr)
562 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
563 return CONTROL_FALSE;
566 /* Get a list of all the streams on this device. */
567 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE,
568 kAudioDevicePropertyStreams,
569 &i_param_size, NULL);
570 if (err != noErr)
572 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams: [%4.4s]\n", (char *)&err);
573 return CONTROL_FALSE;
576 i_streams = i_param_size / sizeof(AudioStreamID);
577 p_streams = (AudioStreamID *)malloc(i_param_size);
578 if (p_streams == NULL)
580 ao_msg(MSGT_AO, MSGL_WARN, "out of memory\n" );
581 return CONTROL_FALSE;
584 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
585 kAudioDevicePropertyStreams,
586 &i_param_size, p_streams);
587 if (err != noErr)
589 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams: [%4.4s]\n", (char *)&err);
590 if (p_streams) free(p_streams);
591 return CONTROL_FALSE;
594 ao_msg(MSGT_AO, MSGL_V, "current device stream number: %d\n", i_streams);
596 for (i = 0; i < i_streams && ao->i_stream_index < 0; ++i)
598 /* Find a stream with a cac3 stream. */
599 AudioStreamBasicDescription *p_format_list = NULL;
600 int i_formats = 0, j = 0, b_digital = 0;
602 /* Retrieve all the stream formats supported by each output stream. */
603 err = AudioStreamGetPropertyInfo(p_streams[i], 0,
604 kAudioStreamPropertyPhysicalFormats,
605 &i_param_size, NULL);
606 if (err != noErr)
608 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streamformats: [%4.4s]\n", (char *)&err);
609 continue;
612 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
613 p_format_list = (AudioStreamBasicDescription *)malloc(i_param_size);
614 if (p_format_list == NULL)
616 ao_msg(MSGT_AO, MSGL_WARN, "could not malloc the memory\n" );
617 continue;
620 err = AudioStreamGetProperty(p_streams[i], 0,
621 kAudioStreamPropertyPhysicalFormats,
622 &i_param_size, p_format_list);
623 if (err != noErr)
625 ao_msg(MSGT_AO, MSGL_WARN, "could not get the list of streamformats: [%4.4s]\n", (char *)&err);
626 if (p_format_list) free(p_format_list);
627 continue;
630 /* Check if one of the supported formats is a digital format. */
631 for (j = 0; j < i_formats; ++j)
633 if (p_format_list[j].mFormatID == 'IAC3' ||
634 p_format_list[j].mFormatID == kAudioFormat60958AC3)
636 b_digital = 1;
637 break;
641 if (b_digital)
643 /* If this stream supports a digital (cac3) format, then set it. */
644 int i_requested_rate_format = -1;
645 int i_current_rate_format = -1;
646 int i_backup_rate_format = -1;
648 ao->i_stream_id = p_streams[i];
649 ao->i_stream_index = i;
651 if (ao->b_revert == 0)
653 /* Retrieve the original format of this stream first if not done so already. */
654 i_param_size = sizeof(ao->sfmt_revert);
655 err = AudioStreamGetProperty(ao->i_stream_id, 0,
656 kAudioStreamPropertyPhysicalFormat,
657 &i_param_size,
658 &ao->sfmt_revert);
659 if (err != noErr)
661 ao_msg(MSGT_AO, MSGL_WARN, "could not retrieve the original streamformat: [%4.4s]\n", (char *)&err);
662 if (p_format_list) free(p_format_list);
663 continue;
665 ao->b_revert = 1;
668 for (j = 0; j < i_formats; ++j)
669 if (p_format_list[j].mFormatID == 'IAC3' ||
670 p_format_list[j].mFormatID == kAudioFormat60958AC3)
672 if (p_format_list[j].mSampleRate == ao->stream_format.mSampleRate)
674 i_requested_rate_format = j;
675 break;
677 if (p_format_list[j].mSampleRate == ao->sfmt_revert.mSampleRate)
678 i_current_rate_format = j;
679 else if (i_backup_rate_format < 0 || p_format_list[j].mSampleRate > p_format_list[i_backup_rate_format].mSampleRate)
680 i_backup_rate_format = j;
683 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio. */
684 ao->stream_format = p_format_list[i_requested_rate_format];
685 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device. */
686 ao->stream_format = p_format_list[i_current_rate_format];
687 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). */
689 if (p_format_list) free(p_format_list);
691 if (p_streams) free(p_streams);
693 if (ao->i_stream_index < 0)
695 ao_msg(MSGT_AO, MSGL_WARN, "can not find any digital output stream format when OpenSPDIF().\n");
696 return CONTROL_FALSE;
699 print_format(MSGL_V, "original stream format:", &ao->sfmt_revert);
701 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
702 return CONTROL_FALSE;
704 err = AudioDeviceAddPropertyListener(ao->i_selected_dev,
705 kAudioPropertyWildcardChannel,
707 kAudioDevicePropertyDeviceHasChanged,
708 DeviceListener,
709 NULL);
710 if (err != noErr)
711 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err);
714 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
715 /* Although there's no such case reported. */
716 #ifdef WORDS_BIGENDIAN
717 if (!(ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian))
718 #else
719 if (ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
720 #endif
721 ao_msg(MSGT_AO, MSGL_WARN, "output stream has a no-native byte-order, digital output may failed.\n");
723 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
724 ao->chunk_size = ao->stream_format.mBytesPerPacket;
726 ao_data.samplerate = ao->stream_format.mSampleRate;
727 ao_data.channels = ao->stream_format.mChannelsPerFrame;
728 ao_data.bps = ao_data.samplerate * (ao->stream_format.mBytesPerPacket/ao->stream_format.mFramesPerPacket);
729 ao_data.outburst = ao->chunk_size;
730 ao_data.buffersize = ao_data.bps;
732 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
733 ao->buffer_len = (ao->num_chunks + 1) * ao->chunk_size;
734 ao->buffer = NULL!=ao->buffer ? realloc(ao->buffer,(ao->num_chunks + 1)*ao->chunk_size)
735 : calloc(ao->num_chunks + 1, ao->chunk_size);
737 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);
740 /* Add IOProc callback. */
741 err = AudioDeviceAddIOProc(ao->i_selected_dev,
742 (AudioDeviceIOProc)RenderCallbackSPDIF,
743 (void *)ao);
744 if (err != noErr)
746 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err);
747 return CONTROL_FALSE;
750 reset();
752 return CONTROL_TRUE;
755 /*****************************************************************************
756 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
757 *****************************************************************************/
758 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id )
760 OSStatus err = noErr;
761 UInt32 i_param_size = 0;
762 AudioStreamID *p_streams = NULL;
763 int i = 0, i_streams = 0;
764 int b_return = CONTROL_FALSE;
766 /* Retrieve all the output streams. */
767 err = AudioDeviceGetPropertyInfo(i_dev_id, 0, FALSE,
768 kAudioDevicePropertyStreams,
769 &i_param_size, NULL);
770 if (err != noErr)
772 ao_msg(MSGT_AO,MSGL_V, "could not get number of streams: [%4.4s]\n", (char *)&err);
773 return CONTROL_FALSE;
776 i_streams = i_param_size / sizeof(AudioStreamID);
777 p_streams = (AudioStreamID *)malloc(i_param_size);
778 if (p_streams == NULL)
780 ao_msg(MSGT_AO,MSGL_V, "out of memory\n");
781 return CONTROL_FALSE;
784 err = AudioDeviceGetProperty(i_dev_id, 0, FALSE,
785 kAudioDevicePropertyStreams,
786 &i_param_size, p_streams);
788 if (err != noErr)
790 ao_msg(MSGT_AO,MSGL_V, "could not get number of streams: [%4.4s]\n", (char *)&err);
791 free(p_streams);
792 return CONTROL_FALSE;
795 for (i = 0; i < i_streams; ++i)
797 if (AudioStreamSupportsDigital(p_streams[i]))
798 b_return = CONTROL_OK;
801 free(p_streams);
802 return b_return;
805 /*****************************************************************************
806 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
807 *****************************************************************************/
808 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id )
810 OSStatus err = noErr;
811 UInt32 i_param_size;
812 AudioStreamBasicDescription *p_format_list = NULL;
813 int i, i_formats, b_return = CONTROL_FALSE;
815 /* Retrieve all the stream formats supported by each output stream. */
816 err = AudioStreamGetPropertyInfo(i_stream_id, 0,
817 kAudioStreamPropertyPhysicalFormats,
818 &i_param_size, NULL);
819 if (err != noErr)
821 ao_msg(MSGT_AO,MSGL_V, "could not get number of streamformats: [%4.4s]\n", (char *)&err);
822 return CONTROL_FALSE;
825 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
826 p_format_list = (AudioStreamBasicDescription *)malloc(i_param_size);
827 if (p_format_list == NULL)
829 ao_msg(MSGT_AO,MSGL_V, "could not malloc the memory\n" );
830 return CONTROL_FALSE;
833 err = AudioStreamGetProperty(i_stream_id, 0,
834 kAudioStreamPropertyPhysicalFormats,
835 &i_param_size, p_format_list);
836 if (err != noErr)
838 ao_msg(MSGT_AO,MSGL_V, "could not get the list of streamformats: [%4.4s]\n", (char *)&err);
839 free(p_format_list);
840 return CONTROL_FALSE;
843 for (i = 0; i < i_formats; ++i)
845 print_format(MSGL_V, "supported format:", &p_format_list[i]);
847 if (p_format_list[i].mFormatID == 'IAC3' ||
848 p_format_list[i].mFormatID == kAudioFormat60958AC3)
849 b_return = CONTROL_OK;
852 free(p_format_list);
853 return b_return;
856 /*****************************************************************************
857 * AudioStreamChangeFormat: Change i_stream_id to change_format
858 *****************************************************************************/
859 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format )
861 OSStatus err = noErr;
862 UInt32 i_param_size = 0;
863 int i;
865 static volatile int stream_format_changed;
866 stream_format_changed = 0;
868 print_format(MSGL_V, "setting stream format:", &change_format);
870 /* Install the callback. */
871 err = AudioStreamAddPropertyListener(i_stream_id, 0,
872 kAudioStreamPropertyPhysicalFormat,
873 StreamListener,
874 (void *)&stream_format_changed);
875 if (err != noErr)
877 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err);
878 return CONTROL_FALSE;
881 /* Change the format. */
882 err = AudioStreamSetProperty(i_stream_id, 0, 0,
883 kAudioStreamPropertyPhysicalFormat,
884 sizeof(AudioStreamBasicDescription),
885 &change_format);
886 if (err != noErr)
888 ao_msg(MSGT_AO, MSGL_WARN, "could not set the stream format: [%4.4s]\n", (char *)&err);
889 return CONTROL_FALSE;
892 /* The AudioStreamSetProperty is not only asynchronious,
893 * it is also not Atomic, in its behaviour.
894 * Therefore we check 5 times before we really give up.
895 * FIXME: failing isn't actually implemented yet. */
896 for (i = 0; i < 5; ++i)
898 AudioStreamBasicDescription actual_format;
899 int j;
900 for (j = 0; !stream_format_changed && j < 50; ++j)
901 usec_sleep(10000);
902 if (stream_format_changed)
903 stream_format_changed = 0;
904 else
905 ao_msg(MSGT_AO, MSGL_V, "reached timeout\n" );
907 i_param_size = sizeof(AudioStreamBasicDescription);
908 err = AudioStreamGetProperty(i_stream_id, 0,
909 kAudioStreamPropertyPhysicalFormat,
910 &i_param_size,
911 &actual_format);
913 print_format(MSGL_V, "actual format in use:", &actual_format);
914 if (actual_format.mSampleRate == change_format.mSampleRate &&
915 actual_format.mFormatID == change_format.mFormatID &&
916 actual_format.mFramesPerPacket == change_format.mFramesPerPacket)
918 /* The right format is now active. */
919 break;
921 /* We need to check again. */
924 /* Removing the property listener. */
925 err = AudioStreamRemovePropertyListener(i_stream_id, 0,
926 kAudioStreamPropertyPhysicalFormat,
927 StreamListener);
928 if (err != noErr)
930 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err);
931 return CONTROL_FALSE;
934 return CONTROL_TRUE;
937 /*****************************************************************************
938 * RenderCallbackSPDIF: callback for SPDIF audio output
939 *****************************************************************************/
940 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
941 const AudioTimeStamp * inNow,
942 const void * inInputData,
943 const AudioTimeStamp * inInputTime,
944 AudioBufferList * outOutputData,
945 const AudioTimeStamp * inOutputTime,
946 void * threadGlobals )
948 int amt = buf_used();
949 int req = outOutputData->mBuffers[ao->i_stream_index].mDataByteSize;
951 if (amt > req)
952 amt = req;
953 if (amt)
954 read_buffer(ao->b_muted ? NULL : (unsigned char *)outOutputData->mBuffers[ao->i_stream_index].mData, amt);
956 return noErr;
960 static int play(void* output_samples,int num_bytes,int flags)
962 int wrote, b_digital;
964 // Check whether we need to reset the digital output stream.
965 if (ao->b_digital && ao->b_stream_format_changed)
967 ao->b_stream_format_changed = 0;
968 b_digital = AudioStreamSupportsDigital(ao->i_stream_id);
969 if (b_digital)
971 /* Current stream support digital format output, let's set it. */
972 ao_msg(MSGT_AO, MSGL_V, "detected current stream support digital, try to restore digital output...\n");
974 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
976 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output failed.\n");
978 else
980 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output succeed.\n");
981 reset();
984 else
985 ao_msg(MSGT_AO, MSGL_V, "detected current stream do not support digital.\n");
988 wrote=write_buffer(output_samples, num_bytes);
989 audio_resume();
990 return wrote;
993 /* set variables and buffer to initial state */
994 static void reset(void)
996 audio_pause();
997 /* reset ring-buffer state */
998 ao->buf_read_pos=0;
999 ao->buf_write_pos=0;
1001 return;
1005 /* return available space */
1006 static int get_space(void)
1008 return buf_free();
1012 /* return delay until audio is played */
1013 static float get_delay(void)
1015 int buffered = ao->buffer_len - ao->chunk_size - buf_free(); // could be less
1016 // inaccurate, should also contain the data buffered e.g. by the OS
1017 return (float)(buffered)/(float)ao_data.bps;
1021 /* unload plugin and deregister from coreaudio */
1022 static void uninit(int immed)
1024 OSStatus err = noErr;
1025 UInt32 i_param_size = 0;
1027 if (!immed) {
1028 long long timeleft=(1000000LL*buf_used())/ao_data.bps;
1029 ao_msg(MSGT_AO,MSGL_DBG2, "%d bytes left @%d bps (%d usec)\n", buf_used(), ao_data.bps, (int)timeleft);
1030 usec_sleep((int)timeleft);
1033 if (!ao->b_digital) {
1034 AudioOutputUnitStop(ao->theOutputUnit);
1035 AudioUnitUninitialize(ao->theOutputUnit);
1036 CloseComponent(ao->theOutputUnit);
1038 else {
1039 /* Stop device. */
1040 err = AudioDeviceStop(ao->i_selected_dev,
1041 (AudioDeviceIOProc)RenderCallbackSPDIF);
1042 if (err != noErr)
1043 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1045 /* Remove IOProc callback. */
1046 err = AudioDeviceRemoveIOProc(ao->i_selected_dev,
1047 (AudioDeviceIOProc)RenderCallbackSPDIF);
1048 if (err != noErr)
1049 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err);
1051 if (ao->b_revert)
1052 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
1054 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
1056 int b_mix;
1057 Boolean b_writeable;
1058 /* Revert mixable to true if we are allowed to. */
1059 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
1060 &i_param_size, &b_writeable);
1061 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
1062 &i_param_size, &b_mix);
1063 if (err != noErr && b_writeable)
1065 b_mix = 1;
1066 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
1067 kAudioDevicePropertySupportsMixing, i_param_size, &b_mix);
1069 if (err != noErr)
1070 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
1072 if (ao->i_hog_pid == getpid())
1074 ao->i_hog_pid = -1;
1075 i_param_size = sizeof(ao->i_hog_pid);
1076 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
1077 kAudioDevicePropertyHogMode, i_param_size, &ao->i_hog_pid);
1078 if (err != noErr) ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n", (char *)&err);
1082 free(ao->buffer);
1083 free(ao);
1084 ao = NULL;
1088 /* stop playing, keep buffers (for pause) */
1089 static void audio_pause(void)
1091 OSErr err=noErr;
1093 /* Stop callback. */
1094 if (!ao->b_digital)
1096 err=AudioOutputUnitStop(ao->theOutputUnit);
1097 if (err != noErr)
1098 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err);
1100 else
1102 err = AudioDeviceStop(ao->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF);
1103 if (err != noErr)
1104 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1106 ao->paused = 1;
1110 /* resume playing, after audio_pause() */
1111 static void audio_resume(void)
1113 OSErr err=noErr;
1115 if (!ao->paused)
1116 return;
1118 /* Start callback. */
1119 if (!ao->b_digital)
1121 err = AudioOutputUnitStart(ao->theOutputUnit);
1122 if (err != noErr)
1123 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err);
1125 else
1127 err = AudioDeviceStart(ao->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF);
1128 if (err != noErr)
1129 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err);
1131 ao->paused = 0;
1134 /*****************************************************************************
1135 * StreamListener
1136 *****************************************************************************/
1137 static OSStatus StreamListener( AudioStreamID inStream,
1138 UInt32 inChannel,
1139 AudioDevicePropertyID inPropertyID,
1140 void * inClientData )
1142 switch (inPropertyID)
1144 case kAudioStreamPropertyPhysicalFormat:
1145 ao_msg(MSGT_AO, MSGL_V, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1146 if (inClientData)
1147 *(volatile int *)inClientData = 1;
1148 default:
1149 break;
1151 return noErr;
1154 static OSStatus DeviceListener( AudioDeviceID inDevice,
1155 UInt32 inChannel,
1156 Boolean isInput,
1157 AudioDevicePropertyID inPropertyID,
1158 void* inClientData )
1160 switch (inPropertyID)
1162 case kAudioDevicePropertyDeviceHasChanged:
1163 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1164 ao->b_stream_format_changed = 1;
1165 default:
1166 break;
1168 return noErr;