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