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