]> git.sesse.net Git - vlc/blob - modules/audio_output/auhal.c
aout: add distinct start/stop callbacks (refs #4787, refs #7601)
[vlc] / modules / audio_output / auhal.c
1 /*****************************************************************************
2  * auhal.c: AUHAL and Coreaudio output plugin
3  *****************************************************************************
4  * Copyright (C) 2005, 2012 the VideoLAN team
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
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 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 General Public License for more details.
19  *
20  * You should have received a copy of the GNU 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 #import <vlc_aout_intf.h>
38
39 #import <AudioUnit/AudioUnit.h>          // AudioUnit
40 #import <CoreAudio/CoreAudio.h>      // AudioDeviceID
41 #import <AudioToolbox/AudioFormat.h>     // AudioFormatGetProperty
42 #import <CoreServices/CoreServices.h>
43
44 #ifndef verify_noerr
45 # define verify_noerr(a) assert((a) == noErr)
46 #endif
47
48 #define STREAM_FORMAT_MSG(pre, sfm) \
49     pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
50     sfm.mSampleRate, (char *)&sfm.mFormatID, \
51     (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
52     (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
53     (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
54
55 #define FRAMESIZE 2048
56 #define BUFSIZE (FRAMESIZE * 8) * 8
57 #define AOUT_VAR_SPDIF_FLAG 0xf00000
58
59 /*
60  * TODO:
61  * - clean up the debug info
62  * - be better at changing stream setup or devices setup changes while playing.
63  * - fix 6.1 and 7.1
64  */
65
66 /*****************************************************************************
67  * aout_sys_t: private audio output method descriptor
68  *****************************************************************************
69  * This structure is part of the audio output thread descriptor.
70  * It describes the CoreAudio specific properties of an output thread.
71  *****************************************************************************/
72 struct aout_sys_t
73 {
74     aout_packet_t               packet;
75     AudioDeviceID               i_default_dev;       /* DeviceID of defaultOutputDevice */
76     AudioDeviceID               i_selected_dev;      /* DeviceID of the selected device */
77     AudioDeviceIOProcID         i_procID;            /* DeviceID of current device */
78     UInt32                      i_devices;           /* Number of CoreAudio Devices */
79     bool                        b_digital;           /* Are we running in digital mode? */
80     mtime_t                     clock_diff;          /* Difference between VLC clock and Device clock */
81
82     /* AUHAL specific */
83     Component                   au_component;        /* The Audiocomponent we use */
84     AudioUnit                   au_unit;             /* The AudioUnit we use */
85     uint8_t                     p_remainder_buffer[BUFSIZE];
86     uint32_t                    i_read_bytes;
87     uint32_t                    i_total_bytes;
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;            /* Wether we need to revert the stream format */
96     bool                        b_changed_mixing;    /* Wether we need to set the mixing mode back */
97 };
98
99 /*****************************************************************************
100  * Local prototypes.
101  *****************************************************************************/
102 static int      Open                    (vlc_object_t *);
103 static int      OpenAnalog              (audio_output_t *);
104 static int      OpenSPDIF               (audio_output_t *);
105 static void     Close                   (vlc_object_t *);
106
107 static void     Probe                   (audio_output_t *);
108
109 static int      AudioDeviceHasOutput    (AudioDeviceID);
110 static int      AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
111 static int      AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
112 static int      AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
113
114 static OSStatus RenderCallbackAnalog    (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
115                                           unsigned int, unsigned int, AudioBufferList *);
116 static OSStatus RenderCallbackSPDIF     (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
117                                           AudioBufferList *, const AudioTimeStamp *, void *);
118 static OSStatus HardwareListener        (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
119 static OSStatus StreamListener          (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
120 static int      AudioDeviceCallback     (vlc_object_t *, const char *,
121                                           vlc_value_t, vlc_value_t, void *);
122
123 static int      VolumeSet               (audio_output_t *, float);
124 static int      MuteSet                 (audio_output_t *, bool);
125
126
127 /*****************************************************************************
128  * Module descriptor
129  *****************************************************************************/
130 #define ADEV_TEXT N_("Audio Device")
131 #define ADEV_LONGTEXT N_("Choose a number corresponding to the number of an " \
132     "audio device, as listed in your 'Audio Device' menu. This device will " \
133     "then be used by default for audio playback.")
134
135 vlc_module_begin ()
136     set_shortname("auhal")
137     set_description(N_("HAL AudioUnit output"))
138     set_capability("audio output", 101)
139     set_category(CAT_AUDIO)
140     set_subcategory(SUBCAT_AUDIO_AOUT)
141     set_callbacks(Open, Close)
142     add_integer("macosx-audio-device", 0, ADEV_TEXT, ADEV_LONGTEXT, false)
143 vlc_module_end ()
144
145 /*****************************************************************************
146  * Open: open macosx audio output
147  *****************************************************************************/
148 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
149 {
150     OSStatus                err = noErr;
151     UInt32                  i_param_size = 0;
152     struct aout_sys_t       *p_sys = NULL;
153     vlc_value_t             val;
154
155     /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
156      * property size */
157     int                     b_alive = false;
158
159     p_sys = p_aout->sys;
160     p_sys->i_default_dev = 0;
161     p_sys->i_selected_dev = 0;
162     p_sys->i_devices = 0;
163     p_sys->b_digital = false;
164     p_sys->au_component = NULL;
165     p_sys->au_unit = NULL;
166     p_sys->clock_diff = (mtime_t) 0;
167     p_sys->i_read_bytes = 0;
168     p_sys->i_total_bytes = 0;
169     p_sys->i_hog_pid = -1;
170     p_sys->i_stream_id = 0;
171     p_sys->i_stream_index = -1;
172     p_sys->b_revert = false;
173     p_sys->b_changed_mixing = false;
174     memset(p_sys->p_remainder_buffer, 0, sizeof(uint8_t) * BUFSIZE);
175
176     p_aout->play = aout_PacketPlay;
177     p_aout->pause = aout_PacketPause;
178     p_aout->flush = aout_PacketFlush;
179
180     aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
181
182     /* Persistent device variable */
183     if (var_Type(p_aout->p_libvlc, "macosx-audio-device") == 0)
184         var_Create(p_aout->p_libvlc, "macosx-audio-device", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT);
185
186     /* Build a list of devices */
187     if (var_Type(p_aout, "audio-device") == 0)
188         Probe(p_aout);
189
190     /* What device do we want? */
191     if (var_Get(p_aout, "audio-device", &val) < 0) {
192         msg_Err(p_aout, "audio-device var does not exist. device probe failed.");
193         goto error;
194     }
195
196     p_sys->i_selected_dev = val.i_int & ~AOUT_VAR_SPDIF_FLAG; /* remove SPDIF flag to get the true DeviceID */
197     bool b_supports_digital = (val.i_int & AOUT_VAR_SPDIF_FLAG);
198     if (b_supports_digital)
199         msg_Dbg(p_aout, "audio device supports digital output");
200
201     /* Check if the desired device is alive and usable */
202     i_param_size = sizeof(b_alive);
203     AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
204                                               kAudioObjectPropertyScopeGlobal,
205                                               kAudioObjectPropertyElementMaster };
206     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
207
208     if (err != noErr) {
209         /* Be tolerant, only give a warning here */
210         msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
211                            (unsigned int)p_sys->i_selected_dev, (char *)&err);
212         b_alive = false;
213     }
214
215     if (!b_alive) {
216         msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
217         p_sys->i_selected_dev = p_sys->i_default_dev;
218     }
219
220     /* add a callback to see if the device dies later on */
221     err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
222     if (err != noErr) {
223         /* Be tolerant, only give a warning here */
224         msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
225                  (unsigned int)p_sys->i_selected_dev, (char *)&err);
226     }
227
228     AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
229                                   kAudioDevicePropertyScopeOutput,
230                                   kAudioObjectPropertyElementMaster };
231     i_param_size = sizeof(p_sys->i_hog_pid);
232     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
233     if (err != noErr) {
234         /* This is not a fatal error. Some drivers simply don't support this property */
235         msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
236                  (char *)&err);
237         p_sys->i_hog_pid = -1;
238     }
239
240     if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
241         msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
242         dialog_Fatal(p_aout, _("Audio output failed"), "%s",
243                         _("The selected audio output device is exclusively in "
244                           "use by another program."));
245         goto error;
246     }
247
248     /* If we change the device we want to use, we should renegotiate the audio chain */
249     var_AddCallback(p_aout, "audio-device", AudioDeviceCallback, NULL);
250
251     /* Check for Digital mode or Analog output mode */
252     if (AOUT_FMT_SPDIF (fmt) && b_supports_digital) {
253         if (OpenSPDIF (p_aout)) {
254             msg_Dbg(p_aout, "digital output successfully opened");
255             return VLC_SUCCESS;
256         }
257     } else {
258         if (OpenAnalog(p_aout)) {
259             msg_Dbg(p_aout, "analog output successfully opened");
260             return VLC_SUCCESS;
261         }
262     }
263
264 error:
265     /* If we reach this, this aout has failed */
266     msg_Err(p_aout, "opening the auhal output failed");
267     var_Destroy(p_aout, "audio-device");
268     return VLC_EGENERIC;
269 }
270
271 /*****************************************************************************
272  * Open: open and setup a HAL AudioUnit to do analog (multichannel) audio output
273  *****************************************************************************/
274 static int OpenAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
275 {
276     struct aout_sys_t           *p_sys = p_aout->sys;
277     OSStatus                    err = noErr;
278     UInt32                      i_param_size = 0;
279     int                         i_original;
280     ComponentDescription        desc;
281     AudioStreamBasicDescription DeviceFormat;
282     AudioChannelLayout          *layout;
283     AudioChannelLayout          new_layout;
284     AURenderCallbackStruct      input;
285
286     /* Lets go find our Component */
287     desc.componentType = kAudioUnitType_Output;
288     desc.componentSubType = kAudioUnitSubType_HALOutput;
289     desc.componentManufacturer = kAudioUnitManufacturer_Apple;
290     desc.componentFlags = 0;
291     desc.componentFlagsMask = 0;
292
293     p_sys->au_component = FindNextComponent(NULL, &desc);
294     if (p_sys->au_component == NULL) {
295         msg_Warn(p_aout, "we cannot find our HAL component");
296         return false;
297     }
298
299     err = OpenAComponent(p_sys->au_component, &p_sys->au_unit);
300     if (err != noErr) {
301         msg_Warn(p_aout, "we cannot open our HAL component");
302         return false;
303     }
304
305     /* Set the device we will use for this output unit */
306     err = AudioUnitSetProperty(p_sys->au_unit,
307                          kAudioOutputUnitProperty_CurrentDevice,
308                          kAudioUnitScope_Global,
309                          0,
310                          &p_sys->i_selected_dev,
311                          sizeof(AudioDeviceID));
312
313     if (err != noErr) {
314         msg_Warn(p_aout, "we cannot select the audio device");
315         return false;
316     }
317
318     /* Get the current format */
319     i_param_size = sizeof(AudioStreamBasicDescription);
320
321     err = AudioUnitGetProperty(p_sys->au_unit,
322                                    kAudioUnitProperty_StreamFormat,
323                                    kAudioUnitScope_Input,
324                                    0,
325                                    &DeviceFormat,
326                                    &i_param_size);
327
328     if (err != noErr)
329         return false;
330     else
331         msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
332
333     /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
334     err = AudioUnitGetPropertyInfo(p_sys->au_unit,
335                                    kAudioDevicePropertyPreferredChannelLayout,
336                                    kAudioUnitScope_Output,
337                                    0,
338                                    &i_param_size,
339                                    NULL);
340
341     if (err == noErr) {
342         layout = (AudioChannelLayout *)malloc(i_param_size);
343
344         verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
345                                        kAudioDevicePropertyPreferredChannelLayout,
346                                        kAudioUnitScope_Output,
347                                        0,
348                                        layout,
349                                        &i_param_size));
350
351         /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
352         if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
353             /* bitmap defined channellayout */
354             verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
355                                     sizeof(UInt32), &layout->mChannelBitmap,
356                                     &i_param_size,
357                                     layout));
358         } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
359         {
360             /* layouttags defined channellayout */
361             verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
362                                     sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
363                                     &i_param_size,
364                                     layout));
365         }
366
367         msg_Dbg(p_aout, "layout of AUHAL has %d channels" , (int)layout->mNumberChannelDescriptions);
368
369         /* Initialize the VLC core channel count */
370         fmt->i_physical_channels = 0;
371         i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
372
373         if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
374             /* We only need Mono or cannot output more than 1 channel */
375             fmt->i_physical_channels = AOUT_CHAN_CENTER;
376         } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
377             /* We only need Stereo or cannot output more than 2 channels */
378             fmt->i_physical_channels = AOUT_CHANS_STEREO;
379         } else {
380             /* We want more than stereo and we can do that */
381             for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
382                 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
383
384                 switch(layout->mChannelDescriptions[i].mChannelLabel) {
385                     case kAudioChannelLabel_Left:
386                         fmt->i_physical_channels |= AOUT_CHAN_LEFT;
387                         continue;
388                     case kAudioChannelLabel_Right:
389                         fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
390                         continue;
391                     case kAudioChannelLabel_Center:
392                         fmt->i_physical_channels |= AOUT_CHAN_CENTER;
393                         continue;
394                     case kAudioChannelLabel_LFEScreen:
395                         fmt->i_physical_channels |= AOUT_CHAN_LFE;
396                         continue;
397                     case kAudioChannelLabel_LeftSurround:
398                         fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
399                         continue;
400                     case kAudioChannelLabel_RightSurround:
401                         fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
402                         continue;
403                     case kAudioChannelLabel_RearSurroundLeft:
404                         fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
405                         continue;
406                     case kAudioChannelLabel_RearSurroundRight:
407                         fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
408                         continue;
409                     case kAudioChannelLabel_CenterSurround:
410                         fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
411                         continue;
412                     default:
413                         msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
414                 }
415             }
416             if (fmt->i_physical_channels == 0) {
417                 fmt->i_physical_channels = AOUT_CHANS_STEREO;
418                 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
419                 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
420                                 _("You should configure your speaker layout with "
421                                   "the \"Audio Midi Setup\" utility in /Applications/"
422                                   "Utilities. Stereo mode is being used now."));
423             }
424         }
425         free(layout);
426     } else {
427         msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
428         fmt->i_physical_channels = AOUT_CHANS_STEREO;
429     }
430
431     msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
432     msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
433
434     memset (&new_layout, 0, sizeof(new_layout));
435     switch(aout_FormatNbChannels(fmt)) {
436         case 1:
437             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
438             break;
439         case 2:
440             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
441             break;
442         case 3:
443             if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
444                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
445             else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
446                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
447             break;
448         case 4:
449             if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
450                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
451             else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
452                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
453             else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
454                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
455             break;
456         case 5:
457             if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
458                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
459             else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
460                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
461             break;
462         case 6:
463             if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
464                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
465             else
466                 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
467             break;
468         case 7:
469             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
470             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
471             break;
472         case 8:
473             /* FIXME: This is incorrect. VLC uses the internal ordering: L R Lm Rm Lr Rr C LFE but this is wrong */
474             new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
475             break;
476     }
477
478     /* Set up the format to be used */
479     DeviceFormat.mSampleRate = fmt->i_rate;
480     DeviceFormat.mFormatID = kAudioFormatLinearPCM;
481
482     /* We use float 32. It's the best supported format by both VLC and Coreaudio */
483     fmt->i_format = VLC_CODEC_FL32;
484     DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
485     DeviceFormat.mBitsPerChannel = 32;
486     DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
487
488     /* Calculate framesizes and stuff */
489     DeviceFormat.mFramesPerPacket = 1;
490     DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
491     DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
492
493     /* Set the desired format */
494     i_param_size = sizeof(AudioStreamBasicDescription);
495     verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
496                                    kAudioUnitProperty_StreamFormat,
497                                    kAudioUnitScope_Input,
498                                    0,
499                                    &DeviceFormat,
500                                    i_param_size));
501
502     msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
503
504     /* Retrieve actual format */
505     verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
506                                    kAudioUnitProperty_StreamFormat,
507                                    kAudioUnitScope_Input,
508                                    0,
509                                    &DeviceFormat,
510                                    &i_param_size));
511
512     msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
513
514     /* Do the last VLC aout setups */
515     aout_FormatPrepare(fmt);
516     aout_PacketInit(p_aout, &p_sys->packet, FRAMESIZE, fmt);
517
518     /* set the IOproc callback */
519     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
520     input.inputProcRefCon = p_aout;
521
522     verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
523                             kAudioUnitProperty_SetRenderCallback,
524                             kAudioUnitScope_Input,
525                             0, &input, sizeof(input)));
526
527     input.inputProc = (AURenderCallback) RenderCallbackAnalog;
528     input.inputProcRefCon = p_aout;
529
530     /* Set the new_layout as the layout VLC will use to feed the AU unit */
531     verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
532                             kAudioUnitProperty_AudioChannelLayout,
533                             kAudioUnitScope_Input,
534                             0, &new_layout, sizeof(new_layout)));
535
536     if (new_layout.mNumberChannelDescriptions > 0)
537         free(new_layout.mChannelDescriptions);
538
539     /* AU initiliaze */
540     verify_noerr(AudioUnitInitialize(p_sys->au_unit));
541
542     /* Find the difference between device clock and mdate clock */
543     p_sys->clock_diff = - (mtime_t)
544         AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
545     p_sys->clock_diff += mdate();
546
547     /* Start the AU */
548     verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
549
550     return true;
551 }
552
553 /*****************************************************************************
554  * Setup a encoded digital stream (SPDIF)
555  *****************************************************************************/
556 static int OpenSPDIF (audio_output_t * p_aout, audio_sample_format_t *fmt)
557 {
558     struct aout_sys_t       *p_sys = p_aout->sys;
559     OSStatus                err = noErr;
560     UInt32                  i_param_size = 0, b_mix = 0;
561     Boolean                 b_writeable = false;
562     AudioStreamID           *p_streams = NULL;
563     unsigned                i_streams = 0;
564
565     /* Start doing the SPDIF setup proces */
566     p_sys->b_digital = true;
567
568     /* Hog the device */
569     AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
570     i_param_size = sizeof(p_sys->i_hog_pid);
571     p_sys->i_hog_pid = getpid() ;
572
573     err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
574
575     if (err != noErr) {
576         msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
577         return false;
578     }
579
580     AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
581
582     if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
583         /* Set mixable to false if we are allowed to */
584         err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
585         err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
586         err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
587
588         if (err == noErr && b_writeable) {
589             b_mix = 0;
590             err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
591             p_sys->b_changed_mixing = true;
592         }
593
594         if (err != noErr) {
595             msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
596             return false;
597         }
598     }
599
600     /* Get a list of all the streams on this device */
601     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
602     err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
603     if (err != noErr) {
604         msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
605         return false;
606     }
607
608     i_streams = i_param_size / sizeof(AudioStreamID);
609     p_streams = (AudioStreamID *)malloc(i_param_size);
610     if (p_streams == NULL)
611         return false;
612
613     err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
614
615     if (err != noErr) {
616         msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
617         free(p_streams);
618         return false;
619     }
620
621     AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
622     for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
623         /* Find a stream with a cac3 stream */
624         AudioStreamRangedDescription *p_format_list = NULL;
625         int                          i_formats = 0;
626         bool                         b_digital = false;
627
628         /* Retrieve all the stream formats supported by each output stream */
629         err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
630         if (err != noErr) {
631             msg_Err(p_aout, "OpenSPDIF: could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
632             continue;
633         }
634
635         i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
636         p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
637         if (p_format_list == NULL)
638             continue;
639
640         err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
641         if (err != noErr) {
642             msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
643             free(p_format_list);
644             continue;
645         }
646
647         /* Check if one of the supported formats is a digital format */
648         for (int j = 0; j < i_formats; j++) {
649             if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
650                p_format_list[j].mFormat.mFormatID == 'iac3' ||
651                p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
652                p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
653                 b_digital = true;
654                 break;
655             }
656         }
657
658         if (b_digital) {
659             /* if this stream supports a digital (cac3) format, then go set it. */
660             int i_requested_rate_format = -1;
661             int i_current_rate_format = -1;
662             int i_backup_rate_format = -1;
663
664             p_sys->i_stream_id = p_streams[i];
665             p_sys->i_stream_index = i;
666
667             if (!p_sys->b_revert) {
668                 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
669                 /* Retrieve the original format of this stream first if not done so already */
670                 i_param_size = sizeof(p_sys->sfmt_revert);
671                 err = AudioObjectGetPropertyData(p_sys->i_stream_id, &currentPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
672                 if (err != noErr) {
673                     msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
674                     continue;
675                 }
676                 p_sys->b_revert = true;
677             }
678
679             for (int j = 0; j < i_formats; j++) {
680                 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
681                    p_format_list[j].mFormat.mFormatID == 'iac3' ||
682                    p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
683                    p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
684                     if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
685                         i_requested_rate_format = j;
686                         break;
687                     } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
688                         i_current_rate_format = j;
689                     else {
690                         if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
691                             i_backup_rate_format = j;
692                     }
693                 }
694
695             }
696
697             if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
698                 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
699             else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
700                 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
701             else
702                 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) */
703         }
704         free(p_format_list);
705     }
706     free(p_streams);
707
708     /* get notified when we don't have spdif-output anymore */
709     err = AudioObjectAddPropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
710     if (err != noErr) {
711         msg_Warn(p_aout, "could not set audio device property streams callback on device: %4.4s",
712                  (char *)&err);
713     }
714
715     msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
716
717     if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
718         return false;
719
720     /* Set the format flags */
721     if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
722         fmt->i_format = VLC_CODEC_SPDIFB;
723     else
724         fmt->i_format = VLC_CODEC_SPDIFL;
725     fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
726     fmt->i_frame_length = A52_FRAME_NB;
727     fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
728     aout_FormatPrepare(fmt);
729     aout_PacketInit(p_aout, &p_sys->packet, A52_FRAME_NB, fmt);
730
731     /* Add IOProc callback */
732     err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
733                                    (AudioDeviceIOProc)RenderCallbackSPDIF,
734                                    (void *)p_aout,
735                                    &p_sys->i_procID);
736     if (err != noErr) {
737         msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
738         aout_PacketDestroy (p_aout);
739         return false;
740     }
741
742     /* Check for the difference between the Device clock and mdate */
743     p_sys->clock_diff = - (mtime_t)
744         AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
745     p_sys->clock_diff += mdate();
746
747     /* Start device */
748     err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
749     if (err != noErr) {
750         msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
751
752         err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
753         if (err != noErr)
754             msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
755
756         aout_PacketDestroy (p_aout);
757         return false;
758     }
759
760     return true;
761 }
762
763
764 /*****************************************************************************
765  * Close: Close HAL AudioUnit
766  *****************************************************************************/
767 static void Stop(audio_output_t *p_aout)
768 {
769     struct aout_sys_t   *p_sys = p_aout->sys;
770     OSStatus            err = noErr;
771     UInt32              i_param_size = 0;
772
773     AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
774     err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, NULL);
775     if (err != noErr)
776         msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
777
778     if (p_sys->b_digital) {
779         AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
780         err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, NULL);
781         if (err != noErr)
782             msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
783     }
784
785     if (p_sys->au_unit) {
786         verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
787         verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
788         verify_noerr(CloseComponent(p_sys->au_unit));
789     }
790
791     if (p_sys->b_digital) {
792         /* Stop device */
793         err = AudioDeviceStop(p_sys->i_selected_dev,
794                                p_sys->i_procID);
795         if (err != noErr)
796             msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
797
798         /* Remove IOProc callback */
799         err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
800                                           p_sys->i_procID);
801         if (err != noErr)
802             msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
803
804         if (p_sys->b_revert)
805             AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
806
807         if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
808             int b_mix;
809             Boolean b_writeable = false;
810             /* Revert mixable to true if we are allowed to */
811             AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
812             err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
813             err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
814
815             if (err == noErr && b_writeable) {
816                 msg_Dbg(p_aout, "mixable is: %d", b_mix);
817                 b_mix = 1;
818                 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
819             }
820
821             if (err != noErr)
822                 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
823         }
824     }
825
826     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
827     err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, NULL);
828
829     if (err != noErr)
830         msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
831
832     if (p_sys->i_hog_pid == getpid()) {
833         p_sys->i_hog_pid = -1;
834         i_param_size = sizeof(p_sys->i_hog_pid);
835         AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
836             kAudioDevicePropertyScopeOutput,
837             kAudioObjectPropertyElementMaster };
838         err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
839         if (err != noErr)
840             msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
841     }
842
843     var_DelCallback(p_aout, "audio-device", AudioDeviceCallback, NULL);
844
845     aout_PacketDestroy(p_aout);
846 }
847
848 /*****************************************************************************
849  * Probe: Check which devices the OS has, and add them to our audio-device menu
850  *****************************************************************************/
851 static void Probe(audio_output_t * p_aout)
852 {
853     OSStatus            err = noErr;
854     UInt32              i_param_size = 0;
855     AudioDeviceID       devid_def = 0;
856     AudioDeviceID       *p_devices = NULL;
857     vlc_value_t         val, text;
858
859     struct aout_sys_t   *p_sys = p_aout->sys;
860
861     /* Get number of devices */
862     AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
863     err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &i_param_size);
864     if (err != noErr) {
865         msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
866         goto error;
867     }
868
869     p_sys->i_devices = i_param_size / sizeof(AudioDeviceID);
870
871     if (p_sys->i_devices < 1) {
872         msg_Err(p_aout, "No audio output devices were found.");
873         goto error;
874     }
875     msg_Dbg(p_aout, "found %u audio device(s)", (unsigned)p_sys->i_devices);
876
877     /* Allocate DeviceID array */
878     p_devices = (AudioDeviceID*)malloc(sizeof(AudioDeviceID) * p_sys->i_devices);
879     if (p_devices == NULL)
880         goto error;
881
882     /* Populate DeviceID array */
883     err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &i_param_size, p_devices);
884     if (err != noErr) {
885         msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
886         goto error;
887     }
888
889     /* Find the ID of the default Device */
890     AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
891     i_param_size = sizeof(AudioDeviceID);
892     err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &i_param_size, &devid_def);
893     if (err != noErr) {
894         msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
895         goto error;
896     }
897     p_sys->i_default_dev = devid_def;
898
899     var_Create(p_aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
900     text.psz_string = (char*)_("Audio Device");
901     var_Change(p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
902
903     AudioObjectPropertyAddress deviceNameAddress = { kAudioDevicePropertyDeviceName, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
904
905     for (unsigned int i = 0; i < p_sys->i_devices; i++) {
906         char *psz_name;
907         i_param_size = 0;
908
909         /* Retrieve the length of the device name */
910         err = AudioObjectGetPropertyDataSize(p_devices[i], &deviceNameAddress, 0, NULL, &i_param_size);
911         if (err != noErr)
912             goto error;
913
914         /* Retrieve the name of the device */
915         psz_name = (char *)malloc(i_param_size);
916         err = AudioObjectGetPropertyData(p_devices[i], &deviceNameAddress, 0, NULL, &i_param_size, psz_name);
917         if (err != noErr)
918             goto error;
919
920         msg_Dbg(p_aout, "DevID: %u DevName: %s", (unsigned)p_devices[i], psz_name);
921
922         if (!AudioDeviceHasOutput(p_devices[i])) {
923             msg_Dbg(p_aout, "this device is INPUT only. skipping...");
924             free(psz_name);
925             continue;
926         }
927
928         /* Add the menu entries */
929         val.i_int = (int)p_devices[i];
930         text.psz_string = psz_name;
931         var_Change(p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
932         text.psz_string = NULL;
933         if (p_sys->i_default_dev == p_devices[i]) {
934             /* The default device is the selected device normally */
935             var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
936             var_Set(p_aout, "audio-device", val);
937         }
938
939         if (AudioDeviceSupportsDigital(p_aout, p_devices[i])) {
940             val.i_int = (int)p_devices[i] | AOUT_VAR_SPDIF_FLAG;
941             if (asprintf(&text.psz_string, _("%s (Encoded Output)"), psz_name) != -1) {
942                 var_Change(p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
943                 free(text.psz_string);
944                 if (p_sys->i_default_dev == p_devices[i] && var_InheritBool(p_aout, "spdif")) {
945                     /* We selected to prefer SPDIF output if available
946                      * then this "dummy" entry should be selected */
947                     var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
948                     var_Set(p_aout, "audio-device", val);
949                 }
950             }
951         }
952
953         free(psz_name);
954     }
955
956     /* If a device is already "preselected", then use this device */
957     var_Get(p_aout->p_libvlc, "macosx-audio-device", &val);
958     if (val.i_int > 0) {
959         msg_Dbg(p_aout, "using preselected output device %#"PRIx64, val.i_int);
960         var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
961         var_Set(p_aout, "audio-device", val);
962     }
963
964     /* Attach a Listener so that we are notified of a change in the Device setup */
965     err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
966     if (err != noErr) {
967         msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
968         goto error;
969     }
970
971     free(p_devices);
972     return;
973
974 error:
975     msg_Warn(p_aout, "audio device already in use");
976     free(p_devices);
977     return;
978 }
979
980 /*****************************************************************************
981  * AudioDeviceHasOutput: Checks if the Device actually provides any outputs at all
982  *****************************************************************************/
983 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
984 {
985     UInt32            dataSize;
986
987     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
988     verify_noerr(AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize));
989     if (dataSize == 0)
990         return FALSE;
991
992     return TRUE;
993 }
994
995 /*****************************************************************************
996  * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
997  *****************************************************************************/
998 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
999 {
1000     OSStatus                    err = noErr;
1001     UInt32                      i_param_size = 0;
1002     AudioStreamID               *p_streams = NULL;
1003     int                         i_streams = 0;
1004     bool                  b_return = false;
1005
1006     /* Retrieve all the output streams */
1007     AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1008     err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1009     if (err != noErr) {
1010         msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1011         return false;
1012     }
1013
1014     i_streams = i_param_size / sizeof(AudioStreamID);
1015     p_streams = (AudioStreamID *)malloc(i_param_size);
1016     if (p_streams == NULL)
1017         return VLC_ENOMEM;
1018
1019     err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1020     if (err != noErr) {
1021         msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1022         return false;
1023     }
1024
1025     for (int i = 0; i < i_streams; i++) {
1026         if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1027             b_return = true;
1028     }
1029
1030     free(p_streams);
1031     return b_return;
1032 }
1033
1034 /*****************************************************************************
1035  * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
1036  *****************************************************************************/
1037 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1038 {
1039     OSStatus                    err = noErr;
1040     UInt32                      i_param_size = 0;
1041     AudioStreamRangedDescription *p_format_list = NULL;
1042     int                         i_formats = 0;
1043     bool                        b_return = false;
1044
1045     /* Retrieve all the stream formats supported by each output stream */
1046     AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1047     err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1048     if (err != noErr) {
1049         msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1050         return false;
1051     }
1052
1053     i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1054     msg_Dbg(p_aout, "found %i stream formats", i_formats);
1055
1056     p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1057     if (p_format_list == NULL)
1058         return false;
1059
1060     err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1061     if (err != noErr) {
1062         msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1063         free(p_format_list);
1064         p_format_list = NULL;
1065         return false;
1066     }
1067
1068     for (int i = 0; i < i_formats; i++) {
1069         msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1070
1071         if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1072            p_format_list[i].mFormat.mFormatID == 'iac3' ||
1073            p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1074            p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1075             b_return = true;
1076     }
1077
1078     free(p_format_list);
1079     return b_return;
1080 }
1081
1082 /*****************************************************************************
1083  * AudioStreamChangeFormat: Change i_stream_id to change_format
1084  *****************************************************************************/
1085 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1086 {
1087     OSStatus            err = noErr;
1088     UInt32              i_param_size = 0;
1089
1090     AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1091
1092     struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1093
1094     msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1095
1096     /* Condition because SetProperty is asynchronious */
1097     vlc_cond_init(&w.cond);
1098     vlc_mutex_init(&w.lock);
1099     vlc_mutex_lock(&w.lock);
1100
1101     /* Install the callback */
1102     err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1103     if (err != noErr) {
1104         msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1105         return false;
1106     }
1107
1108     /* change the format */
1109     err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1110                                      &change_format);
1111     if (err != noErr) {
1112         msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1113         return false;
1114     }
1115
1116     /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1117      * it is also not atomic in its behaviour.
1118      * Therefore we check 5 times before we really give up.
1119      * FIXME: failing isn't actually implemented yet. */
1120     for (int i = 0; i < 5; i++) {
1121         AudioStreamBasicDescription actual_format;
1122         mtime_t timeout = mdate() + 500000;
1123
1124         if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1125             msg_Dbg(p_aout, "reached timeout");
1126
1127         i_param_size = sizeof(AudioStreamBasicDescription);
1128         err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1129
1130         msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1131         if (actual_format.mSampleRate == change_format.mSampleRate &&
1132             actual_format.mFormatID == change_format.mFormatID &&
1133             actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1134             /* The right format is now active */
1135             break;
1136         }
1137         /* We need to check again */
1138     }
1139
1140     /* Removing the property listener */
1141     err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1142     if (err != noErr) {
1143         msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1144         return false;
1145     }
1146
1147     /* Destroy the lock and condition */
1148     vlc_mutex_unlock(&w.lock);
1149     vlc_mutex_destroy(&w.lock);
1150     vlc_cond_destroy(&w.cond);
1151
1152     return true;
1153 }
1154
1155 /*****************************************************************************
1156  * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1157  * us to provide some more audio data.
1158  * Don't print anything during normal playback, calling blocking function from
1159  * this callback is not allowed.
1160  *****************************************************************************/
1161 static OSStatus RenderCallbackAnalog(vlc_object_t *_p_aout,
1162                                       AudioUnitRenderActionFlags *ioActionFlags,
1163                                       const AudioTimeStamp *inTimeStamp,
1164                                       unsigned int inBusNumber,
1165                                       unsigned int inNumberFrames,
1166                                       AudioBufferList *ioData)
1167 {
1168     AudioTimeStamp  host_time;
1169     mtime_t         current_date = 0;
1170     uint32_t        i_mData_bytes = 0;
1171
1172     audio_output_t * p_aout = (audio_output_t *)_p_aout;
1173     struct aout_sys_t * p_sys = p_aout->sys;
1174
1175     VLC_UNUSED(ioActionFlags);
1176     VLC_UNUSED(inBusNumber);
1177     VLC_UNUSED(inNumberFrames);
1178
1179     host_time.mFlags = kAudioTimeStampHostTimeValid;
1180     AudioDeviceTranslateTime(p_sys->i_selected_dev, inTimeStamp, &host_time);
1181
1182     /* Check for the difference between the Device clock and mdate */
1183     p_sys->clock_diff = - (mtime_t)
1184         AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
1185     p_sys->clock_diff += mdate();
1186
1187     current_date = p_sys->clock_diff +
1188                    AudioConvertHostTimeToNanos(host_time.mHostTime) / 1000;
1189                    //- ((mtime_t) 1000000 / p_aout->format.i_rate * 31); // 31 = Latency in Frames. retrieve somewhere
1190
1191     if (ioData == NULL || ioData->mNumberBuffers < 1) {
1192         msg_Err(p_aout, "no iodata or buffers");
1193         return 0;
1194     }
1195     if (ioData->mNumberBuffers > 1)
1196         msg_Err(p_aout, "well this is weird. seems like there is more than one buffer...");
1197
1198
1199     if (p_sys->i_total_bytes > 0) {
1200         i_mData_bytes = __MIN(p_sys->i_total_bytes - p_sys->i_read_bytes, ioData->mBuffers[0].mDataByteSize);
1201         memcpy(ioData->mBuffers[0].mData,
1202                     &p_sys->p_remainder_buffer[p_sys->i_read_bytes],
1203                     i_mData_bytes);
1204         p_sys->i_read_bytes += i_mData_bytes;
1205         current_date += (mtime_t) ((mtime_t) 1000000 / p_sys->packet.format.i_rate) *
1206                         (i_mData_bytes / 4 / aout_FormatNbChannels(&p_sys->packet.format)); // 4 is fl32 specific
1207
1208         if (p_sys->i_read_bytes >= p_sys->i_total_bytes)
1209             p_sys->i_read_bytes = p_sys->i_total_bytes = 0;
1210     }
1211
1212     while(i_mData_bytes < ioData->mBuffers[0].mDataByteSize) {
1213         /* We don't have enough data yet */
1214         block_t * p_buffer;
1215         p_buffer = aout_PacketNext(p_aout, current_date);
1216
1217         if (p_buffer != NULL)
1218         {
1219             uint32_t i_second_mData_bytes = __MIN(p_buffer->i_buffer, ioData->mBuffers[0].mDataByteSize - i_mData_bytes);
1220
1221             memcpy((uint8_t *)ioData->mBuffers[0].mData + i_mData_bytes,
1222                         p_buffer->p_buffer, i_second_mData_bytes);
1223             i_mData_bytes += i_second_mData_bytes;
1224
1225             if (i_mData_bytes >= ioData->mBuffers[0].mDataByteSize)
1226             {
1227                 p_sys->i_total_bytes = p_buffer->i_buffer - i_second_mData_bytes;
1228                 memcpy(p_sys->p_remainder_buffer,
1229                             &p_buffer->p_buffer[i_second_mData_bytes],
1230                             p_sys->i_total_bytes);
1231                 block_Release(p_buffer);
1232                 break;
1233             } else
1234                 /* update current_date */
1235                 current_date += (mtime_t) ((mtime_t) 1000000 / p_sys->packet.format.i_rate) *
1236                                 (i_second_mData_bytes / 4 / aout_FormatNbChannels(&p_sys->packet.format)); // 4 is fl32 specific
1237             block_Release(p_buffer);
1238         } else {
1239             memset((uint8_t *)ioData->mBuffers[0].mData +i_mData_bytes,
1240                    0,ioData->mBuffers[0].mDataByteSize - i_mData_bytes);
1241             i_mData_bytes += ioData->mBuffers[0].mDataByteSize - i_mData_bytes;
1242         }
1243     }
1244     return noErr;
1245 }
1246
1247 /*****************************************************************************
1248  * RenderCallbackSPDIF: callback for SPDIF audio output
1249  *****************************************************************************/
1250 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1251                                     const AudioTimeStamp * inNow,
1252                                     const void * inInputData,
1253                                     const AudioTimeStamp * inInputTime,
1254                                     AudioBufferList * outOutputData,
1255                                     const AudioTimeStamp * inOutputTime,
1256                                     void * threadGlobals)
1257 {
1258     block_t * p_buffer;
1259     mtime_t         current_date;
1260
1261     audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1262     struct aout_sys_t * p_sys = p_aout->sys;
1263
1264     VLC_UNUSED(inDevice);
1265     VLC_UNUSED(inInputData);
1266     VLC_UNUSED(inInputTime);
1267
1268     /* Check for the difference between the Device clock and mdate */
1269     p_sys->clock_diff = - (mtime_t)
1270         AudioConvertHostTimeToNanos(inNow->mHostTime) / 1000;
1271     p_sys->clock_diff += mdate();
1272
1273     current_date = p_sys->clock_diff +
1274                    AudioConvertHostTimeToNanos(inOutputTime->mHostTime) / 1000;
1275                    //- ((mtime_t) 1000000 / p_aout->format.i_rate * 31); // 31 = Latency in Frames. retrieve somewhere
1276
1277     p_buffer = aout_PacketNext(p_aout, current_date);
1278
1279 #define BUFFER outOutputData->mBuffers[p_sys->i_stream_index]
1280     if (p_buffer != NULL) {
1281         if ((int)BUFFER.mDataByteSize != (int)p_buffer->i_buffer)
1282             msg_Warn(p_aout, "bytesize: %d nb_bytes: %d", (int)BUFFER.mDataByteSize, (int)p_buffer->i_buffer);
1283
1284         /* move data into output data buffer */
1285         memcpy(BUFFER.mData, p_buffer->p_buffer, p_buffer->i_buffer);
1286         block_Release(p_buffer);
1287     }
1288     else
1289         memset(BUFFER.mData, 0, BUFFER.mDataByteSize);
1290 #undef BUFFER
1291
1292     return noErr;
1293 }
1294
1295 /*****************************************************************************
1296  * HardwareListener: Warns us of changes in the list of registered devices
1297  *****************************************************************************/
1298 static OSStatus HardwareListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1299 {
1300     OSStatus err = noErr;
1301     audio_output_t     *p_aout = (audio_output_t *)inClientData;
1302     VLC_UNUSED(inObjectID);
1303
1304     for (unsigned int i = 0; i < inNumberAddresses; i++) {
1305         if (inAddresses[i].mSelector == kAudioHardwarePropertyDevices) {
1306             /* something changed in the list of devices */
1307             /* We trigger the audio-device's aout_ChannelsRestart callback */
1308             msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1309             var_TriggerCallback(p_aout, "audio-device");
1310             var_Destroy(p_aout, "audio-device");
1311         } else if (inAddresses[i].mSelector == kAudioDevicePropertyDeviceIsAlive) {
1312             msg_Warn(p_aout, "audio device died, resetting aout");
1313             var_TriggerCallback(p_aout, "audio-device");
1314             var_Destroy(p_aout, "audio-device");
1315         } else if (inAddresses[i].mSelector == kAudioStreamPropertyAvailablePhysicalFormats) {
1316             msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1317             var_TriggerCallback(p_aout, "audio-device");
1318             var_Destroy(p_aout, "audio-device");
1319         }
1320     }
1321
1322     return err;
1323 }
1324
1325 /*****************************************************************************
1326  * StreamListener
1327  *****************************************************************************/
1328 static OSStatus StreamListener(AudioObjectID inObjectID,  UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1329 {
1330     OSStatus err = noErr;
1331     struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1332
1333     VLC_UNUSED(inObjectID);
1334
1335     for (unsigned int i = 0; i < inNumberAddresses; i++) {
1336         if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1337             vlc_mutex_lock(&w->lock);
1338             vlc_cond_signal(&w->cond);
1339             vlc_mutex_unlock(&w->lock);
1340             break;
1341         }
1342     }
1343     return err;
1344 }
1345
1346 /*****************************************************************************
1347  * AudioDeviceCallback: Callback triggered when the audio-device variable is changed
1348  *****************************************************************************/
1349 static int AudioDeviceCallback(vlc_object_t *p_this, const char *psz_variable,
1350                      vlc_value_t old_val, vlc_value_t new_val, void *param)
1351 {
1352     audio_output_t *p_aout = (audio_output_t *)p_this;
1353     var_Set(p_aout->p_libvlc, "macosx-audio-device", new_val);
1354     msg_Dbg(p_aout, "Set Device: %#"PRIx64, new_val.i_int);
1355     return aout_ChannelsRestart(p_this, psz_variable, old_val, new_val, param);
1356 }
1357
1358
1359 /*****************************************************************************
1360  * VolumeSet: Implements volume_set(). Update the CoreAudio AU volume immediately.
1361  *****************************************************************************/
1362 static int VolumeSet(audio_output_t * p_aout, float volume)
1363 {
1364     struct   aout_sys_t *p_sys = p_aout->sys;
1365     OSStatus ostatus;
1366
1367     aout_VolumeReport(p_aout, volume);
1368
1369     volume = volume * volume * volume; // cubic mapping from output.c
1370
1371     /* Set volume for output unit */
1372     ostatus = AudioUnitSetParameter(p_sys->au_unit,
1373                                      kHALOutputParam_Volume,
1374                                      kAudioUnitScope_Global,
1375                                      0,
1376                                      volume,
1377                                      0);
1378
1379     return ostatus;
1380 }
1381
1382 static int MuteSet(audio_output_t * p_aout, bool mute)
1383 {
1384     aout_MuteReport(p_aout, mute);
1385
1386     return 0;
1387 }
1388
1389 static int Open(vlc_object_t *obj)
1390 {
1391     audio_output_t *aout = (audio_output_t *)obj;
1392     aout_sys_t *sys = malloc(sizeof (*sys));
1393
1394     if (unlikely(sys == NULL))
1395         return VLC_ENOMEM;
1396     aout->sys = sys;
1397     aout->start = Start;
1398     aout->stop = Stop;
1399     aout->volume_set = VolumeSet;
1400     aout->mute_set = MuteSet;
1401     return VLC_SUCCESS;
1402 }
1403
1404 static void Close(vlc_object_t *obj)
1405 {
1406     audio_output_t *aout = (audio_output_t *)obj;
1407     aout_sys_t *sys = aout->sys;
1408
1409     free(sys);
1410 }