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