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