]> git.sesse.net Git - vlc/blob - modules/audio_output/auhal.c
f50ff530c1453d32fc67713486db6fc135cda72a
[vlc] / modules / audio_output / auhal.c
1 /*****************************************************************************
2  * auhal.c: AUHAL and Coreaudio output plugin
3  *****************************************************************************
4  * Copyright (C) 2005 - 2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8  *          Felix Paul Kühne <fkuehne at videolan dot org>
9  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
10  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation; either version 2.1 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #pragma mark includes
27
28 #ifdef HAVE_CONFIG_H
29 # import "config.h"
30 #endif
31
32 #import <vlc_common.h>
33 #import <vlc_plugin.h>
34 #import <vlc_dialog.h>                      // dialog_Fatal
35 #import <vlc_aout.h>                        // aout_*
36
37 #import <AudioUnit/AudioUnit.h>             // AudioUnit
38 #import <CoreAudio/CoreAudio.h>             // AudioDeviceID
39 #import <AudioToolbox/AudioFormat.h>        // AudioFormatGetProperty
40 #import <CoreServices/CoreServices.h>
41
42 #import "TPCircularBuffer.h"
43
44 #pragma mark -
45 #pragma mark private declarations
46
47 #ifndef verify_noerr
48 # define verify_noerr(a) assert((a) == noErr)
49 #endif
50
51 #define STREAM_FORMAT_MSG(pre, sfm) \
52     pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
53     sfm.mSampleRate, (char *)&sfm.mFormatID, \
54     (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
55     (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
56     (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
57
58 #define AOUT_VAR_SPDIF_FLAG 0xf00000
59
60 #define AUDIO_BUFFER_SIZE_IN_SECONDS (AOUT_MAX_ADVANCE_TIME / CLOCK_FREQ)
61
62
63 #define AOUT_VOLUME_DEFAULT             256
64 #define AOUT_VOLUME_MAX                 512
65
66 #define VOLUME_TEXT N_("Audio volume")
67 #define VOLUME_LONGTEXT VOLUME_TEXT
68
69 #define DEVICE_TEXT N_("Last audio device")
70 #define DEVICE_LONGTEXT DEVICE_TEXT
71
72 /*****************************************************************************
73  * aout_sys_t: private audio output method descriptor
74  *****************************************************************************
75  * This structure is part of the audio output thread descriptor.
76  * It describes the CoreAudio specific properties of an output thread.
77  *****************************************************************************/
78 struct aout_sys_t
79 {
80     AudioObjectID               i_selected_dev;     /* DeviceID of the selected device */
81     AudioObjectID               i_new_selected_dev; /* DeviceID of device which will be selected on start */
82     bool                        b_selected_dev_is_digital;
83     bool                        b_selected_dev_is_default; /* true if the user selected the default audio device (id 0) */
84
85     AudioDeviceIOProcID         i_procID;           /* DeviceID of current device */
86     bool                        b_digital;          /* Are we running in digital mode? */
87
88     uint8_t                     chans_to_reorder;   /* do we need channel reordering */
89     uint8_t                     chan_table[AOUT_CHAN_MAX];
90
91     TPCircularBuffer            circular_buffer;    /* circular buffer to swap the audio data */
92
93     /* AUHAL specific */
94     AudioComponent              au_component;       /* The AudioComponent we use */
95     AudioUnit                   au_unit;            /* The AudioUnit we use */
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;           /* Whether we need to revert the stream format */
104     bool                        b_changed_mixing;   /* Whether we need to set the mixing mode back */
105
106
107     bool                        b_got_first_sample; /* did the aout core provide something to render? */
108
109     int                         i_rate;             /* media sample rate */
110     int                         i_bytes_per_sample;
111
112     CFArrayRef                  device_list;
113
114     vlc_mutex_t                 var_lock;           /* protects access to device_list and i_selected_dev */
115
116     float                       f_volume;
117     bool                        b_mute;
118
119     vlc_mutex_t                 lock;
120     vlc_cond_t                  cond;
121
122     bool                        b_ignore_streams_changed_callback;
123 };
124
125 #pragma mark -
126 #pragma mark local prototypes & module descriptor
127
128 static int      Open                    (vlc_object_t *);
129 static void     Close                   (vlc_object_t *);
130 static int      Start                   (audio_output_t *, audio_sample_format_t *);
131 static int      StartAnalog             (audio_output_t *, audio_sample_format_t *);
132 static int      StartSPDIF              (audio_output_t *, audio_sample_format_t *);
133 static void     Stop                    (audio_output_t *);
134
135 static void     RebuildDeviceList       (audio_output_t *);
136 static int      SwitchAudioDevice       (audio_output_t *p_aout, const char *name);
137 static int      VolumeSet               (audio_output_t *, float);
138 static int      MuteSet                 (audio_output_t *, bool);
139
140 static void     Play                    (audio_output_t *, block_t *);
141 static void     Pause                   (audio_output_t *, bool, mtime_t);
142 static void     Flush                   (audio_output_t *, bool);
143 static int      TimeGet                 (audio_output_t *, mtime_t *);
144 static OSStatus RenderCallbackAnalog    (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
145                                          UInt32 , UInt32, AudioBufferList *);
146
147 static OSStatus RenderCallbackSPDIF     (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
148                                          AudioBufferList *, const AudioTimeStamp *, void *);
149
150 static OSStatus DevicesListener         (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
151 static OSStatus DeviceAliveListener     (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
152 static OSStatus DefaultDeviceChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
153 static OSStatus StreamsChangedListener  (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
154
155 static OSStatus StreamListener          (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
156
157 static int      ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register);
158 static int      AudioDeviceHasOutput    (AudioDeviceID);
159 static int      AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
160 static int      AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
161 static int      AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
162
163
164 vlc_module_begin ()
165     set_shortname("auhal")
166     set_description(N_("HAL AudioUnit output"))
167     set_capability("audio output", 101)
168     set_category(CAT_AUDIO)
169     set_subcategory(SUBCAT_AUDIO_AOUT)
170     set_callbacks(Open, Close)
171     add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
172                 VOLUME_TEXT, VOLUME_LONGTEXT, true)
173     change_integer_range(0, AOUT_VOLUME_MAX)
174     add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
175     add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
176 vlc_module_end ()
177
178 #pragma mark -
179 #pragma mark initialization
180
181 static int Open(vlc_object_t *obj)
182 {
183     audio_output_t *p_aout = (audio_output_t *)obj;
184     aout_sys_t *p_sys = malloc(sizeof (*p_sys));
185     if (unlikely(p_sys == NULL))
186         return VLC_ENOMEM;
187
188     OSStatus err = noErr;
189
190     vlc_mutex_init(&p_sys->var_lock);
191     vlc_mutex_init(&p_sys->lock);
192     vlc_cond_init(&p_sys->cond);
193     p_sys->b_digital = false;
194     p_sys->b_ignore_streams_changed_callback = false;
195     p_sys->b_selected_dev_is_default = false;
196
197     p_aout->sys = p_sys;
198     p_aout->start = Start;
199     p_aout->stop = Stop;
200     p_aout->volume_set = VolumeSet;
201     p_aout->mute_set = MuteSet;
202     p_aout->device_select = SwitchAudioDevice;
203     p_sys->device_list = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL);
204
205     /* Attach a listener so that we are notified of a change in the device setup */
206     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
207     err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
208     if (err != noErr)
209         msg_Err(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
210
211     /* Attach a listener to be notified about changes in default audio device */
212     AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
213     err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
214     if (err != noErr)
215         msg_Err(p_aout, "failed to add listener for default audio device [%4.4s]", (char *)&err);
216
217     RebuildDeviceList(p_aout);
218
219     /* remember the volume */
220     p_sys->f_volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
221     aout_VolumeReport(p_aout, p_sys->f_volume);
222     p_sys->b_mute = var_InheritBool(p_aout, "mute");
223     aout_MuteReport(p_aout, p_sys->b_mute);
224
225     char *psz_audio_device = config_GetPsz(p_aout, "auhal-audio-device");
226     SwitchAudioDevice(p_aout, psz_audio_device);
227     free(psz_audio_device);
228
229     return VLC_SUCCESS;
230 }
231
232 static void Close(vlc_object_t *obj)
233 {
234     audio_output_t *p_aout = (audio_output_t *)obj;
235     aout_sys_t *p_sys = p_aout->sys;
236
237     OSStatus err = noErr;
238
239     /* remove audio devices callback */
240     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
241     err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
242     if (err != noErr)
243         msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed [%4.4s]", (char *)&err);
244
245     /* remove listener to be notified about changes in default audio device */
246     AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
247     err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
248     if (err != noErr)
249         msg_Err(p_aout, "failed to remove listener for default audio device [%4.4s]", (char *)&err);
250
251     vlc_mutex_lock(&p_sys->var_lock);
252     /* remove streams callbacks */
253     CFIndex count = CFArrayGetCount(p_sys->device_list);
254     if (count > 0) {
255         for (CFIndex x = 0; x < count; x++) {
256             AudioDeviceID deviceId = 0;
257             CFNumberRef cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
258             if (!cfn_device_id)
259                 continue;
260
261             CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &deviceId);
262             if (!(deviceId & AOUT_VAR_SPDIF_FLAG)) {
263                 ManageAudioStreamsCallback(p_aout, deviceId, false);
264             }
265         }
266     }
267
268     CFRelease(p_sys->device_list);
269     vlc_mutex_unlock(&p_sys->var_lock);
270
271     char *psz_device = aout_DeviceGet(p_aout);
272     config_PutPsz(p_aout, "auhal-audio-device", psz_device);
273     free(psz_device);
274
275     vlc_mutex_destroy(&p_sys->var_lock);
276     vlc_mutex_destroy(&p_sys->lock);
277     vlc_cond_destroy(&p_sys->cond);
278
279     free(p_sys);
280 }
281
282 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
283 {
284     OSStatus                err = noErr;
285     UInt32                  i_param_size = 0;
286     struct aout_sys_t       *p_sys = NULL;
287
288     /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
289      * property size */
290     int                     b_alive = false;
291
292     bool                    b_start_digital = false;
293
294     p_sys = p_aout->sys;
295     p_sys->b_digital = false;
296     p_sys->au_component = NULL;
297     p_sys->au_unit = NULL;
298     p_sys->i_hog_pid = -1;
299     p_sys->i_stream_id = 0;
300     p_sys->i_stream_index = -1;
301     p_sys->b_revert = false;
302     p_sys->b_changed_mixing = false;
303     p_sys->i_bytes_per_sample = 0;
304
305     vlc_mutex_lock(&p_sys->var_lock);
306     p_sys->i_selected_dev = p_sys->i_new_selected_dev;
307
308     aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
309
310     msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
311
312     AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
313     if (p_sys->i_selected_dev > 0) {
314         /* Check if the desired device is alive and usable */
315         i_param_size = sizeof(b_alive);
316         err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
317         if (err != noErr) {
318             /* Be tolerant, only give a warning here */
319             msg_Warn(p_aout, "could not check whether device [0x%x] is alive [%4.4s]",
320                      (unsigned int)p_sys->i_selected_dev, (char *)&err);
321             b_alive = false;
322         }
323
324         if (!b_alive)
325             msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
326     }
327
328     p_sys->b_selected_dev_is_default = false;
329     if (!b_alive || p_sys->i_selected_dev == 0) {
330         p_sys->b_selected_dev_is_default = true;
331
332         AudioObjectID defaultDeviceID = 0;
333         UInt32 propertySize = sizeof(AudioObjectID);
334         AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
335         propertySize = sizeof(AudioObjectID);
336         err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
337         if (err != noErr) {
338             msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
339             vlc_mutex_unlock(&p_sys->var_lock);
340             goto error;
341         }
342         else
343             msg_Dbg(p_aout, "using default audio device %i", defaultDeviceID);
344
345         p_sys->i_selected_dev = defaultDeviceID;
346         p_sys->b_selected_dev_is_digital = var_InheritBool(p_aout, "spdif");
347     }
348     vlc_mutex_unlock(&p_sys->var_lock);
349
350     // recheck if device still supports digital
351     b_start_digital = p_sys->b_selected_dev_is_digital;
352     if(!AudioDeviceSupportsDigital(p_aout, p_sys->i_selected_dev))
353         b_start_digital = false;
354
355     if (b_start_digital)
356         msg_Dbg(p_aout, "Using audio device for digital output");
357     else
358         msg_Dbg(p_aout, "Audio device supports PCM mode only");
359
360     /* add a callback to see if the device dies later on */
361     err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, DeviceAliveListener, (void *)p_aout);
362     if (err != noErr) {
363         /* Be tolerant, only give a warning here */
364         msg_Warn(p_aout, "could not set alive check callback on device [0x%x] [%4.4s]",
365                  (unsigned int)p_sys->i_selected_dev, (char *)&err);
366     }
367
368     AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
369                                   kAudioDevicePropertyScopeOutput,
370                                   kAudioObjectPropertyElementMaster };
371     i_param_size = sizeof(p_sys->i_hog_pid);
372     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
373     if (err != noErr) {
374         /* This is not a fatal error. Some drivers simply don't support this property */
375         msg_Warn(p_aout, "could not check whether device is hogged [%4.4s]",
376                  (char *)&err);
377         p_sys->i_hog_pid = -1;
378     }
379
380     if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
381         msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
382         dialog_Fatal(p_aout, _("Audio output failed"), "%s",
383                         _("The selected audio output device is exclusively in "
384                           "use by another program."));
385         goto error;
386     }
387
388     bool b_success = false;
389
390     /* Check for Digital mode or Analog output mode */
391     if (AOUT_FMT_SPDIF (fmt) && b_start_digital) {
392         if (StartSPDIF (p_aout, fmt)) {
393             msg_Dbg(p_aout, "digital output successfully opened");
394             b_success = true;
395         }
396     } else {
397         if (StartAnalog(p_aout, fmt)) {
398             msg_Dbg(p_aout, "analog output successfully opened");
399             b_success = true;
400         }
401     }
402
403     if (b_success) {
404         p_aout->play = Play;
405         p_aout->flush = Flush;
406         p_aout->time_get = TimeGet;
407         p_aout->pause = Pause;
408         return VLC_SUCCESS;
409     }
410
411 error:
412     /* If we reach this, this aout has failed */
413     msg_Err(p_aout, "opening auhal output failed");
414     return VLC_EGENERIC;
415 }
416
417 /*
418  * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
419  */
420 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
421 {
422     struct aout_sys_t           *p_sys = p_aout->sys;
423     OSStatus                    err = noErr;
424     UInt32                      i_param_size = 0;
425     int                         i_original;
426     AudioComponentDescription   desc;
427     AudioStreamBasicDescription DeviceFormat;
428     AudioChannelLayout          *layout;
429     AudioChannelLayout          new_layout;
430     AURenderCallbackStruct      input;
431     p_aout->sys->chans_to_reorder = 0;
432
433     SInt32 currentMinorSystemVersion;
434     if(Gestalt(gestaltSystemVersionMinor, &currentMinorSystemVersion) != noErr)
435         msg_Err(p_aout, "failed to check OSX version");
436
437     /* Lets go find our Component */
438     desc.componentType = kAudioUnitType_Output;
439     desc.componentSubType = kAudioUnitSubType_HALOutput;
440     desc.componentManufacturer = kAudioUnitManufacturer_Apple;
441     desc.componentFlags = 0;
442     desc.componentFlagsMask = 0;
443
444     p_sys->au_component = AudioComponentFindNext(NULL, &desc);
445     if (p_sys->au_component == NULL) {
446         msg_Err(p_aout, "cannot find any HAL component, PCM output failed");
447         return false;
448     }
449
450     err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
451     if (err != noErr) {
452         msg_Err(p_aout, "cannot open HAL component, PCM output failed [%4.4s]", (char *)&err);
453         return false;
454     }
455
456     /* Set the device we will use for this output unit */
457     err = AudioUnitSetProperty(p_sys->au_unit,
458                          kAudioOutputUnitProperty_CurrentDevice,
459                          kAudioUnitScope_Global,
460                          0,
461                          &p_sys->i_selected_dev,
462                          sizeof(AudioObjectID));
463
464     if (err != noErr) {
465         msg_Err(p_aout, "cannot select audio output device, PCM output failed [%4.4s]", (char *)&err);
466         return false;
467     }
468
469     /* Get the current format */
470     i_param_size = sizeof(AudioStreamBasicDescription);
471
472     err = AudioUnitGetProperty(p_sys->au_unit,
473                                    kAudioUnitProperty_StreamFormat,
474                                    kAudioUnitScope_Output,
475                                    0,
476                                    &DeviceFormat,
477                                    &i_param_size);
478
479     if (err != noErr) {
480         msg_Err(p_aout, "failed to detect supported stream formats [%4.4s]", (char *)&err);
481         return false;
482     } else
483         msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
484
485     /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
486     err = AudioUnitGetPropertyInfo(p_sys->au_unit,
487                                    kAudioDevicePropertyPreferredChannelLayout,
488                                    kAudioUnitScope_Output,
489                                    0,
490                                    &i_param_size,
491                                    NULL);
492
493     if (err == noErr) {
494         layout = (AudioChannelLayout *)malloc(i_param_size);
495
496         verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
497                                        kAudioDevicePropertyPreferredChannelLayout,
498                                        kAudioUnitScope_Output,
499                                        0,
500                                        layout,
501                                        &i_param_size));
502
503         /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
504         if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
505             /* bitmap defined channellayout */
506             verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
507                                     sizeof(UInt32), &layout->mChannelBitmap,
508                                     &i_param_size,
509                                     layout));
510         } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
511         {
512             /* layouttags defined channellayout */
513             verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
514                                     sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
515                                     &i_param_size,
516                                     layout));
517         }
518
519         msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
520
521         if (layout->mNumberChannelDescriptions == 0) {
522             msg_Err(p_aout, "insufficient number of output channels");
523             return false;
524         }
525
526         /* Initialize the VLC core channel count */
527         fmt->i_physical_channels = 0;
528         i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
529
530         if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
531             /* We only need Mono or cannot output more than 1 channel */
532             fmt->i_physical_channels = AOUT_CHAN_CENTER;
533         } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
534             /* We only need Stereo or cannot output more than 2 channels */
535             fmt->i_physical_channels = AOUT_CHANS_STEREO;
536         } else {
537             /* We want more than stereo and we can do that */
538             for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
539 #ifndef NDEBUG
540                 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
541 #endif
542
543                 switch(layout->mChannelDescriptions[i].mChannelLabel) {
544                     case kAudioChannelLabel_Left:
545                         fmt->i_physical_channels |= AOUT_CHAN_LEFT;
546                         continue;
547                     case kAudioChannelLabel_Right:
548                         fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
549                         continue;
550                     case kAudioChannelLabel_Center:
551                         fmt->i_physical_channels |= AOUT_CHAN_CENTER;
552                         continue;
553                     case kAudioChannelLabel_LFEScreen:
554                         fmt->i_physical_channels |= AOUT_CHAN_LFE;
555                         continue;
556                     case kAudioChannelLabel_LeftSurround:
557                         fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
558                         continue;
559                     case kAudioChannelLabel_RightSurround:
560                         fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
561                         continue;
562                     case kAudioChannelLabel_RearSurroundLeft:
563                         fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
564                         continue;
565                     case kAudioChannelLabel_RearSurroundRight:
566                         fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
567                         continue;
568                     case kAudioChannelLabel_CenterSurround:
569                         fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
570                         continue;
571                     default:
572                         msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
573                 }
574             }
575             if (fmt->i_physical_channels == 0) {
576                 fmt->i_physical_channels = AOUT_CHANS_STEREO;
577                 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup in /Applications/Utilities. VLC will output Stereo only.");
578                 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
579                                 _("You should configure your speaker layout with "
580                                   "\"Audio Midi Setup\" in /Applications/"
581                                   "Utilities. VLC will output Stereo only."));
582             }
583         }
584         free(layout);
585     } else {
586         msg_Warn(p_aout, "device driver does not support kAudioDevicePropertyPreferredChannelLayout - using stereo fallback [%4.4s]", (char *)&err);
587         fmt->i_physical_channels = AOUT_CHANS_STEREO;
588     }
589
590     msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
591     msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
592
593     memset (&new_layout, 0, sizeof(new_layout));
594     uint32_t chans_out[AOUT_CHAN_MAX];
595     memset(&chans_out, 0, sizeof(chans_out));
596
597     /* Some channel abbreviations used below:
598      * L - left
599      * R - right
600      * C - center
601      * Ls - left surround
602      * Rs - right surround
603      * Cs - center surround
604      * Rls - rear left surround
605      * Rrs - rear right surround
606      * Lw - left wide
607      * Rw - right wide
608      * Lsd - left surround direct
609      * Rsd - right surround direct
610      * Lc - left center
611      * Rc - right center
612      * Ts - top surround
613      * Vhl - vertical height left
614      * Vhc - vertical height center
615      * Vhr - vertical height right
616      * Lt - left matrix total. for matrix encoded stereo.
617      * Rt - right matrix total. for matrix encoded stereo. */
618
619     switch(aout_FormatNbChannels(fmt)) {
620         case 1:
621             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
622             break;
623         case 2:
624             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
625             break;
626         case 3:
627             if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
628                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
629             else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
630                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
631             break;
632         case 4:
633             if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
634                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
635             else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
636                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
637             else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
638                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
639             break;
640         case 5:
641             if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
642                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
643             else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
644                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
645             break;
646         case 6:
647             if (fmt->i_physical_channels & (AOUT_CHAN_LFE)) {
648                 /* note: for some reason, kAudioChannelLayoutTag_DVD_20, which would not require channel reordering, 
649                  does not work anymore */
650                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_5_1; // L R C LFE Ls Rs
651
652                 chans_out[0] = AOUT_CHAN_LEFT;
653                 chans_out[1] = AOUT_CHAN_RIGHT;
654                 chans_out[2] = AOUT_CHAN_CENTER;
655                 chans_out[3] = AOUT_CHAN_LFE;
656                 chans_out[4] = AOUT_CHAN_REARLEFT;
657                 chans_out[5] = AOUT_CHAN_REARRIGHT;
658
659                 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
660                 if (p_aout->sys->chans_to_reorder)
661                     msg_Dbg(p_aout, "channel reordering needed for 5.1 output");
662             } else {
663                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
664
665                 chans_out[0] = AOUT_CHAN_LEFT;
666                 chans_out[1] = AOUT_CHAN_RIGHT;
667                 chans_out[2] = AOUT_CHAN_REARLEFT;
668                 chans_out[3] = AOUT_CHAN_REARRIGHT;
669                 chans_out[4] = AOUT_CHAN_CENTER;
670                 chans_out[5] = AOUT_CHAN_REARCENTER;
671
672                 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
673                 if (p_aout->sys->chans_to_reorder)
674                     msg_Dbg(p_aout, "channel reordering needed for 6.0 output");
675             }
676             break;
677         case 7:
678             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
679
680             chans_out[0] = AOUT_CHAN_LEFT;
681             chans_out[1] = AOUT_CHAN_RIGHT;
682             chans_out[2] = AOUT_CHAN_CENTER;
683             chans_out[3] = AOUT_CHAN_LFE;
684             chans_out[4] = AOUT_CHAN_REARLEFT;
685             chans_out[5] = AOUT_CHAN_REARRIGHT;
686             chans_out[6] = AOUT_CHAN_REARCENTER;
687
688             p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
689             if (p_aout->sys->chans_to_reorder)
690                 msg_Dbg(p_aout, "channel reordering needed for 6.1 output");
691
692             break;
693         case 8:
694             if (fmt->i_physical_channels & (AOUT_CHAN_LFE) || currentMinorSystemVersion < 7) {
695                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
696
697                 chans_out[0] = AOUT_CHAN_LEFT;
698                 chans_out[1] = AOUT_CHAN_RIGHT;
699                 chans_out[2] = AOUT_CHAN_CENTER;
700                 chans_out[3] = AOUT_CHAN_LFE;
701                 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
702                 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
703                 chans_out[6] = AOUT_CHAN_REARLEFT;
704                 chans_out[7] = AOUT_CHAN_REARRIGHT;
705
706                 if (!(fmt->i_physical_channels & (AOUT_CHAN_LFE)))
707                     msg_Warn(p_aout, "8.0 audio output not supported on OS X 10.%i, layout will be incorrect", currentMinorSystemVersion);
708             }
709 #ifdef MAC_OS_X_VERSION_10_7
710             else {
711                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_0_B; // Lc C Rc L R Ls Cs Rs
712
713                 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
714                 chans_out[1] = AOUT_CHAN_CENTER;
715                 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
716                 chans_out[3] = AOUT_CHAN_LEFT;
717                 chans_out[4] = AOUT_CHAN_RIGHT;
718                 chans_out[5] = AOUT_CHAN_REARLEFT;
719                 chans_out[6] = AOUT_CHAN_REARCENTER;
720                 chans_out[7] = AOUT_CHAN_REARRIGHT;
721             }
722 #endif
723             p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
724             if (p_aout->sys->chans_to_reorder)
725                 msg_Dbg(p_aout, "channel reordering needed for 7.1 / 8.0 output");
726
727             break;
728         case 9:
729             if (currentMinorSystemVersion < 7) {
730                 msg_Warn(p_aout, "8.1 audio output not supported on OS X 10.%i", currentMinorSystemVersion);
731                 break;
732             }
733
734 #ifdef MAC_OS_X_VERSION_10_7
735             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_1_B; // Lc C Rc L R Ls Cs Rs LFE
736             chans_out[0] = AOUT_CHAN_MIDDLELEFT;
737             chans_out[1] = AOUT_CHAN_CENTER;
738             chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
739             chans_out[3] = AOUT_CHAN_LEFT;
740             chans_out[4] = AOUT_CHAN_RIGHT;
741             chans_out[5] = AOUT_CHAN_REARLEFT;
742             chans_out[6] = AOUT_CHAN_REARCENTER;
743             chans_out[7] = AOUT_CHAN_REARRIGHT;
744             chans_out[8] = AOUT_CHAN_LFE;
745
746             p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
747             if (p_aout->sys->chans_to_reorder)
748                 msg_Dbg(p_aout, "channel reordering needed for 8.1 output");
749 #endif
750             break;
751     }
752
753     /* Set up the format to be used */
754     DeviceFormat.mSampleRate = fmt->i_rate;
755     DeviceFormat.mFormatID = kAudioFormatLinearPCM;
756     p_sys->i_rate = fmt->i_rate;
757
758     /* We use float 32 since this is VLC's endorsed format */
759     fmt->i_format = VLC_CODEC_FL32;
760     DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
761     DeviceFormat.mBitsPerChannel = 32;
762     DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
763
764     /* Calculate framesizes and stuff */
765     DeviceFormat.mFramesPerPacket = 1;
766     DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
767     DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
768
769     /* Set the desired format */
770     i_param_size = sizeof(AudioStreamBasicDescription);
771     verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
772                                    kAudioUnitProperty_StreamFormat,
773                                    kAudioUnitScope_Input,
774                                    0,
775                                    &DeviceFormat,
776                                    i_param_size));
777
778     msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
779
780     /* Retrieve actual format */
781     verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
782                                    kAudioUnitProperty_StreamFormat,
783                                    kAudioUnitScope_Input,
784                                    0,
785                                    &DeviceFormat,
786                                    &i_param_size));
787
788     msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
789
790     /* Do the last VLC aout setups */
791     aout_FormatPrepare(fmt);
792
793     /* set the IOproc callback */
794     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
795     input.inputProcRefCon = p_aout;
796
797     verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
798                             kAudioUnitProperty_SetRenderCallback,
799                             kAudioUnitScope_Input,
800                             0, &input, sizeof(input)));
801
802     /* Set the new_layout as the layout VLC will use to feed the AU unit */
803     verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
804                             kAudioUnitProperty_AudioChannelLayout,
805                             kAudioUnitScope_Output,
806                             0, &new_layout, sizeof(new_layout)));
807
808     if (new_layout.mNumberChannelDescriptions > 0)
809         free(new_layout.mChannelDescriptions);
810
811     /* AU initiliaze */
812     verify_noerr(AudioUnitInitialize(p_sys->au_unit));
813
814     /* setup circular buffer */
815     TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
816                          fmt->i_rate * fmt->i_bytes_per_frame);
817
818     p_sys->b_got_first_sample = false;
819
820     /* Set volume for output unit */
821     VolumeSet(p_aout, p_sys->f_volume);
822     MuteSet(p_aout, p_sys->b_mute);
823
824     return true;
825 }
826
827 /*
828  * StartSPDIF: Setup an encoded digital stream (SPDIF) output
829  */
830 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
831 {
832     struct aout_sys_t       *p_sys = p_aout->sys;
833     OSStatus                err = noErr;
834     UInt32                  i_param_size = 0, b_mix = 0;
835     Boolean                 b_writeable = false;
836     AudioStreamID           *p_streams = NULL;
837     unsigned                i_streams = 0;
838
839     /* Start doing the SPDIF setup proces */
840     p_sys->b_digital = true;
841
842     /* Hog the device */
843     AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
844     i_param_size = sizeof(p_sys->i_hog_pid);
845     p_sys->i_hog_pid = getpid() ;
846
847     /*
848      * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
849      * directly in the same thread. This call needs to be ignored to avoid endless restarting.
850      */
851     p_sys->b_ignore_streams_changed_callback = true;
852     err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
853     p_sys->b_ignore_streams_changed_callback = false;
854
855     if (err != noErr) {
856         msg_Err(p_aout, "failed to set hogmode [%4.4s]", (char *)&err);
857         return false;
858     }
859
860     AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
861
862     if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
863         /* Set mixable to false if we are allowed to */
864         err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
865         err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
866         err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
867
868         if (err == noErr && b_writeable) {
869             b_mix = 0;
870             err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
871             p_sys->b_changed_mixing = true;
872         }
873
874         if (err != noErr) {
875             msg_Err(p_aout, "failed to set mixmode [%4.4s]", (char *)&err);
876             return false;
877         }
878     }
879
880     /* Get a list of all the streams on this device */
881     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
882     err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
883     if (err != noErr) {
884         msg_Err(p_aout, "could not get size of stream description packet [%4.4s]", (char *)&err);
885         return false;
886     }
887
888     i_streams = i_param_size / sizeof(AudioStreamID);
889     p_streams = (AudioStreamID *)malloc(i_param_size);
890     if (p_streams == NULL)
891         return false;
892
893     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
894
895     if (err != noErr) {
896         msg_Err(p_aout, "could not fetch stream descriptions [%4.4s]", (char *)&err);
897         free(p_streams);
898         return false;
899     }
900
901     AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
902     for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
903         /* Find a stream with a cac3 stream */
904         AudioStreamRangedDescription *p_format_list = NULL;
905         int                          i_formats = 0;
906         bool                         b_digital = false;
907
908         /* Retrieve all the stream formats supported by each output stream */
909         err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
910         if (err != noErr) {
911             msg_Err(p_aout, "could not get number of streamformats: [%4.4s] (%i)", (char *)&err, (int32_t)err);
912             continue;
913         }
914
915         i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
916         p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
917         if (p_format_list == NULL)
918             continue;
919
920         err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
921         if (err != noErr) {
922             msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
923             free(p_format_list);
924             continue;
925         }
926
927         /* Check if one of the supported formats is a digital format */
928         for (int j = 0; j < i_formats; j++) {
929             if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
930                p_format_list[j].mFormat.mFormatID == 'iac3' ||
931                p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
932                p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
933                 b_digital = true;
934                 break;
935             }
936         }
937
938         if (b_digital) {
939             /* if this stream supports a digital (cac3) format, then go set it. */
940             int i_requested_rate_format = -1;
941             int i_current_rate_format = -1;
942             int i_backup_rate_format = -1;
943
944             p_sys->i_stream_id = p_streams[i];
945             p_sys->i_stream_index = i;
946
947             if (!p_sys->b_revert) {
948                 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
949                 /* Retrieve the original format of this stream first if not done so already */
950                 i_param_size = sizeof(p_sys->sfmt_revert);
951                 err = AudioObjectGetPropertyData(p_sys->i_stream_id, &currentPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
952                 if (err != noErr) {
953                     msg_Err(p_aout, "could not retrieve the original streamformat [%4.4s]", (char *)&err);
954                     continue;
955                 }
956                 p_sys->b_revert = true;
957             }
958
959             for (int j = 0; j < i_formats; j++) {
960                 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
961                    p_format_list[j].mFormat.mFormatID == 'iac3' ||
962                    p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
963                    p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
964                     if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
965                         i_requested_rate_format = j;
966                         break;
967                     } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
968                         i_current_rate_format = j;
969                     else {
970                         if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
971                             i_backup_rate_format = j;
972                     }
973                 }
974
975             }
976
977             if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
978                 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
979             else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
980                 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
981             else
982                 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) */
983         }
984         free(p_format_list);
985     }
986     free(p_streams);
987
988     msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
989
990     if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format)) {
991         msg_Err(p_aout, "failed to change stream format for SPDIF output");
992         return false;
993     }
994
995     /* Set the format flags */
996     if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
997         fmt->i_format = VLC_CODEC_SPDIFB;
998     else
999         fmt->i_format = VLC_CODEC_SPDIFL;
1000     fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
1001     fmt->i_frame_length = A52_FRAME_NB;
1002     fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
1003     p_sys->i_rate = fmt->i_rate;
1004     aout_FormatPrepare(fmt);
1005
1006     /* Add IOProc callback */
1007     err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
1008                                    (AudioDeviceIOProc)RenderCallbackSPDIF,
1009                                    (void *)p_aout,
1010                                    &p_sys->i_procID);
1011     if (err != noErr) {
1012         msg_Err(p_aout, "Failed to create Process ID [%4.4s]", (char *)&err);
1013         return false;
1014     }
1015
1016     /* Start device */
1017     err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1018     if (err != noErr) {
1019         msg_Err(p_aout, "Failed to start audio device [%4.4s]", (char *)&err);
1020
1021         err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
1022         if (err != noErr)
1023             msg_Err(p_aout, "Failed to destroy process ID [%4.4s]", (char *)&err);
1024
1025         return false;
1026     }
1027
1028     /* setup circular buffer */
1029     TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
1030
1031     return true;
1032 }
1033
1034 static void Stop(audio_output_t *p_aout)
1035 {
1036     struct aout_sys_t   *p_sys = p_aout->sys;
1037     OSStatus            err = noErr;
1038     UInt32              i_param_size = 0;
1039
1040     if (p_sys->au_unit) {
1041         verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
1042         verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
1043         verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
1044     }
1045
1046     if (p_sys->b_digital) {
1047         /* Stop device */
1048         err = AudioDeviceStop(p_sys->i_selected_dev,
1049                                p_sys->i_procID);
1050         if (err != noErr)
1051             msg_Err(p_aout, "Failed to stop audio device [%4.4s]", (char *)&err);
1052
1053         /* Remove IOProc callback */
1054         err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
1055                                           p_sys->i_procID);
1056         if (err != noErr)
1057             msg_Err(p_aout, "Failed to destroy Process ID [%4.4s]", (char *)&err);
1058
1059         if (p_sys->b_revert)
1060             AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
1061
1062         if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
1063             int b_mix;
1064             Boolean b_writeable = false;
1065             i_param_size = sizeof(int);
1066             /* Revert mixable to true if we are allowed to */
1067             AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1068             err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
1069             err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
1070
1071             if (err == noErr && b_writeable) {
1072                 msg_Dbg(p_aout, "mixable is: %d", b_mix);
1073                 b_mix = 1;
1074                 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
1075             }
1076
1077             if (err != noErr)
1078                 msg_Err(p_aout, "failed to re-set mixmode [%4.4s]", (char *)&err);
1079         }
1080     }
1081
1082     if (p_sys->i_hog_pid == getpid()) {
1083         p_sys->i_hog_pid = -1;
1084         i_param_size = sizeof(p_sys->i_hog_pid);
1085         AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
1086             kAudioDevicePropertyScopeOutput,
1087             kAudioObjectPropertyElementMaster };
1088
1089         /*
1090          * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
1091          * directly in the same thread. This call needs to be ignored to avoid endless restarting.
1092          */
1093         p_sys->b_ignore_streams_changed_callback = true;
1094         err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
1095         p_sys->b_ignore_streams_changed_callback = false;
1096         if (err != noErr)
1097             msg_Err(p_aout, "Failed to release hogmode [%4.4s]", (char *)&err);
1098     }
1099
1100     /* remove audio device alive callback */
1101     AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1102     err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, DeviceAliveListener, (void *)p_aout);
1103     if (err != noErr) {
1104         /* Be tolerant, only give a warning here */
1105         msg_Warn(p_aout, "failed to remove audio device life checker [%4.4s]", (char *)&err);
1106     }
1107
1108     p_sys->i_bytes_per_sample = 0;
1109     p_sys->b_digital = false;
1110
1111     /* clean-up circular buffer */
1112     TPCircularBufferCleanup(&p_sys->circular_buffer);
1113 }
1114
1115 #pragma mark -
1116 #pragma mark core interaction
1117
1118 static void ReportDevice(audio_output_t *p_aout, UInt32 i_id, char *name)
1119 {
1120     char deviceid[10];
1121     sprintf(deviceid, "%i", i_id);
1122
1123     aout_HotplugReport(p_aout, deviceid, name);
1124 }
1125
1126 static void RebuildDeviceList(audio_output_t * p_aout)
1127 {
1128     OSStatus            err = noErr;
1129     UInt32              propertySize = 0;
1130     AudioObjectID       *deviceIDs;
1131     UInt32              numberOfDevices;
1132     CFMutableArrayRef   currentListOfDevices;
1133
1134     struct aout_sys_t   *p_sys = p_aout->sys;
1135
1136     ReportDevice(p_aout, 0, _("System Sound Output Device"));
1137
1138     /* setup local array */
1139     currentListOfDevices = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
1140
1141     /* Get number of devices */
1142     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1143     err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1144     if (err != noErr) {
1145         msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
1146         return;
1147     }
1148
1149     numberOfDevices = propertySize / sizeof(AudioDeviceID);
1150
1151     if (numberOfDevices < 1) {
1152         msg_Err(p_aout, "No audio output devices found.");
1153         return;
1154     }
1155     msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1156
1157     /* Allocate DeviceID array */
1158     deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1159     if (deviceIDs == NULL)
1160         return;
1161
1162     /* Populate DeviceID array */
1163     err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1164     if (err != noErr) {
1165         msg_Err(p_aout, "could not get the device IDs [%4.4s]", (char *)&err);
1166         return;
1167     }
1168
1169     AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1170
1171     for (unsigned int i = 0; i < numberOfDevices; i++) {
1172         CFStringRef device_name_ref;
1173         char *psz_name;
1174         CFIndex length;
1175         bool b_digital = false;
1176         UInt32 i_id = deviceIDs[i];
1177
1178         /* Retrieve the length of the device name */
1179         err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1180         if (err != noErr) {
1181             msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1182             continue;
1183         }
1184
1185         /* Retrieve the name of the device */
1186         err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1187         if (err != noErr) {
1188             msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1189             continue;
1190         }
1191         length = CFStringGetLength(device_name_ref);
1192         length++;
1193         psz_name = (char *)malloc(length);
1194         CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1195
1196         msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1197
1198         if (!AudioDeviceHasOutput(deviceIDs[i])) {
1199             msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1200             free(psz_name);
1201             continue;
1202         }
1203
1204         ReportDevice(p_aout, i_id, psz_name);
1205         CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1206
1207         if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1208             b_digital = true;
1209             msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1210             char *psz_encoded_name = nil;
1211             asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1212             i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1213             ReportDevice(p_aout, i_id, psz_encoded_name);
1214             CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1215             free(psz_encoded_name);
1216         }
1217
1218         // TODO: only register once for each device
1219         ManageAudioStreamsCallback(p_aout, deviceIDs[i], true);
1220
1221         CFRelease(device_name_ref);
1222         free(psz_name);
1223     }
1224
1225     vlc_mutex_lock(&p_sys->var_lock);
1226     CFIndex count = 0;
1227     if (p_sys->device_list)
1228         count = CFArrayGetCount(p_sys->device_list);
1229
1230     if (count > 0) {
1231         CFNumberRef cfn_device_id;
1232         int i_device_id = 0;
1233         for (CFIndex x = 0; x < count; x++) {
1234             if (!CFArrayContainsValue(currentListOfDevices, CFRangeMake(0, count), CFArrayGetValueAtIndex(p_sys->device_list, x))) {
1235                 cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
1236
1237                 if (cfn_device_id) {
1238                     CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &i_device_id);
1239                     ReportDevice(p_aout, i_device_id, NULL);
1240                 }
1241             }
1242         }
1243     }
1244     CFRelease(p_sys->device_list);
1245     p_sys->device_list = CFArrayCreateCopy(kCFAllocatorDefault, currentListOfDevices);
1246     CFRelease(currentListOfDevices);
1247     vlc_mutex_unlock(&p_sys->var_lock);
1248
1249     free(deviceIDs);
1250 }
1251
1252 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1253 {
1254     struct aout_sys_t *p_sys = p_aout->sys;
1255
1256     if (name)
1257         p_sys->i_new_selected_dev = atoi(name);
1258     else
1259         p_sys->i_new_selected_dev = 0;
1260
1261     bool b_supports_digital = (p_sys->i_new_selected_dev & AOUT_VAR_SPDIF_FLAG);
1262     if (b_supports_digital)
1263         p_sys->b_selected_dev_is_digital = true;
1264     else
1265         p_sys->b_selected_dev_is_digital = false;
1266
1267     p_sys->i_new_selected_dev = p_sys->i_new_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1268
1269     aout_DeviceReport(p_aout, name);
1270     aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1271
1272     return 0;
1273 }
1274
1275 static int VolumeSet(audio_output_t * p_aout, float volume)
1276 {
1277     struct aout_sys_t *p_sys = p_aout->sys;
1278     OSStatus ostatus = 0;
1279
1280     if(p_sys->b_digital)
1281         return VLC_EGENERIC;
1282
1283     p_sys->f_volume = volume;
1284     aout_VolumeReport(p_aout, volume);
1285
1286     /* Set volume for output unit */
1287     if(!p_sys->b_mute) {
1288         ostatus = AudioUnitSetParameter(p_sys->au_unit,
1289                                         kHALOutputParam_Volume,
1290                                         kAudioUnitScope_Global,
1291                                         0,
1292                                         volume * volume * volume,
1293                                         0);
1294     }
1295
1296     if (var_InheritBool(p_aout, "volume-save"))
1297         config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1298
1299     return ostatus;
1300 }
1301
1302 static int MuteSet(audio_output_t * p_aout, bool mute)
1303 {
1304     struct   aout_sys_t *p_sys = p_aout->sys;
1305     OSStatus ostatus;
1306
1307     if(p_sys->b_digital)
1308         return VLC_EGENERIC;
1309
1310     p_sys->b_mute = mute;
1311     aout_MuteReport(p_aout, mute);
1312
1313     float volume = .0;
1314     if (!mute)
1315         volume = p_sys->f_volume;
1316
1317     ostatus = AudioUnitSetParameter(p_sys->au_unit,
1318                                     kHALOutputParam_Volume,
1319                                     kAudioUnitScope_Global,
1320                                     0,
1321                                     volume * volume * volume,
1322                                     0);
1323
1324     return ostatus;
1325 }
1326
1327 #pragma mark -
1328 #pragma mark actual playback
1329
1330 static void Play(audio_output_t * p_aout, block_t * p_block)
1331 {
1332     struct aout_sys_t *p_sys = p_aout->sys;
1333
1334     if (p_block->i_nb_samples > 0) {
1335         if (!p_sys->b_got_first_sample) {
1336             /* Start the AU */
1337             verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1338             p_sys->b_got_first_sample = true;
1339         }
1340
1341         /* Do the channel reordering */
1342         if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1343            aout_ChannelReorder(p_block->p_buffer,
1344                                p_block->i_buffer,
1345                                p_sys->chans_to_reorder,
1346                                p_sys->chan_table,
1347                                VLC_CODEC_FL32);
1348         }
1349
1350         /* move data to buffer */
1351         if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1352             msg_Warn(p_aout, "dropped buffer");
1353
1354         if (!p_sys->i_bytes_per_sample)
1355             p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1356     }
1357
1358     block_Release(p_block);
1359 }
1360
1361 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1362 {
1363     struct aout_sys_t * p_sys = p_aout->sys;
1364     VLC_UNUSED(date);
1365
1366     if (p_aout->sys->b_digital) {
1367         if (pause)
1368             AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1369         else
1370             AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1371     } else {
1372         if (pause)
1373             AudioOutputUnitStop(p_sys->au_unit);
1374         else
1375             AudioOutputUnitStart(p_sys->au_unit);
1376     }
1377 }
1378
1379 static void Flush(audio_output_t *p_aout, bool wait)
1380 {
1381     struct aout_sys_t *p_sys = p_aout->sys;
1382
1383     if (wait) {
1384         int32_t availableBytes;
1385         vlc_mutex_lock(&p_sys->lock);
1386         TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1387         while (availableBytes > 0) {
1388             vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1389             TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1390         }
1391         vlc_mutex_unlock(&p_sys->lock);
1392
1393     } else {
1394         p_sys->b_got_first_sample = false;
1395
1396         /* flush circular buffer */
1397         AudioOutputUnitStop(p_aout->sys->au_unit);
1398         TPCircularBufferClear(&p_aout->sys->circular_buffer);
1399     }
1400 }
1401
1402 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1403 {
1404     struct aout_sys_t * p_sys = p_aout->sys;
1405
1406     if (!p_sys->i_bytes_per_sample)
1407         return -1;
1408
1409     int32_t availableBytes;
1410     TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1411
1412     *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1413
1414     return 0;
1415 }
1416
1417 /*****************************************************************************
1418  * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1419  * us to provide some more audio data.
1420  * Don't print anything during normal playback, calling blocking function from
1421  * this callback is not allowed.
1422  *****************************************************************************/
1423 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1424                                     AudioUnitRenderActionFlags *ioActionFlags,
1425                                     const AudioTimeStamp *inTimeStamp,
1426                                     UInt32 inBusNumber,
1427                                     UInt32 inNumberFrames,
1428                                     AudioBufferList *ioData) {
1429     VLC_UNUSED(ioActionFlags);
1430     VLC_UNUSED(inTimeStamp);
1431     VLC_UNUSED(inBusNumber);
1432     VLC_UNUSED(inNumberFrames);
1433
1434     audio_output_t * p_aout = (audio_output_t *)p_obj;
1435     struct aout_sys_t * p_sys = p_aout->sys;
1436
1437     int bytesRequested = ioData->mBuffers[0].mDataByteSize;
1438     Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1439
1440     vlc_mutex_lock(&p_sys->lock);
1441     /* Pull audio from buffer */
1442     int32_t availableBytes;
1443     Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1444
1445     /* check if we have enough data */
1446     if (!availableBytes) {
1447         /* return an empty buffer so silence is played until we have data */
1448         memset(targetBuffer, 0, ioData->mBuffers[0].mDataByteSize);
1449     } else {
1450         int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1451
1452         memcpy(targetBuffer, buffer, bytesToCopy);
1453         TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1454         ioData->mBuffers[0].mDataByteSize = bytesToCopy;
1455     }
1456
1457     vlc_cond_signal(&p_sys->cond);
1458     vlc_mutex_unlock(&p_sys->lock);
1459
1460     return noErr;
1461 }
1462
1463 /*
1464  * RenderCallbackSPDIF: callback for SPDIF audio output
1465  */
1466 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1467                                     const AudioTimeStamp * inNow,
1468                                     const void * inInputData,
1469                                     const AudioTimeStamp * inInputTime,
1470                                     AudioBufferList * outOutputData,
1471                                     const AudioTimeStamp * inOutputTime,
1472                                     void * threadGlobals)
1473 {
1474     VLC_UNUSED(inNow);
1475     VLC_UNUSED(inDevice);
1476     VLC_UNUSED(inInputData);
1477     VLC_UNUSED(inInputTime);
1478     VLC_UNUSED(inOutputTime);
1479
1480     audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1481     struct aout_sys_t * p_sys = p_aout->sys;
1482
1483     int bytesRequested = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1484     char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1485
1486     vlc_mutex_lock(&p_sys->lock);
1487     /* Pull audio from buffer */
1488     int32_t availableBytes;
1489     char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1490
1491     /* check if we have enough data */
1492     if (!availableBytes) {
1493         /* return an empty buffer so silence is played until we have data */
1494         memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1495     } else {
1496         int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1497
1498         memcpy(targetBuffer, buffer, bytesToCopy);
1499         TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1500         outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize = bytesToCopy;
1501     }
1502
1503     vlc_cond_signal(&p_sys->cond);
1504     vlc_mutex_unlock(&p_sys->lock);
1505
1506     return noErr;
1507 }
1508
1509 #pragma mark -
1510 #pragma mark Stream / Hardware Listeners
1511
1512 /*
1513  * Callback when device list changed
1514  */
1515 static OSStatus DevicesListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1516 {
1517     VLC_UNUSED(inObjectID);
1518     VLC_UNUSED(inNumberAddresses);
1519     VLC_UNUSED(inAddresses);
1520
1521     audio_output_t *p_aout = (audio_output_t *)inClientData;
1522     if (!p_aout)
1523         return -1;
1524     aout_sys_t *p_sys = p_aout->sys;
1525
1526     msg_Dbg(p_aout, "audio device configuration changed, resetting cache");
1527     RebuildDeviceList(p_aout);
1528
1529     vlc_mutex_lock(&p_sys->var_lock);
1530     if(!CFArrayContainsValue(p_sys->device_list, CFRangeMake(0, CFArrayGetCount(p_sys->device_list)),CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &p_sys->i_selected_dev)))
1531         aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1532     vlc_mutex_unlock(&p_sys->var_lock);
1533
1534     return noErr;
1535 }
1536
1537 /*
1538  * Callback when current device is not alive anymore
1539  */
1540 static OSStatus DeviceAliveListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1541 {
1542     VLC_UNUSED(inObjectID);
1543     VLC_UNUSED(inNumberAddresses);
1544     VLC_UNUSED(inAddresses);
1545
1546     audio_output_t *p_aout = (audio_output_t *)inClientData;
1547     if (!p_aout)
1548         return -1;
1549
1550     msg_Warn(p_aout, "audio device died, resetting aout");
1551     aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1552
1553     return noErr;
1554 }
1555
1556 /*
1557  * Callback when default audio device changed
1558  */
1559 static OSStatus DefaultDeviceChangedListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1560 {
1561     VLC_UNUSED(inObjectID);
1562     VLC_UNUSED(inNumberAddresses);
1563     VLC_UNUSED(inAddresses);
1564
1565     audio_output_t *p_aout = (audio_output_t *)inClientData;
1566     if (!p_aout)
1567         return -1;
1568
1569     if (!p_aout->sys->b_selected_dev_is_default)
1570         return noErr;
1571
1572     AudioObjectID defaultDeviceID = 0;
1573     UInt32 propertySize = sizeof(AudioObjectID);
1574     AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1575     propertySize = sizeof(AudioObjectID);
1576     OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1577     if (err != noErr) {
1578         msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
1579         return -1;
1580     }
1581
1582     msg_Dbg(p_aout, "default device changed to %i", defaultDeviceID);
1583
1584     /* Default device is changed by the os to allow other apps to play sound while in digital
1585        mode. But this should not affect ourself. */
1586     if (p_aout->sys->b_digital) {
1587         msg_Dbg(p_aout, "ignore, as digital mode is active");
1588         return noErr;
1589     }
1590
1591     /* Also ignore events which announce the same device id */
1592     if(defaultDeviceID == p_aout->sys->i_selected_dev)
1593         return noErr;
1594
1595     msg_Dbg(p_aout, "default device actually changed, resetting aout");
1596     aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1597
1598     return noErr;
1599 }
1600
1601 /*
1602  * Callback when physical formats for device change
1603  */
1604 static OSStatus StreamsChangedListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1605 {
1606     OSStatus                    err = noErr;
1607     UInt32                      i_param_size = 0;
1608     AudioStreamID               *p_streams = NULL;
1609     int                         i_streams = 0;
1610
1611     VLC_UNUSED(inNumberAddresses);
1612     VLC_UNUSED(inAddresses);
1613
1614     audio_output_t *p_aout = (audio_output_t *)inClientData;
1615     if (!p_aout)
1616         return -1;
1617
1618     aout_sys_t *p_sys = p_aout->sys;
1619     if(unlikely(p_sys->b_ignore_streams_changed_callback == true))
1620         return 0;
1621
1622     msg_Dbg(p_aout, "available physical formats for audio device changed");
1623     RebuildDeviceList(p_aout);
1624
1625     /*
1626      * check if changed stream id belongs to current device
1627      */
1628     vlc_mutex_lock(&p_sys->var_lock);
1629     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1630     err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
1631     if (err != noErr) {
1632         msg_Err(p_aout, "could not get number of streams [%4.4s]", (char *)&err);
1633         return VLC_EGENERIC;
1634     }
1635
1636     i_streams = i_param_size / sizeof(AudioStreamID);
1637     p_streams = (AudioStreamID *)malloc(i_param_size);
1638     if (p_streams == NULL)
1639         return VLC_ENOMEM;
1640
1641     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1642     if (err != noErr) {
1643         msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1644         return VLC_EGENERIC;
1645     }
1646     vlc_mutex_unlock(&p_sys->var_lock);
1647
1648     for (int i = 0; i < i_streams; i++) {
1649         if (p_streams[i] == inObjectID) {
1650             msg_Dbg(p_aout, "Restart aout as this affects current device");
1651             aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1652             break;
1653         }
1654     }
1655     free(p_streams);
1656
1657     return noErr;
1658 }
1659
1660 /*
1661  * StreamListener: check whether the device's physical format change is complete
1662  */
1663 static OSStatus StreamListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1664 {
1665     OSStatus err = noErr;
1666     struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1667
1668     VLC_UNUSED(inObjectID);
1669
1670     for (unsigned int i = 0; i < inNumberAddresses; i++) {
1671         if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1672             vlc_mutex_lock(&w->lock);
1673             vlc_cond_signal(&w->cond);
1674             vlc_mutex_unlock(&w->lock);
1675             break;
1676         }
1677     }
1678     return err;
1679 }
1680
1681 #pragma mark -
1682 #pragma mark helpers
1683
1684 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register)
1685 {
1686     OSStatus                    err = noErr;
1687     UInt32                      i_param_size = 0;
1688     AudioStreamID               *p_streams = NULL;
1689     int                         i_streams = 0;
1690
1691     /* Retrieve all the output streams */
1692     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1693     err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1694     if (err != noErr) {
1695         msg_Err(p_aout, "could not get number of streams for device id %i [%4.4s]", i_dev_id, (char *)&err);
1696         return VLC_EGENERIC;
1697     }
1698
1699     i_streams = i_param_size / sizeof(AudioStreamID);
1700     p_streams = (AudioStreamID *)malloc(i_param_size);
1701     if (p_streams == NULL)
1702         return VLC_ENOMEM;
1703
1704     err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1705     if (err != noErr) {
1706         msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1707         return VLC_EGENERIC;
1708     }
1709
1710     for (int i = 0; i < i_streams; i++) {
1711         /* get notified when physical formats change */
1712         AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1713
1714         if (b_register) {
1715             err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1716             if (err != noErr) {
1717                 // nope just means that we already have a callback
1718                 if (err == kAudioHardwareIllegalOperationError) {
1719                     msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i, callback already set? [%4.4s]", p_streams[i],
1720                              (char *)&err);
1721                 } else {
1722                     msg_Err(p_aout, "could not set audio stream formats property callback on stream id %i [%4.4s]", p_streams[i],
1723                             (char *)&err);
1724                 }
1725             }
1726
1727         } else {  /* unregister callback */
1728             err = AudioObjectRemovePropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1729             if (err != noErr)
1730                 msg_Err(p_aout, "failed to remove audio device property streams callback [%4.4s]", (char *)&err);
1731         }
1732
1733     }
1734
1735     free(p_streams);
1736     return VLC_SUCCESS;
1737 }
1738
1739 /*
1740  * AudioDeviceHasOutput: Checks if the device is actually an output device
1741  */
1742 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1743 {
1744     UInt32 dataSize = 0;
1745     OSStatus status;
1746
1747     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1748     status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1749
1750     if (dataSize == 0 || status != noErr)
1751         return FALSE;
1752
1753     return TRUE;
1754 }
1755
1756 /*
1757  * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1758  */
1759 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1760 {
1761     OSStatus                    err = noErr;
1762     UInt32                      i_param_size = 0;
1763     AudioStreamID               *p_streams = NULL;
1764     int                         i_streams = 0;
1765     bool                        b_return = false;
1766
1767     /* Retrieve all the output streams */
1768     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1769     err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1770     if (err != noErr) {
1771         msg_Err(p_aout, "could not get number of streams [%4.4s] (%i)", (char *)&err, (int32_t)err);
1772         return false;
1773     }
1774
1775     i_streams = i_param_size / sizeof(AudioStreamID);
1776     p_streams = (AudioStreamID *)malloc(i_param_size);
1777     if (p_streams == NULL)
1778         return VLC_ENOMEM;
1779
1780     err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1781     if (err != noErr) {
1782         msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1783         return false;
1784     }
1785
1786     for (int i = 0; i < i_streams; i++) {
1787         if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1788             b_return = true;
1789     }
1790
1791     free(p_streams);
1792     return b_return;
1793 }
1794
1795 /*
1796  * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1797  */
1798 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1799 {
1800     OSStatus                    err = noErr;
1801     UInt32                      i_param_size = 0;
1802     AudioStreamRangedDescription *p_format_list = NULL;
1803     int                         i_formats = 0;
1804     bool                        b_return = false;
1805
1806     /* Retrieve all the stream formats supported by each output stream */
1807     AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1808     err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1809     if (err != noErr) {
1810         msg_Err(p_aout, "could not get number of streamformats [%4.4s] (%i)", (char *)&err, (int32_t)err);
1811         return false;
1812     }
1813
1814     i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1815     msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1816
1817     p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1818     if (p_format_list == NULL)
1819         return false;
1820
1821     err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1822     if (err != noErr) {
1823         msg_Err(p_aout, "could not get the list of streamformats [%4.4s]", (char *)&err);
1824         free(p_format_list);
1825         p_format_list = NULL;
1826         return false;
1827     }
1828
1829     for (int i = 0; i < i_formats; i++) {
1830 #ifndef NDEBUG
1831         msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1832 #endif
1833
1834         if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1835             p_format_list[i].mFormat.mFormatID == 'iac3' ||
1836             p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1837             p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1838             b_return = true;
1839     }
1840
1841     free(p_format_list);
1842     return b_return;
1843 }
1844
1845 /*
1846  * AudioStreamChangeFormat: switch stream format based on the provided description
1847  */
1848 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1849 {
1850     OSStatus            err = noErr;
1851     UInt32              i_param_size = 0;
1852
1853     AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1854
1855     struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1856
1857     msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1858
1859     /* Condition because SetProperty is asynchronious */
1860     vlc_cond_init(&w.cond);
1861     vlc_mutex_init(&w.lock);
1862     vlc_mutex_lock(&w.lock);
1863
1864     /* Install the callback */
1865     err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1866     if (err != noErr) {
1867         msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed [%4.4s]", (char *)&err);
1868         return false;
1869     }
1870
1871     /* change the format */
1872     err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1873                                      &change_format);
1874     if (err != noErr) {
1875         msg_Err(p_aout, "could not set the stream format [%4.4s]", (char *)&err);
1876         return false;
1877     }
1878
1879     /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1880      * it is also not atomic in its behaviour.
1881      * Therefore we check 5 times before we really give up.
1882      * FIXME: failing isn't actually implemented yet. */
1883     for (int i = 0; i < 5; i++) {
1884         AudioStreamBasicDescription actual_format;
1885         mtime_t timeout = mdate() + 500000;
1886
1887         if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1888             msg_Dbg(p_aout, "reached timeout");
1889
1890         i_param_size = sizeof(AudioStreamBasicDescription);
1891         err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1892
1893         msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1894         if (actual_format.mSampleRate == change_format.mSampleRate &&
1895             actual_format.mFormatID == change_format.mFormatID &&
1896             actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1897             /* The right format is now active */
1898             break;
1899         }
1900         /* We need to check again */
1901     }
1902
1903     /* Removing the property listener */
1904     err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1905     if (err != noErr) {
1906         msg_Err(p_aout, "AudioStreamRemovePropertyListener failed [%4.4s]", (char *)&err);
1907         return false;
1908     }
1909
1910     /* Destroy the lock and condition */
1911     vlc_mutex_unlock(&w.lock);
1912     vlc_mutex_destroy(&w.lock);
1913     vlc_cond_destroy(&w.cond);
1914
1915     return true;
1916 }