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