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