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