Fix a bunch of warnings and errors
[vlc.git] / modules / audio_output / auhal.c
1 /*****************************************************************************
2  * auhal.c: AUHAL and Coreaudio output plugin
3  *****************************************************************************
4  * Copyright (C) 2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  * 
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <string.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/aout.h>
33
34 #include "aout_internal.h"
35
36 #include <CoreAudio/CoreAudio.h>
37 #include <AudioUnit/AudioUnitProperties.h>
38 #include <AudioUnit/AudioUnitParameters.h>
39 #include <AudioUnit/AudioOutputUnit.h>
40 #include <AudioToolbox/AudioFormat.h>
41
42 #define STREAM_FORMAT_MSG( pre, sfm ) \
43     pre "[%ld][%4.4s][%ld][%ld][%ld][%ld][%ld][%ld]", \
44     (UInt32)sfm.mSampleRate, (char *)&sfm.mFormatID, \
45     sfm.mFormatFlags, sfm.mBytesPerPacket, \
46     sfm.mFramesPerPacket, sfm.mBytesPerFrame, \
47     sfm.mChannelsPerFrame, sfm.mBitsPerChannel
48
49 #define STREAM_FORMAT_MSG_FULL( pre, sfm ) \
50     pre ":\nsamplerate: [%ld]\nFormatID: [%4.4s]\nFormatFlags: [%ld]\nBypesPerPacket: [%ld]\nFramesPerPacket: [%ld]\nBytesPerFrame: [%ld]\nChannelsPerFrame: [%ld]\nBitsPerChannel[%ld]", \
51     (UInt32)sfm.mSampleRate, (char *)&sfm.mFormatID, \
52     sfm.mFormatFlags, sfm.mBytesPerPacket, \
53     sfm.mFramesPerPacket, sfm.mBytesPerFrame, \
54     sfm.mChannelsPerFrame, sfm.mBitsPerChannel
55
56 #define BUFSIZE 0xffffff
57 #define AOUT_VAR_SPDIF_FLAG 0xf00000
58
59 /*
60  * TODO:
61  * - clean up the debug info
62  * - clean up C99'isms
63  * - be better at changing stream setup or devices setup changes while playing.
64  * - fix 6.1 and 7.1
65  */
66
67 /*****************************************************************************
68  * aout_sys_t: private audio output method descriptor
69  *****************************************************************************
70  * This structure is part of the audio output thread descriptor.
71  * It describes the CoreAudio specific properties of an output thread.
72  *****************************************************************************/
73 struct aout_sys_t
74 {
75     AudioDeviceID               i_default_dev;  /* Keeps DeviceID of defaultOutputDevice */
76     AudioDeviceID               i_selected_dev; /* Keeps DeviceID of the selected device */
77     UInt32                      i_devices;      /* Number of CoreAudio Devices */
78     vlc_bool_t                  b_supports_digital;/* Does the currently selected device support digital mode? */
79     vlc_bool_t                  b_digital;      /* Are we running in digital mode? */
80     mtime_t                     clock_diff;     /* Difference between VLC clock and Device clock */
81
82     /* AUHAL specific */
83     Component                   au_component;   /* The Audiocomponent we use */
84     AudioUnit                   au_unit;        /* The AudioUnit we use */
85     uint8_t                     p_remainder_buffer[BUFSIZE];
86     uint32_t                    i_read_bytes;
87     uint32_t                    i_total_bytes;
88
89     /* CoreAudio SPDIF mode specific */
90     pid_t                       i_hog_pid;      /* The keep the pid of our hog status */
91     AudioStreamID               i_stream_id;    /* The StreamID that has a cac3 streamformat */
92     int                         i_stream_index; /* The index of i_stream_id in an AudioBufferList */
93     AudioStreamBasicDescription stream_format;  /* The format we changed the stream to */
94     AudioStreamBasicDescription sfmt_revert;    /* The original format of the stream */
95     vlc_bool_t                  b_revert;       /* Wether we need to revert the stream format */
96     vlc_bool_t                  b_changed_mixing;/* Wether we need to set the mixing mode back */
97 };
98
99 /*****************************************************************************
100  * Local prototypes.
101  *****************************************************************************/
102 static int      Open                    ( vlc_object_t * );
103 static int      OpenAnalog              ( aout_instance_t * );
104 static int      OpenSPDIF               ( aout_instance_t * );
105 static void     Close                   ( vlc_object_t * );
106
107 static void     Play                    ( aout_instance_t * );
108 static void     Probe                   ( aout_instance_t * );
109
110 static int      AudioDeviceHasOutput    ( AudioDeviceID );
111 static int      AudioDeviceSupportsDigital( aout_instance_t *, AudioDeviceID );
112 static int      AudioStreamSupportsDigital( aout_instance_t *, AudioStreamID );
113 static int      AudioStreamChangeFormat ( aout_instance_t *, AudioStreamID, AudioStreamBasicDescription );
114
115 static OSStatus RenderCallbackAnalog    ( vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
116                                           unsigned int, unsigned int, AudioBufferList *);
117 static OSStatus RenderCallbackSPDIF     ( AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
118                                           AudioBufferList *, const AudioTimeStamp *, void * );
119 static OSStatus HardwareListener        ( AudioHardwarePropertyID, void *);
120 static OSStatus StreamListener          ( AudioStreamID, UInt32,
121                                           AudioDevicePropertyID, void * );
122 static int      AudioDeviceCallback     ( vlc_object_t *, const char *,
123                                           vlc_value_t, vlc_value_t, void * );
124
125
126 /*****************************************************************************
127  * Module descriptor
128  *****************************************************************************/
129 #define ADEV_TEXT N_("Audio Device")
130 #define ADEV_LONGTEXT N_("Choose a number corresponding to the number of an " \
131     "audio device, as listed in your 'Audio Device' menu. This device will " \
132     "then be used by default for audio playback.")
133
134 vlc_module_begin();
135     set_shortname( "auhal" );
136     set_description( _("HAL AudioUnit output") );
137     set_capability( "audio output", 101 );
138     set_category( CAT_AUDIO );
139     set_subcategory( SUBCAT_AUDIO_AOUT );
140     set_callbacks( Open, Close );
141     add_integer( "macosx-audio-device", 0, NULL, ADEV_TEXT, ADEV_LONGTEXT, VLC_FALSE ); 
142 vlc_module_end();
143
144 /*****************************************************************************
145  * Open: open macosx audio output
146  *****************************************************************************/
147 static int Open( vlc_object_t * p_this )
148 {
149     OSStatus                err = noErr;
150     UInt32                  i_param_size = 0;
151     struct aout_sys_t       *p_sys = NULL;
152     vlc_bool_t              b_alive = VLC_FALSE;
153     vlc_value_t             val;
154     aout_instance_t         *p_aout = (aout_instance_t *)p_this;
155
156     /* Allocate structure */
157     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
158     if( p_aout->output.p_sys == NULL )
159     {
160         msg_Err( p_aout, "out of memory" );
161         return( VLC_ENOMEM );
162     }
163
164     p_sys = p_aout->output.p_sys;
165     p_sys->i_default_dev = 0;
166     p_sys->i_selected_dev = 0;
167     p_sys->i_devices = 0;
168     p_sys->b_supports_digital = VLC_FALSE;
169     p_sys->b_digital = VLC_FALSE;
170     p_sys->au_component = NULL;
171     p_sys->au_unit = NULL;
172     p_sys->clock_diff = (mtime_t) 0;
173     p_sys->i_read_bytes = 0;
174     p_sys->i_total_bytes = 0;
175     p_sys->i_hog_pid = -1;
176     p_sys->i_stream_id = 0;
177     p_sys->i_stream_index = -1;
178     p_sys->b_revert = VLC_FALSE;
179     p_sys->b_changed_mixing = VLC_FALSE;
180     memset( p_sys->p_remainder_buffer, 0, sizeof(uint8_t) * BUFSIZE );
181
182     p_aout->output.pf_play = Play;
183     
184     aout_FormatPrint( p_aout, "VLC is looking for:", (audio_sample_format_t *)&p_aout->output.output );
185     
186     /* Persistent device variable */
187     if( var_Type( p_aout->p_vlc, "macosx-audio-device" ) == 0 )
188     {
189         var_Create( p_aout->p_vlc, "macosx-audio-device", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
190     }
191
192     /* Build a list of devices */
193     if( var_Type( p_aout, "audio-device" ) == 0 )
194     {
195         Probe( p_aout );
196     }
197
198     /* What device do we want? */
199     if( var_Get( p_aout, "audio-device", &val ) < 0 )
200     {
201         msg_Err( p_aout, "audio-device var does not exist. device probe failed." );
202         goto error;
203     }
204
205     p_sys->i_selected_dev = val.i_int & ~AOUT_VAR_SPDIF_FLAG; /* remove SPDIF flag to get the true DeviceID */
206     p_sys->b_supports_digital = ( val.i_int & AOUT_VAR_SPDIF_FLAG ) ? VLC_TRUE : VLC_FALSE;
207
208     /* Check if the desired device is alive and usable */
209     /* TODO: add a callback to the device to alert us if the device dies */
210     i_param_size = sizeof( b_alive );
211     err = AudioDeviceGetProperty( p_sys->i_selected_dev, 0, FALSE,
212                                   kAudioDevicePropertyDeviceIsAlive,
213                                   &i_param_size, &b_alive );
214
215     if( err != noErr )
216     {
217         msg_Err( p_aout, "could not check whether device is alive: %4.4s", (char *)&err );
218         goto error;
219     }
220
221     if( b_alive == VLC_FALSE )
222     {
223         msg_Warn( p_aout, "selected audio device is not alive, switching to default device" ); 
224         p_sys->i_selected_dev = p_sys->i_default_dev;
225     }
226
227     i_param_size = sizeof( p_sys->i_hog_pid );
228     err = AudioDeviceGetProperty( p_sys->i_selected_dev, 0, FALSE,
229                                   kAudioDevicePropertyHogMode,
230                                   &i_param_size, &p_sys->i_hog_pid );
231
232     if( err != noErr )
233     {
234         /* This is not a fatal error. Some drivers simply don't support this property */
235         msg_Warn( p_aout, "could not check whether device is hogged: %4.4s",
236                  (char *)&err );
237         p_sys->i_hog_pid = -1;
238     }
239
240     if( p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid() )
241     {
242         msg_Err( p_aout, "Selected audio device is exclusively in use by another program." );
243         goto error;
244     }
245
246     /* Check for Digital mode or Analog output mode */
247     if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) && p_sys->b_supports_digital )
248     {
249         if( OpenSPDIF( p_aout ) )
250             return VLC_SUCCESS;
251     }
252     else
253     {
254         if( OpenAnalog( p_aout ) )
255             return VLC_SUCCESS;
256     }
257
258 error:
259     /* If we reach this, this aout has failed */
260     var_Destroy( p_aout, "audio-device" );
261     if( p_sys ) free( p_sys );
262     return VLC_EGENERIC;
263 }
264
265 /*****************************************************************************
266  * Open: open and setup a HAL AudioUnit to do analog (multichannel) audio output
267  *****************************************************************************/
268 static int OpenAnalog( aout_instance_t *p_aout )
269 {
270     struct aout_sys_t           *p_sys = p_aout->output.p_sys;
271     OSStatus                    err = noErr;
272     UInt32                      i_param_size = 0, i = 0;
273     int                         i_original; 
274     ComponentDescription        desc;
275     AudioStreamBasicDescription DeviceFormat;
276     AudioChannelLayout          *layout;
277     AudioChannelLayout          new_layout;
278     AURenderCallbackStruct      input;
279
280     /* Lets go find our Component */
281     desc.componentType = kAudioUnitType_Output;
282     desc.componentSubType = kAudioUnitSubType_HALOutput;
283     desc.componentManufacturer = kAudioUnitManufacturer_Apple;
284     desc.componentFlags = 0;
285     desc.componentFlagsMask = 0;
286
287     p_sys->au_component = FindNextComponent( NULL, &desc );
288     if( p_sys->au_component == NULL )
289     {
290         msg_Warn( p_aout, "we cannot find our HAL component" );
291         return VLC_FALSE;
292     }
293
294     err = OpenAComponent( p_sys->au_component, &p_sys->au_unit );
295     if( err != noErr )
296     {
297         msg_Warn( p_aout, "we cannot open our HAL component" );
298         return VLC_FALSE;
299     }
300     
301     /* Set the device we will use for this output unit */
302     err = AudioUnitSetProperty( p_sys->au_unit,
303                          kAudioOutputUnitProperty_CurrentDevice,
304                          kAudioUnitScope_Global,
305                          0,
306                          &p_sys->i_selected_dev,
307                          sizeof( AudioDeviceID ));
308                          
309     if( err != noErr )
310     {
311         msg_Warn( p_aout, "we cannot select the audio device" );
312         return VLC_FALSE;
313     }
314                          
315     /* Get the current format */
316     i_param_size = sizeof(AudioStreamBasicDescription);
317
318     err = AudioUnitGetProperty( p_sys->au_unit,
319                                    kAudioUnitProperty_StreamFormat,
320                                    kAudioUnitScope_Input,
321                                    0,
322                                    &DeviceFormat,
323                                    &i_param_size );
324                                    
325     if( err != noErr ) return VLC_FALSE;
326     else msg_Dbg( p_aout, STREAM_FORMAT_MSG( "current format is: ", DeviceFormat ) );
327
328     /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
329     err = AudioUnitGetPropertyInfo( p_sys->au_unit,
330                                    kAudioDevicePropertyPreferredChannelLayout,
331                                    kAudioUnitScope_Output,
332                                    0,
333                                    &i_param_size,
334                                    NULL );
335
336     if( err == noErr )
337     {
338         layout = (AudioChannelLayout *)malloc( i_param_size);
339
340         verify_noerr( AudioUnitGetProperty( p_sys->au_unit,
341                                        kAudioDevicePropertyPreferredChannelLayout,
342                                        kAudioUnitScope_Output,
343                                        0,
344                                        layout,
345                                        &i_param_size ));
346                                        
347         /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
348         if( layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap)
349         {
350             /* bitmap defined channellayout */
351             verify_noerr( AudioFormatGetProperty( kAudioFormatProperty_ChannelLayoutForBitmap,
352                                     sizeof( UInt32), &layout->mChannelBitmap,
353                                     &i_param_size,
354                                     layout ));
355         }
356         else if( layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions )
357         {
358             /* layouttags defined channellayout */
359             verify_noerr( AudioFormatGetProperty( kAudioFormatProperty_ChannelLayoutForTag,
360                                     sizeof( AudioChannelLayoutTag ), &layout->mChannelLayoutTag,
361                                     &i_param_size,
362                                     layout ));
363         } 
364
365         msg_Dbg( p_aout, "layout of AUHAL has %d channels" , (int)layout->mNumberChannelDescriptions );
366         
367         /* Initialize the VLC core channel count */
368         p_aout->output.output.i_physical_channels = 0;
369         i_original = p_aout->output.output.i_original_channels & AOUT_CHAN_PHYSMASK;
370         
371         if( i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2 )
372         {
373             /* We only need Mono or cannot output more than 1 channel */
374             p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
375         }
376         else if( i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3 )
377         {
378             /* We only need Stereo or cannot output more than 2 channels */
379             p_aout->output.output.i_physical_channels = AOUT_CHAN_RIGHT | AOUT_CHAN_LEFT;
380         }
381         else
382         {
383             /* We want more than stereo and we can do that */
384             for( i = 0; i < layout->mNumberChannelDescriptions; i++ )
385             {
386                 msg_Dbg( p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel );
387
388                 switch( layout->mChannelDescriptions[i].mChannelLabel )
389                 {
390                     case kAudioChannelLabel_Left:
391                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_LEFT;
392                         continue;
393                     case kAudioChannelLabel_Right:
394                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_RIGHT;
395                         continue;
396                     case kAudioChannelLabel_Center:
397                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_CENTER;
398                         continue;
399                     case kAudioChannelLabel_LFEScreen:
400                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_LFE;
401                         continue;
402                     case kAudioChannelLabel_LeftSurround:
403                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_REARLEFT;
404                         continue;
405                     case kAudioChannelLabel_RightSurround:
406                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_REARRIGHT;
407                         continue;
408                     case kAudioChannelLabel_RearSurroundLeft:
409                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
410                         continue;
411                     case kAudioChannelLabel_RearSurroundRight:
412                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
413                         continue;
414                     case kAudioChannelLabel_CenterSurround:
415                         p_aout->output.output.i_physical_channels |= AOUT_CHAN_REARCENTER;
416                         continue;
417                     default:
418                         msg_Warn( p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel );
419                 }
420             }
421             if( p_aout->output.output.i_physical_channels == 0 )
422             {
423                 p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
424                 msg_Err( p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode." );
425             }
426         }
427         if( layout ) free( layout );
428     }
429     else
430     {
431         msg_Warn( p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!" );
432         p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
433     }
434
435     msg_Dbg( p_aout, "selected %d physical channels for device output", aout_FormatNbChannels( &p_aout->output.output ) );
436     msg_Dbg( p_aout, "VLC will output: %s", aout_FormatPrintChannels( &p_aout->output.output ));
437
438     memset (&new_layout, 0, sizeof(new_layout));
439     switch( aout_FormatNbChannels( &p_aout->output.output ) )
440     {
441         case 1:
442             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
443             break;
444         case 2:
445             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
446             break;
447         case 3:
448             if( p_aout->output.output.i_physical_channels & AOUT_CHAN_CENTER )
449             {
450                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
451             }
452             else if( p_aout->output.output.i_physical_channels & AOUT_CHAN_LFE )
453             {
454                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
455             }
456             break;
457         case 4:
458             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER | AOUT_CHAN_LFE ) )
459             {
460                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
461             }
462             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT ) )
463             {
464                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
465             }
466             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER ) )
467             {
468                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
469             }
470             break;
471         case 5:
472             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER ) )
473             {
474                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
475             }
476             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_LFE ) )
477             {
478                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
479             }
480             break;
481         case 6:
482             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_LFE ) )
483             {
484                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
485             }
486             else
487             {
488                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
489             }
490             break;
491         case 7:
492             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
493             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
494             break;
495         case 8:
496             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
497             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
498             break;
499     }
500
501     /* Set up the format to be used */
502     DeviceFormat.mSampleRate = p_aout->output.output.i_rate;
503     DeviceFormat.mFormatID = kAudioFormatLinearPCM;
504
505     /* We use float 32. It's the best supported format by both VLC and Coreaudio */
506     p_aout->output.output.i_format = VLC_FOURCC( 'f','l','3','2');
507     DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
508     DeviceFormat.mBitsPerChannel = 32;
509     DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels( &p_aout->output.output );
510     
511     /* Calculate framesizes and stuff */
512     DeviceFormat.mFramesPerPacket = 1;
513     DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
514     DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
515  
516     /* Set the desired format */
517     i_param_size = sizeof(AudioStreamBasicDescription);
518     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
519                                    kAudioUnitProperty_StreamFormat,
520                                    kAudioUnitScope_Input,
521                                    0,
522                                    &DeviceFormat,
523                                    i_param_size ));
524                                    
525     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "we set the AU format: " , DeviceFormat ) );
526     
527     /* Retrieve actual format */
528     verify_noerr( AudioUnitGetProperty( p_sys->au_unit,
529                                    kAudioUnitProperty_StreamFormat,
530                                    kAudioUnitScope_Input,
531                                    0,
532                                    &DeviceFormat,
533                                    &i_param_size ));
534                                    
535     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "the actual set AU format is " , DeviceFormat ) );
536
537     /* Do the last VLC aout setups */
538     aout_FormatPrepare( &p_aout->output.output );
539     p_aout->output.i_nb_samples = 2048;
540     aout_VolumeSoftInit( p_aout );
541
542     /* set the IOproc callback */
543     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
544     input.inputProcRefCon = p_aout;
545     
546     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
547                             kAudioUnitProperty_SetRenderCallback,
548                             kAudioUnitScope_Input,
549                             0, &input, sizeof( input ) ) );
550
551     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
552     input.inputProcRefCon = p_aout;
553     
554     /* Set the new_layout as the layout VLC will use to feed the AU unit */
555     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
556                             kAudioUnitProperty_AudioChannelLayout,
557                             kAudioUnitScope_Input,
558                             0, &new_layout, sizeof(new_layout) ) );
559                             
560     if( new_layout.mNumberChannelDescriptions > 0 )
561         free( new_layout.mChannelDescriptions );
562     
563     /* AU initiliaze */
564     verify_noerr( AudioUnitInitialize(p_sys->au_unit) );
565
566     /* Find the difference between device clock and mdate clock */
567     p_sys->clock_diff = - (mtime_t)
568         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
569     p_sys->clock_diff += mdate();
570
571     /* Start the AU */
572     verify_noerr( AudioOutputUnitStart(p_sys->au_unit) );
573     
574     return VLC_TRUE;
575 }
576
577 /*****************************************************************************
578  * Setup a encoded digital stream (SPDIF)
579  *****************************************************************************/
580 static int OpenSPDIF( aout_instance_t * p_aout )
581 {
582     struct aout_sys_t       *p_sys = p_aout->output.p_sys;
583     OSStatus                err = noErr;
584     UInt32                  i_param_size = 0, b_mix = 0;
585     Boolean                 b_writeable = VLC_FALSE;
586     AudioStreamID           *p_streams = NULL;
587     int                     i = 0, i_streams = 0;
588
589     /* Start doing the SPDIF setup proces */
590     p_sys->b_digital = VLC_TRUE;
591
592     /* Hog the device */
593     i_param_size = sizeof( p_sys->i_hog_pid );
594     p_sys->i_hog_pid = getpid() ;
595     
596     err = AudioDeviceSetProperty( p_sys->i_selected_dev, 0, 0, FALSE,
597                                   kAudioDevicePropertyHogMode, i_param_size, &p_sys->i_hog_pid );
598     
599     if( err != noErr )
600     {
601         msg_Err( p_aout, "failed to set hogmode: [%4.4s]", (char *)&err );
602         return VLC_FALSE;
603     }
604
605     /* Set mixable to false if we are allowed to */
606     err = AudioDeviceGetPropertyInfo( p_sys->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
607                                     &i_param_size, &b_writeable );
608
609     err = AudioDeviceGetProperty( p_sys->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
610                                     &i_param_size, &b_mix );
611                                     
612     if( !err && b_writeable )
613     {
614         b_mix = 0;
615         err = AudioDeviceSetProperty( p_sys->i_selected_dev, 0, 0, FALSE,
616                             kAudioDevicePropertySupportsMixing, i_param_size, &b_mix );
617         p_sys->b_changed_mixing = VLC_TRUE;
618     }
619     
620     if( err != noErr )
621     {
622         msg_Err( p_aout, "failed to set mixmode: [%4.4s]", (char *)&err );
623         return VLC_FALSE;
624     }
625
626     /* Get a list of all the streams on this device */
627     err = AudioDeviceGetPropertyInfo( p_sys->i_selected_dev, 0, FALSE,
628                                       kAudioDevicePropertyStreams,
629                                       &i_param_size, NULL );
630     if( err != noErr )
631     {
632         msg_Err( p_aout, "could not get number of streams: [%4.4s]", (char *)&err );
633         return VLC_FALSE;
634     }
635     
636     i_streams = i_param_size / sizeof( AudioStreamID );
637     p_streams = (AudioStreamID *)malloc( i_param_size );
638     if( p_streams == NULL )
639     {
640         msg_Err( p_aout, "out of memory" );
641         return VLC_FALSE;
642     }
643     
644     err = AudioDeviceGetProperty( p_sys->i_selected_dev, 0, FALSE,
645                                     kAudioDevicePropertyStreams,
646                                     &i_param_size, p_streams );
647     
648     if( err != noErr )
649     {
650         msg_Err( p_aout, "could not get number of streams: [%4.4s]", (char *)&err );
651         if( p_streams ) free( p_streams );
652         return VLC_FALSE;
653     }
654
655     for( i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++ )
656     {
657         /* Find a stream with a cac3 stream */
658         AudioStreamBasicDescription *p_format_list = NULL;
659         int                         i_formats = 0, j = 0;
660         vlc_bool_t                  b_digital = VLC_FALSE;
661         
662         /* Retrieve all the stream formats supported by each output stream */
663         err = AudioStreamGetPropertyInfo( p_streams[i], 0,
664                                           kAudioStreamPropertyPhysicalFormats,
665                                           &i_param_size, NULL );
666         if( err != noErr )
667         {
668             msg_Err( p_aout, "could not get number of streamformats: [%4.4s]", (char *)&err );
669             continue;
670         }
671         
672         i_formats = i_param_size / sizeof( AudioStreamBasicDescription );
673         p_format_list = (AudioStreamBasicDescription *)malloc( i_param_size );
674         if( p_format_list == NULL )
675         {
676             msg_Err( p_aout, "could not malloc the memory" );
677             continue;
678         }
679         
680         err = AudioStreamGetProperty( p_streams[i], 0,
681                                           kAudioStreamPropertyPhysicalFormats,
682                                           &i_param_size, p_format_list );
683         if( err != noErr )
684         {
685             msg_Err( p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err );
686             if( p_format_list) free( p_format_list);
687             continue;
688         }
689
690         /* Check if one of the supported formats is a digital format */
691         for( j = 0; j < i_formats; j++ )
692         {
693             if( p_format_list[j].mFormatID == 'IAC3' ||
694                   p_format_list[j].mFormatID == kAudioFormat60958AC3 )
695             {
696                 b_digital = VLC_TRUE;
697                 break;
698             }
699         }
700         
701         if( b_digital )
702         {
703             /* if this stream supports a digital (cac3) format, then go set it. */
704             int i_requested_rate_format = -1;
705             int i_current_rate_format = -1;
706             int i_backup_rate_format = -1;
707
708             p_sys->i_stream_id = p_streams[i];
709             p_sys->i_stream_index = i;
710
711             if( p_sys->b_revert == VLC_FALSE )
712             {
713                 /* Retrieve the original format of this stream first if not done so already */
714                 i_param_size = sizeof( p_sys->sfmt_revert );
715                 err = AudioStreamGetProperty( p_sys->i_stream_id, 0,
716                                               kAudioStreamPropertyPhysicalFormat,
717                                               &i_param_size, 
718                                               &p_sys->sfmt_revert );
719                 if( err != noErr )
720                 {
721                     msg_Err( p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err );
722                     continue; 
723                 }
724                 p_sys->b_revert = VLC_TRUE;
725             }
726
727             for( j = 0; j < i_formats; j++ )
728             {
729                 if( p_format_list[j].mFormatID == 'IAC3' ||
730                       p_format_list[j].mFormatID == kAudioFormat60958AC3 )
731                 {
732                     if( p_format_list[j].mSampleRate == p_aout->output.output.i_rate )
733                     {
734                         i_requested_rate_format = j;
735                         break;
736                     }
737                     else if( p_format_list[j].mSampleRate == p_sys->sfmt_revert.mSampleRate )
738                     {
739                         i_current_rate_format = j;
740                     }
741                     else
742                     {
743                         if( i_backup_rate_format < 0 || p_format_list[j].mSampleRate > p_format_list[i_backup_rate_format].mSampleRate )
744                             i_backup_rate_format = j;
745                     }
746                 }
747                     
748             }
749             
750             if( i_requested_rate_format >= 0 ) /* We prefer to output at the samplerate of the original audio */
751                 p_sys->stream_format = p_format_list[i_requested_rate_format];
752             else if( i_current_rate_format >= 0 ) /* If not possible, we will try to use the current samplerate of the device */
753                 p_sys->stream_format = p_format_list[i_current_rate_format];
754             else p_sys->stream_format = p_format_list[i_backup_rate_format]; /* And if we have to, any digital format will be just fine (highest rate possible) */
755         }
756         if( p_format_list ) free( p_format_list );
757     }
758     if( p_streams ) free( p_streams );
759
760     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "original stream format: ", p_sys->sfmt_revert ) );
761
762     if( !AudioStreamChangeFormat( p_aout, p_sys->i_stream_id, p_sys->stream_format ) )
763         return VLC_FALSE;
764
765     /* Set the format flags */
766     if( p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian )
767         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','b');
768     else
769         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
770     p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
771     p_aout->output.output.i_frame_length = A52_FRAME_NB;
772     p_aout->output.i_nb_samples = p_aout->output.output.i_frame_length;
773     p_aout->output.output.i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
774     aout_FormatPrepare( &p_aout->output.output );
775     aout_VolumeNoneInit( p_aout );
776
777     /* Add IOProc callback */
778     err = AudioDeviceAddIOProc( p_sys->i_selected_dev,
779                                 (AudioDeviceIOProc)RenderCallbackSPDIF,
780                                 (void *)p_aout );
781     if( err != noErr )
782     {
783         msg_Err( p_aout, "AudioDeviceAddIOProc failed: [%4.4s]", (char *)&err );
784         return VLC_FALSE;
785     }
786
787     /* Check for the difference between the Device clock and mdate */
788     p_sys->clock_diff = - (mtime_t)
789         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
790     p_sys->clock_diff += mdate();
791  
792     /* Start device */
793     err = AudioDeviceStart( p_sys->i_selected_dev, (AudioDeviceIOProc)RenderCallbackSPDIF ); 
794     if( err != noErr )
795     {
796         msg_Err( p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err );
797
798         err = AudioDeviceRemoveIOProc( p_sys->i_selected_dev, 
799                                        (AudioDeviceIOProc)RenderCallbackSPDIF );
800         if( err != noErr )
801         {
802             msg_Err( p_aout, "AudioDeviceRemoveIOProc failed: [%4.4s]", (char *)&err );
803         }
804         return VLC_FALSE;
805     }
806
807     return VLC_TRUE;
808 }
809
810
811 /*****************************************************************************
812  * Close: Close HAL AudioUnit
813  *****************************************************************************/
814 static void Close( vlc_object_t * p_this )
815 {
816     aout_instance_t     *p_aout = (aout_instance_t *)p_this;
817     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
818     OSStatus            err = noErr;
819     UInt32              i_param_size = 0;
820     
821     if( p_sys->au_unit )
822     {
823         verify_noerr( AudioOutputUnitStop( p_sys->au_unit ) );
824         verify_noerr( AudioUnitUninitialize( p_sys->au_unit ) );
825         verify_noerr( CloseComponent( p_sys->au_unit ) );
826     }
827     
828     if( p_sys->b_digital )
829     {
830         /* Stop device */
831         err = AudioDeviceStop( p_sys->i_selected_dev, 
832                                (AudioDeviceIOProc)RenderCallbackSPDIF ); 
833         if( err != noErr )
834         {
835             msg_Err( p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err );
836         }
837
838         /* Remove IOProc callback */
839         err = AudioDeviceRemoveIOProc( p_sys->i_selected_dev,
840                                        (AudioDeviceIOProc)RenderCallbackSPDIF );
841         if( err != noErr )
842         {
843             msg_Err( p_aout, "AudioDeviceRemoveIOProc failed: [%4.4s]", (char *)&err );
844         }
845         
846         if( p_sys->b_revert )
847         {
848             AudioStreamChangeFormat( p_aout, p_sys->i_stream_id, p_sys->sfmt_revert );
849         }
850
851         if( p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3 )
852         {
853             int b_mix;
854             Boolean b_writeable;
855             /* Revert mixable to true if we are allowed to */
856             err = AudioDeviceGetPropertyInfo( p_sys->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
857                                         &i_param_size, &b_writeable );
858
859             err = AudioDeviceGetProperty( p_sys->i_selected_dev, 0, FALSE, kAudioDevicePropertySupportsMixing,
860                                         &i_param_size, &b_mix );
861                                         
862             if( !err && b_writeable )
863             {
864                 msg_Dbg( p_aout, "mixable is: %d", b_mix );
865                 b_mix = 1;
866                 err = AudioDeviceSetProperty( p_sys->i_selected_dev, 0, 0, FALSE,
867                                     kAudioDevicePropertySupportsMixing, i_param_size, &b_mix );
868             }
869
870             if( err != noErr )
871             {
872                 msg_Err( p_aout, "failed to set mixmode: [%4.4s]", (char *)&err );
873             }
874         }
875     }
876
877     err = AudioHardwareRemovePropertyListener( kAudioHardwarePropertyDevices,
878                                                HardwareListener );
879                                                
880     if( err != noErr )
881     {
882         msg_Err( p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err );
883     }
884     
885     if( p_sys->i_hog_pid == getpid() )
886     {
887         p_sys->i_hog_pid = -1;
888         i_param_size = sizeof( p_sys->i_hog_pid );
889         err = AudioDeviceSetProperty( p_sys->i_selected_dev, 0, 0, FALSE,
890                                          kAudioDevicePropertyHogMode, i_param_size, &p_sys->i_hog_pid );
891         if( err != noErr ) msg_Err( p_aout, "Could not release hogmode: [%4.4s]", (char *)&err );
892     }
893     
894     if( p_sys ) free( p_sys );
895 }
896
897 /*****************************************************************************
898  * Play: nothing to do
899  *****************************************************************************/
900 static void Play( aout_instance_t * p_aout )
901 {
902 }
903
904
905 /*****************************************************************************
906  * Probe: Check which devices the OS has, and add them to our audio-device menu
907  *****************************************************************************/
908 static void Probe( aout_instance_t * p_aout )
909 {
910     OSStatus            err = noErr;
911     UInt32              i = 0, i_param_size = 0;
912     AudioDeviceID       devid_def = 0;
913     AudioDeviceID       *p_devices = NULL;
914     vlc_value_t         val, text;
915
916     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
917
918     /* Get number of devices */
919     err = AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,
920                                         &i_param_size, NULL );
921     if( err != noErr )
922     {
923         msg_Err( p_aout, "Could not get number of devices: [%4.4s]", (char *)&err );
924         goto error;
925     }
926
927     p_sys->i_devices = i_param_size / sizeof( AudioDeviceID );
928
929     if( p_sys->i_devices < 1 )
930     {
931         msg_Err( p_aout, "No audio output devices were found." );
932         goto error;
933     }
934
935     msg_Dbg( p_aout, "system has [%ld] device(s)", p_sys->i_devices );
936
937     /* Allocate DeviceID array */
938     p_devices = (AudioDeviceID*)malloc( sizeof(AudioDeviceID) * p_sys->i_devices );
939     if( p_devices == NULL )
940     {
941         msg_Err( p_aout, "out of memory" );
942         goto error;
943     }
944
945     /* Populate DeviceID array */
946     err = AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
947                                     &i_param_size, p_devices );
948     if( err != noErr )
949     {
950         msg_Err( p_aout, "could not get the device IDs: [%4.4s]", (char *)&err );
951         goto error;
952     }
953
954     /* Find the ID of the default Device */
955     i_param_size = sizeof( AudioDeviceID );
956     err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice,
957                                     &i_param_size, &devid_def );
958     if( err != noErr )
959     {
960         msg_Err( p_aout, "could not get default audio device: [%4.4s]", (char *)&err );
961         goto error;
962     }
963     p_sys->i_default_dev = devid_def;
964     
965     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE );
966     text.psz_string = _("Audio Device");
967     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
968     
969     for( i = 0; i < p_sys->i_devices; i++ )
970     {
971         char *psz_name;
972         i_param_size = 0;
973
974         /* Retrieve the length of the device name */
975         err = AudioDeviceGetPropertyInfo(
976                     p_devices[i], 0, VLC_FALSE,
977                     kAudioDevicePropertyDeviceName,
978                     &i_param_size, NULL);
979         if( err ) goto error;
980
981         /* Retrieve the name of the device */
982         psz_name = (char *)malloc( i_param_size );
983         err = AudioDeviceGetProperty(
984                     p_devices[i], 0, VLC_FALSE,
985                     kAudioDevicePropertyDeviceName,
986                     &i_param_size, psz_name);
987         if( err ) goto error;
988
989         msg_Dbg( p_aout, "DevID: %#lx DevName: %s", p_devices[i], psz_name );
990
991         if( !AudioDeviceHasOutput( p_devices[i]) )
992         {
993             msg_Dbg( p_aout, "this device is INPUT only. skipping..." );
994             continue;
995         }
996
997         /* Add the menu entries */
998         val.i_int = (int)p_devices[i];
999         text.psz_string = strdup( psz_name );
1000         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
1001         if( p_sys->i_default_dev == p_devices[i] )
1002         {
1003             /* The default device is the selected device normally */
1004             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
1005             var_Set( p_aout, "audio-device", val );
1006         }
1007
1008         if( AudioDeviceSupportsDigital( p_aout, p_devices[i] ) )
1009         {
1010             val.i_int = (int)p_devices[i] | AOUT_VAR_SPDIF_FLAG;
1011             asprintf( &text.psz_string, _("%s (Encoded Output)"), psz_name );
1012             var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
1013             if( p_sys->i_default_dev == p_devices[i] && config_GetInt( p_aout, "spdif" ) )
1014             {
1015                 /* We selected to prefer SPDIF output if available
1016                  * then this "dummy" entry should be selected */
1017                 var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
1018                 var_Set( p_aout, "audio-device", val );
1019             }
1020         }
1021         
1022         free( psz_name);
1023     }
1024     
1025     /* If a device is already "preselected", then use this device */
1026     var_Get( p_aout->p_vlc, "macosx-audio-device", &val );
1027     if( val.i_int > 0 )
1028     {
1029         var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
1030         var_Set( p_aout, "audio-device", val );
1031     }
1032     
1033     /* If we change the device we want to use, we should renegotiate the audio chain */
1034     var_AddCallback( p_aout, "audio-device", AudioDeviceCallback, NULL );
1035
1036     /* Attach a Listener so that we are notified of a change in the Device setup */
1037     err = AudioHardwareAddPropertyListener( kAudioHardwarePropertyDevices,
1038                                             HardwareListener, 
1039                                             (void *)p_aout );
1040     if( err )
1041         goto error;
1042
1043     if( p_devices ) free( p_devices );
1044     return;
1045
1046 error:
1047     var_Destroy( p_aout, "audio-device" );
1048     if( p_devices ) free( p_devices );
1049     return;
1050 }
1051
1052 /*****************************************************************************
1053  * AudioDeviceHasOutput: Checks if the Device actually provides any outputs at all
1054  *****************************************************************************/
1055 static int AudioDeviceHasOutput( AudioDeviceID i_dev_id )
1056 {
1057     UInt32                      dataSize;
1058     Boolean                     isWritable;
1059         
1060     verify_noerr( AudioDeviceGetPropertyInfo( i_dev_id, 0, FALSE, kAudioDevicePropertyStreams, &dataSize, &isWritable) );
1061     if (dataSize == 0) return FALSE;
1062     
1063     return TRUE;
1064 }
1065
1066 /*****************************************************************************
1067  * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
1068  *****************************************************************************/
1069 static int AudioDeviceSupportsDigital( aout_instance_t *p_aout, AudioDeviceID i_dev_id )
1070 {
1071     OSStatus                    err = noErr;
1072     UInt32                      i_param_size = 0;
1073     AudioStreamID               *p_streams = NULL;
1074     int                         i = 0, i_streams = 0;
1075     vlc_bool_t                  b_return = VLC_FALSE;
1076     
1077     /* Retrieve all the output streams */
1078     err = AudioDeviceGetPropertyInfo( i_dev_id, 0, FALSE,
1079                                       kAudioDevicePropertyStreams,
1080                                       &i_param_size, NULL );
1081     if( err != noErr )
1082     {
1083         msg_Err( p_aout, "could not get number of streams: [%4.4s]", (char *)&err );
1084         return VLC_FALSE;
1085     }
1086     
1087     i_streams = i_param_size / sizeof( AudioStreamID );
1088     p_streams = (AudioStreamID *)malloc( i_param_size );
1089     if( p_streams == NULL )
1090     {
1091         msg_Err( p_aout, "out of memory" );
1092         return VLC_ENOMEM;
1093     }
1094     
1095     err = AudioDeviceGetProperty( i_dev_id, 0, FALSE,
1096                                     kAudioDevicePropertyStreams,
1097                                     &i_param_size, p_streams );
1098     
1099     if( err != noErr )
1100     {
1101         msg_Err( p_aout, "could not get number of streams: [%4.4s]", (char *)&err );
1102         return VLC_FALSE;
1103     }
1104
1105     for( i = 0; i < i_streams; i++ )
1106     {
1107         if( AudioStreamSupportsDigital( p_aout, p_streams[i] ) )
1108             b_return = VLC_TRUE;
1109     }
1110     
1111     if( p_streams ) free( p_streams );
1112     return b_return;
1113 }
1114
1115 /*****************************************************************************
1116  * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
1117  *****************************************************************************/
1118 static int AudioStreamSupportsDigital( aout_instance_t *p_aout, AudioStreamID i_stream_id )
1119 {
1120     OSStatus                    err = noErr;
1121     UInt32                      i_param_size = 0;
1122     AudioStreamBasicDescription *p_format_list = NULL;
1123     int                         i = 0, i_formats = 0;
1124     vlc_bool_t                  b_return = VLC_FALSE;
1125     
1126     /* Retrieve all the stream formats supported by each output stream */
1127     err = AudioStreamGetPropertyInfo( i_stream_id, 0,
1128                                       kAudioStreamPropertyPhysicalFormats,
1129                                       &i_param_size, NULL );
1130     if( err != noErr )
1131     {
1132         msg_Err( p_aout, "could not get number of streamformats: [%4.4s]", (char *)&err );
1133         return VLC_FALSE;
1134     }
1135     
1136     i_formats = i_param_size / sizeof( AudioStreamBasicDescription );
1137     p_format_list = (AudioStreamBasicDescription *)malloc( i_param_size );
1138     if( p_format_list == NULL )
1139     {
1140         msg_Err( p_aout, "could not malloc the memory" );
1141         return VLC_FALSE;
1142     }
1143     
1144     err = AudioStreamGetProperty( i_stream_id, 0,
1145                                       kAudioStreamPropertyPhysicalFormats,
1146                                       &i_param_size, p_format_list );
1147     if( err != noErr )
1148     {
1149         msg_Err( p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err );
1150         free( p_format_list);
1151         p_format_list = NULL;
1152         return VLC_FALSE;
1153     }
1154
1155     for( i = 0; i < i_formats; i++ )
1156     {
1157         msg_Dbg( p_aout, STREAM_FORMAT_MSG( "supported format: ", p_format_list[i] ) );
1158         
1159         if( p_format_list[i].mFormatID == 'IAC3' ||
1160                   p_format_list[i].mFormatID == kAudioFormat60958AC3 )
1161         {
1162             b_return = VLC_TRUE;
1163         }
1164     }
1165     
1166     if( p_format_list ) free( p_format_list );
1167     return b_return;
1168 }
1169
1170 /*****************************************************************************
1171  * AudioStreamChangeFormat: Change i_stream_id to change_format
1172  *****************************************************************************/
1173 static int AudioStreamChangeFormat( aout_instance_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format )
1174 {
1175     OSStatus            err = noErr;
1176     UInt32              i_param_size = 0;
1177     int i;
1178
1179     struct timeval now;
1180     struct timespec timeout;
1181     struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1182     
1183     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "setting stream format: ", change_format ) );
1184
1185     /* Condition because SetProperty is asynchronious */ 
1186     vlc_cond_init( p_aout, &w.cond );
1187     vlc_mutex_init( p_aout, &w.lock );
1188     vlc_mutex_lock( &w.lock );
1189
1190     /* Install the callback */
1191     err = AudioStreamAddPropertyListener( i_stream_id, 0,
1192                                       kAudioStreamPropertyPhysicalFormat,
1193                                       StreamListener, (void *)&w );
1194     if( err != noErr )
1195     {
1196         msg_Err( p_aout, "AudioStreamAddPropertyListener failed: [%4.4s]", (char *)&err );
1197         return VLC_FALSE;
1198     }
1199
1200     /* change the format */
1201     err = AudioStreamSetProperty( i_stream_id, 0, 0,
1202                                   kAudioStreamPropertyPhysicalFormat,
1203                                   sizeof( AudioStreamBasicDescription ),
1204                                   &change_format ); 
1205     if( err != noErr )
1206     {
1207         msg_Err( p_aout, "could not set the stream format: [%4.4s]", (char *)&err );
1208         return VLC_FALSE;
1209     }
1210
1211     /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1212      * it is also not Atomic, in it's behaviour.
1213      * Therefore we check 5 times before we really give up.
1214      * FIXME: failing isn't actually implemented yet. */
1215     for( i = 0; i < 5; i++ )
1216     {
1217         AudioStreamBasicDescription actual_format;
1218
1219         gettimeofday( &now, NULL );
1220         timeout.tv_sec = now.tv_sec;
1221         timeout.tv_nsec = (now.tv_usec + 500000) * 1000;
1222
1223         if( pthread_cond_timedwait( &w.cond.cond, &w.lock.mutex, &timeout ) )
1224         {
1225             msg_Dbg( p_aout, "reached timeout" );
1226         }
1227
1228         i_param_size = sizeof( AudioStreamBasicDescription );
1229         err = AudioStreamGetProperty( i_stream_id, 0,
1230                                       kAudioStreamPropertyPhysicalFormat,
1231                                       &i_param_size, 
1232                                       &actual_format );
1233
1234         msg_Dbg( p_aout, STREAM_FORMAT_MSG( "actual format in use: ", actual_format ) );
1235         if( actual_format.mSampleRate == change_format.mSampleRate &&
1236             actual_format.mFormatID == change_format.mFormatID &&
1237             actual_format.mFramesPerPacket == change_format.mFramesPerPacket )
1238         {
1239             /* The right format is now active */
1240             break;
1241         }
1242         /* We need to check again */
1243     }
1244     
1245     /* Removing the property listener */
1246     err = AudioStreamRemovePropertyListener( i_stream_id, 0,
1247                                             kAudioStreamPropertyPhysicalFormat,
1248                                             StreamListener );
1249     if( err != noErr )
1250     {
1251         msg_Err( p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err );
1252         return VLC_FALSE;
1253     }
1254     
1255     /* Destroy the lock and condition */
1256     vlc_mutex_unlock( &w.lock );
1257     vlc_mutex_destroy( &w.lock );
1258     vlc_cond_destroy( &w.cond );
1259     
1260     return VLC_TRUE;
1261 }
1262
1263 /*****************************************************************************
1264  * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1265  * us to provide some more audio data.
1266  * Don't print anything during normal playback, calling blocking function from
1267  * this callback is not allowed.
1268  *****************************************************************************/
1269 static OSStatus RenderCallbackAnalog( vlc_object_t *_p_aout,
1270                                       AudioUnitRenderActionFlags *ioActionFlags,
1271                                       const AudioTimeStamp *inTimeStamp,
1272                                       unsigned int inBusNummer,
1273                                       unsigned int inNumberFrames,
1274                                       AudioBufferList *ioData )
1275 {
1276     AudioTimeStamp  host_time;
1277     mtime_t         current_date = 0;
1278     uint32_t        i_mData_bytes = 0;    
1279
1280     aout_instance_t * p_aout = (aout_instance_t *)_p_aout;
1281     struct aout_sys_t * p_sys = p_aout->output.p_sys;
1282
1283     host_time.mFlags = kAudioTimeStampHostTimeValid;
1284     AudioDeviceTranslateTime( p_sys->i_selected_dev, inTimeStamp, &host_time );
1285
1286     /* Check for the difference between the Device clock and mdate */
1287     p_sys->clock_diff = - (mtime_t)
1288         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
1289     p_sys->clock_diff += mdate();
1290
1291     current_date = p_sys->clock_diff +
1292                    AudioConvertHostTimeToNanos( host_time.mHostTime ) / 1000;
1293                    //- ((mtime_t) 1000000 / p_aout->output.output.i_rate * 31 ); // 31 = Latency in Frames. retrieve somewhere
1294
1295     if( ioData == NULL && ioData->mNumberBuffers < 1 )
1296     {
1297         msg_Err( p_aout, "no iodata or buffers");
1298         return 0;
1299     }
1300     if( ioData->mNumberBuffers > 1 )
1301         msg_Err( p_aout, "well this is weird. seems like there is more than one buffer..." );
1302
1303
1304     if( p_sys->i_total_bytes > 0 )
1305     {
1306         i_mData_bytes = __MIN( p_sys->i_total_bytes - p_sys->i_read_bytes, ioData->mBuffers[0].mDataByteSize );
1307         p_aout->p_vlc->pf_memcpy( ioData->mBuffers[0].mData, &p_sys->p_remainder_buffer[p_sys->i_read_bytes], i_mData_bytes );
1308         p_sys->i_read_bytes += i_mData_bytes;
1309         current_date += (mtime_t) ( (mtime_t) 1000000 / p_aout->output.output.i_rate ) *
1310                         ( i_mData_bytes / 4 / aout_FormatNbChannels( &p_aout->output.output )  ); // 4 is fl32 specific
1311         
1312         if( p_sys->i_read_bytes >= p_sys->i_total_bytes )
1313             p_sys->i_read_bytes = p_sys->i_total_bytes = 0;
1314     }
1315     
1316     while( i_mData_bytes < ioData->mBuffers[0].mDataByteSize )
1317     {
1318         /* We don't have enough data yet */
1319         aout_buffer_t * p_buffer;
1320         p_buffer = aout_OutputNextBuffer( p_aout, current_date , VLC_FALSE );
1321         
1322         if( p_buffer != NULL )
1323         {
1324             uint32_t i_second_mData_bytes = __MIN( p_buffer->i_nb_bytes, ioData->mBuffers[0].mDataByteSize - i_mData_bytes );
1325             
1326             p_aout->p_vlc->pf_memcpy( (uint8_t *)ioData->mBuffers[0].mData + i_mData_bytes, p_buffer->p_buffer, i_second_mData_bytes );
1327             i_mData_bytes += i_second_mData_bytes;
1328
1329             if( i_mData_bytes >= ioData->mBuffers[0].mDataByteSize )
1330             {
1331                 p_sys->i_total_bytes = p_buffer->i_nb_bytes - i_second_mData_bytes;
1332                 p_aout->p_vlc->pf_memcpy( p_sys->p_remainder_buffer, &p_buffer->p_buffer[i_second_mData_bytes], p_sys->i_total_bytes );
1333             }
1334             else
1335             {
1336                 /* update current_date */
1337                 current_date += (mtime_t) ( (mtime_t) 1000000 / p_aout->output.output.i_rate ) *
1338                                 ( i_second_mData_bytes / 4 / aout_FormatNbChannels( &p_aout->output.output )  ); // 4 is fl32 specific
1339             }
1340             aout_BufferFree( p_buffer );
1341         }
1342         else
1343         {
1344              p_aout->p_vlc->pf_memset( (uint8_t *)ioData->mBuffers[0].mData +i_mData_bytes, 0, ioData->mBuffers[0].mDataByteSize - i_mData_bytes );
1345              i_mData_bytes += ioData->mBuffers[0].mDataByteSize - i_mData_bytes;
1346         }
1347     }
1348     return( noErr );     
1349 }
1350
1351 /*****************************************************************************
1352  * RenderCallbackSPDIF: callback for SPDIF audio output
1353  *****************************************************************************/
1354 static OSStatus RenderCallbackSPDIF( AudioDeviceID inDevice,
1355                                     const AudioTimeStamp * inNow, 
1356                                     const void * inInputData,
1357                                     const AudioTimeStamp * inInputTime, 
1358                                     AudioBufferList * outOutputData,
1359                                     const AudioTimeStamp * inOutputTime, 
1360                                     void * threadGlobals )
1361 {
1362     aout_buffer_t * p_buffer;
1363     mtime_t         current_date;
1364
1365     aout_instance_t * p_aout = (aout_instance_t *)threadGlobals;
1366     struct aout_sys_t * p_sys = p_aout->output.p_sys;
1367
1368     /* Check for the difference between the Device clock and mdate */
1369     p_sys->clock_diff = - (mtime_t)
1370         AudioConvertHostTimeToNanos( inNow->mHostTime ) / 1000; 
1371     p_sys->clock_diff += mdate();
1372
1373     current_date = p_sys->clock_diff +
1374                    AudioConvertHostTimeToNanos( inOutputTime->mHostTime ) / 1000;
1375                    //- ((mtime_t) 1000000 / p_aout->output.output.i_rate * 31 ); // 31 = Latency in Frames. retrieve somewhere
1376
1377     p_buffer = aout_OutputNextBuffer( p_aout, current_date, VLC_TRUE );
1378
1379 #define BUFFER outOutputData->mBuffers[p_sys->i_stream_index]
1380     if( p_buffer != NULL )
1381     {
1382         if( (int)BUFFER.mDataByteSize != (int)p_buffer->i_nb_bytes)
1383             msg_Warn( p_aout, "bytesize: %d nb_bytes: %d", (int)BUFFER.mDataByteSize, (int)p_buffer->i_nb_bytes );
1384         
1385         /* move data into output data buffer */
1386         p_aout->p_vlc->pf_memcpy( BUFFER.mData,
1387                                   p_buffer->p_buffer, p_buffer->i_nb_bytes );
1388         aout_BufferFree( p_buffer );
1389     }
1390     else
1391     {
1392         p_aout->p_vlc->pf_memset( BUFFER.mData, 0, BUFFER.mDataByteSize );
1393     }
1394 #undef BUFFER
1395
1396     return( noErr );     
1397 }
1398
1399 /*****************************************************************************
1400  * HardwareListener: Warns us of changes in the list of registered devices
1401  *****************************************************************************/
1402 static OSStatus HardwareListener( AudioHardwarePropertyID inPropertyID,
1403                                   void * inClientData )
1404 {
1405     OSStatus err = noErr;
1406     aout_instance_t     *p_aout = (aout_instance_t *)inClientData;
1407
1408     switch( inPropertyID )
1409     {
1410         case kAudioHardwarePropertyDevices:
1411         {
1412             /* something changed in the list of devices */
1413             /* We trigger the audio-device's aout_ChannelsRestart callback */
1414             var_Change( p_aout, "audio-device", VLC_VAR_TRIGGER_CALLBACKS, NULL, NULL );
1415             var_Destroy( p_aout, "audio-device" );
1416         }
1417         break;
1418     }
1419
1420     return( err );
1421 }
1422
1423 /*****************************************************************************
1424  * StreamListener 
1425  *****************************************************************************/
1426 static OSStatus StreamListener( AudioStreamID inStream,
1427                                 UInt32 inChannel,
1428                                 AudioDevicePropertyID inPropertyID,
1429                                 void * inClientData )
1430 {
1431     OSStatus err = noErr;
1432     struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1433     
1434     switch( inPropertyID )
1435     {
1436         case kAudioStreamPropertyPhysicalFormat:
1437             vlc_mutex_lock( &w->lock );
1438             vlc_cond_signal( &w->cond );
1439             vlc_mutex_unlock( &w->lock ); 
1440             break;
1441
1442         default:
1443             break;
1444     }
1445     return( err );
1446 }
1447
1448 /*****************************************************************************
1449  * AudioDeviceCallback: Callback triggered when the audio-device variable is changed
1450  *****************************************************************************/
1451 static int AudioDeviceCallback( vlc_object_t *p_this, const char *psz_variable,
1452                      vlc_value_t old_val, vlc_value_t new_val, void *param )
1453 {
1454     aout_instance_t *p_aout = (aout_instance_t *)p_this;
1455     var_Set( p_aout->p_vlc, "macosx-audio-device", new_val );
1456     msg_Dbg( p_aout, "Set Device: %#x", new_val.i_int );
1457     return aout_ChannelsRestart( p_this, psz_variable, old_val, new_val, param );
1458 }
1459