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