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