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