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>
44 # define verify_noerr(a) assert((a) == noErr)
47 #define STREAM_FORMAT_MSG(pre, sfm) \
48 pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
49 sfm.mSampleRate, (char *)&sfm.mFormatID, \
50 (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
51 (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
52 (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
54 #define FRAMESIZE 2048
55 #define BUFSIZE (FRAMESIZE * 8) * 8
56 #define AOUT_VAR_SPDIF_FLAG 0xf00000
58 #define AOUT_VOLUME_DEFAULT 256
59 #define AOUT_VOLUME_MAX 512
62 /*****************************************************************************
63 * aout_sys_t: private audio output method descriptor
64 *****************************************************************************
65 * This structure is part of the audio output thread descriptor.
66 * It describes the CoreAudio specific properties of an output thread.
67 *****************************************************************************/
71 AudioDeviceID i_default_dev; /* DeviceID of defaultOutputDevice */
72 AudioDeviceID i_selected_dev; /* DeviceID of the selected device */
73 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
74 UInt32 i_devices; /* Number of CoreAudio Devices */
75 bool b_digital; /* Are we running in digital mode? */
76 mtime_t clock_diff; /* Difference between VLC clock and Device clock */
78 uint8_t chans_to_reorder; /* do we need channel reordering */
79 uint8_t chan_table[AOUT_CHAN_MAX];
82 Component au_component; /* The Audiocomponent we use */
83 AudioUnit au_unit; /* The AudioUnit we use */
84 uint8_t p_remainder_buffer[BUFSIZE];
85 uint32_t i_read_bytes;
86 uint32_t i_total_bytes;
88 /* CoreAudio SPDIF mode specific */
89 pid_t i_hog_pid; /* The keep the pid of our hog status */
90 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
91 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
92 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
93 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
94 bool b_revert; /* Wether we need to revert the stream format */
95 bool b_changed_mixing; /* Wether we need to set the mixing mode back */
98 /*****************************************************************************
100 *****************************************************************************/
101 static int Open (vlc_object_t *);
102 static int OpenAnalog (audio_output_t *, audio_sample_format_t *);
103 static int OpenSPDIF (audio_output_t *, audio_sample_format_t *);
104 static void Close (vlc_object_t *);
106 static void Probe (audio_output_t *);
108 static int AudioDeviceHasOutput (AudioDeviceID);
109 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
110 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
111 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
113 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
114 unsigned int, unsigned int, AudioBufferList *);
115 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
116 AudioBufferList *, const AudioTimeStamp *, void *);
117 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
118 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
119 static int AudioDeviceCallback (vlc_object_t *, const char *,
120 vlc_value_t, vlc_value_t, void *);
122 static int VolumeSet (audio_output_t *, float);
123 static int MuteSet (audio_output_t *, bool);
126 /*****************************************************************************
128 *****************************************************************************/
129 #define ADEV_TEXT N_("Audio Device")
130 #define ADEV_LONGTEXT N_("Choose a number corresponding to the number of an " \
131 "audio device, as listed in your 'Audio Device' menu. This device will " \
132 "then be used by default for audio playback.")
134 #define VOLUME_TEXT N_("Audio volume")
135 #define VOLUME_LONGTEXT VOLUME_TEXT
138 set_shortname("auhal")
139 set_description(N_("HAL AudioUnit output"))
140 set_capability("audio output", 101)
141 set_category(CAT_AUDIO)
142 set_subcategory(SUBCAT_AUDIO_AOUT)
143 set_callbacks(Open, Close)
144 add_integer("macosx-audio-device", 0, ADEV_TEXT, ADEV_LONGTEXT, false)
145 add_integer( "auhal-volume", AOUT_VOLUME_DEFAULT,
146 VOLUME_TEXT, VOLUME_LONGTEXT, true )
147 change_integer_range( 0, AOUT_VOLUME_MAX )
150 /*****************************************************************************
151 * Open: open macosx audio output
152 *****************************************************************************/
153 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
155 OSStatus err = noErr;
156 UInt32 i_param_size = 0;
157 struct aout_sys_t *p_sys = NULL;
160 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
165 p_sys->i_default_dev = 0;
166 p_sys->i_selected_dev = 0;
167 p_sys->i_devices = 0;
168 p_sys->b_digital = false;
169 p_sys->au_component = NULL;
170 p_sys->au_unit = NULL;
171 p_sys->clock_diff = (mtime_t) 0;
172 p_sys->i_read_bytes = 0;
173 p_sys->i_total_bytes = 0;
174 p_sys->i_hog_pid = -1;
175 p_sys->i_stream_id = 0;
176 p_sys->i_stream_index = -1;
177 p_sys->b_revert = false;
178 p_sys->b_changed_mixing = false;
179 memset(p_sys->p_remainder_buffer, 0, sizeof(uint8_t) * BUFSIZE);
181 p_aout->time_get = aout_PacketTimeGet;
182 p_aout->play = aout_PacketPlay;
183 p_aout->pause = NULL;
184 p_aout->flush = aout_PacketFlush;
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 /* Check for Digital mode or Analog output mode */
258 if (AOUT_FMT_SPDIF (fmt) && b_supports_digital) {
259 if (OpenSPDIF (p_aout, fmt)) {
260 msg_Dbg(p_aout, "digital output successfully opened");
264 if (OpenAnalog(p_aout, fmt)) {
265 msg_Dbg(p_aout, "analog output successfully opened");
271 /* If we reach this, this aout has failed */
272 msg_Err(p_aout, "opening the auhal output failed");
273 var_Destroy(p_aout, "audio-device");
277 /*****************************************************************************
278 * Open: open and setup a HAL AudioUnit to do analog (multichannel) audio output
279 *****************************************************************************/
280 static int OpenAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
282 struct aout_sys_t *p_sys = p_aout->sys;
283 OSStatus err = noErr;
284 UInt32 i_param_size = 0;
286 ComponentDescription desc;
287 AudioStreamBasicDescription DeviceFormat;
288 AudioChannelLayout *layout;
289 AudioChannelLayout new_layout;
290 AURenderCallbackStruct input;
292 /* Lets go find our Component */
293 desc.componentType = kAudioUnitType_Output;
294 desc.componentSubType = kAudioUnitSubType_HALOutput;
295 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
296 desc.componentFlags = 0;
297 desc.componentFlagsMask = 0;
299 p_sys->au_component = FindNextComponent(NULL, &desc);
300 if (p_sys->au_component == NULL) {
301 msg_Warn(p_aout, "we cannot find our HAL component");
305 err = OpenAComponent(p_sys->au_component, &p_sys->au_unit);
307 msg_Warn(p_aout, "we cannot open our HAL component");
311 /* Set the device we will use for this output unit */
312 err = AudioUnitSetProperty(p_sys->au_unit,
313 kAudioOutputUnitProperty_CurrentDevice,
314 kAudioUnitScope_Global,
316 &p_sys->i_selected_dev,
317 sizeof(AudioDeviceID));
320 msg_Warn(p_aout, "we cannot select the audio device");
324 /* Get the current format */
325 i_param_size = sizeof(AudioStreamBasicDescription);
327 err = AudioUnitGetProperty(p_sys->au_unit,
328 kAudioUnitProperty_StreamFormat,
329 kAudioUnitScope_Input,
337 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
339 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
340 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
341 kAudioDevicePropertyPreferredChannelLayout,
342 kAudioUnitScope_Output,
348 layout = (AudioChannelLayout *)malloc(i_param_size);
350 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
351 kAudioDevicePropertyPreferredChannelLayout,
352 kAudioUnitScope_Output,
357 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
358 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
359 /* bitmap defined channellayout */
360 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
361 sizeof(UInt32), &layout->mChannelBitmap,
364 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
366 /* layouttags defined channellayout */
367 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
368 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
373 msg_Dbg(p_aout, "layout of AUHAL has %d channels" , (int)layout->mNumberChannelDescriptions);
375 /* Initialize the VLC core channel count */
376 fmt->i_physical_channels = 0;
377 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
379 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
380 /* We only need Mono or cannot output more than 1 channel */
381 fmt->i_physical_channels = AOUT_CHAN_CENTER;
382 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
383 /* We only need Stereo or cannot output more than 2 channels */
384 fmt->i_physical_channels = AOUT_CHANS_STEREO;
386 /* We want more than stereo and we can do that */
387 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
389 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
392 switch(layout->mChannelDescriptions[i].mChannelLabel) {
393 case kAudioChannelLabel_Left:
394 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
396 case kAudioChannelLabel_Right:
397 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
399 case kAudioChannelLabel_Center:
400 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
402 case kAudioChannelLabel_LFEScreen:
403 fmt->i_physical_channels |= AOUT_CHAN_LFE;
405 case kAudioChannelLabel_LeftSurround:
406 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
408 case kAudioChannelLabel_RightSurround:
409 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
411 case kAudioChannelLabel_RearSurroundLeft:
412 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
414 case kAudioChannelLabel_RearSurroundRight:
415 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
417 case kAudioChannelLabel_CenterSurround:
418 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
421 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
424 if (fmt->i_physical_channels == 0) {
425 fmt->i_physical_channels = AOUT_CHANS_STEREO;
426 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
427 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
428 _("You should configure your speaker layout with "
429 "the \"Audio Midi Setup\" utility in /Applications/"
430 "Utilities. Stereo mode is being used now."));
435 msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
436 fmt->i_physical_channels = AOUT_CHANS_STEREO;
439 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
440 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
442 memset (&new_layout, 0, sizeof(new_layout));
443 uint32_t chans_out[AOUT_CHAN_MAX];
445 switch(aout_FormatNbChannels(fmt)) {
447 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
450 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
453 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
454 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
455 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
456 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
459 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
460 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
461 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
462 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
463 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
464 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
467 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
468 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
469 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
470 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
473 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
474 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
476 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
479 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
481 chans_out[0] = AOUT_CHAN_LEFT;
482 chans_out[1] = AOUT_CHAN_RIGHT;
483 chans_out[2] = AOUT_CHAN_CENTER;
484 chans_out[3] = AOUT_CHAN_LFE;
485 chans_out[4] = AOUT_CHAN_REARLEFT;
486 chans_out[5] = AOUT_CHAN_REARRIGHT;
487 chans_out[6] = AOUT_CHAN_REARCENTER;
489 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder( NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table );
490 if (p_aout->sys->chans_to_reorder)
491 msg_Dbg( p_aout, "channel reordering needed" );
495 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
497 chans_out[0] = AOUT_CHAN_LEFT;
498 chans_out[1] = AOUT_CHAN_RIGHT;
499 chans_out[2] = AOUT_CHAN_CENTER;
500 chans_out[3] = AOUT_CHAN_LFE;
501 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
502 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
503 chans_out[6] = AOUT_CHAN_REARLEFT;
504 chans_out[7] = AOUT_CHAN_REARRIGHT;
506 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder( NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table );
507 if (p_aout->sys->chans_to_reorder)
508 msg_Dbg( p_aout, "channel reordering needed" );
513 /* Set up the format to be used */
514 DeviceFormat.mSampleRate = fmt->i_rate;
515 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
517 /* We use float 32. It's the best supported format by both VLC and Coreaudio */
518 fmt->i_format = VLC_CODEC_FL32;
519 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
520 DeviceFormat.mBitsPerChannel = 32;
521 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
523 /* Calculate framesizes and stuff */
524 DeviceFormat.mFramesPerPacket = 1;
525 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
526 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
528 /* Set the desired format */
529 i_param_size = sizeof(AudioStreamBasicDescription);
530 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
531 kAudioUnitProperty_StreamFormat,
532 kAudioUnitScope_Input,
537 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
539 /* Retrieve actual format */
540 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
541 kAudioUnitProperty_StreamFormat,
542 kAudioUnitScope_Input,
547 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
549 /* Do the last VLC aout setups */
550 aout_FormatPrepare(fmt);
551 aout_PacketInit(p_aout, &p_sys->packet, FRAMESIZE, fmt);
553 /* set the IOproc callback */
554 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
555 input.inputProcRefCon = p_aout;
557 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
558 kAudioUnitProperty_SetRenderCallback,
559 kAudioUnitScope_Input,
560 0, &input, sizeof(input)));
562 /* Set the new_layout as the layout VLC will use to feed the AU unit */
563 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
564 kAudioUnitProperty_AudioChannelLayout,
565 kAudioUnitScope_Output,
566 0, &new_layout, sizeof(new_layout)));
568 if (new_layout.mNumberChannelDescriptions > 0)
569 free(new_layout.mChannelDescriptions);
572 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
574 /* Find the difference between device clock and mdate clock */
575 p_sys->clock_diff = - (mtime_t)
576 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
577 p_sys->clock_diff += mdate();
580 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
582 /* Set volume for output unit */
583 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
584 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
585 kHALOutputParam_Volume,
586 kAudioUnitScope_Global,
588 volume * volume * volume,
594 /*****************************************************************************
595 * Setup a encoded digital stream (SPDIF)
596 *****************************************************************************/
597 static int OpenSPDIF (audio_output_t * p_aout, audio_sample_format_t *fmt)
599 struct aout_sys_t *p_sys = p_aout->sys;
600 OSStatus err = noErr;
601 UInt32 i_param_size = 0, b_mix = 0;
602 Boolean b_writeable = false;
603 AudioStreamID *p_streams = NULL;
604 unsigned i_streams = 0;
606 /* Start doing the SPDIF setup proces */
607 p_sys->b_digital = true;
610 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
611 i_param_size = sizeof(p_sys->i_hog_pid);
612 p_sys->i_hog_pid = getpid() ;
614 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
617 msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
621 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
623 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
624 /* Set mixable to false if we are allowed to */
625 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
626 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
627 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
629 if (err == noErr && b_writeable) {
631 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
632 p_sys->b_changed_mixing = true;
636 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
641 /* Get a list of all the streams on this device */
642 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
643 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
645 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
649 i_streams = i_param_size / sizeof(AudioStreamID);
650 p_streams = (AudioStreamID *)malloc(i_param_size);
651 if (p_streams == NULL)
654 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
657 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
662 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
663 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
664 /* Find a stream with a cac3 stream */
665 AudioStreamRangedDescription *p_format_list = NULL;
667 bool b_digital = false;
669 /* Retrieve all the stream formats supported by each output stream */
670 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
672 msg_Err(p_aout, "OpenSPDIF: could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
676 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
677 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
678 if (p_format_list == NULL)
681 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
683 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
688 /* Check if one of the supported formats is a digital format */
689 for (int j = 0; j < i_formats; j++) {
690 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
691 p_format_list[j].mFormat.mFormatID == 'iac3' ||
692 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
693 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
700 /* if this stream supports a digital (cac3) format, then go set it. */
701 int i_requested_rate_format = -1;
702 int i_current_rate_format = -1;
703 int i_backup_rate_format = -1;
705 p_sys->i_stream_id = p_streams[i];
706 p_sys->i_stream_index = i;
708 if (!p_sys->b_revert) {
709 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
710 /* Retrieve the original format of this stream first if not done so already */
711 i_param_size = sizeof(p_sys->sfmt_revert);
712 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
714 msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
717 p_sys->b_revert = true;
720 for (int j = 0; j < i_formats; j++) {
721 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
722 p_format_list[j].mFormat.mFormatID == 'iac3' ||
723 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
724 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
725 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
726 i_requested_rate_format = j;
728 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
729 i_current_rate_format = j;
731 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
732 i_backup_rate_format = j;
738 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
739 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
740 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
741 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
743 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) */
749 /* get notified when we don't have spdif-output anymore */
750 err = AudioObjectAddPropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
752 msg_Warn(p_aout, "could not set audio device property streams callback on device: %4.4s",
756 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
758 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
761 /* Set the format flags */
762 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
763 fmt->i_format = VLC_CODEC_SPDIFB;
765 fmt->i_format = VLC_CODEC_SPDIFL;
766 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
767 fmt->i_frame_length = A52_FRAME_NB;
768 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
769 aout_FormatPrepare(fmt);
770 aout_PacketInit(p_aout, &p_sys->packet, A52_FRAME_NB, fmt);
772 /* Add IOProc callback */
773 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
774 (AudioDeviceIOProc)RenderCallbackSPDIF,
778 msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
779 aout_PacketDestroy (p_aout);
783 /* Check for the difference between the Device clock and mdate */
784 p_sys->clock_diff = - (mtime_t)
785 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
786 p_sys->clock_diff += mdate();
789 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
791 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
793 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
795 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
797 aout_PacketDestroy (p_aout);
805 /*****************************************************************************
806 * Close: Close HAL AudioUnit
807 *****************************************************************************/
808 static void Stop(audio_output_t *p_aout)
810 struct aout_sys_t *p_sys = p_aout->sys;
811 OSStatus err = noErr;
812 UInt32 i_param_size = 0;
814 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
815 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, NULL);
817 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
819 if (p_sys->b_digital) {
820 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
821 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, NULL);
823 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
826 if (p_sys->au_unit) {
827 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
828 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
829 verify_noerr(CloseComponent(p_sys->au_unit));
832 if (p_sys->b_digital) {
834 err = AudioDeviceStop(p_sys->i_selected_dev,
837 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
839 /* Remove IOProc callback */
840 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
843 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
846 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
848 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
850 Boolean b_writeable = false;
851 /* Revert mixable to true if we are allowed to */
852 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
853 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
854 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
856 if (err == noErr && b_writeable) {
857 msg_Dbg(p_aout, "mixable is: %d", b_mix);
859 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
863 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
867 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
868 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, NULL);
871 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
873 if (p_sys->i_hog_pid == getpid()) {
874 p_sys->i_hog_pid = -1;
875 i_param_size = sizeof(p_sys->i_hog_pid);
876 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
877 kAudioDevicePropertyScopeOutput,
878 kAudioObjectPropertyElementMaster };
879 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
881 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
884 var_DelCallback(p_aout, "audio-device", AudioDeviceCallback, NULL);
886 aout_PacketDestroy(p_aout);
889 /*****************************************************************************
890 * Probe: Check which devices the OS has, and add them to our audio-device menu
891 *****************************************************************************/
892 static void Probe(audio_output_t * p_aout)
894 OSStatus err = noErr;
895 UInt32 i_param_size = 0;
896 AudioDeviceID devid_def = 0;
897 AudioDeviceID *p_devices = NULL;
898 vlc_value_t val, text;
900 struct aout_sys_t *p_sys = p_aout->sys;
902 /* Get number of devices */
903 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
904 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &i_param_size);
906 msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
910 p_sys->i_devices = i_param_size / sizeof(AudioDeviceID);
912 if (p_sys->i_devices < 1) {
913 msg_Err(p_aout, "No audio output devices were found.");
916 msg_Dbg(p_aout, "found %u audio device(s)", (unsigned)p_sys->i_devices);
918 /* Allocate DeviceID array */
919 p_devices = (AudioDeviceID*)malloc(sizeof(AudioDeviceID) * p_sys->i_devices);
920 if (p_devices == NULL)
923 /* Populate DeviceID array */
924 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &i_param_size, p_devices);
926 msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
930 /* Find the ID of the default Device */
931 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
932 i_param_size = sizeof(AudioDeviceID);
933 err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &i_param_size, &devid_def);
935 msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
938 p_sys->i_default_dev = devid_def;
940 var_Create(p_aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
941 text.psz_string = (char*)_("Audio Device");
942 var_Change(p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
944 AudioObjectPropertyAddress deviceNameAddress = { kAudioDevicePropertyDeviceName, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
946 for (unsigned int i = 0; i < p_sys->i_devices; i++) {
950 /* Retrieve the length of the device name */
951 err = AudioObjectGetPropertyDataSize(p_devices[i], &deviceNameAddress, 0, NULL, &i_param_size);
955 /* Retrieve the name of the device */
956 psz_name = (char *)malloc(i_param_size);
957 err = AudioObjectGetPropertyData(p_devices[i], &deviceNameAddress, 0, NULL, &i_param_size, psz_name);
961 msg_Dbg(p_aout, "DevID: %u DevName: %s", (unsigned)p_devices[i], psz_name);
963 if (!AudioDeviceHasOutput(p_devices[i])) {
964 msg_Dbg(p_aout, "this device is INPUT only. skipping...");
969 /* Add the menu entries */
970 val.i_int = (int)p_devices[i];
971 text.psz_string = psz_name;
972 var_Change(p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
973 text.psz_string = NULL;
974 if (p_sys->i_default_dev == p_devices[i]) {
975 /* The default device is the selected device normally */
976 var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
977 var_Set(p_aout, "audio-device", val);
980 if (AudioDeviceSupportsDigital(p_aout, p_devices[i])) {
981 val.i_int = (int)p_devices[i] | AOUT_VAR_SPDIF_FLAG;
982 if (asprintf(&text.psz_string, _("%s (Encoded Output)"), psz_name) != -1) {
983 var_Change(p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
984 free(text.psz_string);
985 if (p_sys->i_default_dev == p_devices[i] && var_InheritBool(p_aout, "spdif")) {
986 /* We selected to prefer SPDIF output if available
987 * then this "dummy" entry should be selected */
988 var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
989 var_Set(p_aout, "audio-device", val);
997 /* If a device is already "preselected", then use this device */
998 var_Get(p_aout->p_libvlc, "macosx-audio-device", &val);
1000 msg_Dbg(p_aout, "using preselected output device %#"PRIx64, val.i_int);
1001 var_Change(p_aout, "audio-device", VLC_VAR_SETDEFAULT, &val, NULL);
1002 var_Set(p_aout, "audio-device", val);
1005 /* Attach a Listener so that we are notified of a change in the Device setup */
1006 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
1008 msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
1016 msg_Warn(p_aout, "audio device already in use");
1021 /*****************************************************************************
1022 * AudioDeviceHasOutput: Checks if the Device actually provides any outputs at all
1023 *****************************************************************************/
1024 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1028 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1029 verify_noerr(AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize));
1036 /*****************************************************************************
1037 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
1038 *****************************************************************************/
1039 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1041 OSStatus err = noErr;
1042 UInt32 i_param_size = 0;
1043 AudioStreamID *p_streams = NULL;
1045 bool b_return = false;
1047 /* Retrieve all the output streams */
1048 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1049 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1051 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1055 i_streams = i_param_size / sizeof(AudioStreamID);
1056 p_streams = (AudioStreamID *)malloc(i_param_size);
1057 if (p_streams == NULL)
1060 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1062 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1066 for (int i = 0; i < i_streams; i++) {
1067 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1075 /*****************************************************************************
1076 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
1077 *****************************************************************************/
1078 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1080 OSStatus err = noErr;
1081 UInt32 i_param_size = 0;
1082 AudioStreamRangedDescription *p_format_list = NULL;
1084 bool b_return = false;
1086 /* Retrieve all the stream formats supported by each output stream */
1087 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1088 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1090 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1094 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1095 msg_Dbg(p_aout, "found %i stream formats", i_formats);
1097 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1098 if (p_format_list == NULL)
1101 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1103 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1104 free(p_format_list);
1105 p_format_list = NULL;
1109 for (int i = 0; i < i_formats; i++) {
1111 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1114 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1115 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1116 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1117 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1121 free(p_format_list);
1125 /*****************************************************************************
1126 * AudioStreamChangeFormat: Change i_stream_id to change_format
1127 *****************************************************************************/
1128 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1130 OSStatus err = noErr;
1131 UInt32 i_param_size = 0;
1133 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1135 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1137 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1139 /* Condition because SetProperty is asynchronious */
1140 vlc_cond_init(&w.cond);
1141 vlc_mutex_init(&w.lock);
1142 vlc_mutex_lock(&w.lock);
1144 /* Install the callback */
1145 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1147 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1151 /* change the format */
1152 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1155 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1159 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1160 * it is also not atomic in its behaviour.
1161 * Therefore we check 5 times before we really give up.
1162 * FIXME: failing isn't actually implemented yet. */
1163 for (int i = 0; i < 5; i++) {
1164 AudioStreamBasicDescription actual_format;
1165 mtime_t timeout = mdate() + 500000;
1167 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1168 msg_Dbg(p_aout, "reached timeout");
1170 i_param_size = sizeof(AudioStreamBasicDescription);
1171 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1173 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1174 if (actual_format.mSampleRate == change_format.mSampleRate &&
1175 actual_format.mFormatID == change_format.mFormatID &&
1176 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1177 /* The right format is now active */
1180 /* We need to check again */
1183 /* Removing the property listener */
1184 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1186 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1190 /* Destroy the lock and condition */
1191 vlc_mutex_unlock(&w.lock);
1192 vlc_mutex_destroy(&w.lock);
1193 vlc_cond_destroy(&w.cond);
1198 /*****************************************************************************
1199 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1200 * us to provide some more audio data.
1201 * Don't print anything during normal playback, calling blocking function from
1202 * this callback is not allowed.
1203 *****************************************************************************/
1204 static OSStatus RenderCallbackAnalog(vlc_object_t *_p_aout,
1205 AudioUnitRenderActionFlags *ioActionFlags,
1206 const AudioTimeStamp *inTimeStamp,
1207 unsigned int inBusNumber,
1208 unsigned int inNumberFrames,
1209 AudioBufferList *ioData)
1211 AudioTimeStamp host_time;
1212 mtime_t current_date = 0;
1213 uint32_t i_mData_bytes = 0;
1215 audio_output_t * p_aout = (audio_output_t *)_p_aout;
1216 struct aout_sys_t * p_sys = p_aout->sys;
1218 VLC_UNUSED(ioActionFlags);
1219 VLC_UNUSED(inBusNumber);
1220 VLC_UNUSED(inNumberFrames);
1222 host_time.mFlags = kAudioTimeStampHostTimeValid;
1223 AudioDeviceTranslateTime(p_sys->i_selected_dev, inTimeStamp, &host_time);
1225 /* Check for the difference between the Device clock and mdate */
1226 p_sys->clock_diff = - (mtime_t)
1227 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
1228 p_sys->clock_diff += mdate();
1230 current_date = p_sys->clock_diff +
1231 AudioConvertHostTimeToNanos(host_time.mHostTime) / 1000;
1232 //- ((mtime_t) 1000000 / p_aout->format.i_rate * 31); // 31 = Latency in Frames. retrieve somewhere
1234 if (ioData == NULL || ioData->mNumberBuffers < 1) {
1235 msg_Err(p_aout, "no iodata or buffers");
1238 if (ioData->mNumberBuffers > 1)
1239 msg_Err(p_aout, "well this is weird. seems like there is more than one buffer...");
1241 if (p_sys->i_total_bytes > 0) {
1242 i_mData_bytes = __MIN(p_sys->i_total_bytes - p_sys->i_read_bytes, ioData->mBuffers[0].mDataByteSize);
1243 memcpy(ioData->mBuffers[0].mData,
1244 &p_sys->p_remainder_buffer[p_sys->i_read_bytes],
1246 p_sys->i_read_bytes += i_mData_bytes;
1247 current_date += (mtime_t) ((mtime_t) 1000000 / p_sys->packet.format.i_rate) *
1248 (i_mData_bytes / 4 / aout_FormatNbChannels(&p_sys->packet.format)); // 4 is fl32 specific
1250 if (p_sys->i_read_bytes >= p_sys->i_total_bytes)
1251 p_sys->i_read_bytes = p_sys->i_total_bytes = 0;
1254 while(i_mData_bytes < ioData->mBuffers[0].mDataByteSize) {
1255 /* We don't have enough data yet */
1257 p_buffer = aout_PacketNext(p_aout, current_date);
1259 if (p_buffer != NULL)
1261 /* Do the channel reordering */
1262 if (p_buffer && p_sys->chans_to_reorder)
1264 aout_ChannelReorder(p_buffer->p_buffer,
1266 p_sys->chans_to_reorder,
1271 uint32_t i_second_mData_bytes = __MIN(p_buffer->i_buffer, ioData->mBuffers[0].mDataByteSize - i_mData_bytes);
1273 memcpy((uint8_t *)ioData->mBuffers[0].mData + i_mData_bytes,
1274 p_buffer->p_buffer, i_second_mData_bytes);
1275 i_mData_bytes += i_second_mData_bytes;
1277 if (i_mData_bytes >= ioData->mBuffers[0].mDataByteSize)
1279 p_sys->i_total_bytes = p_buffer->i_buffer - i_second_mData_bytes;
1280 memcpy(p_sys->p_remainder_buffer,
1281 &p_buffer->p_buffer[i_second_mData_bytes],
1282 p_sys->i_total_bytes);
1283 block_Release(p_buffer);
1286 /* update current_date */
1287 current_date += (mtime_t) ((mtime_t) 1000000 / p_sys->packet.format.i_rate) *
1288 (i_second_mData_bytes / 4 / aout_FormatNbChannels(&p_sys->packet.format)); // 4 is fl32 specific
1289 block_Release(p_buffer);
1291 memset((uint8_t *)ioData->mBuffers[0].mData +i_mData_bytes,
1292 0,ioData->mBuffers[0].mDataByteSize - i_mData_bytes);
1293 i_mData_bytes += ioData->mBuffers[0].mDataByteSize - i_mData_bytes;
1299 /*****************************************************************************
1300 * RenderCallbackSPDIF: callback for SPDIF audio output
1301 *****************************************************************************/
1302 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1303 const AudioTimeStamp * inNow,
1304 const void * inInputData,
1305 const AudioTimeStamp * inInputTime,
1306 AudioBufferList * outOutputData,
1307 const AudioTimeStamp * inOutputTime,
1308 void * threadGlobals)
1311 mtime_t current_date;
1313 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1314 struct aout_sys_t * p_sys = p_aout->sys;
1316 VLC_UNUSED(inDevice);
1317 VLC_UNUSED(inInputData);
1318 VLC_UNUSED(inInputTime);
1320 /* Check for the difference between the Device clock and mdate */
1321 p_sys->clock_diff = - (mtime_t)
1322 AudioConvertHostTimeToNanos(inNow->mHostTime) / 1000;
1323 p_sys->clock_diff += mdate();
1325 current_date = p_sys->clock_diff +
1326 AudioConvertHostTimeToNanos(inOutputTime->mHostTime) / 1000;
1327 //- ((mtime_t) 1000000 / p_aout->format.i_rate * 31); // 31 = Latency in Frames. retrieve somewhere
1329 p_buffer = aout_PacketNext(p_aout, current_date);
1331 #define BUFFER outOutputData->mBuffers[p_sys->i_stream_index]
1332 if (p_buffer != NULL) {
1333 if ((int)BUFFER.mDataByteSize != (int)p_buffer->i_buffer)
1334 msg_Warn(p_aout, "bytesize: %d nb_bytes: %d", (int)BUFFER.mDataByteSize, (int)p_buffer->i_buffer);
1336 /* move data into output data buffer */
1337 memcpy(BUFFER.mData, p_buffer->p_buffer, p_buffer->i_buffer);
1338 block_Release(p_buffer);
1341 memset(BUFFER.mData, 0, BUFFER.mDataByteSize);
1347 /*****************************************************************************
1348 * HardwareListener: Warns us of changes in the list of registered devices
1349 *****************************************************************************/
1350 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1352 OSStatus err = noErr;
1353 audio_output_t *p_aout = (audio_output_t *)inClientData;
1354 VLC_UNUSED(inObjectID);
1356 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1357 if (inAddresses[i].mSelector == kAudioHardwarePropertyDevices) {
1358 /* something changed in the list of devices */
1359 /* We trigger the audio-device's aout_ChannelsRestart callback */
1360 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1361 var_TriggerCallback(p_aout, "audio-device");
1362 var_Destroy(p_aout, "audio-device");
1363 } else if (inAddresses[i].mSelector == kAudioDevicePropertyDeviceIsAlive) {
1364 msg_Warn(p_aout, "audio device died, resetting aout");
1365 var_TriggerCallback(p_aout, "audio-device");
1366 var_Destroy(p_aout, "audio-device");
1367 } else if (inAddresses[i].mSelector == kAudioStreamPropertyAvailablePhysicalFormats) {
1368 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1369 var_TriggerCallback(p_aout, "audio-device");
1370 var_Destroy(p_aout, "audio-device");
1377 /*****************************************************************************
1379 *****************************************************************************/
1380 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1382 OSStatus err = noErr;
1383 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1385 VLC_UNUSED(inObjectID);
1387 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1388 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1389 vlc_mutex_lock(&w->lock);
1390 vlc_cond_signal(&w->cond);
1391 vlc_mutex_unlock(&w->lock);
1398 /*****************************************************************************
1399 * AudioDeviceCallback: Callback triggered when the audio-device variable is changed
1400 *****************************************************************************/
1401 static int AudioDeviceCallback(vlc_object_t *p_this, const char *psz_variable,
1402 vlc_value_t old_val, vlc_value_t new_val, void *param)
1404 audio_output_t *p_aout = (audio_output_t *)p_this;
1405 var_Set(p_aout->p_libvlc, "macosx-audio-device", new_val);
1406 msg_Dbg(p_aout, "Set Device: %#"PRIx64, new_val.i_int);
1407 return aout_ChannelsRestart(p_this, psz_variable, old_val, new_val, param);
1411 /*****************************************************************************
1412 * VolumeSet: Implements volume_set(). Update the CoreAudio AU volume immediately.
1413 *****************************************************************************/
1414 static int VolumeSet(audio_output_t * p_aout, float volume)
1416 struct aout_sys_t *p_sys = p_aout->sys;
1419 aout_VolumeReport(p_aout, volume);
1421 /* Set volume for output unit */
1422 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1423 kHALOutputParam_Volume,
1424 kAudioUnitScope_Global,
1426 volume * volume * volume,
1429 if (var_InheritBool(p_aout, "volume-save"))
1430 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1435 static int MuteSet(audio_output_t * p_aout, bool mute)
1437 struct aout_sys_t *p_sys = p_aout->sys;
1440 aout_MuteReport(p_aout, mute);
1445 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1447 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1448 kHALOutputParam_Volume,
1449 kAudioUnitScope_Global,
1451 volume * volume * volume,
1457 static int Open(vlc_object_t *obj)
1459 audio_output_t *aout = (audio_output_t *)obj;
1460 aout_sys_t *sys = malloc(sizeof (*sys));
1462 if (unlikely(sys == NULL))
1465 aout->start = Start;
1467 aout->volume_set = VolumeSet;
1468 aout->mute_set = MuteSet;
1470 /* remember the volume */
1471 aout_VolumeReport(aout, var_InheritInteger(aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
1472 MuteSet(aout, var_InheritBool(aout, "mute"));
1477 static void Close(vlc_object_t *obj)
1479 audio_output_t *aout = (audio_output_t *)obj;
1480 aout_sys_t *sys = aout->sys;