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