1 /*****************************************************************************
2 * auhal.c: AUHAL and Coreaudio output plugin
3 *****************************************************************************
4 * Copyright (C) 2005 - 2012 VLC authors and VideoLAN
7 * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8 * Felix Paul Kühne <fkuehne at videolan dot org>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
33 #import <vlc_common.h>
34 #import <vlc_plugin.h>
35 #import <vlc_dialog.h> // dialog_Fatal
36 #import <vlc_aout.h> // aout_*
38 #import <AudioUnit/AudioUnit.h> // AudioUnit
39 #import <CoreAudio/CoreAudio.h> // AudioDeviceID
40 #import <AudioToolbox/AudioFormat.h> // AudioFormatGetProperty
41 #import <CoreServices/CoreServices.h>
43 #import "TPCircularBuffer.h"
46 # define verify_noerr(a) assert((a) == noErr)
49 #define STREAM_FORMAT_MSG(pre, sfm) \
50 pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
51 sfm.mSampleRate, (char *)&sfm.mFormatID, \
52 (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
53 (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
54 (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
56 #define FRAMESIZE 2048
57 #define BUFSIZE (FRAMESIZE * 8) * 8
58 #define AOUT_VAR_SPDIF_FLAG 0xf00000
60 #define kBufferLength BUFSIZE
62 #define AOUT_VOLUME_DEFAULT 256
63 #define AOUT_VOLUME_MAX 512
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 *****************************************************************************/
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 */
82 uint8_t chans_to_reorder; /* do we need channel reordering */
83 uint8_t chan_table[AOUT_CHAN_MAX];
85 UInt32 i_numberOfChannels;
86 TPCircularBuffer circular_buffer; /* circular buffer to swap the audio data */
89 Component au_component; /* The Audiocomponent we use */
90 AudioUnit au_unit; /* The AudioUnit we use */
92 /* CoreAudio SPDIF mode specific */
93 pid_t i_hog_pid; /* The keep the pid of our hog status */
94 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
95 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
96 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
97 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
98 bool b_revert; /* Wether we need to revert the stream format */
99 bool b_changed_mixing; /* Wether we need to set the mixing mode back */
102 /*****************************************************************************
104 *****************************************************************************/
105 static int Open (vlc_object_t *);
106 static int OpenAnalog (audio_output_t *, audio_sample_format_t *);
107 static int OpenSPDIF (audio_output_t *, audio_sample_format_t *);
108 static void Close (vlc_object_t *);
110 static void PlayAnalog (audio_output_t *, block_t *);
111 static void FlushAnalog (audio_output_t *aout, bool wait);
112 static int TimeGet (audio_output_t *aout, mtime_t *);
114 static void Probe (audio_output_t *);
116 static int AudioDeviceHasOutput (AudioDeviceID);
117 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
118 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
119 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
121 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *, unsigned int, unsigned int, AudioBufferList *);
123 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
124 AudioBufferList *, const AudioTimeStamp *, void *);
125 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
126 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
127 static int AudioDeviceCallback (vlc_object_t *, const char *,
128 vlc_value_t, vlc_value_t, void *);
130 static int VolumeSet (audio_output_t *, float);
131 static int MuteSet (audio_output_t *, bool);
134 /*****************************************************************************
136 *****************************************************************************/
137 #define ADEV_TEXT N_("Audio Device")
138 #define ADEV_LONGTEXT N_("Choose a number corresponding to the number of an " \
139 "audio device, as listed in your 'Audio Device' menu. This device will " \
140 "then be used by default for audio playback.")
142 #define VOLUME_TEXT N_("Audio volume")
143 #define VOLUME_LONGTEXT VOLUME_TEXT
146 set_shortname("auhal")
147 set_description(N_("HAL AudioUnit output"))
148 set_capability("audio output", 101)
149 set_category(CAT_AUDIO)
150 set_subcategory(SUBCAT_AUDIO_AOUT)
151 set_callbacks(Open, Close)
152 add_integer("macosx-audio-device", 0, ADEV_TEXT, ADEV_LONGTEXT, false)
153 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
154 VOLUME_TEXT, VOLUME_LONGTEXT, true)
155 change_integer_range(0, AOUT_VOLUME_MAX)
158 /*****************************************************************************
159 * Open: open macosx audio output
160 *****************************************************************************/
161 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
163 OSStatus err = noErr;
164 UInt32 i_param_size = 0;
165 struct aout_sys_t *p_sys = NULL;
168 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
173 p_sys->i_default_dev = 0;
174 p_sys->i_selected_dev = 0;
175 p_sys->i_devices = 0;
176 p_sys->b_digital = false;
177 p_sys->au_component = NULL;
178 p_sys->au_unit = NULL;
179 p_sys->clock_diff = (mtime_t) 0;
180 p_sys->i_hog_pid = -1;
181 p_sys->i_stream_id = 0;
182 p_sys->i_stream_index = -1;
183 p_sys->b_revert = false;
184 p_sys->b_changed_mixing = false;
186 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
188 /* Persistent device variable */
189 if (var_Type(p_aout->p_libvlc, "macosx-audio-device") == 0)
190 var_Create(p_aout->p_libvlc, "macosx-audio-device", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT);
192 /* Build a list of devices */
193 if (var_Type(p_aout, "audio-device") == 0)
196 /* What device do we want? */
197 if (var_Get(p_aout, "audio-device", &val) < 0) {
198 msg_Err(p_aout, "audio-device var does not exist. device probe failed.");
202 p_sys->i_selected_dev = val.i_int & ~AOUT_VAR_SPDIF_FLAG; /* remove SPDIF flag to get the true DeviceID */
203 bool b_supports_digital = (val.i_int & AOUT_VAR_SPDIF_FLAG);
204 if (b_supports_digital)
205 msg_Dbg(p_aout, "audio device supports digital output");
207 /* Check if the desired device is alive and usable */
208 i_param_size = sizeof(b_alive);
209 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
210 kAudioObjectPropertyScopeGlobal,
211 kAudioObjectPropertyElementMaster };
212 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
215 /* Be tolerant, only give a warning here */
216 msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
217 (unsigned int)p_sys->i_selected_dev, (char *)&err);
222 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
223 p_sys->i_selected_dev = p_sys->i_default_dev;
226 /* add a callback to see if the device dies later on */
227 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
229 /* Be tolerant, only give a warning here */
230 msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
231 (unsigned int)p_sys->i_selected_dev, (char *)&err);
234 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
235 kAudioDevicePropertyScopeOutput,
236 kAudioObjectPropertyElementMaster };
237 i_param_size = sizeof(p_sys->i_hog_pid);
238 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
240 /* This is not a fatal error. Some drivers simply don't support this property */
241 msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
243 p_sys->i_hog_pid = -1;
246 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
247 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
248 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
249 _("The selected audio output device is exclusively in "
250 "use by another program."));
254 /* If we change the device we want to use, we should renegotiate the audio chain */
255 var_AddCallback(p_aout, "audio-device", AudioDeviceCallback, NULL);
257 /* setup circular buffer */
258 TPCircularBufferInit(&p_sys->circular_buffer, kBufferLength);
260 /* Check for Digital mode or Analog output mode */
261 if (AOUT_FMT_SPDIF (fmt) && b_supports_digital) {
262 if (OpenSPDIF (p_aout, fmt)) {
263 msg_Dbg(p_aout, "digital output successfully opened");
267 if (OpenAnalog(p_aout, fmt)) {
268 msg_Dbg(p_aout, "analog output successfully opened");
274 /* If we reach this, this aout has failed */
275 msg_Err(p_aout, "opening the auhal output failed");
276 var_Destroy(p_aout, "audio-device");
280 /*****************************************************************************
281 * Open: open and setup a HAL AudioUnit to do analog (multichannel) audio output
282 *****************************************************************************/
283 static int OpenAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
285 struct aout_sys_t *p_sys = p_aout->sys;
286 OSStatus err = noErr;
287 UInt32 i_param_size = 0;
289 ComponentDescription desc;
290 AudioStreamBasicDescription DeviceFormat;
291 AudioChannelLayout *layout;
292 AudioChannelLayout new_layout;
293 AURenderCallbackStruct input;
295 /* Lets go find our Component */
296 desc.componentType = kAudioUnitType_Output;
297 desc.componentSubType = kAudioUnitSubType_HALOutput;
298 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
299 desc.componentFlags = 0;
300 desc.componentFlagsMask = 0;
302 p_sys->au_component = FindNextComponent(NULL, &desc);
303 if (p_sys->au_component == NULL) {
304 msg_Warn(p_aout, "we cannot find our HAL component");
308 err = OpenAComponent(p_sys->au_component, &p_sys->au_unit);
310 msg_Warn(p_aout, "we cannot open our HAL component");
314 /* Set the device we will use for this output unit */
315 err = AudioUnitSetProperty(p_sys->au_unit,
316 kAudioOutputUnitProperty_CurrentDevice,
317 kAudioUnitScope_Global,
319 &p_sys->i_selected_dev,
320 sizeof(AudioDeviceID));
323 msg_Warn(p_aout, "we cannot select the audio device");
327 /* Get the current format */
328 i_param_size = sizeof(AudioStreamBasicDescription);
330 err = AudioUnitGetProperty(p_sys->au_unit,
331 kAudioUnitProperty_StreamFormat,
332 kAudioUnitScope_Input,
340 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
342 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
343 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
344 kAudioDevicePropertyPreferredChannelLayout,
345 kAudioUnitScope_Output,
351 layout = (AudioChannelLayout *)malloc(i_param_size);
353 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
354 kAudioDevicePropertyPreferredChannelLayout,
355 kAudioUnitScope_Output,
360 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
361 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
362 /* bitmap defined channellayout */
363 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
364 sizeof(UInt32), &layout->mChannelBitmap,
367 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
369 /* layouttags defined channellayout */
370 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
371 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
376 msg_Dbg(p_aout, "layout of AUHAL has %d channels" , (int)layout->mNumberChannelDescriptions);
378 /* Initialize the VLC core channel count */
379 fmt->i_physical_channels = 0;
380 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
382 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
383 /* We only need Mono or cannot output more than 1 channel */
384 fmt->i_physical_channels = AOUT_CHAN_CENTER;
385 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
386 /* We only need Stereo or cannot output more than 2 channels */
387 fmt->i_physical_channels = AOUT_CHANS_STEREO;
389 /* We want more than stereo and we can do that */
390 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
392 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
395 switch(layout->mChannelDescriptions[i].mChannelLabel) {
396 case kAudioChannelLabel_Left:
397 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
399 case kAudioChannelLabel_Right:
400 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
402 case kAudioChannelLabel_Center:
403 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
405 case kAudioChannelLabel_LFEScreen:
406 fmt->i_physical_channels |= AOUT_CHAN_LFE;
408 case kAudioChannelLabel_LeftSurround:
409 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
411 case kAudioChannelLabel_RightSurround:
412 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
414 case kAudioChannelLabel_RearSurroundLeft:
415 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
417 case kAudioChannelLabel_RearSurroundRight:
418 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
420 case kAudioChannelLabel_CenterSurround:
421 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
424 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
427 if (fmt->i_physical_channels == 0) {
428 fmt->i_physical_channels = AOUT_CHANS_STEREO;
429 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
430 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
431 _("You should configure your speaker layout with "
432 "the \"Audio Midi Setup\" utility in /Applications/"
433 "Utilities. Stereo mode is being used now."));
438 msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
439 fmt->i_physical_channels = AOUT_CHANS_STEREO;
442 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
443 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
444 p_sys->i_numberOfChannels = aout_FormatNbChannels(fmt);
446 memset (&new_layout, 0, sizeof(new_layout));
447 uint32_t chans_out[AOUT_CHAN_MAX];
449 switch(aout_FormatNbChannels(fmt)) {
451 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
454 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
457 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
458 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
459 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
460 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
463 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
464 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
465 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
466 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
467 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
468 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
471 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
472 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
473 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
474 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
477 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
478 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
480 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
483 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
485 chans_out[0] = AOUT_CHAN_LEFT;
486 chans_out[1] = AOUT_CHAN_RIGHT;
487 chans_out[2] = AOUT_CHAN_CENTER;
488 chans_out[3] = AOUT_CHAN_LFE;
489 chans_out[4] = AOUT_CHAN_REARLEFT;
490 chans_out[5] = AOUT_CHAN_REARRIGHT;
491 chans_out[6] = AOUT_CHAN_REARCENTER;
493 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
494 if (p_aout->sys->chans_to_reorder)
495 msg_Dbg(p_aout, "channel reordering needed");
499 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
501 chans_out[0] = AOUT_CHAN_LEFT;
502 chans_out[1] = AOUT_CHAN_RIGHT;
503 chans_out[2] = AOUT_CHAN_CENTER;
504 chans_out[3] = AOUT_CHAN_LFE;
505 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
506 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
507 chans_out[6] = AOUT_CHAN_REARLEFT;
508 chans_out[7] = AOUT_CHAN_REARRIGHT;
510 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
511 if (p_aout->sys->chans_to_reorder)
512 msg_Dbg(p_aout, "channel reordering needed");
517 /* Set up the format to be used */
518 DeviceFormat.mSampleRate = fmt->i_rate;
519 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
521 /* We use float 32 since this is VLC's endorsed format */
522 fmt->i_format = VLC_CODEC_FL32;
523 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
524 DeviceFormat.mBitsPerChannel = 32;
525 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
527 /* Calculate framesizes and stuff */
528 DeviceFormat.mFramesPerPacket = 1;
529 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
530 msg_Dbg(p_aout, "bytes per frame %i", DeviceFormat.mBytesPerFrame);
531 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
533 /* Set the desired format */
534 i_param_size = sizeof(AudioStreamBasicDescription);
535 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
536 kAudioUnitProperty_StreamFormat,
537 kAudioUnitScope_Input,
542 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
544 /* Retrieve actual format */
545 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
546 kAudioUnitProperty_StreamFormat,
547 kAudioUnitScope_Input,
552 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
554 /* Do the last VLC aout setups */
555 aout_FormatPrepare(fmt);
557 /* set the IOproc callback */
558 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
559 input.inputProcRefCon = p_aout;
561 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
562 kAudioUnitProperty_SetRenderCallback,
563 kAudioUnitScope_Input,
564 0, &input, sizeof(input)));
566 /* Set the new_layout as the layout VLC will use to feed the AU unit */
567 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
568 kAudioUnitProperty_AudioChannelLayout,
569 kAudioUnitScope_Output,
570 0, &new_layout, sizeof(new_layout)));
572 if (new_layout.mNumberChannelDescriptions > 0)
573 free(new_layout.mChannelDescriptions);
576 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
578 /* Find the difference between device clock and mdate clock */
579 p_sys->clock_diff = - (mtime_t)
580 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
581 p_sys->clock_diff += mdate();
584 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
586 /* Set volume for output unit */
587 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
588 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
589 kHALOutputParam_Volume,
590 kAudioUnitScope_Global,
592 volume * volume * volume,
595 p_aout->time_get = TimeGet;
596 p_aout->play = PlayAnalog;
597 p_aout->pause = NULL;
598 p_aout->flush = FlushAnalog;
603 /*****************************************************************************
604 * Setup a encoded digital stream (SPDIF)
605 *****************************************************************************/
606 static int OpenSPDIF (audio_output_t * p_aout, audio_sample_format_t *fmt)
608 struct aout_sys_t *p_sys = p_aout->sys;
609 OSStatus err = noErr;
610 UInt32 i_param_size = 0, b_mix = 0;
611 Boolean b_writeable = false;
612 AudioStreamID *p_streams = NULL;
613 unsigned i_streams = 0;
615 /* Start doing the SPDIF setup proces */
616 p_sys->b_digital = true;
619 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
620 i_param_size = sizeof(p_sys->i_hog_pid);
621 p_sys->i_hog_pid = getpid() ;
623 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
626 msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
630 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
632 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
633 /* Set mixable to false if we are allowed to */
634 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
635 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
636 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
638 if (err == noErr && b_writeable) {
640 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
641 p_sys->b_changed_mixing = true;
645 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
650 /* Get a list of all the streams on this device */
651 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
652 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
654 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
658 i_streams = i_param_size / sizeof(AudioStreamID);
659 p_streams = (AudioStreamID *)malloc(i_param_size);
660 if (p_streams == NULL)
663 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
666 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
671 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
672 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
673 /* Find a stream with a cac3 stream */
674 AudioStreamRangedDescription *p_format_list = NULL;
676 bool b_digital = false;
678 /* Retrieve all the stream formats supported by each output stream */
679 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
681 msg_Err(p_aout, "OpenSPDIF: could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
685 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
686 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
687 if (p_format_list == NULL)
690 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
692 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
697 /* Check if one of the supported formats is a digital format */
698 for (int j = 0; j < i_formats; j++) {
699 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
700 p_format_list[j].mFormat.mFormatID == 'iac3' ||
701 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
702 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
709 /* if this stream supports a digital (cac3) format, then go set it. */
710 int i_requested_rate_format = -1;
711 int i_current_rate_format = -1;
712 int i_backup_rate_format = -1;
714 p_sys->i_stream_id = p_streams[i];
715 p_sys->i_stream_index = i;
717 if (!p_sys->b_revert) {
718 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
719 /* Retrieve the original format of this stream first if not done so already */
720 i_param_size = sizeof(p_sys->sfmt_revert);
721 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
723 msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
726 p_sys->b_revert = true;
729 for (int j = 0; j < i_formats; j++) {
730 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
731 p_format_list[j].mFormat.mFormatID == 'iac3' ||
732 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
733 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
734 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
735 i_requested_rate_format = j;
737 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
738 i_current_rate_format = j;
740 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
741 i_backup_rate_format = j;
747 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
748 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
749 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
750 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
752 p_sys->stream_format = p_format_list[i_backup_rate_format].mFormat; /* And if we have to, any digital format will be just fine (highest rate possible) */
758 /* get notified when we don't have spdif-output anymore */
759 err = AudioObjectAddPropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
761 msg_Warn(p_aout, "could not set audio device property streams callback on device: %4.4s",
765 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
767 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
770 /* Set the format flags */
771 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
772 fmt->i_format = VLC_CODEC_SPDIFB;
774 fmt->i_format = VLC_CODEC_SPDIFL;
775 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
776 fmt->i_frame_length = A52_FRAME_NB;
777 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
778 aout_FormatPrepare(fmt);
779 aout_PacketInit(p_aout, &p_sys->packet, A52_FRAME_NB, fmt);
781 /* Add IOProc callback */
782 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
783 (AudioDeviceIOProc)RenderCallbackSPDIF,
787 msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
788 aout_PacketDestroy (p_aout);
792 /* Check for the difference between the Device clock and mdate */
793 p_sys->clock_diff = - (mtime_t)
794 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
795 p_sys->clock_diff += mdate();
798 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
800 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
802 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
804 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
806 aout_PacketDestroy (p_aout);
814 /*****************************************************************************
815 * Close: Close HAL AudioUnit
816 *****************************************************************************/
817 static void Stop(audio_output_t *p_aout)
819 struct aout_sys_t *p_sys = p_aout->sys;
820 OSStatus err = noErr;
821 UInt32 i_param_size = 0;
823 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
824 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, NULL);
826 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
828 if (p_sys->b_digital) {
829 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
830 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, NULL);
832 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
835 if (p_sys->au_unit) {
836 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
837 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
838 verify_noerr(CloseComponent(p_sys->au_unit));
841 if (p_sys->b_digital) {
843 err = AudioDeviceStop(p_sys->i_selected_dev,
846 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
848 /* Remove IOProc callback */
849 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
852 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
855 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
857 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
859 Boolean b_writeable = false;
860 /* Revert mixable to true if we are allowed to */
861 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
862 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
863 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
865 if (err == noErr && b_writeable) {
866 msg_Dbg(p_aout, "mixable is: %d", b_mix);
868 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
872 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
876 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
877 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, NULL);
880 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
882 if (p_sys->i_hog_pid == getpid()) {
883 p_sys->i_hog_pid = -1;
884 i_param_size = sizeof(p_sys->i_hog_pid);
885 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
886 kAudioDevicePropertyScopeOutput,
887 kAudioObjectPropertyElementMaster };
888 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
890 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
893 var_DelCallback(p_aout, "audio-device", AudioDeviceCallback, NULL);
895 /* clean-up circular buffer */
896 TPCircularBufferCleanup(&p_sys->circular_buffer);
898 if (p_sys->b_digital)
899 aout_PacketDestroy(p_aout);
902 /*****************************************************************************
903 * Probe: Check which devices the OS has, and add them to our audio-device menu
904 *****************************************************************************/
905 static void Probe(audio_output_t * p_aout)
907 OSStatus err = noErr;
908 UInt32 i_param_size = 0;
909 AudioDeviceID devid_def = 0;
910 AudioDeviceID *p_devices = NULL;
911 vlc_value_t val, text;
913 struct aout_sys_t *p_sys = p_aout->sys;
915 /* Get number of devices */
916 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
917 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &i_param_size);
919 msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
923 p_sys->i_devices = i_param_size / sizeof(AudioDeviceID);
925 if (p_sys->i_devices < 1) {
926 msg_Err(p_aout, "No audio output devices were found.");
929 msg_Dbg(p_aout, "found %u audio device(s)", (unsigned)p_sys->i_devices);
931 /* Allocate DeviceID array */
932 p_devices = (AudioDeviceID*)malloc(sizeof(AudioDeviceID) * p_sys->i_devices);
933 if (p_devices == NULL)
936 /* Populate DeviceID array */
937 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &i_param_size, p_devices);
939 msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
943 /* Find the ID of the default Device */
944 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
945 i_param_size = sizeof(AudioDeviceID);
946 err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &i_param_size, &devid_def);
948 msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
951 p_sys->i_default_dev = devid_def;
953 var_Create(p_aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
954 text.psz_string = (char*)_("Audio Device");
955 var_Change(p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
957 AudioObjectPropertyAddress deviceNameAddress = { kAudioDevicePropertyDeviceName, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
959 for (unsigned int i = 0; i < p_sys->i_devices; i++) {
963 /* Retrieve the length of the device name */
964 err = AudioObjectGetPropertyDataSize(p_devices[i], &deviceNameAddress, 0, NULL, &i_param_size);
968 /* Retrieve the name of the device */
969 psz_name = (char *)malloc(i_param_size);
970 err = AudioObjectGetPropertyData(p_devices[i], &deviceNameAddress, 0, NULL, &i_param_size, psz_name);
974 msg_Dbg(p_aout, "DevID: %u DevName: %s", (unsigned)p_devices[i], psz_name);
976 if (!AudioDeviceHasOutput(p_devices[i])) {
977 msg_Dbg(p_aout, "this device is INPUT only. skipping...");
982 /* Add the menu entries */
983 val.i_int = (int)p_devices[i];
984 text.psz_string = psz_name;
985 var_Change(p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
986 text.psz_string = NULL;
987 if (p_sys->i_default_dev == p_devices[i]) {
988 /* The default device is the selected device normally */
989 var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
990 var_Set(p_aout, "audio-device", val);
993 if (AudioDeviceSupportsDigital(p_aout, p_devices[i])) {
994 val.i_int = (int)p_devices[i] | AOUT_VAR_SPDIF_FLAG;
995 if (asprintf(&text.psz_string, _("%s (Encoded Output)"), psz_name) != -1) {
996 var_Change(p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
997 free(text.psz_string);
998 if (p_sys->i_default_dev == p_devices[i] && var_InheritBool(p_aout, "spdif")) {
999 /* We selected to prefer SPDIF output if available
1000 * then this "dummy" entry should be selected */
1001 var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
1002 var_Set(p_aout, "audio-device", val);
1010 /* If a device is already "preselected", then use this device */
1011 var_Get(p_aout->p_libvlc, "macosx-audio-device", &val);
1012 if (val.i_int > 0) {
1013 msg_Dbg(p_aout, "using preselected output device %#"PRIx64, val.i_int);
1014 var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
1015 var_Set(p_aout, "audio-device", val);
1018 /* Attach a Listener so that we are notified of a change in the Device setup */
1019 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
1021 msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
1029 msg_Warn(p_aout, "audio device already in use");
1034 /*****************************************************************************
1035 * AudioDeviceHasOutput: Checks if the Device actually provides any outputs at all
1036 *****************************************************************************/
1037 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1041 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1042 verify_noerr(AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize));
1049 /*****************************************************************************
1050 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
1051 *****************************************************************************/
1052 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1054 OSStatus err = noErr;
1055 UInt32 i_param_size = 0;
1056 AudioStreamID *p_streams = NULL;
1058 bool b_return = false;
1060 /* Retrieve all the output streams */
1061 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1062 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1064 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1068 i_streams = i_param_size / sizeof(AudioStreamID);
1069 p_streams = (AudioStreamID *)malloc(i_param_size);
1070 if (p_streams == NULL)
1073 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1075 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1079 for (int i = 0; i < i_streams; i++) {
1080 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1088 /*****************************************************************************
1089 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
1090 *****************************************************************************/
1091 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1093 OSStatus err = noErr;
1094 UInt32 i_param_size = 0;
1095 AudioStreamRangedDescription *p_format_list = NULL;
1097 bool b_return = false;
1099 /* Retrieve all the stream formats supported by each output stream */
1100 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1101 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1103 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1107 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1108 msg_Dbg(p_aout, "found %i stream formats", i_formats);
1110 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1111 if (p_format_list == NULL)
1114 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1116 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1117 free(p_format_list);
1118 p_format_list = NULL;
1122 for (int i = 0; i < i_formats; i++) {
1124 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1127 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1128 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1129 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1130 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1134 free(p_format_list);
1138 /*****************************************************************************
1139 * AudioStreamChangeFormat: Change i_stream_id to change_format
1140 *****************************************************************************/
1141 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1143 OSStatus err = noErr;
1144 UInt32 i_param_size = 0;
1146 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1148 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1150 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1152 /* Condition because SetProperty is asynchronious */
1153 vlc_cond_init(&w.cond);
1154 vlc_mutex_init(&w.lock);
1155 vlc_mutex_lock(&w.lock);
1157 /* Install the callback */
1158 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1160 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1164 /* change the format */
1165 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1168 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1172 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1173 * it is also not atomic in its behaviour.
1174 * Therefore we check 5 times before we really give up.
1175 * FIXME: failing isn't actually implemented yet. */
1176 for (int i = 0; i < 5; i++) {
1177 AudioStreamBasicDescription actual_format;
1178 mtime_t timeout = mdate() + 500000;
1180 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1181 msg_Dbg(p_aout, "reached timeout");
1183 i_param_size = sizeof(AudioStreamBasicDescription);
1184 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1186 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1187 if (actual_format.mSampleRate == change_format.mSampleRate &&
1188 actual_format.mFormatID == change_format.mFormatID &&
1189 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1190 /* The right format is now active */
1193 /* We need to check again */
1196 /* Removing the property listener */
1197 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1199 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1203 /* Destroy the lock and condition */
1204 vlc_mutex_unlock(&w.lock);
1205 vlc_mutex_destroy(&w.lock);
1206 vlc_cond_destroy(&w.cond);
1211 static void PlayAnalog (audio_output_t * p_aout, block_t * p_block)
1213 struct aout_sys_t *p_sys = p_aout->sys;
1215 if (p_block->i_nb_samples > 0) {
1216 /* Do the channel reordering */
1217 if (p_sys->chans_to_reorder)
1219 aout_ChannelReorder(p_block->p_buffer,
1221 p_sys->chans_to_reorder,
1226 /* Render audio into buffer */
1227 AudioBufferList bufferList;
1228 bufferList.mNumberBuffers = 1;
1229 bufferList.mBuffers[0].mNumberChannels = p_sys->i_numberOfChannels;
1230 bufferList.mBuffers[0].mData = malloc(p_block->i_nb_samples * sizeof(Float32) * p_sys->i_numberOfChannels);
1231 bufferList.mBuffers[0].mDataByteSize = p_block->i_nb_samples * sizeof(Float32) * p_sys->i_numberOfChannels;
1233 memcpy(bufferList.mBuffers[0].mData, p_block->p_buffer, p_block->i_buffer);
1235 /* move data to buffer */
1236 TPCircularBufferProduceBytes(&p_sys->circular_buffer, bufferList.mBuffers[0].mData, bufferList.mBuffers[0].mDataByteSize);
1239 block_Release(p_block);
1242 static void FlushAnalog(audio_output_t *p_aout, bool wait)
1245 AudioUnitReset(p_aout->sys->au_unit, kAudioUnitScope_Global, 0);
1248 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1256 /*****************************************************************************
1257 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1258 * us to provide some more audio data.
1259 * Don't print anything during normal playback, calling blocking function from
1260 * this callback is not allowed.
1261 *****************************************************************************/
1262 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1263 AudioUnitRenderActionFlags *ioActionFlags,
1264 const AudioTimeStamp *inTimeStamp,
1266 UInt32 inNumberFrames,
1267 AudioBufferList *ioData) {
1268 VLC_UNUSED(ioActionFlags);
1269 VLC_UNUSED(inTimeStamp);
1270 VLC_UNUSED(inBusNumber);
1271 VLC_UNUSED(inNumberFrames);
1273 audio_output_t * p_aout = (audio_output_t *)p_obj;
1274 struct aout_sys_t * p_sys = p_aout->sys;
1276 int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1277 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1279 /* Pull audio from buffer */
1280 int32_t availableBytes;
1281 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1282 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1283 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1288 /*****************************************************************************
1289 * RenderCallbackSPDIF: callback for SPDIF audio output
1290 *****************************************************************************/
1291 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1292 const AudioTimeStamp * inNow,
1293 const void * inInputData,
1294 const AudioTimeStamp * inInputTime,
1295 AudioBufferList * outOutputData,
1296 const AudioTimeStamp * inOutputTime,
1297 void * threadGlobals)
1300 mtime_t current_date;
1302 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1303 struct aout_sys_t * p_sys = p_aout->sys;
1305 VLC_UNUSED(inDevice);
1306 VLC_UNUSED(inInputData);
1307 VLC_UNUSED(inInputTime);
1309 /* Check for the difference between the Device clock and mdate */
1310 p_sys->clock_diff = - (mtime_t)
1311 AudioConvertHostTimeToNanos(inNow->mHostTime) / 1000;
1312 p_sys->clock_diff += mdate();
1314 current_date = p_sys->clock_diff +
1315 AudioConvertHostTimeToNanos(inOutputTime->mHostTime) / 1000;
1316 //- ((mtime_t) 1000000 / p_aout->format.i_rate * 31); // 31 = Latency in Frames. retrieve somewhere
1318 p_buffer = aout_PacketNext(p_aout, current_date);
1320 #define BUFFER outOutputData->mBuffers[p_sys->i_stream_index]
1321 if (p_buffer != NULL) {
1322 if ((int)BUFFER.mDataByteSize != (int)p_buffer->i_buffer)
1323 msg_Warn(p_aout, "bytesize: %d nb_bytes: %d", (int)BUFFER.mDataByteSize, (int)p_buffer->i_buffer);
1325 /* move data into output data buffer */
1326 memcpy(BUFFER.mData, p_buffer->p_buffer, p_buffer->i_buffer);
1327 block_Release(p_buffer);
1330 memset(BUFFER.mData, 0, BUFFER.mDataByteSize);
1336 /*****************************************************************************
1337 * HardwareListener: Warns us of changes in the list of registered devices
1338 *****************************************************************************/
1339 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1341 OSStatus err = noErr;
1342 audio_output_t *p_aout = (audio_output_t *)inClientData;
1343 VLC_UNUSED(inObjectID);
1345 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1346 if (inAddresses[i].mSelector == kAudioHardwarePropertyDevices) {
1347 /* something changed in the list of devices */
1348 /* We trigger the audio-device's aout_ChannelsRestart callback */
1349 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1350 var_TriggerCallback(p_aout, "audio-device");
1351 var_Destroy(p_aout, "audio-device");
1352 } else if (inAddresses[i].mSelector == kAudioDevicePropertyDeviceIsAlive) {
1353 msg_Warn(p_aout, "audio device died, resetting aout");
1354 var_TriggerCallback(p_aout, "audio-device");
1355 var_Destroy(p_aout, "audio-device");
1356 } else if (inAddresses[i].mSelector == kAudioStreamPropertyAvailablePhysicalFormats) {
1357 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1358 var_TriggerCallback(p_aout, "audio-device");
1359 var_Destroy(p_aout, "audio-device");
1366 /*****************************************************************************
1368 *****************************************************************************/
1369 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1371 OSStatus err = noErr;
1372 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1374 VLC_UNUSED(inObjectID);
1376 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1377 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1378 vlc_mutex_lock(&w->lock);
1379 vlc_cond_signal(&w->cond);
1380 vlc_mutex_unlock(&w->lock);
1387 /*****************************************************************************
1388 * AudioDeviceCallback: Callback triggered when the audio-device variable is changed
1389 *****************************************************************************/
1390 static int AudioDeviceCallback(vlc_object_t *p_this, const char *psz_variable,
1391 vlc_value_t old_val, vlc_value_t new_val, void *param)
1393 audio_output_t *p_aout = (audio_output_t *)p_this;
1394 var_Set(p_aout->p_libvlc, "macosx-audio-device", new_val);
1395 msg_Dbg(p_aout, "Set Device: %#"PRIx64, new_val.i_int);
1396 return aout_ChannelsRestart(p_this, psz_variable, old_val, new_val, param);
1400 /*****************************************************************************
1401 * VolumeSet: Implements volume_set(). Update the CoreAudio AU volume immediately.
1402 *****************************************************************************/
1403 static int VolumeSet(audio_output_t * p_aout, float volume)
1405 struct aout_sys_t *p_sys = p_aout->sys;
1408 aout_VolumeReport(p_aout, volume);
1410 /* Set volume for output unit */
1411 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1412 kHALOutputParam_Volume,
1413 kAudioUnitScope_Global,
1415 volume * volume * volume,
1418 if (var_InheritBool(p_aout, "volume-save"))
1419 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1424 static int MuteSet(audio_output_t * p_aout, bool mute)
1426 struct aout_sys_t *p_sys = p_aout->sys;
1429 aout_MuteReport(p_aout, mute);
1434 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1436 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1437 kHALOutputParam_Volume,
1438 kAudioUnitScope_Global,
1440 volume * volume * volume,
1446 static int Open(vlc_object_t *obj)
1448 audio_output_t *aout = (audio_output_t *)obj;
1449 aout_sys_t *sys = malloc(sizeof (*sys));
1451 if (unlikely(sys == NULL))
1454 aout->start = Start;
1456 aout->volume_set = VolumeSet;
1457 aout->mute_set = MuteSet;
1459 /* remember the volume */
1460 aout_VolumeReport(aout, var_InheritInteger(aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
1461 MuteSet(aout, var_InheritBool(aout, "mute"));
1466 static void Close(vlc_object_t *obj)
1468 audio_output_t *aout = (audio_output_t *)obj;
1469 aout_sys_t *sys = aout->sys;