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