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