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