]> git.sesse.net Git - vlc/blob - modules/audio_output/auhal.c
* backport of auhal.c [11020] trough [11310] from trunk
[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 #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_LeftCenter:
293                 p_aout->output.output.i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
294                 continue;
295             case kAudioChannelLabel_RightCenter:
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                 switch( layout->mNumberChannelDescriptions )
304                 {
305                     /* We make assumptions based on number of channels here.
306                      * Unfortunatly Apple has provided no 100% method to retrieve the speaker configuration */
307                     case 1:
308                         p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
309                         break;
310                     case 4:
311                         p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
312                                                                     AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
313                         break;
314                     case 6:
315                         p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
316                                                                     AOUT_CHAN_CENTER | AOUT_CHAN_LFE |
317                                                                     AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
318                         break;
319                     case 7:
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 | AOUT_CHAN_REARCENTER;
323                         break;
324                     case 8:
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 |
328                                                                     AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
329                         break;
330                     case 2:
331                     default:
332                         p_aout->output.output.i_physical_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
333                 }
334                 break;
335         }
336     }
337     free( layout );
338
339     msg_Dbg( p_aout, "defined %d physical channels for vlc core", aout_FormatNbChannels( &p_aout->output.output ) );
340     msg_Dbg( p_aout, "%s", aout_FormatPrintChannels( &p_aout->output.output ));
341     
342     AudioChannelLayout new_layout;
343     memset (&new_layout, 0, sizeof(new_layout));
344     switch( aout_FormatNbChannels( &p_aout->output.output ) )
345     {
346         case 1:
347             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
348             break;
349         case 2:
350             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
351             break;
352         case 3:
353             if( p_aout->output.output.i_physical_channels & AOUT_CHAN_CENTER )
354             {
355                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
356             }
357             else if( p_aout->output.output.i_physical_channels & AOUT_CHAN_LFE )
358             {
359                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
360             }
361             break;
362         case 4:
363             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER | AOUT_CHAN_LFE ) )
364             {
365                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
366             }
367             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT ) )
368             {
369                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
370             }
371             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER ) )
372             {
373                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
374             }
375             break;
376         case 5:
377             if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_CENTER ) )
378             {
379                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
380             }
381             else if( p_aout->output.output.i_physical_channels & ( AOUT_CHAN_LFE ) )
382             {
383                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
384             }
385             break;
386         case 6:
387             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
388             break;
389         case 7:
390             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
391             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
392             break;
393         case 8:
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_7_1_A; // L R C LFE Ls Rs Lc Rc
396             break;
397     }
398
399     /* Set up the format to be used */
400     DeviceFormat.mSampleRate = p_aout->output.output.i_rate;
401     DeviceFormat.mFormatID = kAudioFormatLinearPCM;
402
403     /* We use float 32. It's the best supported format by both VLC and Coreaudio */
404     p_aout->output.output.i_format = VLC_FOURCC( 'f','l','3','2');
405     DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
406     DeviceFormat.mBitsPerChannel = 32;
407     DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels( &p_aout->output.output );
408     
409     /* Calculate framesizes and stuff */
410     aout_FormatPrepare( &p_aout->output.output );
411     DeviceFormat.mFramesPerPacket = 1;
412     DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
413     DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
414  
415     i_param_size = sizeof(AudioStreamBasicDescription);
416     /* Set desired format (Use CAStreamBasicDescription )*/
417     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
418                                    kAudioUnitProperty_StreamFormat,
419                                    kAudioUnitScope_Input,
420                                    0,
421                                    &DeviceFormat,
422                                    i_param_size ));
423                                    
424     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "we set the AU format: " , DeviceFormat ) );
425     
426     /* Retrieve actual format??? */
427     verify_noerr( AudioUnitGetProperty( p_sys->au_unit,
428                                    kAudioUnitProperty_StreamFormat,
429                                    kAudioUnitScope_Input,
430                                    0,
431                                    &DeviceFormat,
432                                    &i_param_size ));
433                                    
434     msg_Dbg( p_aout, STREAM_FORMAT_MSG( "the actual set AU format is " , DeviceFormat ) );
435
436     p_aout->output.i_nb_samples = 2048;
437     aout_VolumeSoftInit( p_aout );
438
439     /* Let's pray for the following operation to be atomic... */
440     p_sys->clock_diff = - (mtime_t)
441         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
442     p_sys->clock_diff += mdate();
443     
444     p_sys->i_read_bytes = 0;
445     p_sys->i_total_bytes = 0;
446
447     /* set the IOproc callback */
448     AURenderCallbackStruct input;
449     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
450     input.inputProcRefCon = p_aout;
451     
452     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
453                             kAudioUnitProperty_SetRenderCallback,
454                             kAudioUnitScope_Input,
455                             0, &input, sizeof( input ) ) );
456
457     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
458     input.inputProcRefCon = p_aout;
459     
460     /* Set the new_layout as the layout VLC feeds to the AU unit */
461     verify_noerr( AudioUnitSetProperty( p_sys->au_unit,
462                             kAudioUnitProperty_AudioChannelLayout,
463                             kAudioUnitScope_Input,
464                             0, &new_layout, sizeof(new_layout) ) );
465     
466     /* AU initiliaze */
467     verify_noerr( AudioUnitInitialize(p_sys->au_unit) );
468
469     verify_noerr( AudioOutputUnitStart(p_sys->au_unit) );
470     return( VLC_SUCCESS );
471 }
472
473 /*****************************************************************************
474  * Close: Close HAL AudioUnit
475  *****************************************************************************/
476 static void Close( vlc_object_t * p_this )
477 {
478     aout_instance_t     *p_aout = (aout_instance_t *)p_this;
479     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
480     
481     if( p_sys->au_unit )
482     {
483         verify_noerr( AudioOutputUnitStop( p_sys->au_unit ) );
484         verify_noerr( AudioUnitUninitialize( p_sys->au_unit ) );
485         verify_noerr( CloseComponent( p_sys->au_unit ) );
486     }
487     free( p_sys );
488 }
489
490 /*****************************************************************************
491  * Play: nothing to do
492  *****************************************************************************/
493 static void Play( aout_instance_t * p_aout )
494 {
495 }
496
497
498 /*****************************************************************************
499  * Probe
500  *****************************************************************************/
501 static int Probe( aout_instance_t * p_aout )
502 {
503     OSStatus            err = noErr;
504     UInt32              i, i_param_size;
505     AudioDeviceID       devid_def;
506     AudioDeviceID       *p_devices = NULL;
507     vlc_value_t         val, text;
508
509     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
510
511     /* Get number of devices */
512     err = AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,
513                                         &i_param_size, NULL );
514     if( err != noErr )
515     {
516         msg_Err( p_aout, "could not get number of devices: [%4.4s]", (char *)&err );
517         goto error;
518     }
519
520     p_sys->i_devices = i_param_size / sizeof( AudioDeviceID );
521
522     if( p_sys->i_devices < 1 )
523     {
524         msg_Err( p_aout, "no devices found" );
525         goto error;
526     }
527
528     msg_Dbg( p_aout, "system has [%ld] device(s)", p_sys->i_devices );
529
530     /* Allocate DeviceID array */
531     p_devices = (AudioDeviceID *)malloc( i_param_size );
532     if( p_devices == NULL )
533     {
534         msg_Err( p_aout, "out of memory" );
535         goto error;
536     }
537
538     /* Populate DeviceID array */
539     err = AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
540                                     &i_param_size, (void *)p_devices );
541     if( err != noErr )
542     {
543         msg_Err( p_aout, "could not get the device ID's: [%4.4s]", (char *)&err );
544         goto error;
545     }
546
547     /* Find the ID of the default Device */
548     i_param_size = sizeof( AudioDeviceID );
549     err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice,
550                                     &i_param_size, (void *)&devid_def );
551     if( err != noErr )
552     {
553         msg_Err( p_aout, "could not get default audio device: [%4.4s]", (char *)&err );
554         goto error;
555     }
556     p_sys->i_default_dev = devid_def;
557     
558     var_Create( p_aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE );
559     text.psz_string = _("Audio Device");
560     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
561     
562     for( i = 0; i < p_sys->i_devices; i++ )
563     {
564         char psz_devuid[1024];
565         char psz_name[1024];
566         CFStringRef devUID;
567             
568         i_param_size = sizeof psz_name;
569         err = AudioDeviceGetProperty(
570                     p_devices[i], 0, VLC_FALSE,
571                     kAudioDevicePropertyDeviceName,
572                     &i_param_size, psz_name);
573         if( err )
574             goto error;
575
576         i_param_size = sizeof(CFStringRef);    
577         err = AudioDeviceGetProperty(
578                     p_devices[i], 0, VLC_FALSE,
579                     kAudioDevicePropertyDeviceUID,
580                     &i_param_size, &devUID);
581         if( err )
582             goto error;
583
584         CFStringGetCString( devUID, psz_devuid, sizeof psz_devuid, CFStringGetSystemEncoding() );
585         msg_Dbg( p_aout, "DevID: %lu  DevName: %s  DevUID: %s", p_devices[i], psz_name, psz_devuid );
586         CFRelease( devUID );
587
588         val.i_int = (int) p_devices[i];
589         text.psz_string = psz_name;
590         var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text );
591         if( devid_def == p_devices[i] )
592         {
593             var_Change( p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL );
594             var_Set( p_aout, "audio-device", val );
595         }
596     }
597     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
598     
599     /* attach a Listener so that we are notified of a change in the Device setup */
600     /* err = AudioHardwareAddPropertyListener( kAudioHardwarePropertyDevices,
601                                             HardwareListener, 
602                                             (void *)p_aout );
603     if( err )
604         goto error;*/
605     
606     msg_Dbg( p_aout, "succesful finish of deviceslist" );
607     if( p_devices ) free( p_devices );
608     return (VLC_SUCCESS);
609
610 error:
611     var_Destroy( p_aout, "audio-device" );
612     if( p_devices ) free( p_devices );
613     return VLC_EGENERIC;
614 }
615
616 /*****************************************************************************
617  * DeviceDigitalMode: Check i_dev_id for digital stream support.
618  *****************************************************************************/
619 static int DeviceDigitalMode( aout_instance_t *p_aout, AudioDeviceID i_dev_id )
620 {
621     OSStatus                    err = noErr;
622     UInt32                      i_param_size;
623     AudioStreamBasicDescription *p_format_list;
624     int                         i, i_formats;
625     struct aout_sys_t           *p_sys = p_aout->output.p_sys;
626     
627     p_sys->b_supports_digital = VLC_FALSE;
628     
629     err = AudioDeviceGetPropertyInfo( i_dev_id, 0, FALSE,
630                                       kAudioDevicePropertyStreamFormats,
631                                       &i_param_size, NULL );
632     if( err != noErr )
633     {
634         msg_Err( p_aout, "could not get number of streamsformats: [%4.4s]", (char *)&err );
635         return( VLC_EGENERIC );
636     }
637     
638     i_formats = i_param_size / sizeof( AudioStreamBasicDescription );
639     p_format_list = (AudioStreamBasicDescription *)malloc( i_param_size );
640     if( p_format_list == NULL )
641     {
642         return( VLC_ENOMEM );
643     }
644     
645     err = AudioDeviceGetProperty( i_dev_id, 0, FALSE,
646                                       kAudioDevicePropertyStreamFormats,
647                                       &i_param_size, (void *)p_format_list );
648     if( err != noErr )
649     {
650         msg_Err( p_aout, "could not get the list of formats: [%4.4s]", (char *)&err );
651         return( VLC_EGENERIC );
652     }
653
654     for( i = 0; i < i_formats; i++ )
655     {
656         msg_Dbg( p_aout, STREAM_FORMAT_MSG( "supported format", p_format_list[i] ) );
657         
658         if( p_format_list[i].mFormatID == 'IAC3' ||
659                   p_format_list[i].mFormatID == kAudioFormat60958AC3 )
660         {
661             p_sys->b_supports_digital = VLC_TRUE;
662             msg_Dbg( p_aout, "this device supports a digital stream" );
663             break;
664         }
665     }
666     
667     free( (void *)p_format_list );
668     return VLC_SUCCESS;
669 }
670
671 /*****************************************************************************
672  * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
673  * us to provide some more audio data.
674  * Don't print anything during normal playback, calling blocking function from
675  * this callback is not allowed.
676  *****************************************************************************/
677 static OSStatus RenderCallbackAnalog( vlc_object_t *_p_aout,
678                                       AudioUnitRenderActionFlags *ioActionFlags,
679                                       const AudioTimeStamp *inTimeStamp,
680                                       unsigned int inBusNummer,
681                                       unsigned int inNumberFrames,
682                                       AudioBufferList *ioData )
683 {
684     AudioTimeStamp  host_time;
685     mtime_t         current_date = 0;
686     uint32_t        i_mData_bytes = 0;    
687
688     aout_instance_t * p_aout = (aout_instance_t *)_p_aout;
689     struct aout_sys_t * p_sys = p_aout->output.p_sys;
690
691     host_time.mFlags = kAudioTimeStampHostTimeValid;
692     AudioDeviceTranslateTime( p_sys->i_selected_dev, inTimeStamp, &host_time );
693
694     p_sys->clock_diff = - (mtime_t)
695         AudioConvertHostTimeToNanos( AudioGetCurrentHostTime() ) / 1000; 
696     p_sys->clock_diff += mdate();
697
698     current_date = p_sys->clock_diff +
699                    AudioConvertHostTimeToNanos( host_time.mHostTime ) / 1000;
700
701     if( ioData == NULL && ioData->mNumberBuffers < 1 )
702     {
703         msg_Err( p_aout, "no iodata or buffers");
704         return 0;
705     }
706     if( ioData->mNumberBuffers > 1 )
707         msg_Err( p_aout, "well this is weird. seems like there is more than one buffer..." );
708
709
710     if( p_sys->i_total_bytes > 0 )
711     {
712         i_mData_bytes = __MIN( p_sys->i_total_bytes - p_sys->i_read_bytes, ioData->mBuffers[0].mDataByteSize );
713         p_aout->p_vlc->pf_memcpy( ioData->mBuffers[0].mData, &p_sys->p_remainder_buffer[p_sys->i_read_bytes], i_mData_bytes );
714         p_sys->i_read_bytes += i_mData_bytes;
715         current_date += (mtime_t) ( (mtime_t) 1000000 / p_aout->output.output.i_rate ) *
716                         ( i_mData_bytes / 4 / aout_FormatNbChannels( &p_aout->output.output )  ); // 4 is fl32 specific
717         
718         if( p_sys->i_read_bytes >= p_sys->i_total_bytes )
719             p_sys->i_read_bytes = p_sys->i_total_bytes = 0;
720     }
721     
722     while( i_mData_bytes < ioData->mBuffers[0].mDataByteSize )
723     {
724         /* We don't have enough data yet */
725         aout_buffer_t * p_buffer;
726         p_buffer = aout_OutputNextBuffer( p_aout, current_date , VLC_FALSE );
727         
728         if( p_buffer != NULL )
729         {
730             uint32_t i_second_mData_bytes = __MIN( p_buffer->i_nb_bytes, ioData->mBuffers[0].mDataByteSize - i_mData_bytes );
731             
732             p_aout->p_vlc->pf_memcpy( (uint8_t *)ioData->mBuffers[0].mData + i_mData_bytes, p_buffer->p_buffer, i_second_mData_bytes );
733             i_mData_bytes += i_second_mData_bytes;
734
735             if( i_mData_bytes >= ioData->mBuffers[0].mDataByteSize )
736             {
737                 p_sys->i_total_bytes = p_buffer->i_nb_bytes - i_second_mData_bytes;
738                 p_aout->p_vlc->pf_memcpy( p_sys->p_remainder_buffer, &p_buffer->p_buffer[i_second_mData_bytes], p_sys->i_total_bytes );
739             }
740             else
741             {
742                 // update current_date
743                 current_date += (mtime_t) ( (mtime_t) 1000000 / p_aout->output.output.i_rate ) *
744                                 ( i_second_mData_bytes / 4 / aout_FormatNbChannels( &p_aout->output.output )  ); // 4 is fl32 specific
745             }
746             aout_BufferFree( p_buffer );
747         }
748         else
749         {
750              p_aout->p_vlc->pf_memset( (uint8_t *)ioData->mBuffers[0].mData +i_mData_bytes, 0, ioData->mBuffers[0].mDataByteSize - i_mData_bytes );
751              i_mData_bytes += ioData->mBuffers[0].mDataByteSize - i_mData_bytes;
752         }
753     }
754     return( noErr );     
755 }
756
757
758 /*****************************************************************************
759  * Setup a digital stream
760  *****************************************************************************/
761 static int DigitalInit( aout_instance_t * p_aout )
762 {
763     OSStatus            err = noErr;
764     UInt32              i, i_param_size;
765     AudioDeviceID       devid_def;
766     AudioDeviceID       *p_devices = NULL;
767     vlc_value_t         val, text;
768
769     struct aout_sys_t   *p_sys = p_aout->output.p_sys;
770
771     
772     
773     return (VLC_SUCCESS);
774
775 error:
776     return VLC_EGENERIC;
777 }
778
779
780 /*****************************************************************************
781  * HardwareListener: Warns us of changes in the list of registered devices
782  *****************************************************************************/
783 static OSStatus HardwareListener( AudioHardwarePropertyID inPropertyID,
784                                   void * inClientData )
785 {
786     OSStatus err = noErr;
787
788     aout_instance_t     *p_aout = (aout_instance_t *)inClientData;
789     /* struct aout_sys_t   *p_sys = p_aout->output.p_sys; */
790
791     switch( inPropertyID )
792     {
793         case kAudioHardwarePropertyDevices:
794         {
795             /* something changed in the list of devices */
796             /* We trigger the audio-device's aout_ChannelsRestart callback */
797             var_Change( p_aout, "audio-device", VLC_VAR_TRIGGER_CALLBACKS, NULL, NULL );
798         }
799         break;
800     }
801
802     return( err );
803 }