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