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