av_sub: Set size correctly for decoded text subs
[mplayer/glamo.git] / libao2 / ao_coreaudio.c
blobdffab4dd2e1e24ef7be80955590940bb5c3bf7dc
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"
57 static const ao_info_t info =
59 "Darwin/Mac OS X native audio output",
60 "coreaudio",
61 "Timothy J. Wood & Dan Christiansen & Chris Roccati",
65 LIBAO_EXTERN(coreaudio)
67 /* Prefix for all mp_msg() calls */
68 #define ao_msg(a, b, c...) mp_msg(a, b, "AO: [coreaudio] " c)
70 typedef struct ao_coreaudio_s
72 AudioDeviceID i_selected_dev; /* Keeps DeviceID of the selected device. */
73 int b_supports_digital; /* Does the currently selected device support digital mode? */
74 int b_digital; /* Are we running in digital mode? */
75 int b_muted; /* Are we muted in digital mode? */
77 /* AudioUnit */
78 AudioUnit theOutputUnit;
80 /* CoreAudio SPDIF mode specific */
81 pid_t i_hog_pid; /* Keeps the pid of our hog status. */
82 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
83 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
84 AudioStreamBasicDescription stream_format;/* The format we changed the stream to */
85 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
86 int b_revert; /* Whether we need to revert the stream format */
87 int b_changed_mixing; /* Whether we need to set the mixing mode back */
88 int b_stream_format_changed; /* Flag for main thread to reset stream's format to digital and reset buffer */
90 /* Original common part */
91 int packetSize;
92 int paused;
94 /* Ring-buffer */
95 AVFifoBuffer *buffer;
96 unsigned int buffer_len; ///< must always be num_chunks * chunk_size
97 unsigned int num_chunks;
98 unsigned int chunk_size;
99 } ao_coreaudio_t;
101 static ao_coreaudio_t *ao = NULL;
104 * \brief add data to ringbuffer
106 static int write_buffer(unsigned char* data, int len){
107 int free = ao->buffer_len - av_fifo_size(ao->buffer);
108 if (len > free) len = free;
109 return av_fifo_generic_write(ao->buffer, data, len, NULL);
113 * \brief remove data from ringbuffer
115 static int read_buffer(unsigned char* data,int len){
116 int buffered = av_fifo_size(ao->buffer);
117 if (len > buffered) len = buffered;
118 av_fifo_generic_read(ao->buffer, data, len, NULL);
119 return len;
122 static OSStatus theRenderProc(void *inRefCon,
123 AudioUnitRenderActionFlags *inActionFlags,
124 const AudioTimeStamp *inTimeStamp,
125 UInt32 inBusNumber, UInt32 inNumFrames,
126 AudioBufferList *ioData)
128 int amt=av_fifo_size(ao->buffer);
129 int req=(inNumFrames)*ao->packetSize;
131 if(amt>req)
132 amt=req;
134 if(amt)
135 read_buffer((unsigned char *)ioData->mBuffers[0].mData, amt);
136 else audio_pause();
137 ioData->mBuffers[0].mDataByteSize = amt;
139 return noErr;
142 static int control(int cmd,void *arg){
143 ao_control_vol_t *control_vol;
144 OSStatus err;
145 Float32 vol;
146 switch (cmd) {
147 case AOCONTROL_GET_VOLUME:
148 control_vol = (ao_control_vol_t*)arg;
149 if (ao->b_digital) {
150 // Digital output has no volume adjust.
151 return CONTROL_FALSE;
153 err = AudioUnitGetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, &vol);
155 if(err==0) {
156 // printf("GET VOL=%f\n", vol);
157 control_vol->left=control_vol->right=vol*100.0/4.0;
158 return CONTROL_TRUE;
160 else {
161 ao_msg(MSGT_AO, MSGL_WARN, "could not get HAL output volume: [%4.4s]\n", (char *)&err);
162 return CONTROL_FALSE;
165 case AOCONTROL_SET_VOLUME:
166 control_vol = (ao_control_vol_t*)arg;
168 if (ao->b_digital) {
169 // Digital output can not set volume. Here we have to return true
170 // to make mixer forget it. Else mixer will add a soft filter,
171 // that's not we expected and the filter not support ac3 stream
172 // will cause mplayer die.
174 // Although not support set volume, but at least we support mute.
175 // MPlayer set mute by set volume to zero, we handle it.
176 if (control_vol->left == 0 && control_vol->right == 0)
177 ao->b_muted = 1;
178 else
179 ao->b_muted = 0;
180 return CONTROL_TRUE;
183 vol=(control_vol->left+control_vol->right)*4.0/200.0;
184 err = AudioUnitSetParameter(ao->theOutputUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, 0, vol, 0);
185 if(err==0) {
186 // printf("SET VOL=%f\n", vol);
187 return CONTROL_TRUE;
189 else {
190 ao_msg(MSGT_AO, MSGL_WARN, "could not set HAL output volume: [%4.4s]\n", (char *)&err);
191 return CONTROL_FALSE;
193 /* Everything is currently unimplemented */
194 default:
195 return CONTROL_FALSE;
201 static void print_format(int lev, const char* str, const AudioStreamBasicDescription *f){
202 uint32_t flags=(uint32_t) f->mFormatFlags;
203 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",
204 str, f->mSampleRate, f->mBitsPerChannel,
205 (int)(f->mFormatID & 0xff000000) >> 24,
206 (int)(f->mFormatID & 0x00ff0000) >> 16,
207 (int)(f->mFormatID & 0x0000ff00) >> 8,
208 (int)(f->mFormatID & 0x000000ff) >> 0,
209 f->mFormatFlags, f->mBytesPerPacket,
210 f->mFramesPerPacket, f->mBytesPerFrame,
211 f->mChannelsPerFrame,
212 (flags&kAudioFormatFlagIsFloat) ? "float" : "int",
213 (flags&kAudioFormatFlagIsBigEndian) ? "BE" : "LE",
214 (flags&kAudioFormatFlagIsSignedInteger) ? "S" : "U",
215 (flags&kAudioFormatFlagIsPacked) ? " packed" : "",
216 (flags&kAudioFormatFlagIsAlignedHigh) ? " aligned" : "",
217 (flags&kAudioFormatFlagIsNonInterleaved) ? " ni" : "" );
221 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id );
222 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id );
223 static int OpenSPDIF(void);
224 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format );
225 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
226 const AudioTimeStamp * inNow,
227 const void * inInputData,
228 const AudioTimeStamp * inInputTime,
229 AudioBufferList * outOutputData,
230 const AudioTimeStamp * inOutputTime,
231 void * threadGlobals );
232 static OSStatus StreamListener( AudioStreamID inStream,
233 UInt32 inChannel,
234 AudioDevicePropertyID inPropertyID,
235 void * inClientData );
236 static OSStatus DeviceListener( AudioDeviceID inDevice,
237 UInt32 inChannel,
238 Boolean isInput,
239 AudioDevicePropertyID inPropertyID,
240 void* inClientData );
242 static int init(int rate,int channels,int format,int flags)
244 AudioStreamBasicDescription inDesc;
245 ComponentDescription desc;
246 Component comp;
247 AURenderCallbackStruct renderCallback;
248 OSStatus err;
249 UInt32 size, maxFrames, i_param_size;
250 char *psz_name;
251 AudioDeviceID devid_def = 0;
252 int b_alive;
254 ao_msg(MSGT_AO,MSGL_V, "init([%dHz][%dch][%s][%d])\n", rate, channels, af_fmt2str_short(format), flags);
256 ao = calloc(1, sizeof(ao_coreaudio_t));
258 ao->i_selected_dev = 0;
259 ao->b_supports_digital = 0;
260 ao->b_digital = 0;
261 ao->b_muted = 0;
262 ao->b_stream_format_changed = 0;
263 ao->i_hog_pid = -1;
264 ao->i_stream_id = 0;
265 ao->i_stream_index = -1;
266 ao->b_revert = 0;
267 ao->b_changed_mixing = 0;
269 /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
270 if (AF_FORMAT_IS_AC3(format))
272 /* Find the ID of the default Device. */
273 i_param_size = sizeof(AudioDeviceID);
274 err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
275 &i_param_size, &devid_def);
276 if (err != noErr)
278 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device: [%4.4s]\n", (char *)&err);
279 goto err_out;
282 /* Retrieve the length of the device name. */
283 i_param_size = 0;
284 err = AudioDeviceGetPropertyInfo(devid_def, 0, 0,
285 kAudioDevicePropertyDeviceName,
286 &i_param_size, NULL);
287 if (err != noErr)
289 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name length: [%4.4s]\n", (char *)&err);
290 goto err_out;
293 /* Retrieve the name of the device. */
294 psz_name = malloc(i_param_size);
295 err = AudioDeviceGetProperty(devid_def, 0, 0,
296 kAudioDevicePropertyDeviceName,
297 &i_param_size, psz_name);
298 if (err != noErr)
300 ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name: [%4.4s]\n", (char *)&err);
301 free( psz_name);
302 goto err_out;
305 ao_msg(MSGT_AO,MSGL_V, "got default audio output device ID: %#lx Name: %s\n", devid_def, psz_name );
307 if (AudioDeviceSupportsDigital(devid_def))
309 ao->b_supports_digital = 1;
310 ao->i_selected_dev = devid_def;
312 ao_msg(MSGT_AO,MSGL_V, "probe default audio output device whether support digital s/pdif output:%d\n", ao->b_supports_digital );
314 free( psz_name);
317 // Build Description for the input format
318 inDesc.mSampleRate=rate;
319 inDesc.mFormatID=ao->b_supports_digital ? kAudioFormat60958AC3 : kAudioFormatLinearPCM;
320 inDesc.mChannelsPerFrame=channels;
321 inDesc.mBitsPerChannel=af_fmt2bits(format);
323 if((format&AF_FORMAT_POINT_MASK)==AF_FORMAT_F) {
324 // float
325 inDesc.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked;
327 else if((format&AF_FORMAT_SIGN_MASK)==AF_FORMAT_SI) {
328 // signed int
329 inDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger|kAudioFormatFlagIsPacked;
331 else {
332 // unsigned int
333 inDesc.mFormatFlags = kAudioFormatFlagIsPacked;
335 if ((format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
336 inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
338 inDesc.mFramesPerPacket = 1;
339 ao->packetSize = inDesc.mBytesPerPacket = inDesc.mBytesPerFrame = inDesc.mFramesPerPacket*channels*(inDesc.mBitsPerChannel/8);
340 print_format(MSGL_V, "source:",&inDesc);
342 if (ao->b_supports_digital)
344 b_alive = 1;
345 i_param_size = sizeof(b_alive);
346 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
347 kAudioDevicePropertyDeviceIsAlive,
348 &i_param_size, &b_alive);
349 if (err != noErr)
350 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is alive: [%4.4s]\n", (char *)&err);
351 if (!b_alive)
352 ao_msg(MSGT_AO, MSGL_WARN, "device is not alive\n" );
353 /* S/PDIF output need device in HogMode. */
354 i_param_size = sizeof(ao->i_hog_pid);
355 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
356 kAudioDevicePropertyHogMode,
357 &i_param_size, &ao->i_hog_pid);
359 if (err != noErr)
361 /* This is not a fatal error. Some drivers simply don't support this property. */
362 ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is hogged: [%4.4s]\n",
363 (char *)&err);
364 ao->i_hog_pid = -1;
367 if (ao->i_hog_pid != -1 && ao->i_hog_pid != getpid())
369 ao_msg(MSGT_AO, MSGL_WARN, "Selected audio device is exclusively in use by another program.\n" );
370 goto err_out;
372 ao->stream_format = inDesc;
373 return OpenSPDIF();
376 /* original analog output code */
377 desc.componentType = kAudioUnitType_Output;
378 desc.componentSubType = kAudioUnitSubType_DefaultOutput;
379 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
380 desc.componentFlags = 0;
381 desc.componentFlagsMask = 0;
383 comp = FindNextComponent(NULL, &desc); //Finds an component that meets the desc spec's
384 if (comp == NULL) {
385 ao_msg(MSGT_AO, MSGL_WARN, "Unable to find Output Unit component\n");
386 goto err_out;
389 err = OpenAComponent(comp, &(ao->theOutputUnit)); //gains access to the services provided by the component
390 if (err) {
391 ao_msg(MSGT_AO, MSGL_WARN, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err);
392 goto err_out;
395 // Initialize AudioUnit
396 err = AudioUnitInitialize(ao->theOutputUnit);
397 if (err) {
398 ao_msg(MSGT_AO, MSGL_WARN, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err);
399 goto err_out1;
402 size = sizeof(AudioStreamBasicDescription);
403 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inDesc, size);
405 if (err) {
406 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the input format: [%4.4s]\n", (char *)&err);
407 goto err_out2;
410 size = sizeof(UInt32);
411 err = AudioUnitGetProperty(ao->theOutputUnit, kAudioDevicePropertyBufferSize, kAudioUnitScope_Input, 0, &maxFrames, &size);
413 if (err)
415 ao_msg(MSGT_AO,MSGL_WARN, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err);
416 goto err_out2;
419 ao->chunk_size = maxFrames;//*inDesc.mBytesPerFrame;
421 ao_data.samplerate = inDesc.mSampleRate;
422 ao_data.channels = inDesc.mChannelsPerFrame;
423 ao_data.bps = ao_data.samplerate * inDesc.mBytesPerFrame;
424 ao_data.outburst = ao->chunk_size;
425 ao_data.buffersize = ao_data.bps;
427 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
428 ao->buffer_len = ao->num_chunks * ao->chunk_size;
429 ao->buffer = av_fifo_alloc(ao->buffer_len);
431 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);
433 renderCallback.inputProc = theRenderProc;
434 renderCallback.inputProcRefCon = 0;
435 err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
436 if (err) {
437 ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the render callback: [%4.4s]\n", (char *)&err);
438 goto err_out2;
441 reset();
443 return CONTROL_OK;
445 err_out2:
446 AudioUnitUninitialize(ao->theOutputUnit);
447 err_out1:
448 CloseComponent(ao->theOutputUnit);
449 err_out:
450 av_fifo_free(ao->buffer);
451 free(ao);
452 ao = NULL;
453 return CONTROL_FALSE;
456 /*****************************************************************************
457 * Setup a encoded digital stream (SPDIF)
458 *****************************************************************************/
459 static int OpenSPDIF(void)
461 OSStatus err = noErr;
462 UInt32 i_param_size, b_mix = 0;
463 Boolean b_writeable = 0;
464 AudioStreamID *p_streams = NULL;
465 int i, i_streams = 0;
467 /* Start doing the SPDIF setup process. */
468 ao->b_digital = 1;
470 /* Hog the device. */
471 i_param_size = sizeof(ao->i_hog_pid);
472 ao->i_hog_pid = getpid() ;
474 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
475 kAudioDevicePropertyHogMode, i_param_size, &ao->i_hog_pid);
477 if (err != noErr)
479 ao_msg(MSGT_AO, MSGL_WARN, "failed to set hogmode: [%4.4s]\n", (char *)&err);
480 ao->i_hog_pid = -1;
481 goto err_out;
484 /* Set mixable to false if we are allowed to. */
485 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE,
486 kAudioDevicePropertySupportsMixing,
487 &i_param_size, &b_writeable);
488 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
489 kAudioDevicePropertySupportsMixing,
490 &i_param_size, &b_mix);
491 if (err != noErr && b_writeable)
493 b_mix = 0;
494 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
495 kAudioDevicePropertySupportsMixing,
496 i_param_size, &b_mix);
497 ao->b_changed_mixing = 1;
499 if (err != noErr)
501 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
502 goto err_out;
505 /* Get a list of all the streams on this device. */
506 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE,
507 kAudioDevicePropertyStreams,
508 &i_param_size, NULL);
509 if (err != noErr)
511 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams: [%4.4s]\n", (char *)&err);
512 goto err_out;
515 i_streams = i_param_size / sizeof(AudioStreamID);
516 p_streams = malloc(i_param_size);
517 if (p_streams == NULL)
519 ao_msg(MSGT_AO, MSGL_WARN, "out of memory\n" );
520 goto err_out;
523 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE,
524 kAudioDevicePropertyStreams,
525 &i_param_size, p_streams);
526 if (err != noErr)
528 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streams: [%4.4s]\n", (char *)&err);
529 if (p_streams) free(p_streams);
530 goto err_out;
533 ao_msg(MSGT_AO, MSGL_V, "current device stream number: %d\n", i_streams);
535 for (i = 0; i < i_streams && ao->i_stream_index < 0; ++i)
537 /* Find a stream with a cac3 stream. */
538 AudioStreamBasicDescription *p_format_list = NULL;
539 int i_formats = 0, j = 0, b_digital = 0;
541 /* Retrieve all the stream formats supported by each output stream. */
542 err = AudioStreamGetPropertyInfo(p_streams[i], 0,
543 kAudioStreamPropertyPhysicalFormats,
544 &i_param_size, NULL);
545 if (err != noErr)
547 ao_msg(MSGT_AO, MSGL_WARN, "could not get number of streamformats: [%4.4s]\n", (char *)&err);
548 continue;
551 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
552 p_format_list = malloc(i_param_size);
553 if (p_format_list == NULL)
555 ao_msg(MSGT_AO, MSGL_WARN, "could not malloc the memory\n" );
556 continue;
559 err = AudioStreamGetProperty(p_streams[i], 0,
560 kAudioStreamPropertyPhysicalFormats,
561 &i_param_size, p_format_list);
562 if (err != noErr)
564 ao_msg(MSGT_AO, MSGL_WARN, "could not get the list of streamformats: [%4.4s]\n", (char *)&err);
565 if (p_format_list) free(p_format_list);
566 continue;
569 /* Check if one of the supported formats is a digital format. */
570 for (j = 0; j < i_formats; ++j)
572 if (p_format_list[j].mFormatID == 'IAC3' ||
573 p_format_list[j].mFormatID == kAudioFormat60958AC3)
575 b_digital = 1;
576 break;
580 if (b_digital)
582 /* If this stream supports a digital (cac3) format, then set it. */
583 int i_requested_rate_format = -1;
584 int i_current_rate_format = -1;
585 int i_backup_rate_format = -1;
587 ao->i_stream_id = p_streams[i];
588 ao->i_stream_index = i;
590 if (ao->b_revert == 0)
592 /* Retrieve the original format of this stream first if not done so already. */
593 i_param_size = sizeof(ao->sfmt_revert);
594 err = AudioStreamGetProperty(ao->i_stream_id, 0,
595 kAudioStreamPropertyPhysicalFormat,
596 &i_param_size,
597 &ao->sfmt_revert);
598 if (err != noErr)
600 ao_msg(MSGT_AO, MSGL_WARN, "could not retrieve the original streamformat: [%4.4s]\n", (char *)&err);
601 if (p_format_list) free(p_format_list);
602 continue;
604 ao->b_revert = 1;
607 for (j = 0; j < i_formats; ++j)
608 if (p_format_list[j].mFormatID == 'IAC3' ||
609 p_format_list[j].mFormatID == kAudioFormat60958AC3)
611 if (p_format_list[j].mSampleRate == ao->stream_format.mSampleRate)
613 i_requested_rate_format = j;
614 break;
616 if (p_format_list[j].mSampleRate == ao->sfmt_revert.mSampleRate)
617 i_current_rate_format = j;
618 else if (i_backup_rate_format < 0 || p_format_list[j].mSampleRate > p_format_list[i_backup_rate_format].mSampleRate)
619 i_backup_rate_format = j;
622 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio. */
623 ao->stream_format = p_format_list[i_requested_rate_format];
624 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device. */
625 ao->stream_format = p_format_list[i_current_rate_format];
626 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). */
628 if (p_format_list) free(p_format_list);
630 if (p_streams) free(p_streams);
632 if (ao->i_stream_index < 0)
634 ao_msg(MSGT_AO, MSGL_WARN, "can not find any digital output stream format when OpenSPDIF().\n");
635 goto err_out;
638 print_format(MSGL_V, "original stream format:", &ao->sfmt_revert);
640 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
641 goto err_out;
643 err = AudioDeviceAddPropertyListener(ao->i_selected_dev,
644 kAudioPropertyWildcardChannel,
646 kAudioDevicePropertyDeviceHasChanged,
647 DeviceListener,
648 NULL);
649 if (err != noErr)
650 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddPropertyListener for kAudioDevicePropertyDeviceHasChanged failed: [%4.4s]\n", (char *)&err);
653 /* FIXME: If output stream is not native byte-order, we need change endian somewhere. */
654 /* Although there's no such case reported. */
655 #if HAVE_BIGENDIAN
656 if (!(ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian))
657 #else
658 if (ao->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
659 #endif
660 ao_msg(MSGT_AO, MSGL_WARN, "output stream has a no-native byte-order, digital output may failed.\n");
662 /* For ac3/dts, just use packet size 6144 bytes as chunk size. */
663 ao->chunk_size = ao->stream_format.mBytesPerPacket;
665 ao_data.samplerate = ao->stream_format.mSampleRate;
666 ao_data.channels = ao->stream_format.mChannelsPerFrame;
667 ao_data.bps = ao_data.samplerate * (ao->stream_format.mBytesPerPacket/ao->stream_format.mFramesPerPacket);
668 ao_data.outburst = ao->chunk_size;
669 ao_data.buffersize = ao_data.bps;
671 ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
672 ao->buffer_len = ao->num_chunks * ao->chunk_size;
673 ao->buffer = av_fifo_alloc(ao->buffer_len);
675 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);
678 /* Add IOProc callback. */
679 err = AudioDeviceAddIOProc(ao->i_selected_dev,
680 (AudioDeviceIOProc)RenderCallbackSPDIF,
681 (void *)ao);
682 if (err != noErr)
684 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceAddIOProc failed: [%4.4s]\n", (char *)&err);
685 goto err_out1;
688 reset();
690 return CONTROL_TRUE;
692 err_out1:
693 if (ao->b_revert)
694 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
695 err_out:
696 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
698 int b_mix = 1;
699 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
700 kAudioDevicePropertySupportsMixing,
701 i_param_size, &b_mix);
702 if (err != noErr)
703 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n",
704 (char *)&err);
706 if (ao->i_hog_pid == getpid())
708 ao->i_hog_pid = -1;
709 i_param_size = sizeof(ao->i_hog_pid);
710 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
711 kAudioDevicePropertyHogMode,
712 i_param_size, &ao->i_hog_pid);
713 if (err != noErr)
714 ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n",
715 (char *)&err);
717 av_fifo_free(ao->buffer);
718 free(ao);
719 ao = NULL;
720 return CONTROL_FALSE;
723 /*****************************************************************************
724 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
725 *****************************************************************************/
726 static int AudioDeviceSupportsDigital( AudioDeviceID i_dev_id )
728 OSStatus err = noErr;
729 UInt32 i_param_size = 0;
730 AudioStreamID *p_streams = NULL;
731 int i = 0, i_streams = 0;
732 int b_return = CONTROL_FALSE;
734 /* Retrieve all the output streams. */
735 err = AudioDeviceGetPropertyInfo(i_dev_id, 0, FALSE,
736 kAudioDevicePropertyStreams,
737 &i_param_size, NULL);
738 if (err != noErr)
740 ao_msg(MSGT_AO,MSGL_V, "could not get number of streams: [%4.4s]\n", (char *)&err);
741 return CONTROL_FALSE;
744 i_streams = i_param_size / sizeof(AudioStreamID);
745 p_streams = malloc(i_param_size);
746 if (p_streams == NULL)
748 ao_msg(MSGT_AO,MSGL_V, "out of memory\n");
749 return CONTROL_FALSE;
752 err = AudioDeviceGetProperty(i_dev_id, 0, FALSE,
753 kAudioDevicePropertyStreams,
754 &i_param_size, p_streams);
756 if (err != noErr)
758 ao_msg(MSGT_AO,MSGL_V, "could not get number of streams: [%4.4s]\n", (char *)&err);
759 free(p_streams);
760 return CONTROL_FALSE;
763 for (i = 0; i < i_streams; ++i)
765 if (AudioStreamSupportsDigital(p_streams[i]))
766 b_return = CONTROL_OK;
769 free(p_streams);
770 return b_return;
773 /*****************************************************************************
774 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
775 *****************************************************************************/
776 static int AudioStreamSupportsDigital( AudioStreamID i_stream_id )
778 OSStatus err = noErr;
779 UInt32 i_param_size;
780 AudioStreamBasicDescription *p_format_list = NULL;
781 int i, i_formats, b_return = CONTROL_FALSE;
783 /* Retrieve all the stream formats supported by each output stream. */
784 err = AudioStreamGetPropertyInfo(i_stream_id, 0,
785 kAudioStreamPropertyPhysicalFormats,
786 &i_param_size, NULL);
787 if (err != noErr)
789 ao_msg(MSGT_AO,MSGL_V, "could not get number of streamformats: [%4.4s]\n", (char *)&err);
790 return CONTROL_FALSE;
793 i_formats = i_param_size / sizeof(AudioStreamBasicDescription);
794 p_format_list = malloc(i_param_size);
795 if (p_format_list == NULL)
797 ao_msg(MSGT_AO,MSGL_V, "could not malloc the memory\n" );
798 return CONTROL_FALSE;
801 err = AudioStreamGetProperty(i_stream_id, 0,
802 kAudioStreamPropertyPhysicalFormats,
803 &i_param_size, p_format_list);
804 if (err != noErr)
806 ao_msg(MSGT_AO,MSGL_V, "could not get the list of streamformats: [%4.4s]\n", (char *)&err);
807 free(p_format_list);
808 return CONTROL_FALSE;
811 for (i = 0; i < i_formats; ++i)
813 print_format(MSGL_V, "supported format:", &p_format_list[i]);
815 if (p_format_list[i].mFormatID == 'IAC3' ||
816 p_format_list[i].mFormatID == kAudioFormat60958AC3)
817 b_return = CONTROL_OK;
820 free(p_format_list);
821 return b_return;
824 /*****************************************************************************
825 * AudioStreamChangeFormat: Change i_stream_id to change_format
826 *****************************************************************************/
827 static int AudioStreamChangeFormat( AudioStreamID i_stream_id, AudioStreamBasicDescription change_format )
829 OSStatus err = noErr;
830 UInt32 i_param_size = 0;
831 int i;
833 static volatile int stream_format_changed;
834 stream_format_changed = 0;
836 print_format(MSGL_V, "setting stream format:", &change_format);
838 /* Install the callback. */
839 err = AudioStreamAddPropertyListener(i_stream_id, 0,
840 kAudioStreamPropertyPhysicalFormat,
841 StreamListener,
842 (void *)&stream_format_changed);
843 if (err != noErr)
845 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamAddPropertyListener failed: [%4.4s]\n", (char *)&err);
846 return CONTROL_FALSE;
849 /* Change the format. */
850 err = AudioStreamSetProperty(i_stream_id, 0, 0,
851 kAudioStreamPropertyPhysicalFormat,
852 sizeof(AudioStreamBasicDescription),
853 &change_format);
854 if (err != noErr)
856 ao_msg(MSGT_AO, MSGL_WARN, "could not set the stream format: [%4.4s]\n", (char *)&err);
857 return CONTROL_FALSE;
860 /* The AudioStreamSetProperty is not only asynchronious,
861 * it is also not Atomic, in its behaviour.
862 * Therefore we check 5 times before we really give up.
863 * FIXME: failing isn't actually implemented yet. */
864 for (i = 0; i < 5; ++i)
866 AudioStreamBasicDescription actual_format;
867 int j;
868 for (j = 0; !stream_format_changed && j < 50; ++j)
869 usec_sleep(10000);
870 if (stream_format_changed)
871 stream_format_changed = 0;
872 else
873 ao_msg(MSGT_AO, MSGL_V, "reached timeout\n" );
875 i_param_size = sizeof(AudioStreamBasicDescription);
876 err = AudioStreamGetProperty(i_stream_id, 0,
877 kAudioStreamPropertyPhysicalFormat,
878 &i_param_size,
879 &actual_format);
881 print_format(MSGL_V, "actual format in use:", &actual_format);
882 if (actual_format.mSampleRate == change_format.mSampleRate &&
883 actual_format.mFormatID == change_format.mFormatID &&
884 actual_format.mFramesPerPacket == change_format.mFramesPerPacket)
886 /* The right format is now active. */
887 break;
889 /* We need to check again. */
892 /* Removing the property listener. */
893 err = AudioStreamRemovePropertyListener(i_stream_id, 0,
894 kAudioStreamPropertyPhysicalFormat,
895 StreamListener);
896 if (err != noErr)
898 ao_msg(MSGT_AO, MSGL_WARN, "AudioStreamRemovePropertyListener failed: [%4.4s]\n", (char *)&err);
899 return CONTROL_FALSE;
902 return CONTROL_TRUE;
905 /*****************************************************************************
906 * RenderCallbackSPDIF: callback for SPDIF audio output
907 *****************************************************************************/
908 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
909 const AudioTimeStamp * inNow,
910 const void * inInputData,
911 const AudioTimeStamp * inInputTime,
912 AudioBufferList * outOutputData,
913 const AudioTimeStamp * inOutputTime,
914 void * threadGlobals )
916 int amt = av_fifo_size(ao->buffer);
917 int req = outOutputData->mBuffers[ao->i_stream_index].mDataByteSize;
919 if (amt > req)
920 amt = req;
921 if (amt)
922 read_buffer(ao->b_muted ? NULL : (unsigned char *)outOutputData->mBuffers[ao->i_stream_index].mData, amt);
924 return noErr;
928 static int play(void* output_samples,int num_bytes,int flags)
930 int wrote, b_digital;
932 // Check whether we need to reset the digital output stream.
933 if (ao->b_digital && ao->b_stream_format_changed)
935 ao->b_stream_format_changed = 0;
936 b_digital = AudioStreamSupportsDigital(ao->i_stream_id);
937 if (b_digital)
939 /* Current stream support digital format output, let's set it. */
940 ao_msg(MSGT_AO, MSGL_V, "detected current stream support digital, try to restore digital output...\n");
942 if (!AudioStreamChangeFormat(ao->i_stream_id, ao->stream_format))
944 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output failed.\n");
946 else
948 ao_msg(MSGT_AO, MSGL_WARN, "restore digital output succeed.\n");
949 reset();
952 else
953 ao_msg(MSGT_AO, MSGL_V, "detected current stream do not support digital.\n");
956 wrote=write_buffer(output_samples, num_bytes);
957 audio_resume();
958 return wrote;
961 /* set variables and buffer to initial state */
962 static void reset(void)
964 audio_pause();
965 av_fifo_reset(ao->buffer);
969 /* return available space */
970 static int get_space(void)
972 return ao->buffer_len - av_fifo_size(ao->buffer);
976 /* return delay until audio is played */
977 static float get_delay(void)
979 // inaccurate, should also contain the data buffered e.g. by the OS
980 return (float)av_fifo_size(ao->buffer)/(float)ao_data.bps;
984 /* unload plugin and deregister from coreaudio */
985 static void uninit(int immed)
987 OSStatus err = noErr;
988 UInt32 i_param_size = 0;
990 if (!immed) {
991 long long timeleft=(1000000LL*av_fifo_size(ao->buffer))/ao_data.bps;
992 ao_msg(MSGT_AO,MSGL_DBG2, "%d bytes left @%d bps (%d usec)\n", av_fifo_size(ao->buffer), ao_data.bps, (int)timeleft);
993 usec_sleep((int)timeleft);
996 if (!ao->b_digital) {
997 AudioOutputUnitStop(ao->theOutputUnit);
998 AudioUnitUninitialize(ao->theOutputUnit);
999 CloseComponent(ao->theOutputUnit);
1001 else {
1002 /* Stop device. */
1003 err = AudioDeviceStop(ao->i_selected_dev,
1004 (AudioDeviceIOProc)RenderCallbackSPDIF);
1005 if (err != noErr)
1006 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1008 /* Remove IOProc callback. */
1009 err = AudioDeviceRemoveIOProc(ao->i_selected_dev,
1010 (AudioDeviceIOProc)RenderCallbackSPDIF);
1011 if (err != noErr)
1012 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceRemoveIOProc failed: [%4.4s]\n", (char *)&err);
1014 if (ao->b_revert)
1015 AudioStreamChangeFormat(ao->i_stream_id, ao->sfmt_revert);
1017 if (ao->b_changed_mixing && ao->sfmt_revert.mFormatID != kAudioFormat60958AC3)
1019 int b_mix;
1020 Boolean b_writeable;
1021 /* Revert mixable to true if we are allowed to. */
1022 err = AudioDeviceGetPropertyInfo(ao->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
1023 &i_param_size, &b_writeable);
1024 err = AudioDeviceGetProperty(ao->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
1025 &i_param_size, &b_mix);
1026 if (err != noErr && b_writeable)
1028 b_mix = 1;
1029 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
1030 kAudioDevicePropertySupportsMixing, i_param_size, &b_mix);
1032 if (err != noErr)
1033 ao_msg(MSGT_AO, MSGL_WARN, "failed to set mixmode: [%4.4s]\n", (char *)&err);
1035 if (ao->i_hog_pid == getpid())
1037 ao->i_hog_pid = -1;
1038 i_param_size = sizeof(ao->i_hog_pid);
1039 err = AudioDeviceSetProperty(ao->i_selected_dev, 0, 0, FALSE,
1040 kAudioDevicePropertyHogMode, i_param_size, &ao->i_hog_pid);
1041 if (err != noErr) ao_msg(MSGT_AO, MSGL_WARN, "Could not release hogmode: [%4.4s]\n", (char *)&err);
1045 av_fifo_free(ao->buffer);
1046 free(ao);
1047 ao = NULL;
1051 /* stop playing, keep buffers (for pause) */
1052 static void audio_pause(void)
1054 OSErr err=noErr;
1056 /* Stop callback. */
1057 if (!ao->b_digital)
1059 err=AudioOutputUnitStop(ao->theOutputUnit);
1060 if (err != noErr)
1061 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStop returned [%4.4s]\n", (char *)&err);
1063 else
1065 err = AudioDeviceStop(ao->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF);
1066 if (err != noErr)
1067 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStop failed: [%4.4s]\n", (char *)&err);
1069 ao->paused = 1;
1073 /* resume playing, after audio_pause() */
1074 static void audio_resume(void)
1076 OSErr err=noErr;
1078 if (!ao->paused)
1079 return;
1081 /* Start callback. */
1082 if (!ao->b_digital)
1084 err = AudioOutputUnitStart(ao->theOutputUnit);
1085 if (err != noErr)
1086 ao_msg(MSGT_AO,MSGL_WARN, "AudioOutputUnitStart returned [%4.4s]\n", (char *)&err);
1088 else
1090 err = AudioDeviceStart(ao->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF);
1091 if (err != noErr)
1092 ao_msg(MSGT_AO, MSGL_WARN, "AudioDeviceStart failed: [%4.4s]\n", (char *)&err);
1094 ao->paused = 0;
1097 /*****************************************************************************
1098 * StreamListener
1099 *****************************************************************************/
1100 static OSStatus StreamListener( AudioStreamID inStream,
1101 UInt32 inChannel,
1102 AudioDevicePropertyID inPropertyID,
1103 void * inClientData )
1105 switch (inPropertyID)
1107 case kAudioStreamPropertyPhysicalFormat:
1108 ao_msg(MSGT_AO, MSGL_V, "got notify kAudioStreamPropertyPhysicalFormat changed.\n");
1109 if (inClientData)
1110 *(volatile int *)inClientData = 1;
1111 default:
1112 break;
1114 return noErr;
1117 static OSStatus DeviceListener( AudioDeviceID inDevice,
1118 UInt32 inChannel,
1119 Boolean isInput,
1120 AudioDevicePropertyID inPropertyID,
1121 void* inClientData )
1123 switch (inPropertyID)
1125 case kAudioDevicePropertyDeviceHasChanged:
1126 ao_msg(MSGT_AO, MSGL_WARN, "got notify kAudioDevicePropertyDeviceHasChanged.\n");
1127 ao->b_stream_format_changed = 1;
1128 default:
1129 break;
1131 return noErr;