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