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