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