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