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