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