]> git.sesse.net Git - vlc/blob - modules/audio_output/auhal.c
d45770a2141038e0c50e8a421622c024e35d1e43
[vlc] / modules / audio_output / auhal.c
1 /*****************************************************************************
2  * auhal.c: AUHAL and Coreaudio output plugin
3  *****************************************************************************
4  * Copyright (C) 2005 - 2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8  *          Felix Paul Kühne <fkuehne at videolan dot org>
9  *
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 AOUT_VAR_SPDIF_FLAG 0xf00000
57
58 #define kBufferLength 2048 * 8 * 8 * 4
59
60 #define AOUT_VOLUME_DEFAULT             256
61 #define AOUT_VOLUME_MAX                 512
62
63
64 /*****************************************************************************
65  * aout_sys_t: private audio output method descriptor
66  *****************************************************************************
67  * This structure is part of the audio output thread descriptor.
68  * It describes the CoreAudio specific properties of an output thread.
69  *****************************************************************************/
70 struct aout_sys_t
71 {
72     AudioObjectID               i_default_dev;      /* DeviceID of defaultOutputDevice */
73     AudioObjectID               i_selected_dev;     /* DeviceID of the selected device */
74     bool                        b_selected_dev_is_digital;
75     AudioDeviceIOProcID         i_procID;           /* DeviceID of current device */
76     bool                        b_digital;          /* Are we running in digital mode? */
77     mtime_t                     clock_diff;         /* Difference between VLC clock and Device clock */
78
79     uint8_t                     chans_to_reorder;   /* do we need channel reordering */
80     uint8_t                     chan_table[AOUT_CHAN_MAX];
81
82     UInt32                      i_numberOfChannels;
83     TPCircularBuffer            circular_buffer;    /* circular buffer to swap the audio data */
84
85     /* AUHAL specific */
86     AudioComponent              au_component;       /* The AudioComponent we use */
87     AudioUnit                   au_unit;            /* The AudioUnit we use */
88
89     /* CoreAudio SPDIF mode specific */
90     pid_t                       i_hog_pid;          /* The keep the pid of our hog status */
91     AudioStreamID               i_stream_id;        /* The StreamID that has a cac3 streamformat */
92     int                         i_stream_index;     /* The index of i_stream_id in an AudioBufferList */
93     AudioStreamBasicDescription stream_format;      /* The format we changed the stream to */
94     AudioStreamBasicDescription sfmt_revert;        /* The original format of the stream */
95     bool                        b_revert;           /* Whether we need to revert the stream format */
96     bool                        b_changed_mixing;   /* Whether we need to set the mixing mode back */
97     bool                        b_got_first_sample; /* did the aout core provide something to render? */
98
99     int                         i_rate;             /* media sample rate */
100     mtime_t                     i_played_length;    /* how much did we play already */
101     mtime_t                     i_last_sample_time; /* last sample time played by the AudioUnit */
102
103     struct audio_device_t       *devices;
104
105     vlc_mutex_t                 lock;
106 };
107
108 struct audio_device_t
109 {
110     struct audio_device_t *next;
111     UInt32 deviceid;
112     char *name;
113 };
114
115 /*****************************************************************************
116  * Local prototypes.
117  *****************************************************************************/
118 static int      Open                    (vlc_object_t *);
119 static int      OpenAnalog              (audio_output_t *, audio_sample_format_t *);
120 static int      OpenSPDIF               (audio_output_t *, audio_sample_format_t *);
121 static void     Close                   (vlc_object_t *);
122
123 static void     Play                    (audio_output_t *, block_t *);
124 static void     Flush                   (audio_output_t *, bool);
125 static void     Pause                   (audio_output_t *, bool, mtime_t);
126 static int      TimeGet                 (audio_output_t *, mtime_t *);
127
128 static int      DeviceList              (audio_output_t *p_aout, char ***namesp, char ***descsp);
129 static void     RebuildDeviceList       (audio_output_t *);
130 static int      SwitchAudioDevice       (audio_output_t *p_aout, const char *name);
131
132 static int      AudioDeviceHasOutput    (AudioDeviceID);
133 static int      AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
134 static int      AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
135 static int      AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
136
137 static OSStatus RenderCallbackAnalog    (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *, UInt32 , UInt32, AudioBufferList *);
138
139 static OSStatus RenderCallbackSPDIF     (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
140                                           AudioBufferList *, const AudioTimeStamp *, void *);
141 static OSStatus HardwareListener        (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
142 static OSStatus StreamListener          (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
143
144 static int      VolumeSet               (audio_output_t *, float);
145 static int      MuteSet                 (audio_output_t *, bool);
146
147
148 /*****************************************************************************
149  * Module descriptor
150  *****************************************************************************/
151 #define VOLUME_TEXT N_("Audio volume")
152 #define VOLUME_LONGTEXT VOLUME_TEXT
153
154 vlc_module_begin ()
155     set_shortname("auhal")
156     set_description(N_("HAL AudioUnit output"))
157     set_capability("audio output", 101)
158     set_category(CAT_AUDIO)
159     set_subcategory(SUBCAT_AUDIO_AOUT)
160     set_callbacks(Open, Close)
161     add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
162                 VOLUME_TEXT, VOLUME_LONGTEXT, true)
163     change_integer_range(0, AOUT_VOLUME_MAX)
164     add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
165 vlc_module_end ()
166
167 /*****************************************************************************
168  * Open: open macosx audio output
169  *****************************************************************************/
170 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
171 {
172     OSStatus                err = noErr;
173     UInt32                  i_param_size = 0;
174     struct aout_sys_t       *p_sys = NULL;
175
176     /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
177      * property size */
178     int                     b_alive = false;
179
180     p_sys = p_aout->sys;
181     p_sys->b_digital = false;
182     p_sys->au_component = NULL;
183     p_sys->au_unit = NULL;
184     p_sys->clock_diff = (mtime_t) 0;
185     p_sys->i_hog_pid = -1;
186     p_sys->i_stream_id = 0;
187     p_sys->i_stream_index = -1;
188     p_sys->b_revert = false;
189     p_sys->b_changed_mixing = false;
190
191     aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
192
193     if (p_sys->b_selected_dev_is_digital)
194         msg_Dbg(p_aout, "audio device supports digital output");
195
196     msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
197
198     /* Check if the desired device is alive and usable */
199     i_param_size = sizeof(b_alive);
200     AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
201                                               kAudioObjectPropertyScopeGlobal,
202                                               kAudioObjectPropertyElementMaster };
203     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
204
205     if (err != noErr) {
206         /* Be tolerant, only give a warning here */
207         msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
208                            (unsigned int)p_sys->i_selected_dev, (char *)&err);
209         b_alive = false;
210     }
211
212     if (!b_alive) {
213         msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
214         p_sys->i_selected_dev = p_sys->i_default_dev;
215     }
216
217     /* add a callback to see if the device dies later on */
218     err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
219     if (err != noErr) {
220         /* Be tolerant, only give a warning here */
221         msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
222                  (unsigned int)p_sys->i_selected_dev, (char *)&err);
223     }
224
225     AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
226                                   kAudioDevicePropertyScopeOutput,
227                                   kAudioObjectPropertyElementMaster };
228     i_param_size = sizeof(p_sys->i_hog_pid);
229     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
230     if (err != noErr) {
231         /* This is not a fatal error. Some drivers simply don't support this property */
232         msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
233                  (char *)&err);
234         p_sys->i_hog_pid = -1;
235     }
236
237     if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
238         msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
239         dialog_Fatal(p_aout, _("Audio output failed"), "%s",
240                         _("The selected audio output device is exclusively in "
241                           "use by another program."));
242         goto error;
243     }
244
245     bool b_success = false;
246
247     /* Check for Digital mode or Analog output mode */
248     if (AOUT_FMT_SPDIF (fmt) && p_sys->b_selected_dev_is_digital) {
249         if (OpenSPDIF (p_aout, fmt)) {
250             msg_Dbg(p_aout, "digital output successfully opened");
251             b_success = true;
252         }
253     } else {
254         if (OpenAnalog(p_aout, fmt)) {
255             msg_Dbg(p_aout, "analog output successfully opened");
256             b_success = true;
257         }
258     }
259
260     if (b_success) {
261         p_aout->play = Play;
262         p_aout->flush = Flush;
263         p_aout->time_get = TimeGet;
264         p_aout->pause = Pause;
265         return VLC_SUCCESS;
266     }
267
268 error:
269     /* If we reach this, this aout has failed */
270     msg_Err(p_aout, "opening the auhal output failed");
271     return VLC_EGENERIC;
272 }
273
274 /*****************************************************************************
275  * Open: open and setup a HAL AudioUnit to do analog (multichannel) audio output
276  *****************************************************************************/
277 static int OpenAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
278 {
279     struct aout_sys_t           *p_sys = p_aout->sys;
280     OSStatus                    err = noErr;
281     UInt32                      i_param_size = 0;
282     int                         i_original;
283     AudioComponentDescription   desc;
284     AudioStreamBasicDescription DeviceFormat;
285     AudioChannelLayout          *layout;
286     AudioChannelLayout          new_layout;
287     AURenderCallbackStruct      input;
288     p_aout->sys->chans_to_reorder = 0;
289
290     /* Lets go find our Component */
291     desc.componentType = kAudioUnitType_Output;
292     desc.componentSubType = kAudioUnitSubType_HALOutput;
293     desc.componentManufacturer = kAudioUnitManufacturer_Apple;
294     desc.componentFlags = 0;
295     desc.componentFlagsMask = 0;
296
297     p_sys->au_component = AudioComponentFindNext(NULL, &desc);
298     if (p_sys->au_component == NULL) {
299         msg_Warn(p_aout, "we cannot find our HAL component");
300         return false;
301     }
302
303     err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
304     if (err != noErr) {
305         msg_Warn(p_aout, "we cannot open our HAL component");
306         return false;
307     }
308
309     /* Set the device we will use for this output unit */
310     err = AudioUnitSetProperty(p_sys->au_unit,
311                          kAudioOutputUnitProperty_CurrentDevice,
312                          kAudioUnitScope_Global,
313                          0,
314                          &p_sys->i_selected_dev,
315                          sizeof(AudioObjectID));
316
317     if (err != noErr) {
318         msg_Warn(p_aout, "we cannot select the audio device");
319         return false;
320     }
321
322     /* Get the current format */
323     i_param_size = sizeof(AudioStreamBasicDescription);
324
325     err = AudioUnitGetProperty(p_sys->au_unit,
326                                    kAudioUnitProperty_StreamFormat,
327                                    kAudioUnitScope_Output,
328                                    0,
329                                    &DeviceFormat,
330                                    &i_param_size);
331
332     if (err != noErr)
333         return false;
334     else
335         msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
336
337     /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
338     err = AudioUnitGetPropertyInfo(p_sys->au_unit,
339                                    kAudioDevicePropertyPreferredChannelLayout,
340                                    kAudioUnitScope_Output,
341                                    0,
342                                    &i_param_size,
343                                    NULL);
344
345     if (err == noErr) {
346         layout = (AudioChannelLayout *)malloc(i_param_size);
347
348         verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
349                                        kAudioDevicePropertyPreferredChannelLayout,
350                                        kAudioUnitScope_Output,
351                                        0,
352                                        layout,
353                                        &i_param_size));
354
355         /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
356         if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
357             /* bitmap defined channellayout */
358             verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
359                                     sizeof(UInt32), &layout->mChannelBitmap,
360                                     &i_param_size,
361                                     layout));
362         } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
363         {
364             /* layouttags defined channellayout */
365             verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
366                                     sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
367                                     &i_param_size,
368                                     layout));
369         }
370
371         msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
372
373         if (layout->mNumberChannelDescriptions == 0) {
374             msg_Err(p_aout, "insufficient number of output channels");
375             return false;
376         }
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     p_sys->i_rate = fmt->i_rate;
521
522     /* We use float 32 since this is VLC's endorsed format */
523     fmt->i_format = VLC_CODEC_FL32;
524     DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
525     DeviceFormat.mBitsPerChannel = 32;
526     DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
527
528     /* Calculate framesizes and stuff */
529     DeviceFormat.mFramesPerPacket = 1;
530     DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
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     /* setup circular buffer */
584     TPCircularBufferInit(&p_sys->circular_buffer, kBufferLength);
585
586     p_sys->b_got_first_sample = false;
587     p_sys->i_played_length = 0;
588     p_sys->i_last_sample_time = 0;
589
590     /* Set volume for output unit */
591     float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
592     volume = volume * volume * volume;
593     verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
594                                     kHALOutputParam_Volume,
595                                     kAudioUnitScope_Global,
596                                     0,
597                                     volume,
598                                     0));
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     p_sys->i_rate = fmt->i_rate;
779     aout_FormatPrepare(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         return false;
789     }
790
791     /* Check for the difference between the Device clock and mdate */
792     p_sys->clock_diff = - (mtime_t)
793         AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
794     p_sys->clock_diff += mdate();
795
796     /* Start device */
797     err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
798     if (err != noErr) {
799         msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
800
801         err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
802         if (err != noErr)
803             msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
804
805         return false;
806     }
807
808     return true;
809 }
810
811
812 /*****************************************************************************
813  * Close: Close HAL AudioUnit
814  *****************************************************************************/
815 static void Stop(audio_output_t *p_aout)
816 {
817     struct aout_sys_t   *p_sys = p_aout->sys;
818     OSStatus            err = noErr;
819     UInt32              i_param_size = 0;
820
821     AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
822     err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
823     if (err != noErr)
824         msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
825
826     if (p_sys->b_digital) {
827         AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
828         err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
829         if (err != noErr)
830             msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
831     }
832
833     if (p_sys->au_unit) {
834         verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
835         verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
836         verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
837     }
838
839     if (p_sys->b_digital) {
840         /* Stop device */
841         err = AudioDeviceStop(p_sys->i_selected_dev,
842                                p_sys->i_procID);
843         if (err != noErr)
844             msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
845
846         /* Remove IOProc callback */
847         err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
848                                           p_sys->i_procID);
849         if (err != noErr)
850             msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
851
852         if (p_sys->b_revert)
853             AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
854
855         if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
856             int b_mix;
857             Boolean b_writeable = false;
858             /* Revert mixable to true if we are allowed to */
859             AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
860             err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
861             err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
862
863             if (err == noErr && b_writeable) {
864                 msg_Dbg(p_aout, "mixable is: %d", b_mix);
865                 b_mix = 1;
866                 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
867             }
868
869             if (err != noErr)
870                 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
871         }
872     }
873
874     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
875     err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
876
877     if (err != noErr)
878         msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
879
880     if (p_sys->i_hog_pid == getpid()) {
881         p_sys->i_hog_pid = -1;
882         i_param_size = sizeof(p_sys->i_hog_pid);
883         AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
884             kAudioDevicePropertyScopeOutput,
885             kAudioObjectPropertyElementMaster };
886         err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
887         if (err != noErr)
888             msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
889     }
890
891     p_sys->i_played_length = 0;
892     p_sys->i_last_sample_time = 0;
893
894     /* clean-up circular buffer */
895     TPCircularBufferCleanup(&p_sys->circular_buffer);
896 }
897
898 static int DeviceList(audio_output_t *p_aout, char ***namesp, char ***descsp)
899 {
900     struct aout_sys_t   *p_sys = p_aout->sys;
901     char **names, **descs;
902     unsigned n = 0;
903
904     for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next)
905         n++;
906
907     *namesp = names = xmalloc(sizeof(*names) * n);
908     *descsp = descs = xmalloc(sizeof(*descs) * n);
909
910     char deviceid[100];
911     for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next) {
912         sprintf(deviceid, "%i", device->deviceid);
913         *(names++) = strdup(deviceid);
914         *(descs++) = strdup(device->name);
915     }
916
917     return n;
918 }
919
920 static void add_device_to_list(audio_output_t * p_aout, UInt32 i_id, char *name)
921 {
922     struct aout_sys_t *p_sys = p_aout->sys;
923
924     struct audio_device_t *device = malloc(sizeof(*device));
925     if (unlikely(device == NULL))
926         return;
927
928     device->next = p_sys->devices;
929     device->deviceid = i_id;
930     device->name = strdup(name);
931
932     p_sys->devices = device;
933 }
934
935 static void RebuildDeviceList(audio_output_t * p_aout)
936 {
937     OSStatus            err = noErr;
938     UInt32              propertySize = 0;
939     AudioObjectID       defaultDeviceID = 0;
940     AudioObjectID       *deviceIDs;
941     UInt32              numberOfDevices;
942
943     struct aout_sys_t   *p_sys = p_aout->sys;
944
945     if (p_sys->devices)
946         free(p_sys->devices);
947
948     /* Get number of devices */
949     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
950     err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
951     if (err != noErr) {
952         msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
953         return;
954     }
955
956     numberOfDevices = propertySize / sizeof(AudioDeviceID);
957
958     if (numberOfDevices < 1) {
959         msg_Err(p_aout, "No audio output devices were found.");
960         return;
961     }
962     msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
963
964     /* Allocate DeviceID array */
965     deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
966     if (deviceIDs == NULL)
967         return;
968
969     /* Populate DeviceID array */
970     err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
971     if (err != noErr) {
972         msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
973         return;
974     }
975
976     /* Find the ID of the default Device */
977     AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
978     propertySize = sizeof(AudioObjectID);
979     err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
980     if (err != noErr) {
981         msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
982         return;
983     }
984     p_sys->i_default_dev = defaultDeviceID;
985
986     AudioObjectPropertyAddress deviceNameAddress = { kAudioDevicePropertyDeviceName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
987
988     for (unsigned int i = 0; i < numberOfDevices; i++) {
989         char *psz_name;
990         bool b_digital = false;
991         UInt32 i_id = deviceIDs[i];
992
993         /* Retrieve the length of the device name */
994         err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
995         if (err != noErr) {
996             msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
997             continue;
998         }
999
1000         /* Retrieve the name of the device */
1001         psz_name = (char *)malloc(propertySize);
1002         err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, psz_name);
1003         if (err != noErr) {
1004             msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1005             continue;
1006         }
1007
1008         msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1009
1010         if (!AudioDeviceHasOutput(deviceIDs[i])) {
1011             msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1012             free(psz_name);
1013             continue;
1014         }
1015
1016         add_device_to_list(p_aout, i_id, psz_name);
1017
1018         if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1019             b_digital = true;
1020             msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1021             asprintf(&psz_name, _("%s (Encoded Output)"), psz_name);
1022             i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1023             add_device_to_list(p_aout, i_id, psz_name);
1024         }
1025
1026         free(psz_name);
1027     }
1028
1029     /* Attach a Listener so that we are notified of a change in the Device setup */
1030     err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
1031     if (err != noErr)
1032         msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
1033
1034     free(deviceIDs);
1035 }
1036
1037 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1038 {
1039     struct aout_sys_t *p_sys = p_aout->sys;
1040
1041     if (name)
1042         p_sys->i_selected_dev = atoi(name);
1043     else
1044         p_sys->i_selected_dev = 0;
1045
1046     bool b_supports_digital = (p_sys->i_selected_dev & AOUT_VAR_SPDIF_FLAG);
1047     if (b_supports_digital)
1048         p_sys->b_selected_dev_is_digital = true;
1049     else
1050         p_sys->b_selected_dev_is_digital = false;
1051
1052     p_sys->i_selected_dev = p_sys->i_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1053
1054     aout_DeviceReport(p_aout, name);
1055     aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1056
1057     return 0;
1058 }
1059
1060 /*****************************************************************************
1061  * AudioDeviceHasOutput: Checks if the Device actually provides any outputs at all
1062  *****************************************************************************/
1063 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1064 {
1065     UInt32 dataSize = 0;
1066     OSStatus status;
1067
1068     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1069     status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1070
1071     if (dataSize == 0 || status != noErr)
1072         return FALSE;
1073
1074     return TRUE;
1075 }
1076
1077 /*****************************************************************************
1078  * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
1079  *****************************************************************************/
1080 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1081 {
1082     OSStatus                    err = noErr;
1083     UInt32                      i_param_size = 0;
1084     AudioStreamID               *p_streams = NULL;
1085     int                         i_streams = 0;
1086     bool                        b_return = false;
1087
1088     /* Retrieve all the output streams */
1089     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1090     err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1091     if (err != noErr) {
1092         msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1093         return false;
1094     }
1095
1096     i_streams = i_param_size / sizeof(AudioStreamID);
1097     p_streams = (AudioStreamID *)malloc(i_param_size);
1098     if (p_streams == NULL)
1099         return VLC_ENOMEM;
1100
1101     err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1102     if (err != noErr) {
1103         msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1104         return false;
1105     }
1106
1107     for (int i = 0; i < i_streams; i++) {
1108         if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1109             b_return = true;
1110     }
1111
1112     free(p_streams);
1113     return b_return;
1114 }
1115
1116 /*****************************************************************************
1117  * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
1118  *****************************************************************************/
1119 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1120 {
1121     OSStatus                    err = noErr;
1122     UInt32                      i_param_size = 0;
1123     AudioStreamRangedDescription *p_format_list = NULL;
1124     int                         i_formats = 0;
1125     bool                        b_return = false;
1126
1127     /* Retrieve all the stream formats supported by each output stream */
1128     AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1129     err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1130     if (err != noErr) {
1131         msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1132         return false;
1133     }
1134
1135     i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1136     msg_Dbg(p_aout, "found %i stream formats", i_formats);
1137
1138     p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1139     if (p_format_list == NULL)
1140         return false;
1141
1142     err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1143     if (err != noErr) {
1144         msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1145         free(p_format_list);
1146         p_format_list = NULL;
1147         return false;
1148     }
1149
1150     for (int i = 0; i < i_formats; i++) {
1151 #ifndef NDEBUG
1152         msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1153 #endif
1154
1155         if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1156             p_format_list[i].mFormat.mFormatID == 'iac3' ||
1157             p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1158             p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1159             b_return = true;
1160     }
1161
1162     free(p_format_list);
1163     return b_return;
1164 }
1165
1166 /*****************************************************************************
1167  * AudioStreamChangeFormat: Change i_stream_id to change_format
1168  *****************************************************************************/
1169 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1170 {
1171     OSStatus            err = noErr;
1172     UInt32              i_param_size = 0;
1173
1174     AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1175
1176     struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1177
1178     msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1179
1180     /* Condition because SetProperty is asynchronious */
1181     vlc_cond_init(&w.cond);
1182     vlc_mutex_init(&w.lock);
1183     vlc_mutex_lock(&w.lock);
1184
1185     /* Install the callback */
1186     err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1187     if (err != noErr) {
1188         msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1189         return false;
1190     }
1191
1192     /* change the format */
1193     err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1194                                      &change_format);
1195     if (err != noErr) {
1196         msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1197         return false;
1198     }
1199
1200     /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1201      * it is also not atomic in its behaviour.
1202      * Therefore we check 5 times before we really give up.
1203      * FIXME: failing isn't actually implemented yet. */
1204     for (int i = 0; i < 5; i++) {
1205         AudioStreamBasicDescription actual_format;
1206         mtime_t timeout = mdate() + 500000;
1207
1208         if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1209             msg_Dbg(p_aout, "reached timeout");
1210
1211         i_param_size = sizeof(AudioStreamBasicDescription);
1212         err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1213
1214         msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1215         if (actual_format.mSampleRate == change_format.mSampleRate &&
1216             actual_format.mFormatID == change_format.mFormatID &&
1217             actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1218             /* The right format is now active */
1219             break;
1220         }
1221         /* We need to check again */
1222     }
1223
1224     /* Removing the property listener */
1225     err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1226     if (err != noErr) {
1227         msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1228         return false;
1229     }
1230
1231     /* Destroy the lock and condition */
1232     vlc_mutex_unlock(&w.lock);
1233     vlc_mutex_destroy(&w.lock);
1234     vlc_cond_destroy(&w.cond);
1235
1236     return true;
1237 }
1238
1239 static void Play (audio_output_t * p_aout, block_t * p_block)
1240 {
1241     struct aout_sys_t *p_sys = p_aout->sys;
1242
1243     if (p_block->i_nb_samples > 0) {
1244         if (!p_sys->b_got_first_sample) {
1245             /* Start the AU */
1246             verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1247             p_sys->b_got_first_sample = true;
1248         }
1249
1250         /* Do the channel reordering */
1251         if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1252            aout_ChannelReorder(p_block->p_buffer,
1253                                p_block->i_buffer,
1254                                p_sys->chans_to_reorder,
1255                                p_sys->chan_table,
1256                                VLC_CODEC_FL32);
1257         }
1258
1259         /* Render audio into buffer */
1260         AudioBufferList bufferList;
1261         bufferList.mNumberBuffers = 1;
1262         bufferList.mBuffers[0].mNumberChannels = p_sys->i_numberOfChannels;
1263         bufferList.mBuffers[0].mData = malloc(p_block->i_nb_samples * sizeof(Float32) * p_sys->i_numberOfChannels);
1264         bufferList.mBuffers[0].mDataByteSize = p_block->i_nb_samples * sizeof(Float32) * p_sys->i_numberOfChannels;
1265
1266         memcpy(bufferList.mBuffers[0].mData, p_block->p_buffer, p_block->i_buffer);
1267
1268         /* keep track of the played data */
1269         p_aout->sys->i_played_length += p_block->i_length;
1270
1271         /* move data to buffer */
1272         TPCircularBufferProduceBytes(&p_sys->circular_buffer, bufferList.mBuffers[0].mData, bufferList.mBuffers[0].mDataByteSize);
1273     }
1274
1275     block_Release(p_block);
1276 }
1277
1278 static void Pause (audio_output_t *p_aout, bool pause, mtime_t date)
1279 {
1280     struct aout_sys_t * p_sys = p_aout->sys;
1281     VLC_UNUSED(date);
1282
1283     if (p_aout->sys->b_digital) {
1284         if (pause)
1285             AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1286         else
1287             AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1288     } else {
1289         if (pause)
1290             AudioOutputUnitStop(p_sys->au_unit);
1291         else
1292             AudioOutputUnitStart(p_sys->au_unit);
1293     }
1294 }
1295
1296 static void Flush(audio_output_t *p_aout, bool wait)
1297 {
1298     struct aout_sys_t * p_sys = p_aout->sys;
1299     VLC_UNUSED(wait);
1300
1301     p_sys->b_got_first_sample = false;
1302
1303     /* flush circular buffer */
1304     AudioOutputUnitStop(p_aout->sys->au_unit);
1305     TPCircularBufferClear(&p_aout->sys->circular_buffer);
1306
1307     p_sys->i_played_length = 0;
1308     p_sys->i_last_sample_time = 0;
1309 }
1310
1311 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1312 {
1313     struct aout_sys_t * p_sys = p_aout->sys;
1314
1315     vlc_mutex_lock(&p_sys->lock);
1316     mtime_t i_pos = p_sys->i_last_sample_time * CLOCK_FREQ / p_sys->i_rate;
1317     vlc_mutex_unlock(&p_sys->lock);
1318
1319     if (i_pos > 0) {
1320         *delay = p_aout->sys->i_played_length - i_pos;
1321         return 0;
1322     }
1323     else
1324         return -1;
1325 }
1326
1327 /*****************************************************************************
1328  * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1329  * us to provide some more audio data.
1330  * Don't print anything during normal playback, calling blocking function from
1331  * this callback is not allowed.
1332  *****************************************************************************/
1333 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1334                                     AudioUnitRenderActionFlags *ioActionFlags,
1335                                     const AudioTimeStamp *inTimeStamp,
1336                                     UInt32 inBusNumber,
1337                                     UInt32 inNumberFrames,
1338                                     AudioBufferList *ioData) {
1339     VLC_UNUSED(ioActionFlags);
1340     VLC_UNUSED(inTimeStamp);
1341     VLC_UNUSED(inBusNumber);
1342
1343     audio_output_t * p_aout = (audio_output_t *)p_obj;
1344     struct aout_sys_t * p_sys = p_aout->sys;
1345
1346     int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1347     Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1348
1349     /* Pull audio from buffer */
1350     int32_t availableBytes;
1351     Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1352
1353     /* check if we have enough data */
1354     if (!availableBytes) {
1355         /* return an empty buffer so silence is played until we have data */
1356         for (UInt32 j = 0; j < inNumberFrames; j++)
1357             targetBuffer[j] = 0.;
1358     } else {
1359         memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1360         TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1361         VLC_UNUSED(inNumberFrames);
1362         vlc_mutex_lock(&p_sys->lock);
1363         p_sys->i_last_sample_time = inTimeStamp->mSampleTime;
1364         vlc_mutex_unlock(&p_sys->lock);
1365     }
1366
1367     return noErr;
1368 }
1369
1370 /*****************************************************************************
1371  * RenderCallbackSPDIF: callback for SPDIF audio output
1372  *****************************************************************************/
1373 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1374                                     const AudioTimeStamp * inNow,
1375                                     const void * inInputData,
1376                                     const AudioTimeStamp * inInputTime,
1377                                     AudioBufferList * outOutputData,
1378                                     const AudioTimeStamp * inOutputTime,
1379                                     void * threadGlobals)
1380 {
1381     VLC_UNUSED(inNow);
1382     VLC_UNUSED(inDevice);
1383     VLC_UNUSED(inInputData);
1384     VLC_UNUSED(inInputTime);
1385
1386     audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1387     struct aout_sys_t * p_sys = p_aout->sys;
1388
1389     int bytesToCopy = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1390     Float32 *targetBuffer = (Float32*)outOutputData->mBuffers[p_sys->i_stream_index].mData;
1391
1392     /* Pull audio from buffer */
1393     int32_t availableBytes;
1394     Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1395
1396     /* check if we have enough data */
1397     if (!availableBytes) {
1398         /* return an empty buffer so silence is played until we have data */
1399         memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1400     } else {
1401         memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1402         TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1403         vlc_mutex_lock(&p_sys->lock);
1404         p_sys->i_last_sample_time = inOutputTime->mSampleTime;
1405         vlc_mutex_unlock(&p_sys->lock);
1406     }
1407
1408     return noErr;
1409 }
1410
1411 /*****************************************************************************
1412  * HardwareListener: Warns us of changes in the list of registered devices
1413  *****************************************************************************/
1414 static OSStatus HardwareListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1415 {
1416     OSStatus err = noErr;
1417     audio_output_t     *p_aout = (audio_output_t *)inClientData;
1418     VLC_UNUSED(inObjectID);
1419     VLC_UNUSED(inNumberAddresses);
1420     VLC_UNUSED(inAddresses);
1421
1422     if (!p_aout)
1423         return -1;
1424
1425 #ifndef NDEBUG
1426     for (unsigned int i = 0; i < inNumberAddresses; i++) {
1427         switch (inAddresses[i].mSelector) {
1428             case kAudioHardwarePropertyDevices:
1429                 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1430                 break;
1431
1432             case kAudioDevicePropertyDeviceIsAlive:
1433                 msg_Warn(p_aout, "audio device died, resetting aout");
1434                 break;
1435
1436             case kAudioStreamPropertyAvailablePhysicalFormats:
1437                 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1438                 break;
1439
1440             default:
1441                 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1442                 break;
1443         }
1444     }
1445 #endif
1446
1447     RebuildDeviceList(p_aout);
1448
1449     return err;
1450 }
1451
1452 /*****************************************************************************
1453  * StreamListener
1454  *****************************************************************************/
1455 static OSStatus StreamListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1456 {
1457     OSStatus err = noErr;
1458     struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1459
1460     VLC_UNUSED(inObjectID);
1461
1462     for (unsigned int i = 0; i < inNumberAddresses; i++) {
1463         if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1464             vlc_mutex_lock(&w->lock);
1465             vlc_cond_signal(&w->cond);
1466             vlc_mutex_unlock(&w->lock);
1467             break;
1468         }
1469     }
1470     return err;
1471 }
1472
1473 /*****************************************************************************
1474  * VolumeSet: Implements volume_set(). Update the CoreAudio AU volume immediately.
1475  *****************************************************************************/
1476 static int VolumeSet(audio_output_t * p_aout, float volume)
1477 {
1478     struct aout_sys_t *p_sys = p_aout->sys;
1479     OSStatus ostatus;
1480
1481     aout_VolumeReport(p_aout, volume);
1482
1483     /* Set volume for output unit */
1484     ostatus = AudioUnitSetParameter(p_sys->au_unit,
1485                                     kHALOutputParam_Volume,
1486                                     kAudioUnitScope_Global,
1487                                     0,
1488                                     volume * volume * volume,
1489                                     0);
1490
1491     if (var_InheritBool(p_aout, "volume-save"))
1492         config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1493
1494     return ostatus;
1495 }
1496
1497 static int MuteSet(audio_output_t * p_aout, bool mute)
1498 {
1499     struct   aout_sys_t *p_sys = p_aout->sys;
1500     OSStatus ostatus;
1501
1502     aout_MuteReport(p_aout, mute);
1503
1504     float volume = .0;
1505
1506     if (!mute)
1507         volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1508
1509     ostatus = AudioUnitSetParameter(p_sys->au_unit,
1510                                     kHALOutputParam_Volume,
1511                                     kAudioUnitScope_Global,
1512                                     0,
1513                                     volume * volume * volume,
1514                                     0);
1515
1516     return ostatus;
1517 }
1518
1519 static int Open(vlc_object_t *obj)
1520 {
1521     audio_output_t *aout = (audio_output_t *)obj;
1522     aout_sys_t *sys = malloc(sizeof (*sys));
1523
1524     if (unlikely(sys == NULL))
1525         return VLC_ENOMEM;
1526
1527     vlc_mutex_init(&sys->lock);
1528
1529     aout->sys = sys;
1530     aout->start = Start;
1531     aout->stop = Stop;
1532     aout->volume_set = VolumeSet;
1533     aout->mute_set = MuteSet;
1534     aout->device_enum = DeviceList;
1535     aout->sys->devices = NULL;
1536     aout->device_select = SwitchAudioDevice;
1537
1538     RebuildDeviceList(aout);
1539
1540     /* remember the volume */
1541     aout_VolumeReport(aout, var_InheritInteger(aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
1542     MuteSet(aout, var_InheritBool(aout, "mute"));
1543
1544     return VLC_SUCCESS;
1545 }
1546
1547 static void Close(vlc_object_t *obj)
1548 {
1549     audio_output_t *aout = (audio_output_t *)obj;
1550     aout_sys_t *sys = aout->sys;
1551
1552     vlc_mutex_destroy(&sys->lock);
1553
1554     free(sys);
1555 }