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