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