ad_pcm: Track pts explicitly
[mplayer.git] / libao2 / ao_macosx.c
blobfcbda6f1a1ccf8eadf4e918dd050f343d5542c62
1 /*
2 * Mac OS X audio output driver
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"
56 static ao_info_t info =
58 "Darwin/Mac OS X native audio output",
59 "macosx",
60 "Timothy J. Wood & Dan Christiansen & Chris Roccati",
64 LIBAO_EXTERN(macosx)
66 /* Prefix for all mp_msg() calls */
67 #define ao_msg(a, b, c...) mp_msg(a, b, "AO: [macosx] " c)
69 typedef struct ao_macosx_s
71 AudioDeviceID i_selected_dev; /* Keeps DeviceID of the selected device. */
72 int b_supports_digital; /* Does the currently selected device support digital mode? */
73 int b_digital; /* Are we running in digital mode? */
74 int b_muted; /* Are we muted in digital mode? */
76 /* AudioUnit */
77 AudioUnit theOutputUnit;
79 /* CoreAudio SPDIF mode specific */
80 pid_t i_hog_pid; /* Keeps the pid of our hog status. */
81 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
82 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
83 AudioStreamBasicDescription stream_format;/* The format we changed the stream to */
84 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
85 int b_revert; /* Whether we need to revert the stream format */
86 int b_changed_mixing; /* Whether we need to set the mixing mode back */
87 int b_stream_format_changed; /* Flag for main thread to reset stream's format to digital and reset buffer */
89 /* Original common part */
90 int packetSize;
91 int paused;
93 /* Ring-buffer */
94 /* does not need explicit synchronization, but needs to allocate
95 * (num_chunks + 1) * chunk_size memory to store num_chunks * chunk_size
96 * data */
97 unsigned char *buffer;
98 unsigned int buffer_len; ///< must always be (num_chunks + 1) * chunk_size
99 unsigned int num_chunks;
100 unsigned int chunk_size;
102 unsigned int buf_read_pos;
103 unsigned int buf_write_pos;
104 } ao_macosx_t;
106 static ao_macosx_t *ao = NULL;
109 * \brief return number of free bytes in the buffer
110 * may only be called by mplayer's thread
111 * \return minimum number of free bytes in buffer, value may change between
112 * two immediately following calls, and the real number of free bytes
113 * might actually be larger!
115 static int buf_free(void) {
116 int free = ao->buf_read_pos - ao->buf_write_pos - ao->chunk_size;
117 if (free < 0) free += ao->buffer_len;
118 return free;
122 * \brief return number of buffered bytes
123 * may only be called by playback thread
124 * \return minimum number of buffered bytes, value may change between
125 * two immediately following calls, and the real number of buffered bytes
126 * might actually be larger!
128 static int buf_used(void) {
129 int used = ao->buf_write_pos - ao->buf_read_pos;
130 if (used < 0) used += ao->buffer_len;
131 return used;
135 * \brief add data to ringbuffer
137 static int write_buffer(unsigned char* data, int len){
138 int first_len = ao->buffer_len - ao->buf_write_pos;
139 int free = buf_free();
140 if (len > free) len = free;
141 if (first_len > len) first_len = len;
142 // till end of buffer
143 memcpy (&ao->buffer[ao->buf_write_pos], data, first_len);
144 if (len > first_len) { // we have to wrap around
145 // remaining part from beginning of buffer
146 memcpy (ao->buffer, &data[first_len], len - first_len);
148 ao->buf_write_pos = (ao->buf_write_pos + len) % ao->buffer_len;
149 return len;
153 * \brief remove data from ringbuffer
155 static int read_buffer(unsigned char* data,int len){
156 int first_len = ao->buffer_len - ao->buf_read_pos;
157 int buffered = buf_used();
158 if (len > buffered) len = buffered;
159 if (first_len > len) first_len = len;
160 // till end of buffer
161 if (data) {
162 memcpy (data, &ao->buffer[ao->buf_read_pos], first_len);
163 if (len > first_len) { // we have to wrap around
164 // remaining part from beginning of buffer
165 memcpy (&data[first_len], ao->buffer, len - first_len);
168 ao->buf_read_pos = (ao->buf_read_pos + len) % ao->buffer_len;
169 return len;
172 OSStatus theRenderProc(void *inRefCon, AudioUnitRenderActionFlags *inActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumFrames, AudioBufferList *ioData)
174 int amt=buf_used();
175 int req=(inNumFrames)*ao->packetSize;
177 if(amt>req)
178 amt=req;
180 if(amt)
181 read_buffer((unsigned char *)ioData->mBuffers[0].mData, amt);
182 else audio_pause();
183 ioData->mBuffers[0].mDataByteSize = amt;
185 return noErr;
188 static int control(int cmd,void *arg){
189 ao_control_vol_t *control_vol;
190 OSStatus err;
191 Float32 vol;
192 switch (cmd) {
193 case AOCONTROL_GET_VOLUME:
194 control_vol = (ao_control_vol_t*)arg;
195 if (ao->b_digital) {
196 // Digital output has no volume adjust.
197 return CONTROL_FALSE;
199 err = AudioUnitGetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, &vol);
201 if(err==0) {
202 // printf("GET VOL=%f\n", vol);
203 control_vol->left=control_vol->right=vol*100.0/4.0;
204 return CONTROL_TRUE;
206 else {
207 ao_msg(MSGT_AO, MSGL_WARN, "could not get HAL output volume: [%4.4s]\n", (char *)&err);
208 return CONTROL_FALSE;
211 case AOCONTROL_SET_VOLUME:
212 control_vol = (ao_control_vol_t*)arg;
214 if (ao->b_digital) {
215 // Digital output can not set volume. Here we have to return true
216 // to make mixer forget it. Else mixer will add a soft filter,
217 // that's not we expected and the filter not support ac3 stream
218 // will cause mplayer die.
220 // Although not support set volume, but at least we support mute.
221 // MPlayer set mute by set volume to zero, we handle it.
222 if (control_vol->left == 0 && control_vol->right == 0)
223 ao->b_muted = 1;
224 else
225 ao->b_muted = 0;
226 return CONTROL_TRUE;
229 vol=(control_vol->left+control_vol->right)*4.0/200.0;
230 err = AudioUnitSetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, vol, 0);
231 if(err==0) {
232 // printf("SET VOL=%f\n", vol);
233 return CONTROL_TRUE;
235 else {
236 ao_msg(MSGT_AO, MSGL_WARN, "could not set HAL output volume: [%4.4s]\n", (char *)&err);
237 return CONTROL_FALSE;
239 /* Everything is currently unimplemented */
240 default:
241 return CONTROL_FALSE;
247 static void print_format(int lev, const char* str, const AudioStreamBasicDescription *f){
248 uint32_t flags=(uint32_t) f->mFormatFlags;
249 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",
250 str, f->mSampleRate, f->mBitsPerChannel,
251 (int)(f->mFormatID & 0xff000000) >> 24,
252 (int)(f->mFormatID & 0x00ff0000) >> 16,
253 (int)(f->mFormatID & 0x0000ff00) >> 8,
254 (int)(f->mFormatID & 0x000000ff) >> 0,
255 f->mFormatFlags, f->mBytesPerPacket,
256 f->mFramesPerPacket, f->mBytesPerFrame,
257 f->mChannelsPerFrame,
258 (flags&kAudioFormatFlagIsFloat) ? "float" : "int",
259 (flags&kAudioFormatFlagIsBigEndian) ? "BE" : "LE",
260 (flags&kAudioFormatFlagIsSignedInteger) ? "S" : "U",
261 (flags&kAudioFormatFlagIsPacked) ? " packed" : "",
262 (flags&kAudioFormatFlagIsAlignedHigh) ? " aligned" : "",
263 (flags&kAudioFormatFlagIsNonInterleaved) ? " ni" : "" );
267 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id );
268 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id );
269 static int OpenSPDIF();
270 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format );
271 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
272 const AudioTimeStamp * inNow,
273 const void * inInputData,
274 const AudioTimeStamp * inInputTime,
275 AudioBufferList * outOutputData,
276 const AudioTimeStamp * inOutputTime,
277 void * threadGlobals );
278 static OSStatus StreamListener( AudioStreamID inStream,
279 UInt32 inChannel,
280 AudioDevicePropertyID inPropertyID,
281 void * inClientData );
282 static OSStatus DeviceListener( AudioDeviceID inDevice,
283 UInt32 inChannel,
284 Boolean isInput,
285 AudioDevicePropertyID inPropertyID,
286 void* inClientData );
288 static int init(int rate,int channels,int format,int flags)
290 AudioStreamBasicDescription inDesc;
291 ComponentDescription desc;
292 Component comp;
293 AURenderCallbackStruct renderCallback;
294 OSStatus err;
295 UInt32 size, maxFrames, i_param_size;
296 char *psz_name;
297 AudioDeviceID devid_def = 0;
298 int b_alive;
300 ao_msg(MSGT_AO,MSGL_V, "init([%dHz][%dch][%s][%d])\n", rate, channels, af_fmt2str_short(format), flags);
302 ao = calloc(1, sizeof(ao_macosx_t));
304 ao->i_selected_dev = 0;
305 ao->b_supports_digital = 0;
306 ao->b_digital = 0;
307 ao->b_muted = 0;
308 ao->b_stream_format_changed = 0;
309 ao->i_hog_pid = -1;
310 ao->i_stream_id = 0;
311 ao->i_stream_index = -1;
312 ao->b_revert = 0;
313 ao->b_changed_mixing = 0;
315 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
316 if ((format & AF_FORMAT_SPECIAL_MASK) == AF_FORMAT_AC3)
318 /* Find the ID of the default Device. */
319 i_param_size = sizeof(AudioDeviceID);
320 err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
321 &i_param_size, &devid_def);
322 if (err != noErr)
324 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device: [%4.4s]\n", (char *)&err);
325 goto err_out;
328 /* Retrieve the length of the device name. */
329 i_param_size = 0;
330 err = AudioDeviceGetPropertyInfo(devid_def, 0, 0,
331 kAudioDevicePropertyDeviceName,
332 &i_param_size, NULL);
333 if (err != noErr)
335 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name length: [%4.4s]\n", (char *)&err);
336 goto err_out;
339 /* Retrieve the name of the device. */
340 psz_name = (char *)malloc(i_param_size);
341 err = AudioDeviceGetProperty(devid_def, 0, 0,
342 kAudioDevicePropertyDeviceName,
343 &i_param_size, psz_name);
344 if (err != noErr)
346 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name: [%4.4s]\n", (char *)&err);
347 free( psz_name);
348 goto err_out;
351 ao_msg(MSGT_AO,MSGL_V, "got default audio output device ID: %#lx Name: %s\n", devid_def, psz_name );
353 if (AudioDeviceSupportsDigital(devid_def))
355 ao->b_supports_digital = 1;
356 ao->i_selected_dev = devid_def;
358 ao_msg(MSGT_AO,MSGL_V, "probe default audio output device whether support digital s/pdif output:%d\n", ao->b_supports_digital );
360 free( psz_name);
363 // Build Description for the input format
364 inDesc.mSampleRate=rate;
365 inDesc.mFormatID=ao->b_supports_digital ? kAudioFormat60958AC3 : kAudioFormatLinearPCM;
366 inDesc.mChannelsPerFrame=channels;
367 switch(format&AF_FORMAT_BITS_MASK){
368 case AF_FORMAT_8BIT:
369 inDesc.mBitsPerChannel=8;
370 break;
371 case AF_FORMAT_16BIT:
372 inDesc.mBitsPerChannel=16;
373 break;
374 case AF_FORMAT_24BIT:
375 inDesc.mBitsPerChannel=24;
376 break;
377 case AF_FORMAT_32BIT:
378 inDesc.mBitsPerChannel=32;
379 break;
380 default:
381 ao_msg(MSGT_AO, MSGL_WARN, "Unsupported format (0x%08x)\n", format);
382 goto err_out;
385 if((format&AF_FORMAT_POINT_MASK)==AF_FORMAT_F) {
386 // float
387 inDesc.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked;
389 else if((format&AF_FORMAT_SIGN_MASK)==AF_FORMAT_SI) {
390 // signed int
391 inDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger|kAudioFormatFlagIsPacked;
393 else {
394 // unsigned int
395 inDesc.mFormatFlags = kAudioFormatFlagIsPacked;
397 if ((format & AF_FORMAT_SPECIAL_MASK) == AF_FORMAT_AC3) {
398 // Currently ac3 input (comes from hwac3) is always in native byte-order.
399 #ifdef WORDS_BIGENDIAN
400 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
401 #endif
403 else if ((format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
404 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
406 inDesc.mFramesPerPacket = 1;
407 ao->packetSize = inDesc.mBytesPerPacket = inDesc.mBytesPerFrame = inDesc.mFramesPerPacket*channels*(inDesc.mBitsPerChannel/8);
408 print_format(MSGL_V, "source:",&inDesc);
410 if (ao->b_supports_digital)
412 b_alive = 1;
413 i_param_size = sizeof(b_alive);
414 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
415 kAudioDevicePropertyDeviceIsAlive,
416 &i_param_size, &b_alive);
417 if (err != noErr)
418 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is alive: [%4.4s]\n", (char *)&err);
419 if (!b_alive)
420 ao_msg(MSGT_AO, MSGL_WARN, "device is not alive\n" );
421 /* S/PDIF output need device in HogMode. */
422 i_param_size = sizeof(ao->i_hog_pid);
423 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
424 kAudioDevicePropertyHogMode,
425 &i_param_size, &ao->i_hog_pid);
427 if (err != noErr)
429 /* This is not a fatal error. Some drivers simply don't support this property. */
430 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is hogged: [%4.4s]\n",
431 (char *)&err);
432 ao->i_hog_pid = -1;
435 if (ao->i_hog_pid != -1 && ao->i_hog_pid != getpid())
437 ao_msg(MSGT_AO, MSGL_WARN, "Selected audio device is exclusively in use by another program.\n" );
438 goto err_out;
440 ao->stream_format = inDesc;
441 return OpenSPDIF();
444 /* original analog output code */
445 desc.componentType = kAudioUnitType_Output;
446 desc.componentSubType = kAudioUnitSubType_DefaultOutput;
447 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
448 desc.componentFlags = 0;
449 desc.componentFlagsMask = 0;
451 comp = FindNextComponent(NULL, &desc); //Finds an component that meets the desc spec's
452 if (comp == NULL) {
453 ao_msg(MSGT_AO, MSGL_WARN, "Unable to find Output Unit component\n");
454 goto err_out;
457 err = OpenAComponent(comp, &(ao->theOutputUnit)); //gains access to the services provided by the component
458 if (err) {
459 ao_msg(MSGT_AO, MSGL_WARN, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err);
460 goto err_out;
463 // Initialize AudioUnit
464 err = AudioUnitInitialize(ao->theOutputUnit);
465 if (err) {
466 ao_msg(MSGT_AO, MSGL_WARN, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err);
467 goto err_out1;
470 size = sizeof(AudioStreamBasicDescription);
471 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inDesc, size);
473 if (err) {
474 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the input format: [%4.4s]\n", (char *)&err);
475 goto err_out2;
478 size = sizeof(UInt32);
479 err = AudioUnitGetProperty(ao->theOutputUnit, kAudioDevicePropertyBufferSize, kAudioUnitScope_Input, 0, &maxFrames, &size);
481 if (err)
483 ao_msg(MSGT_AO,MSGL_WARN, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err);
484 goto err_out2;
487 ao->chunk_size = maxFrames;//*inDesc.mBytesPerFrame;
489 ao_data.samplerate = inDesc.mSampleRate;
490 ao_data.channels = inDesc.mChannelsPerFrame;
491 ao_data.bps = ao_data.samplerate * inDesc.mBytesPerFrame;
492 ao_data.outburst = ao->chunk_size;
493 ao_data.buffersize = ao_data.bps;
495 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
496 ao->buffer_len = (ao->num_chunks + 1) * ao->chunk_size;
497 ao->buffer = calloc(ao->num_chunks + 1, ao->chunk_size);
499 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);
501 renderCallback.inputProc = theRenderProc;
502 renderCallback.inputProcRefCon = 0;
503 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
504 if (err) {
505 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the render callback: [%4.4s]\n", (char *)&err);
506 goto err_out2;
509 reset();
511 return CONTROL_OK;
513 err_out2:
514 AudioUnitUninitialize(ao->theOutputUnit);
515 err_out1:
516 CloseComponent(ao->theOutputUnit);
517 err_out:
518 free(ao->buffer);
519 free(ao);
520 ao = NULL;
521 return CONTROL_FALSE;
524 /*****************************************************************************
525 * Setup a encoded digital stream (SPDIF)
526 *****************************************************************************/
527 static int OpenSPDIF()
529 OSStatus err = noErr;
530 UInt32 i_param_size, b_mix = 0;
531 Boolean b_writeable = 0;
532 AudioStreamID *p_streams = NULL;
533 int i, i_streams = 0;
535 /* Start doing the SPDIF setup process. */
536 ao->b_digital = 1;
538 /* Hog the device. */
539 i_param_size = sizeof(ao->i_hog_pid);
540 ao->i_hog_pid = getpid() ;
542 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
543 kAudioDevicePropertyHogMode, i_param_size, &ao->i_hog_pid);
545 if (err != noErr)
547 ao_msg(MSGT_AO, MSGL_WARN, "failed to set hogmode: [%4.4s]\n", (char *)&err);
548 ao->i_hog_pid = -1;
549 goto err_out;
552 /* Set mixable to false if we are allowed to. */
553 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE,
554 kAudioDevicePropertySupportsMixing,
555 &i_param_size, &b_writeable);
556 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
557 kAudioDevicePropertySupportsMixing,
558 &i_param_size, &b_mix);
559 if (err != noErr && b_writeable)
561 b_mix = 0;
562 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
563 kAudioDevicePropertySupportsMixing,
564 i_param_size, &b_mix);
565 ao->b_changed_mixing = 1;
567 if (err != noErr)
569 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
570 goto err_out;
573 /* Get a list of all the streams on this device. */
574 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE,
575 kAudioDevicePropertyStreams,
576 &i_param_size, NULL);
577 if (err != noErr)
579 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams: [%4.4s]\n", (char *)&err);
580 goto err_out;
583 i_streams = i_param_size / sizeof(AudioStreamID);
584 p_streams = (AudioStreamID *)malloc(i_param_size);
585 if (p_streams == NULL)
587 ao_msg(MSGT_AO, MSGL_WARN, "out of memory\n" );
588 goto err_out;
591 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
592 kAudioDevicePropertyStreams,
593 &i_param_size, p_streams);
594 if (err != noErr)
596 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams: [%4.4s]\n", (char *)&err);
597 if (p_streams) free(p_streams);
598 goto err_out;
601 ao_msg(MSGT_AO, MSGL_V, "current device stream number: %d\n", i_streams);
603 for (i = 0; i < i_streams && ao->i_stream_index < 0; ++i)
605 /* Find a stream with a cac3 stream. */
606 AudioStreamBasicDescription *p_format_list = NULL;
607 int i_formats = 0, j = 0, b_digital = 0;
609 /* Retrieve all the stream formats supported by each output stream. */
610 err = AudioStreamGetPropertyInfo(p_streams[i], 0,
611 kAudioStreamPropertyPhysicalFormats,
612 &i_param_size, NULL);
613 if (err != noErr)
615 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streamformats: [%4.4s]\n", (char *)&err);
616 continue;
619 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
620 p_format_list = (AudioStreamBasicDescription *)malloc(i_param_size);
621 if (p_format_list == NULL)
623 ao_msg(MSGT_AO, MSGL_WARN, "could not malloc the memory\n" );
624 continue;
627 err = AudioStreamGetProperty(p_streams[i], 0,
628 kAudioStreamPropertyPhysicalFormats,
629 &i_param_size, p_format_list);
630 if (err != noErr)
632 ao_msg(MSGT_AO, MSGL_WARN, "could not get the list of streamformats: [%4.4s]\n", (char *)&err);
633 if (p_format_list) free(p_format_list);
634 continue;
637 /* Check if one of the supported formats is a digital format. */
638 for (j = 0; j < i_formats; ++j)
640 if (p_format_list[j].mFormatID == 'IAC3' ||
641 p_format_list[j].mFormatID == kAudioFormat60958AC3)
643 b_digital = 1;
644 break;
648 if (b_digital)
650 /* If this stream supports a digital (cac3) format, then set it. */
651 int i_requested_rate_format = -1;
652 int i_current_rate_format = -1;
653 int i_backup_rate_format = -1;
655 ao->i_stream_id = p_streams[i];
656 ao->i_stream_index = i;
658 if (ao->b_revert == 0)
660 /* Retrieve the original format of this stream first if not done so already. */
661 i_param_size = sizeof(ao->sfmt_revert);
662 err = AudioStreamGetProperty(ao->i_stream_id, 0,
663 kAudioStreamPropertyPhysicalFormat,
664 &i_param_size,
665 &ao->sfmt_revert);
666 if (err != noErr)
668 ao_msg(MSGT_AO, MSGL_WARN, "could not retrieve the original streamformat: [%4.4s]\n", (char *)&err);
669 if (p_format_list) free(p_format_list);
670 continue;
672 ao->b_revert = 1;
675 for (j = 0; j < i_formats; ++j)
676 if (p_format_list[j].mFormatID == 'IAC3' ||
677 p_format_list[j].mFormatID == kAudioFormat60958AC3)
679 if (p_format_list[j].mSampleRate == ao->stream_format.mSampleRate)
681 i_requested_rate_format = j;
682 break;
684 if (p_format_list[j].mSampleRate == ao->sfmt_revert.mSampleRate)
685 i_current_rate_format = j;
686 else if (i_backup_rate_format < 0 || p_format_list[j].mSampleRate > p_format_list[i_backup_rate_format].mSampleRate)
687 i_backup_rate_format = j;
690 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio. */
691 ao->stream_format = p_format_list[i_requested_rate_format];
692 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device. */
693 ao->stream_format = p_format_list[i_current_rate_format];
694 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). */
696 if (p_format_list) free(p_format_list);
698 if (p_streams) free(p_streams);
700 if (ao->i_stream_index < 0)
702 ao_msg(MSGT_AO, MSGL_WARN, "can not find any digital output stream format when OpenSPDIF().\n");
703 goto err_out;
706 print_format(MSGL_V, "original stream format:", &ao->sfmt_revert);
708 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
709 goto err_out;
711 err = AudioDeviceAddPropertyListener(ao->i_selected_dev,
712 kAudioPropertyWildcardChannel,
714 kAudioDevicePropertyDeviceHasChanged,
715 DeviceListener,
716 NULL);
717 if (err != noErr)
718 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err);
721 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
722 /* Although there's no such case reported. */
723 #ifdef WORDS_BIGENDIAN
724 if (!(ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian))
725 #else
726 if (ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
727 #endif
728 ao_msg(MSGT_AO, MSGL_WARN, "output stream has a no-native byte-order, digital output may failed.\n");
730 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
731 ao->chunk_size = ao->stream_format.mBytesPerPacket;
733 ao_data.samplerate = ao->stream_format.mSampleRate;
734 ao_data.channels = ao->stream_format.mChannelsPerFrame;
735 ao_data.bps = ao_data.samplerate * (ao->stream_format.mBytesPerPacket/ao->stream_format.mFramesPerPacket);
736 ao_data.outburst = ao->chunk_size;
737 ao_data.buffersize = ao_data.bps;
739 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
740 ao->buffer_len = (ao->num_chunks + 1) * ao->chunk_size;
741 ao->buffer = calloc(ao->num_chunks + 1, ao->chunk_size);
743 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);
746 /* Add IOProc callback. */
747 err = AudioDeviceAddIOProc(ao->i_selected_dev,
748 (AudioDeviceIOProc)RenderCallbackSPDIF,
749 (void *)ao);
750 if (err != noErr)
752 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err);
753 goto err_out1;
756 reset();
758 return CONTROL_TRUE;
760 err_out1:
761 if (ao->b_revert)
762 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
763 err_out:
764 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
766 int b_mix = 1;
767 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
768 kAudioDevicePropertySupportsMixing,
769 i_param_size, &b_mix);
770 if (err != noErr)
771 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n",
772 (char *)&err);
774 if (ao->i_hog_pid == getpid())
776 ao->i_hog_pid = -1;
777 i_param_size = sizeof(ao->i_hog_pid);
778 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
779 kAudioDevicePropertyHogMode,
780 i_param_size, &ao->i_hog_pid);
781 if (err != noErr)
782 ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n",
783 (char *)&err);
785 free(ao->buffer);
786 free(ao);
787 ao = NULL;
788 return CONTROL_FALSE;
791 /*****************************************************************************
792 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
793 *****************************************************************************/
794 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id )
796 OSStatus err = noErr;
797 UInt32 i_param_size = 0;
798 AudioStreamID *p_streams = NULL;
799 int i = 0, i_streams = 0;
800 int b_return = CONTROL_FALSE;
802 /* Retrieve all the output streams. */
803 err = AudioDeviceGetPropertyInfo(i_dev_id, 0, FALSE,
804 kAudioDevicePropertyStreams,
805 &i_param_size, NULL);
806 if (err != noErr)
808 ao_msg(MSGT_AO,MSGL_V, "could not get number of streams: [%4.4s]\n", (char *)&err);
809 return CONTROL_FALSE;
812 i_streams = i_param_size / sizeof(AudioStreamID);
813 p_streams = (AudioStreamID *)malloc(i_param_size);
814 if (p_streams == NULL)
816 ao_msg(MSGT_AO,MSGL_V, "out of memory\n");
817 return CONTROL_FALSE;
820 err = AudioDeviceGetProperty(i_dev_id, 0, FALSE,
821 kAudioDevicePropertyStreams,
822 &i_param_size, p_streams);
824 if (err != noErr)
826 ao_msg(MSGT_AO,MSGL_V, "could not get number of streams: [%4.4s]\n", (char *)&err);
827 free(p_streams);
828 return CONTROL_FALSE;
831 for (i = 0; i < i_streams; ++i)
833 if (AudioStreamSupportsDigital(p_streams[i]))
834 b_return = CONTROL_OK;
837 free(p_streams);
838 return b_return;
841 /*****************************************************************************
842 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
843 *****************************************************************************/
844 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id )
846 OSStatus err = noErr;
847 UInt32 i_param_size;
848 AudioStreamBasicDescription *p_format_list = NULL;
849 int i, i_formats, b_return = CONTROL_FALSE;
851 /* Retrieve all the stream formats supported by each output stream. */
852 err = AudioStreamGetPropertyInfo(i_stream_id, 0,
853 kAudioStreamPropertyPhysicalFormats,
854 &i_param_size, NULL);
855 if (err != noErr)
857 ao_msg(MSGT_AO,MSGL_V, "could not get number of streamformats: [%4.4s]\n", (char *)&err);
858 return CONTROL_FALSE;
861 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
862 p_format_list = (AudioStreamBasicDescription *)malloc(i_param_size);
863 if (p_format_list == NULL)
865 ao_msg(MSGT_AO,MSGL_V, "could not malloc the memory\n" );
866 return CONTROL_FALSE;
869 err = AudioStreamGetProperty(i_stream_id, 0,
870 kAudioStreamPropertyPhysicalFormats,
871 &i_param_size, p_format_list);
872 if (err != noErr)
874 ao_msg(MSGT_AO,MSGL_V, "could not get the list of streamformats: [%4.4s]\n", (char *)&err);
875 free(p_format_list);
876 return CONTROL_FALSE;
879 for (i = 0; i < i_formats; ++i)
881 print_format(MSGL_V, "supported format:", &p_format_list[i]);
883 if (p_format_list[i].mFormatID == 'IAC3' ||
884 p_format_list[i].mFormatID == kAudioFormat60958AC3)
885 b_return = CONTROL_OK;
888 free(p_format_list);
889 return b_return;
892 /*****************************************************************************
893 * AudioStreamChangeFormat: Change i_stream_id to change_format
894 *****************************************************************************/
895 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format )
897 OSStatus err = noErr;
898 UInt32 i_param_size = 0;
899 int i;
901 static volatile int stream_format_changed;
902 stream_format_changed = 0;
904 print_format(MSGL_V, "setting stream format:", &change_format);
906 /* Install the callback. */
907 err = AudioStreamAddPropertyListener(i_stream_id, 0,
908 kAudioStreamPropertyPhysicalFormat,
909 StreamListener,
910 (void *)&stream_format_changed);
911 if (err != noErr)
913 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err);
914 return CONTROL_FALSE;
917 /* Change the format. */
918 err = AudioStreamSetProperty(i_stream_id, 0, 0,
919 kAudioStreamPropertyPhysicalFormat,
920 sizeof(AudioStreamBasicDescription),
921 &change_format);
922 if (err != noErr)
924 ao_msg(MSGT_AO, MSGL_WARN, "could not set the stream format: [%4.4s]\n", (char *)&err);
925 return CONTROL_FALSE;
928 /* The AudioStreamSetProperty is not only asynchronious,
929 * it is also not Atomic, in its behaviour.
930 * Therefore we check 5 times before we really give up.
931 * FIXME: failing isn't actually implemented yet. */
932 for (i = 0; i < 5; ++i)
934 AudioStreamBasicDescription actual_format;
935 int j;
936 for (j = 0; !stream_format_changed && j < 50; ++j)
937 usec_sleep(10000);
938 if (stream_format_changed)
939 stream_format_changed = 0;
940 else
941 ao_msg(MSGT_AO, MSGL_V, "reached timeout\n" );
943 i_param_size = sizeof(AudioStreamBasicDescription);
944 err = AudioStreamGetProperty(i_stream_id, 0,
945 kAudioStreamPropertyPhysicalFormat,
946 &i_param_size,
947 &actual_format);
949 print_format(MSGL_V, "actual format in use:", &actual_format);
950 if (actual_format.mSampleRate == change_format.mSampleRate &&
951 actual_format.mFormatID == change_format.mFormatID &&
952 actual_format.mFramesPerPacket == change_format.mFramesPerPacket)
954 /* The right format is now active. */
955 break;
957 /* We need to check again. */
960 /* Removing the property listener. */
961 err = AudioStreamRemovePropertyListener(i_stream_id, 0,
962 kAudioStreamPropertyPhysicalFormat,
963 StreamListener);
964 if (err != noErr)
966 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err);
967 return CONTROL_FALSE;
970 return CONTROL_TRUE;
973 /*****************************************************************************
974 * RenderCallbackSPDIF: callback for SPDIF audio output
975 *****************************************************************************/
976 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
977 const AudioTimeStamp * inNow,
978 const void * inInputData,
979 const AudioTimeStamp * inInputTime,
980 AudioBufferList * outOutputData,
981 const AudioTimeStamp * inOutputTime,
982 void * threadGlobals )
984 int amt = buf_used();
985 int req = outOutputData->mBuffers[ao->i_stream_index].mDataByteSize;
987 if (amt > req)
988 amt = req;
989 if (amt)
990 read_buffer(ao->b_muted ? NULL : (unsigned char *)outOutputData->mBuffers[ao->i_stream_index].mData, amt);
992 return noErr;
996 static int play(void* output_samples,int num_bytes,int flags)
998 int wrote, b_digital;
1000 // Check whether we need to reset the digital output stream.
1001 if (ao->b_digital && ao->b_stream_format_changed)
1003 ao->b_stream_format_changed = 0;
1004 b_digital = AudioStreamSupportsDigital(ao->i_stream_id);
1005 if (b_digital)
1007 /* Current stream support digital format output, let's set it. */
1008 ao_msg(MSGT_AO, MSGL_V, "detected current stream support digital, try to restore digital output...\n");
1010 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
1012 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output failed.\n");
1014 else
1016 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output succeed.\n");
1017 reset();
1020 else
1021 ao_msg(MSGT_AO, MSGL_V, "detected current stream do not support digital.\n");
1024 wrote=write_buffer(output_samples, num_bytes);
1025 audio_resume();
1026 return wrote;
1029 /* set variables and buffer to initial state */
1030 static void reset(void)
1032 audio_pause();
1033 /* reset ring-buffer state */
1034 ao->buf_read_pos=0;
1035 ao->buf_write_pos=0;
1037 return;
1041 /* return available space */
1042 static int get_space(void)
1044 return buf_free();
1048 /* return delay until audio is played */
1049 static float get_delay(void)
1051 int buffered = ao->buffer_len - ao->chunk_size - buf_free(); // could be less
1052 // inaccurate, should also contain the data buffered e.g. by the OS
1053 return (float)(buffered)/(float)ao_data.bps;
1057 /* unload plugin and deregister from coreaudio */
1058 static void uninit(int immed)
1060 OSStatus err = noErr;
1061 UInt32 i_param_size = 0;
1063 if (!immed) {
1064 long long timeleft=(1000000LL*buf_used())/ao_data.bps;
1065 ao_msg(MSGT_AO,MSGL_DBG2, "%d bytes left @%d bps (%d usec)\n", buf_used(), ao_data.bps, (int)timeleft);
1066 usec_sleep((int)timeleft);
1069 if (!ao->b_digital) {
1070 AudioOutputUnitStop(ao->theOutputUnit);
1071 AudioUnitUninitialize(ao->theOutputUnit);
1072 CloseComponent(ao->theOutputUnit);
1074 else {
1075 /* Stop device. */
1076 err = AudioDeviceStop(ao->i_selected_dev,
1077 (AudioDeviceIOProc)RenderCallbackSPDIF);
1078 if (err != noErr)
1079 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1081 /* Remove IOProc callback. */
1082 err = AudioDeviceRemoveIOProc(ao->i_selected_dev,
1083 (AudioDeviceIOProc)RenderCallbackSPDIF);
1084 if (err != noErr)
1085 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err);
1087 if (ao->b_revert)
1088 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
1090 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
1092 int b_mix;
1093 Boolean b_writeable;
1094 /* Revert mixable to true if we are allowed to. */
1095 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
1096 &i_param_size, &b_writeable);
1097 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
1098 &i_param_size, &b_mix);
1099 if (err != noErr && b_writeable)
1101 b_mix = 1;
1102 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
1103 kAudioDevicePropertySupportsMixing, i_param_size, &b_mix);
1105 if (err != noErr)
1106 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
1108 if (ao->i_hog_pid == getpid())
1110 ao->i_hog_pid = -1;
1111 i_param_size = sizeof(ao->i_hog_pid);
1112 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
1113 kAudioDevicePropertyHogMode, i_param_size, &ao->i_hog_pid);
1114 if (err != noErr) ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n", (char *)&err);
1118 free(ao->buffer);
1119 free(ao);
1120 ao = NULL;
1124 /* stop playing, keep buffers (for pause) */
1125 static void audio_pause(void)
1127 OSErr err=noErr;
1129 /* Stop callback. */
1130 if (!ao->b_digital)
1132 err=AudioOutputUnitStop(ao->theOutputUnit);
1133 if (err != noErr)
1134 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err);
1136 else
1138 err = AudioDeviceStop(ao->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF);
1139 if (err != noErr)
1140 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1142 ao->paused = 1;
1146 /* resume playing, after audio_pause() */
1147 static void audio_resume(void)
1149 OSErr err=noErr;
1151 if (!ao->paused)
1152 return;
1154 /* Start callback. */
1155 if (!ao->b_digital)
1157 err = AudioOutputUnitStart(ao->theOutputUnit);
1158 if (err != noErr)
1159 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err);
1161 else
1163 err = AudioDeviceStart(ao->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF);
1164 if (err != noErr)
1165 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err);
1167 ao->paused = 0;
1170 /*****************************************************************************
1171 * StreamListener
1172 *****************************************************************************/
1173 static OSStatus StreamListener( AudioStreamID inStream,
1174 UInt32 inChannel,
1175 AudioDevicePropertyID inPropertyID,
1176 void * inClientData )
1178 switch (inPropertyID)
1180 case kAudioStreamPropertyPhysicalFormat:
1181 ao_msg(MSGT_AO, MSGL_V, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1182 if (inClientData)
1183 *(volatile int *)inClientData = 1;
1184 default:
1185 break;
1187 return noErr;
1190 static OSStatus DeviceListener( AudioDeviceID inDevice,
1191 UInt32 inChannel,
1192 Boolean isInput,
1193 AudioDevicePropertyID inPropertyID,
1194 void* inClientData )
1196 switch (inPropertyID)
1198 case kAudioDevicePropertyDeviceHasChanged:
1199 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1200 ao->b_stream_format_changed = 1;
1201 default:
1202 break;
1204 return noErr;