]> git.sesse.net Git - vlc/blob - modules/audio_output/auhal.c
* Don't list 'Input only' devices
[vlc] / modules / audio_output / auhal.c
1 /*****************************************************************************
2  * auhal.c: AUHAL output plugin
3  *****************************************************************************
4  * Copyright (C) 2005 VideoLAN
5  * $Id$
6  *
7  * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  * 
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <string.h>
28 #include <stdlib.h>
29
30 #include <vlc/vlc.h>
31 #include <vlc/aout.h>
32
33 #include "aout_internal.h"
34
35 #include <CoreAudio/CoreAudio.h>
36 #include <CoreAudio/CoreAudioTypes.h>
37 #include <AudioUnit/AudioUnitProperties.h>
38 #include <AudioUnit/AudioUnitParameters.h>
39 #include <AudioUnit/AudioOutputUnit.h>
40 #include <AudioToolbox/AudioFormat.h>
41
42 #define STREAM_FORMAT_MSG( pre, sfm ) \
43     pre ":\nsamplerate: [%ld]\nFormatID: [%4.4s]\nFormatFlags: [%ld]\nBypesPerPacket: [%ld]\nFramesPerPacket: [%ld]\nBytesPerFrame: [%ld]\nChannelsPerFrame: [%ld]\nBitsPerChannel[%ld]", \
44     (UInt32)sfm.mSampleRate, (char *)&sfm.mFormatID, \
45     sfm.mFormatFlags, sfm.mBytesPerPacket, \
46     sfm.mFramesPerPacket, sfm.mBytesPerFrame, \
47     sfm.mChannelsPerFrame, sfm.mBitsPerChannel
48
49 #define BUFSIZE 0xffffff
50
51 /*****************************************************************************
52  * aout_sys_t: private audio output method descriptor
53  *****************************************************************************
54  * This structure is part of the audio output thread descriptor.
55  * It describes the CoreAudio specific properties of an output thread.
56  *****************************************************************************/
57 struct aout_sys_t
58 {
59     AudioDeviceID               i_default_dev;  /* Keeps DeviceID of defaultOutputDevice */
60     AudioDeviceID               i_selected_dev; /* Keeps DeviceID of the selected device */
61     UInt32                      i_devices;      /* Number of CoreAudio Devices */
62     vlc_bool_t                  b_supports_digital;/* Does the currently selected device support digital mode? */
63     vlc_bool_t                  b_digital;      /* Are we running in digital mode? */
64     Component                   au_component;   /* The Audiocomponent we use */
65     AudioUnit                   au_unit;        /* The AudioUnit we use */
66     mtime_t                     clock_diff;
67     uint8_t                      p_remainder_buffer[BUFSIZE];
68     uint32_t                    i_read_bytes;
69     uint32_t                    i_total_bytes;
70     audio_date_t                end_date_t;
71     
72     
73 };
74
75 /*****************************************************************************
76  * Local prototypes.
77  *****************************************************************************/
78 static int      Open                    ( vlc_object_t * );
79 static void     Close                   ( vlc_object_t * );
80
81 static void     Play                    ( aout_instance_t *);
82
83 static int      Probe                   ( aout_instance_t * );
84 static int      DeviceDigitalMode       ( aout_instance_t *, AudioDeviceID );
85 int             AudioDeviceHasOutput    ( AudioDeviceID );
86 static int      DigitalInit             ( aout_instance_t * );
87
88 static OSStatus RenderCallbackAnalog    ( vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
89                                           unsigned int, unsigned int, AudioBufferList *);
90 static OSStatus HardwareListener        ( AudioHardwarePropertyID, void *);
91
92 /*****************************************************************************
93  * Module descriptor
94  *****************************************************************************/
95 #define ADEV_TEXT N_("Audio Device")
96 #define ADEV_LONGTEXT N_("Choose a number corresponding to the number of an " \
97     "audio device, as listed in your 'Audio Device' menu. This device will " \
98     "then be used by default for audio playback.")
99
100 vlc_module_begin();
101     set_shortname( "auhal" );
102     set_description( _("HAL AudioUnit output") );
103     set_capability( "audio output", 101 );
104     set_category( CAT_AUDIO );
105     set_subcategory( SUBCAT_AUDIO_AOUT );
106     set_callbacks( Open, Close );
107     //add_integer( "coreaudio-dev", -1, NULL, ADEV_TEXT, ADEV_LONGTEXT, VLC_FALSE ); 
108 vlc_module_end();
109
110 /*****************************************************************************
111  * Open: open a HAL AudioUnit
112  *****************************************************************************/
113 static int Open( vlc_object_t * p_this )
114 {
115     OSStatus                err = noErr;
116     ComponentDescription    desc;
117     UInt32                  i_param_size,i;
118     struct aout_sys_t       *p_sys;
119     vlc_value_t             val;
120     aout_instance_t         *p_aout = (aout_instance_t *)p_this;
121
122     /* Allocate structure */
123     p_sys = (struct aout_sys_t *)malloc( sizeof( struct aout_sys_t ) );
124     if( p_sys == NULL )
125     {
126         msg_Err( p_aout, "out of memory" );
127         return( VLC_ENOMEM );
128     }
129
130     memset( p_sys, 0, sizeof( struct aout_sys_t ) );
131
132     p_sys->b_digital = VLC_FALSE; /* We assume we are not digital */
133
134     p_aout->output.p_sys = p_sys;
135     p_aout->output.pf_play = Play;
136     
137     aout_FormatPrint( p_aout, "VLC is looking for:\n", (audio_sample_format_t *)&p_aout->output.output );
138     
139     /* Build a list of devices */
140     if( var_Type( p_aout, "audio-device" ) == 0 )
141     {
142         Probe( p_aout );
143         /*if( Probe( p_aout ) != VLC_SUCCESS );
144         {
145             msg_Err( p_aout, "Probe failed" );
146             free( p_sys );
147             return VLC_EGENERIC;
148         }*/
149     }
150     
151     /* What device do we want? */
152     if( var_Get( p_aout, "audio-device", &val ) < 0 )
153     {
154         msg_Err( p_aout, "audio-device var does not exist" );
155         free( p_sys );
156         return( VLC_ENOVAR );
157     }
158     p_sys->i_selected_dev = val.i_int;
159
160     /* what is vlc format? if digital, take digital route else AUHAL route */
161     DeviceDigitalMode( p_aout, p_sys->i_selected_dev );
162     /*if( DeviceDigitalMode( p_aout, p_sys->i_selected_dev ) != VLC_SUCCESS );
163     {
164         msg_Err( p_aout, "DeviceDigitalMode failed" );
165         free( p_sys );
166         return VLC_EGENERIC;
167     }
168     */
169     
170     if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) && p_sys->b_supports_digital )
171     {
172         p_sys->b_digital = VLC_TRUE;
173         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
174         msg_Dbg( p_aout, "we found a digital stream, and we WANT a digital stream" );
175     }
176     else if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) && !p_sys->b_supports_digital )
177     {
178         msg_Dbg( p_aout, "we had requested a digital stream, but it's not possible for this device" );
179     }
180  
181     /* If analog only start setting up AUHAL */
182
183     /* Lets go find our Component */
184     desc.componentType = kAudioUnitType_Output;
185     desc.componentSubType = kAudioUnitSubType_HALOutput;
186     desc.componentManufacturer = kAudioUnitManufacturer_Apple;
187     desc.componentFlags = 0;
188     desc.componentFlagsMask = 0;
189
190     p_sys->au_component = FindNextComponent( NULL, &desc );
191     if( p_sys->au_component == NULL )
192     {
193         msg_Err( p_aout, "we cannot find our HAL component" );
194         free( p_sys );
195         return VLC_EGENERIC;
196     }
197
198     err = OpenAComponent( p_sys->au_component, &p_sys->au_unit );
199     if( err )
200     {
201         
202         msg_Err( p_aout, "we cannot find our HAL component" );
203         free( p_sys );
204         return VLC_EGENERIC;
205     }
206     
207     /* Enable IO for the component */
208     
209     /* Set the device */
210     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
211                          kAudioOutputUnitProperty_CurrentDevice,
212                          kAudioUnitScope_Global,
213                          0,
214                          &p_sys->i_selected_dev,
215                          sizeof(p_sys->i_selected_dev)));
216                          
217     /* Get the current format */
218     AudioStreamBasicDescription DeviceFormat;
219     
220     i_param_size = sizeof(AudioStreamBasicDescription);
221
222     verify_noerr( AudioUnitGetProperty( p_sys->au_unit,
223                                    kAudioUnitProperty_StreamFormat,
224                                    kAudioUnitScope_Input,
225                                    0,
226                                    &DeviceFormat,
227                                    &i_param_size ));
228                                    
229     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "current format is " , DeviceFormat ) );
230
231     /* Get the channel layout */
232     AudioChannelLayout *layout;
233     verify_noerr( AudioUnitGetPropertyInfo( p_sys->au_unit,
234                                    kAudioDevicePropertyPreferredChannelLayout,
235                                    kAudioUnitScope_Output,
236                                    0,
237                                    &i_param_size,
238                                    NULL ));
239
240     layout = (AudioChannelLayout *)malloc( i_param_size);
241
242     verify_noerr( AudioUnitGetProperty( p_sys->au_unit,
243                                    kAudioDevicePropertyPreferredChannelLayout,
244                                    kAudioUnitScope_Output,
245                                    0,
246                                    layout,
247                                    &i_param_size ));
248                                    
249     /* Lets fill out the ChannelLayout */
250     if( layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap)
251     {
252         msg_Dbg( p_aout, "bitmap defined channellayout" );
253         verify_noerr( AudioFormatGetProperty( kAudioFormatProperty_ChannelLayoutForBitmap,
254                                 sizeof( UInt32), &layout->mChannelBitmap,
255                                 &i_param_size,
256                                 layout ));
257     }
258     else if( layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions )
259     {
260         msg_Dbg( p_aout, "layouttags defined channellayout" );
261         verify_noerr( AudioFormatGetProperty( kAudioFormatProperty_ChannelLayoutForTag,
262                                 sizeof( AudioChannelLayoutTag ), &layout->mChannelLayoutTag,
263                                 &i_param_size,
264                                 layout ));
265     }
266
267     msg_Dbg( p_aout, "Layout of AUHAL has %d channels" , (int)layout->mNumberChannelDescriptions );
268     
269     p_aout->output.output.i_physical_channels = 0;
270     for( i = 0; i < layout->mNumberChannelDescriptions; i++ )
271     {
272         msg_Dbg( p_aout, "This is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel );
273
274         switch( layout->mChannelDescriptions[i].mChannelLabel )
275         {
276             case kAudioChannelLabel_Left:
277                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_LEFT;
278                 continue;
279             case kAudioChannelLabel_Right:
280                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_RIGHT;
281                 continue;
282             case kAudioChannelLabel_Center:
283                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_CENTER;
284                 continue;
285             case kAudioChannelLabel_LFEScreen:
286                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_LFE;
287                 continue;
288             case kAudioChannelLabel_LeftSurround:
289                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_REARLEFT;
290                 continue;
291             case kAudioChannelLabel_RightSurround:
292                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_REARRIGHT;
293                 continue;
294             case kAudioChannelLabel_RearSurroundLeft:
295                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
296                 continue;
297             case kAudioChannelLabel_RearSurroundRight:
298                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
299                 continue;
300             case kAudioChannelLabel_CenterSurround:
301                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_REARCENTER;
302                 continue;
303             default:
304                 msg_Warn( p_aout, "Unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel );
305                 if( i == 0 )
306                 {
307                     msg_Warn( p_aout, "Probably no channellayout is set. force based on channelcount" );
308                     switch( layout->mNumberChannelDescriptions )
309                     {
310                         /* We make assumptions based on number of channels here.
311                          * Unfortunatly Apple has provided no 100% method to retrieve the speaker configuration */
312                         case 1:
313                             p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
314                             break;
315                         case 4:
316                             p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
317                                                                         AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
318                             break;
319                         case 6:
320                             p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
321                                                                         AOUT_CHAN_CENTER | AOUT_CHAN_LFE |
322                                                                         AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
323                             break;
324                         case 7:
325                             p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
326                                                                         AOUT_CHAN_CENTER | AOUT_CHAN_LFE |
327                                                                         AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_REARCENTER;
328                             break;
329                         case 8:
330                             p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
331                                                                         AOUT_CHAN_CENTER | AOUT_CHAN_LFE |
332                                                                         AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT |
333                                                                         AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
334                             break;
335                         case 2:
336                         default:
337                             p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
338                     }
339                 }
340                 break;
341         }
342     }
343     free( layout );
344
345     msg_Dbg( p_aout, "defined %d physical channels for vlc core", aout_FormatNbChannels( &p_aout->output.output ) );
346     msg_Dbg( p_aout, "%s", aout_FormatPrintChannels( &p_aout->output.output ));
347     
348     AudioChannelLayout new_layout;
349     memset (&new_layout, 0, sizeof(new_layout));
350     switch( aout_FormatNbChannels( &p_aout->output.output ) )
351     {
352         case 1:
353             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
354             break;
355         case 2:
356             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
357             break;
358         case 3:
359             if( p_aout->output.output.i_physical_channels & AOUT_CHAN_CENTER )
360             {
361                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
362             }
363             else if( p_aout->output.output.i_physical_channels & AOUT_CHAN_LFE )
364             {
365                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
366             }
367             break;
368         case 4:
369             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER | AOUT_CHAN_LFE ) )
370             {
371                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
372             }
373             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT ) )
374             {
375                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
376             }
377             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER ) )
378             {
379                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
380             }
381             break;
382         case 5:
383             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER ) )
384             {
385                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
386             }
387             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_LFE ) )
388             {
389                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
390             }
391             break;
392         case 6:
393             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
394             break;
395         case 7:
396             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
397             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
398             break;
399         case 8:
400             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
401             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
402             break;
403     }
404
405     /* Set up the format to be used */
406     DeviceFormat.mSampleRate = p_aout->output.output.i_rate;
407     DeviceFormat.mFormatID = kAudioFormatLinearPCM;
408
409     /* We use float 32. It's the best supported format by both VLC and Coreaudio */
410     p_aout->output.output.i_format = VLC_FOURCC( 'f','l','3','2');
411     DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
412     DeviceFormat.mBitsPerChannel = 32;
413     DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels( &p_aout->output.output );
414     
415     /* Calculate framesizes and stuff */
416     aout_FormatPrepare( &p_aout->output.output );
417     DeviceFormat.mFramesPerPacket = 1;
418     DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
419     DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
420  
421     i_param_size = sizeof(AudioStreamBasicDescription);
422     /* Set desired format (Use CAStreamBasicDescription )*/
423     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
424                                    kAudioUnitProperty_StreamFormat,
425                                    kAudioUnitScope_Input,
426                                    0,
427                                    &DeviceFormat,
428                                    i_param_size ));
429                                    
430     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "we set the AU format: " , DeviceFormat ) );
431     
432     /* Retrieve actual format??? */
433     verify_noerr( AudioUnitGetProperty( p_sys->au_unit,
434                                    kAudioUnitProperty_StreamFormat,
435                                    kAudioUnitScope_Input,
436                                    0,
437                                    &DeviceFormat,
438                                    &i_param_size ));
439                                    
440     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "the actual set AU format is " , DeviceFormat ) );
441
442     p_aout->output.i_nb_samples = 2048;
443     aout_VolumeSoftInit( p_aout );
444
445     /* Let's pray for the following operation to be atomic... */
446     p_sys->clock_diff = - (mtime_t)
447         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
448     p_sys->clock_diff += mdate();
449     
450     p_sys->i_read_bytes = 0;
451     p_sys->i_total_bytes = 0;
452
453     /* set the IOproc callback */
454     AURenderCallbackStruct input;
455     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
456     input.inputProcRefCon = p_aout;
457     
458     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
459                             kAudioUnitProperty_SetRenderCallback,
460                             kAudioUnitScope_Input,
461                             0, &input, sizeof( input ) ) );
462
463     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
464     input.inputProcRefCon = p_aout;
465     
466     /* Set the new_layout as the layout VLC feeds to the AU unit */
467     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
468                             kAudioUnitProperty_AudioChannelLayout,
469                             kAudioUnitScope_Input,
470                             0, &new_layout, sizeof(new_layout) ) );
471     
472     /* AU initiliaze */
473     verify_noerr( AudioUnitInitialize(p_sys->au_unit) );
474
475     verify_noerr( AudioOutputUnitStart(p_sys->au_unit) );
476     return( VLC_SUCCESS );
477 }
478
479 /*****************************************************************************
480  * Close: Close HAL AudioUnit
481  *****************************************************************************/
482 static void Close( vlc_object_t * p_this )
483 {
484     aout_instance_t     *p_aout = (aout_instance_t *)p_this;
485     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
486     
487     if( p_sys->au_unit )
488     {
489         verify_noerr( AudioOutputUnitStop( p_sys->au_unit ) );
490         verify_noerr( AudioUnitUninitialize( p_sys->au_unit ) );
491         verify_noerr( CloseComponent( p_sys->au_unit ) );
492     }
493     free( p_sys );
494 }
495
496 /*****************************************************************************
497  * Play: nothing to do
498  *****************************************************************************/
499 static void Play( aout_instance_t * p_aout )
500 {
501 }
502
503
504 /*****************************************************************************
505  * Probe
506  *****************************************************************************/
507 static int Probe( aout_instance_t * p_aout )
508 {
509     OSStatus            err = noErr;
510     UInt32              i, i_param_size;
511     AudioDeviceID       devid_def;
512     AudioDeviceID       *p_devices = NULL;
513     vlc_value_t         val, text;
514
515     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
516
517     /* Get number of devices */
518     err = AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,
519                                         &i_param_size, NULL );
520     if( err != noErr )
521     {
522         msg_Err( p_aout, "could not get number of devices: [%4.4s]", (char *)&err );
523         goto error;
524     }
525
526     p_sys->i_devices = i_param_size / sizeof( AudioDeviceID );
527
528     if( p_sys->i_devices < 1 )
529     {
530         msg_Err( p_aout, "no devices found" );
531         goto error;
532     }
533
534     msg_Dbg( p_aout, "system has [%ld] device(s)", p_sys->i_devices );
535
536     /* Allocate DeviceID array */
537     p_devices = (AudioDeviceID *)malloc( i_param_size );
538     if( p_devices == NULL )
539     {
540         msg_Err( p_aout, "out of memory" );
541         goto error;
542     }
543
544     /* Populate DeviceID array */
545     err = AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
546                                     &i_param_size, (void *)p_devices );
547     if( err != noErr )
548     {
549         msg_Err( p_aout, "could not get the device ID's: [%4.4s]", (char *)&err );
550         goto error;
551     }
552
553     /* Find the ID of the default Device */
554     i_param_size = sizeof( AudioDeviceID );
555     err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice,
556                                     &i_param_size, (void *)&devid_def );
557     if( err != noErr )
558     {
559         msg_Err( p_aout, "could not get default audio device: [%4.4s]", (char *)&err );
560         goto error;
561     }
562     p_sys->i_default_dev = devid_def;
563     
564     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE );
565     text.psz_string = _("Audio Device");
566     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
567     
568     for( i = 0; i < p_sys->i_devices; i++ )
569     {
570         char psz_devuid[1024];
571         char psz_name[1024];
572         CFStringRef devUID;
573
574         i_param_size = sizeof psz_name;
575         err = AudioDeviceGetProperty(
576                     p_devices[i], 0, VLC_FALSE,
577                     kAudioDevicePropertyDeviceName,
578                     &i_param_size, psz_name);
579         if( err )
580             goto error;
581
582         i_param_size = sizeof(CFStringRef);    
583         err = AudioDeviceGetProperty(
584                     p_devices[i], 0, VLC_FALSE,
585                     kAudioDevicePropertyDeviceUID,
586                     &i_param_size, &devUID);
587         if( err )
588             goto error;
589
590         CFStringGetCString( devUID, psz_devuid, sizeof psz_devuid, CFStringGetSystemEncoding() );
591         msg_Dbg( p_aout, "DevID: %lu  DevName: %s  DevUID: %s", p_devices[i], psz_name, psz_devuid );
592         CFRelease( devUID );
593
594         if( !AudioDeviceHasOutput(p_aout, p_devices[i]) )
595         {
596             msg_Dbg( p_aout, "this device is INPUT only. skipping..." );
597             continue;
598         }
599
600         val.i_int = (int) p_devices[i];
601         text.psz_string = psz_name;
602         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
603         if( devid_def == p_devices[i] )
604         {
605             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
606             var_Set( p_aout, "audio-device", val );
607         }
608     }
609     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
610     
611     /* attach a Listener so that we are notified of a change in the Device setup */
612     /* err = AudioHardwareAddPropertyListener( kAudioHardwarePropertyDevices,
613                                             HardwareListener, 
614                                             (void *)p_aout );
615     if( err )
616         goto error;*/
617     
618     msg_Dbg( p_aout, "succesful finish of deviceslist" );
619     if( p_devices ) free( p_devices );
620     return (VLC_SUCCESS);
621
622 error:
623     var_Destroy( p_aout, "audio-device" );
624     if( p_devices ) free( p_devices );
625     return VLC_EGENERIC;
626 }
627
628 /*****************************************************************************
629  * DeviceDigitalMode: Check i_dev_id for digital stream support.
630  *****************************************************************************/
631 static int DeviceDigitalMode( aout_instance_t *p_aout, AudioDeviceID i_dev_id )
632 {
633     OSStatus                    err = noErr;
634     UInt32                      i_param_size;
635     AudioStreamBasicDescription *p_format_list;
636     int                         i, i_formats;
637     struct aout_sys_t           *p_sys = p_aout->output.p_sys;
638     
639     p_sys->b_supports_digital = VLC_FALSE;
640     
641     err = AudioDeviceGetPropertyInfo( i_dev_id, 0, FALSE,
642                                       kAudioDevicePropertyStreamFormats,
643                                       &i_param_size, NULL );
644     if( err != noErr )
645     {
646         msg_Err( p_aout, "could not get number of streamsformats: [%4.4s]", (char *)&err );
647         return( VLC_EGENERIC );
648     }
649     
650     i_formats = i_param_size / sizeof( AudioStreamBasicDescription );
651     p_format_list = (AudioStreamBasicDescription *)malloc( i_param_size );
652     if( p_format_list == NULL )
653     {
654         return( VLC_ENOMEM );
655     }
656     
657     err = AudioDeviceGetProperty( i_dev_id, 0, FALSE,
658                                       kAudioDevicePropertyStreamFormats,
659                                       &i_param_size, (void *)p_format_list );
660     if( err != noErr )
661     {
662         msg_Err( p_aout, "could not get the list of formats: [%4.4s]", (char *)&err );
663         return( VLC_EGENERIC );
664     }
665
666     for( i = 0; i < i_formats; i++ )
667     {
668         msg_Dbg( p_aout, STREAM_FORMAT_MSG( "supported format", p_format_list[i] ) );
669         
670         if( p_format_list[i].mFormatID == 'IAC3' ||
671                   p_format_list[i].mFormatID == kAudioFormat60958AC3 )
672         {
673             p_sys->b_supports_digital = VLC_TRUE;
674             msg_Dbg( p_aout, "this device supports a digital stream" );
675             break;
676         }
677     }
678     
679     free( (void *)p_format_list );
680     return VLC_SUCCESS;
681 }
682
683 /*****************************************************************************
684  * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
685  * us to provide some more audio data.
686  * Don't print anything during normal playback, calling blocking function from
687  * this callback is not allowed.
688  *****************************************************************************/
689 static OSStatus RenderCallbackAnalog( vlc_object_t *_p_aout,
690                                       AudioUnitRenderActionFlags *ioActionFlags,
691                                       const AudioTimeStamp *inTimeStamp,
692                                       unsigned int inBusNummer,
693                                       unsigned int inNumberFrames,
694                                       AudioBufferList *ioData )
695 {
696     AudioTimeStamp  host_time;
697     mtime_t         current_date = 0;
698     uint32_t        i_mData_bytes = 0;    
699
700     aout_instance_t * p_aout = (aout_instance_t *)_p_aout;
701     struct aout_sys_t * p_sys = p_aout->output.p_sys;
702
703     host_time.mFlags = kAudioTimeStampHostTimeValid;
704     AudioDeviceTranslateTime( p_sys->i_selected_dev, inTimeStamp, &host_time );
705
706     p_sys->clock_diff = - (mtime_t)
707         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
708     p_sys->clock_diff += mdate();
709
710     current_date = p_sys->clock_diff +
711                    AudioConvertHostTimeToNanos( host_time.mHostTime ) / 1000;
712
713     if( ioData == NULL && ioData->mNumberBuffers < 1 )
714     {
715         msg_Err( p_aout, "no iodata or buffers");
716         return 0;
717     }
718     if( ioData->mNumberBuffers > 1 )
719         msg_Err( p_aout, "well this is weird. seems like there is more than one buffer..." );
720
721
722     if( p_sys->i_total_bytes > 0 )
723     {
724         i_mData_bytes = __MIN( p_sys->i_total_bytes - p_sys->i_read_bytes, ioData->mBuffers[0].mDataByteSize );
725         p_aout->p_vlc->pf_memcpy( ioData->mBuffers[0].mData, &p_sys->p_remainder_buffer[p_sys->i_read_bytes], i_mData_bytes );
726         p_sys->i_read_bytes += i_mData_bytes;
727         current_date += (mtime_t) ( (mtime_t) 1000000 / p_aout->output.output.i_rate ) *
728                         ( i_mData_bytes / 4 / aout_FormatNbChannels( &p_aout->output.output )  ); // 4 is fl32 specific
729         
730         if( p_sys->i_read_bytes >= p_sys->i_total_bytes )
731             p_sys->i_read_bytes = p_sys->i_total_bytes = 0;
732     }
733     
734     while( i_mData_bytes < ioData->mBuffers[0].mDataByteSize )
735     {
736         /* We don't have enough data yet */
737         aout_buffer_t * p_buffer;
738         p_buffer = aout_OutputNextBuffer( p_aout, current_date , VLC_FALSE );
739         
740         if( p_buffer != NULL )
741         {
742             uint32_t i_second_mData_bytes = __MIN( p_buffer->i_nb_bytes, ioData->mBuffers[0].mDataByteSize - i_mData_bytes );
743             
744             p_aout->p_vlc->pf_memcpy( (uint8_t *)ioData->mBuffers[0].mData + i_mData_bytes, p_buffer->p_buffer, i_second_mData_bytes );
745             i_mData_bytes += i_second_mData_bytes;
746
747             if( i_mData_bytes >= ioData->mBuffers[0].mDataByteSize )
748             {
749                 p_sys->i_total_bytes = p_buffer->i_nb_bytes - i_second_mData_bytes;
750                 p_aout->p_vlc->pf_memcpy( p_sys->p_remainder_buffer, &p_buffer->p_buffer[i_second_mData_bytes], p_sys->i_total_bytes );
751             }
752             else
753             {
754                 // update current_date
755                 current_date += (mtime_t) ( (mtime_t) 1000000 / p_aout->output.output.i_rate ) *
756                                 ( i_second_mData_bytes / 4 / aout_FormatNbChannels( &p_aout->output.output )  ); // 4 is fl32 specific
757             }
758             aout_BufferFree( p_buffer );
759         }
760         else
761         {
762              p_aout->p_vlc->pf_memset( (uint8_t *)ioData->mBuffers[0].mData +i_mData_bytes, 0, ioData->mBuffers[0].mDataByteSize - i_mData_bytes );
763              i_mData_bytes += ioData->mBuffers[0].mDataByteSize - i_mData_bytes;
764         }
765     }
766     return( noErr );     
767 }
768
769
770 /*****************************************************************************
771  * Setup a digital stream
772  *****************************************************************************/
773 static int DigitalInit( aout_instance_t * p_aout )
774 {
775     OSStatus            err = noErr;
776     UInt32              i, i_param_size;
777     AudioDeviceID       devid_def;
778     AudioDeviceID       *p_devices = NULL;
779     vlc_value_t         val, text;
780
781     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
782
783     
784     
785     return (VLC_SUCCESS);
786
787 error:
788     return VLC_EGENERIC;
789 }
790
791 int AudioDeviceHasOutput( AudioDeviceID i_dev_id )
792 {
793     UInt32                      dataSize;
794     Boolean                     isWritable;
795         
796     verify_noerr( AudioDeviceGetPropertyInfo( i_dev_id, 0, FALSE, kAudioDevicePropertyStreams, &dataSize, &isWritable) );
797     if (dataSize == 0) return FALSE;
798     
799     return TRUE;
800 }
801
802
803 /*****************************************************************************
804  * HardwareListener: Warns us of changes in the list of registered devices
805  *****************************************************************************/
806 static OSStatus HardwareListener( AudioHardwarePropertyID inPropertyID,
807                                   void * inClientData )
808 {
809     OSStatus err = noErr;
810
811     aout_instance_t     *p_aout = (aout_instance_t *)inClientData;
812     /* struct aout_sys_t   *p_sys = p_aout->output.p_sys; */
813
814     switch( inPropertyID )
815     {
816         case kAudioHardwarePropertyDevices:
817         {
818             /* something changed in the list of devices */
819             /* We trigger the audio-device's aout_ChannelsRestart callback */
820             var_Change( p_aout, "audio-device", VLC_VAR_TRIGGER_CALLBACKS, NULL, NULL );
821         }
822         break;
823     }
824
825     return( err );
826 }