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