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