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