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