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