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