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