1 /*****************************************************************************
2 * auhal.c: AUHAL and Coreaudio output plugin
3 *****************************************************************************
4 * Copyright (C) 2005 - 2013 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 AOUT_VAR_SPDIF_FLAG 0xf00000
58 #define kBufferLength 2048 * 8 * 8 * 4
60 #define AOUT_VOLUME_DEFAULT 256
61 #define AOUT_VOLUME_MAX 512
64 /*****************************************************************************
65 * aout_sys_t: private audio output method descriptor
66 *****************************************************************************
67 * This structure is part of the audio output thread descriptor.
68 * It describes the CoreAudio specific properties of an output thread.
69 *****************************************************************************/
72 AudioObjectID i_default_dev; /* DeviceID of defaultOutputDevice */
73 AudioObjectID i_selected_dev; /* DeviceID of the selected device */
74 bool b_selected_dev_is_digital;
75 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
76 bool b_digital; /* Are we running in digital mode? */
77 mtime_t clock_diff; /* Difference between VLC clock and Device clock */
79 uint8_t chans_to_reorder; /* do we need channel reordering */
80 uint8_t chan_table[AOUT_CHAN_MAX];
82 UInt32 i_numberOfChannels;
83 TPCircularBuffer circular_buffer; /* circular buffer to swap the audio data */
86 AudioComponent au_component; /* The AudioComponent we use */
87 AudioUnit au_unit; /* The AudioUnit we use */
89 /* CoreAudio SPDIF mode specific */
90 pid_t i_hog_pid; /* The keep the pid of our hog status */
91 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
92 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
93 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
94 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
95 bool b_revert; /* Whether we need to revert the stream format */
96 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
97 bool b_got_first_sample; /* did the aout core provide something to render? */
99 int i_rate; /* media sample rate */
100 mtime_t i_played_length; /* how much did we play already */
101 mtime_t i_last_sample_time; /* last sample time played by the AudioUnit */
103 struct audio_device_t *devices;
108 struct audio_device_t
110 struct audio_device_t *next;
115 /*****************************************************************************
117 *****************************************************************************/
118 static int Open (vlc_object_t *);
119 static int OpenAnalog (audio_output_t *, audio_sample_format_t *);
120 static int OpenSPDIF (audio_output_t *, audio_sample_format_t *);
121 static void Close (vlc_object_t *);
123 static void Play (audio_output_t *, block_t *);
124 static void Flush (audio_output_t *, bool);
125 static void Pause (audio_output_t *, bool, mtime_t);
126 static int TimeGet (audio_output_t *, mtime_t *);
128 static int DeviceList (audio_output_t *p_aout, char ***namesp, char ***descsp);
129 static void RebuildDeviceList (audio_output_t *);
130 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
132 static int AudioDeviceHasOutput (AudioDeviceID);
133 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
134 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
135 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
137 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *, UInt32 , UInt32, AudioBufferList *);
139 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
140 AudioBufferList *, const AudioTimeStamp *, void *);
141 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
142 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
144 static int VolumeSet (audio_output_t *, float);
145 static int MuteSet (audio_output_t *, bool);
148 /*****************************************************************************
150 *****************************************************************************/
151 #define VOLUME_TEXT N_("Audio volume")
152 #define VOLUME_LONGTEXT VOLUME_TEXT
155 set_shortname("auhal")
156 set_description(N_("HAL AudioUnit output"))
157 set_capability("audio output", 101)
158 set_category(CAT_AUDIO)
159 set_subcategory(SUBCAT_AUDIO_AOUT)
160 set_callbacks(Open, Close)
161 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
162 VOLUME_TEXT, VOLUME_LONGTEXT, true)
163 change_integer_range(0, AOUT_VOLUME_MAX)
164 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
167 /*****************************************************************************
168 * Open: open macosx audio output
169 *****************************************************************************/
170 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
172 OSStatus err = noErr;
173 UInt32 i_param_size = 0;
174 struct aout_sys_t *p_sys = NULL;
176 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
181 p_sys->b_digital = false;
182 p_sys->au_component = NULL;
183 p_sys->au_unit = NULL;
184 p_sys->clock_diff = (mtime_t) 0;
185 p_sys->i_hog_pid = -1;
186 p_sys->i_stream_id = 0;
187 p_sys->i_stream_index = -1;
188 p_sys->b_revert = false;
189 p_sys->b_changed_mixing = false;
191 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
193 if (p_sys->b_selected_dev_is_digital)
194 msg_Dbg(p_aout, "audio device supports digital output");
196 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
198 /* Check if the desired device is alive and usable */
199 i_param_size = sizeof(b_alive);
200 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
201 kAudioObjectPropertyScopeGlobal,
202 kAudioObjectPropertyElementMaster };
203 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
206 /* Be tolerant, only give a warning here */
207 msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
208 (unsigned int)p_sys->i_selected_dev, (char *)&err);
213 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
214 p_sys->i_selected_dev = p_sys->i_default_dev;
217 /* add a callback to see if the device dies later on */
218 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
220 /* Be tolerant, only give a warning here */
221 msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
222 (unsigned int)p_sys->i_selected_dev, (char *)&err);
225 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
226 kAudioDevicePropertyScopeOutput,
227 kAudioObjectPropertyElementMaster };
228 i_param_size = sizeof(p_sys->i_hog_pid);
229 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
231 /* This is not a fatal error. Some drivers simply don't support this property */
232 msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
234 p_sys->i_hog_pid = -1;
237 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
238 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
239 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
240 _("The selected audio output device is exclusively in "
241 "use by another program."));
245 bool b_success = false;
247 /* Check for Digital mode or Analog output mode */
248 if (AOUT_FMT_SPDIF (fmt) && p_sys->b_selected_dev_is_digital) {
249 if (OpenSPDIF (p_aout, fmt)) {
250 msg_Dbg(p_aout, "digital output successfully opened");
254 if (OpenAnalog(p_aout, fmt)) {
255 msg_Dbg(p_aout, "analog output successfully opened");
262 p_aout->flush = Flush;
263 p_aout->time_get = TimeGet;
264 p_aout->pause = Pause;
269 /* If we reach this, this aout has failed */
270 msg_Err(p_aout, "opening the auhal output failed");
274 /*****************************************************************************
275 * Open: open and setup a HAL AudioUnit to do analog (multichannel) audio output
276 *****************************************************************************/
277 static int OpenAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
279 struct aout_sys_t *p_sys = p_aout->sys;
280 OSStatus err = noErr;
281 UInt32 i_param_size = 0;
283 AudioComponentDescription desc;
284 AudioStreamBasicDescription DeviceFormat;
285 AudioChannelLayout *layout;
286 AudioChannelLayout new_layout;
287 AURenderCallbackStruct input;
288 p_aout->sys->chans_to_reorder = 0;
290 /* Lets go find our Component */
291 desc.componentType = kAudioUnitType_Output;
292 desc.componentSubType = kAudioUnitSubType_HALOutput;
293 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
294 desc.componentFlags = 0;
295 desc.componentFlagsMask = 0;
297 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
298 if (p_sys->au_component == NULL) {
299 msg_Warn(p_aout, "we cannot find our HAL component");
303 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
305 msg_Warn(p_aout, "we cannot open our HAL component");
309 /* Set the device we will use for this output unit */
310 err = AudioUnitSetProperty(p_sys->au_unit,
311 kAudioOutputUnitProperty_CurrentDevice,
312 kAudioUnitScope_Global,
314 &p_sys->i_selected_dev,
315 sizeof(AudioObjectID));
318 msg_Warn(p_aout, "we cannot select the audio device");
322 /* Get the current format */
323 i_param_size = sizeof(AudioStreamBasicDescription);
325 err = AudioUnitGetProperty(p_sys->au_unit,
326 kAudioUnitProperty_StreamFormat,
327 kAudioUnitScope_Output,
335 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
337 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
338 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
339 kAudioDevicePropertyPreferredChannelLayout,
340 kAudioUnitScope_Output,
346 layout = (AudioChannelLayout *)malloc(i_param_size);
348 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
349 kAudioDevicePropertyPreferredChannelLayout,
350 kAudioUnitScope_Output,
355 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
356 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
357 /* bitmap defined channellayout */
358 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
359 sizeof(UInt32), &layout->mChannelBitmap,
362 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
364 /* layouttags defined channellayout */
365 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
366 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
371 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
373 if (layout->mNumberChannelDescriptions == 0) {
374 msg_Err(p_aout, "insufficient number of output channels");
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;
520 p_sys->i_rate = fmt->i_rate;
522 /* We use float 32 since this is VLC's endorsed format */
523 fmt->i_format = VLC_CODEC_FL32;
524 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
525 DeviceFormat.mBitsPerChannel = 32;
526 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
528 /* Calculate framesizes and stuff */
529 DeviceFormat.mFramesPerPacket = 1;
530 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
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();
583 /* setup circular buffer */
584 TPCircularBufferInit(&p_sys->circular_buffer, kBufferLength);
586 p_sys->b_got_first_sample = false;
587 p_sys->i_played_length = 0;
588 p_sys->i_last_sample_time = 0;
590 /* Set volume for output unit */
591 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
592 volume = volume * volume * volume;
593 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
594 kHALOutputParam_Volume,
595 kAudioUnitScope_Global,
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 p_sys->i_rate = fmt->i_rate;
779 aout_FormatPrepare(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);
791 /* Check for the difference between the Device clock and mdate */
792 p_sys->clock_diff = - (mtime_t)
793 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
794 p_sys->clock_diff += mdate();
797 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
799 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
801 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
803 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
812 /*****************************************************************************
813 * Close: Close HAL AudioUnit
814 *****************************************************************************/
815 static void Stop(audio_output_t *p_aout)
817 struct aout_sys_t *p_sys = p_aout->sys;
818 OSStatus err = noErr;
819 UInt32 i_param_size = 0;
821 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
822 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
824 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
826 if (p_sys->b_digital) {
827 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
828 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
830 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
833 if (p_sys->au_unit) {
834 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
835 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
836 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
839 if (p_sys->b_digital) {
841 err = AudioDeviceStop(p_sys->i_selected_dev,
844 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
846 /* Remove IOProc callback */
847 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
850 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
853 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
855 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
857 Boolean b_writeable = false;
858 /* Revert mixable to true if we are allowed to */
859 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
860 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
861 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
863 if (err == noErr && b_writeable) {
864 msg_Dbg(p_aout, "mixable is: %d", b_mix);
866 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
870 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
874 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
875 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
878 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
880 if (p_sys->i_hog_pid == getpid()) {
881 p_sys->i_hog_pid = -1;
882 i_param_size = sizeof(p_sys->i_hog_pid);
883 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
884 kAudioDevicePropertyScopeOutput,
885 kAudioObjectPropertyElementMaster };
886 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
888 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
891 p_sys->i_played_length = 0;
892 p_sys->i_last_sample_time = 0;
894 /* clean-up circular buffer */
895 TPCircularBufferCleanup(&p_sys->circular_buffer);
898 static int DeviceList(audio_output_t *p_aout, char ***namesp, char ***descsp)
900 struct aout_sys_t *p_sys = p_aout->sys;
901 char **names, **descs;
904 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next)
907 *namesp = names = xmalloc(sizeof(*names) * n);
908 *descsp = descs = xmalloc(sizeof(*descs) * n);
911 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next) {
912 sprintf(deviceid, "%i", device->deviceid);
913 *(names++) = strdup(deviceid);
914 *(descs++) = strdup(device->name);
920 static void add_device_to_list(audio_output_t * p_aout, UInt32 i_id, char *name)
922 struct aout_sys_t *p_sys = p_aout->sys;
924 struct audio_device_t *device = malloc(sizeof(*device));
925 if (unlikely(device == NULL))
928 device->next = p_sys->devices;
929 device->deviceid = i_id;
930 device->name = strdup(name);
932 p_sys->devices = device;
935 static void RebuildDeviceList(audio_output_t * p_aout)
937 OSStatus err = noErr;
938 UInt32 propertySize = 0;
939 AudioObjectID defaultDeviceID = 0;
940 AudioObjectID *deviceIDs;
941 UInt32 numberOfDevices;
943 struct aout_sys_t *p_sys = p_aout->sys;
945 if (p_sys->devices) {
946 for (struct audio_device_t * device = p_sys->devices, *next; device != NULL; device = next) {
953 /* Get number of devices */
954 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
955 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
957 msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
961 numberOfDevices = propertySize / sizeof(AudioDeviceID);
963 if (numberOfDevices < 1) {
964 msg_Err(p_aout, "No audio output devices were found.");
967 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
969 /* Allocate DeviceID array */
970 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
971 if (deviceIDs == NULL)
974 /* Populate DeviceID array */
975 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
977 msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
981 /* Find the ID of the default Device */
982 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
983 propertySize = sizeof(AudioObjectID);
984 err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
986 msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
989 p_sys->i_default_dev = defaultDeviceID;
991 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
993 for (unsigned int i = 0; i < numberOfDevices; i++) {
994 CFStringRef device_name_ref;
997 bool b_digital = false;
998 UInt32 i_id = deviceIDs[i];
1000 /* Retrieve the length of the device name */
1001 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1003 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1007 /* Retrieve the name of the device */
1008 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1010 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1013 length = CFStringGetLength(device_name_ref);
1015 psz_name = (char *)malloc(length);
1016 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1018 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1020 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1021 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1026 add_device_to_list(p_aout, i_id, psz_name);
1028 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1030 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1031 char *psz_encoded_name = nil;
1032 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1033 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1034 add_device_to_list(p_aout, i_id, psz_encoded_name);
1035 free(psz_encoded_name);
1038 CFRelease(device_name_ref);
1042 /* Attach a Listener so that we are notified of a change in the Device setup */
1043 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
1045 msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
1050 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1052 struct aout_sys_t *p_sys = p_aout->sys;
1055 p_sys->i_selected_dev = atoi(name);
1057 p_sys->i_selected_dev = 0;
1059 bool b_supports_digital = (p_sys->i_selected_dev & AOUT_VAR_SPDIF_FLAG);
1060 if (b_supports_digital)
1061 p_sys->b_selected_dev_is_digital = true;
1063 p_sys->b_selected_dev_is_digital = false;
1065 p_sys->i_selected_dev = p_sys->i_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1067 aout_DeviceReport(p_aout, name);
1068 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1073 /*****************************************************************************
1074 * AudioDeviceHasOutput: Checks if the Device actually provides any outputs at all
1075 *****************************************************************************/
1076 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1078 UInt32 dataSize = 0;
1081 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1082 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1084 if (dataSize == 0 || status != noErr)
1090 /*****************************************************************************
1091 * AudioDeviceSupportsDigital: Check i_dev_id for digital stream support.
1092 *****************************************************************************/
1093 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1095 OSStatus err = noErr;
1096 UInt32 i_param_size = 0;
1097 AudioStreamID *p_streams = NULL;
1099 bool b_return = false;
1101 /* Retrieve all the output streams */
1102 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1103 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1105 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1109 i_streams = i_param_size / sizeof(AudioStreamID);
1110 p_streams = (AudioStreamID *)malloc(i_param_size);
1111 if (p_streams == NULL)
1114 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1116 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1120 for (int i = 0; i < i_streams; i++) {
1121 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1129 /*****************************************************************************
1130 * AudioStreamSupportsDigital: Check i_stream_id for digital stream support.
1131 *****************************************************************************/
1132 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1134 OSStatus err = noErr;
1135 UInt32 i_param_size = 0;
1136 AudioStreamRangedDescription *p_format_list = NULL;
1138 bool b_return = false;
1140 /* Retrieve all the stream formats supported by each output stream */
1141 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1142 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1144 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1148 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1149 msg_Dbg(p_aout, "found %i stream formats", i_formats);
1151 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1152 if (p_format_list == NULL)
1155 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1157 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1158 free(p_format_list);
1159 p_format_list = NULL;
1163 for (int i = 0; i < i_formats; i++) {
1165 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1168 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1169 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1170 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1171 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1175 free(p_format_list);
1179 /*****************************************************************************
1180 * AudioStreamChangeFormat: Change i_stream_id to change_format
1181 *****************************************************************************/
1182 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1184 OSStatus err = noErr;
1185 UInt32 i_param_size = 0;
1187 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1189 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1191 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1193 /* Condition because SetProperty is asynchronious */
1194 vlc_cond_init(&w.cond);
1195 vlc_mutex_init(&w.lock);
1196 vlc_mutex_lock(&w.lock);
1198 /* Install the callback */
1199 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1201 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1205 /* change the format */
1206 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1209 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1213 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1214 * it is also not atomic in its behaviour.
1215 * Therefore we check 5 times before we really give up.
1216 * FIXME: failing isn't actually implemented yet. */
1217 for (int i = 0; i < 5; i++) {
1218 AudioStreamBasicDescription actual_format;
1219 mtime_t timeout = mdate() + 500000;
1221 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1222 msg_Dbg(p_aout, "reached timeout");
1224 i_param_size = sizeof(AudioStreamBasicDescription);
1225 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1227 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1228 if (actual_format.mSampleRate == change_format.mSampleRate &&
1229 actual_format.mFormatID == change_format.mFormatID &&
1230 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1231 /* The right format is now active */
1234 /* We need to check again */
1237 /* Removing the property listener */
1238 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1240 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1244 /* Destroy the lock and condition */
1245 vlc_mutex_unlock(&w.lock);
1246 vlc_mutex_destroy(&w.lock);
1247 vlc_cond_destroy(&w.cond);
1252 static void Play (audio_output_t * p_aout, block_t * p_block)
1254 struct aout_sys_t *p_sys = p_aout->sys;
1256 if (p_block->i_nb_samples > 0) {
1257 if (!p_sys->b_got_first_sample) {
1259 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1260 p_sys->b_got_first_sample = true;
1263 /* Do the channel reordering */
1264 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1265 aout_ChannelReorder(p_block->p_buffer,
1267 p_sys->chans_to_reorder,
1272 /* Render audio into buffer */
1273 AudioBufferList bufferList;
1274 bufferList.mNumberBuffers = 1;
1275 bufferList.mBuffers[0].mNumberChannels = p_sys->i_numberOfChannels;
1276 bufferList.mBuffers[0].mData = malloc(p_block->i_nb_samples * sizeof(Float32) * p_sys->i_numberOfChannels);
1277 bufferList.mBuffers[0].mDataByteSize = p_block->i_nb_samples * sizeof(Float32) * p_sys->i_numberOfChannels;
1279 memcpy(bufferList.mBuffers[0].mData, p_block->p_buffer, p_block->i_buffer);
1281 /* keep track of the played data */
1282 p_aout->sys->i_played_length += p_block->i_length;
1284 /* move data to buffer */
1285 TPCircularBufferProduceBytes(&p_sys->circular_buffer, bufferList.mBuffers[0].mData, bufferList.mBuffers[0].mDataByteSize);
1288 block_Release(p_block);
1291 static void Pause (audio_output_t *p_aout, bool pause, mtime_t date)
1293 struct aout_sys_t * p_sys = p_aout->sys;
1296 if (p_aout->sys->b_digital) {
1298 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1300 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1303 AudioOutputUnitStop(p_sys->au_unit);
1305 AudioOutputUnitStart(p_sys->au_unit);
1309 static void Flush(audio_output_t *p_aout, bool wait)
1311 struct aout_sys_t * p_sys = p_aout->sys;
1314 p_sys->b_got_first_sample = false;
1316 /* flush circular buffer */
1317 AudioOutputUnitStop(p_aout->sys->au_unit);
1318 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1320 p_sys->i_played_length = 0;
1321 p_sys->i_last_sample_time = 0;
1324 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1326 struct aout_sys_t * p_sys = p_aout->sys;
1328 vlc_mutex_lock(&p_sys->lock);
1329 mtime_t i_pos = p_sys->i_last_sample_time * CLOCK_FREQ / p_sys->i_rate;
1330 vlc_mutex_unlock(&p_sys->lock);
1333 *delay = p_aout->sys->i_played_length - i_pos;
1340 /*****************************************************************************
1341 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1342 * us to provide some more audio data.
1343 * Don't print anything during normal playback, calling blocking function from
1344 * this callback is not allowed.
1345 *****************************************************************************/
1346 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1347 AudioUnitRenderActionFlags *ioActionFlags,
1348 const AudioTimeStamp *inTimeStamp,
1350 UInt32 inNumberFrames,
1351 AudioBufferList *ioData) {
1352 VLC_UNUSED(ioActionFlags);
1353 VLC_UNUSED(inTimeStamp);
1354 VLC_UNUSED(inBusNumber);
1356 audio_output_t * p_aout = (audio_output_t *)p_obj;
1357 struct aout_sys_t * p_sys = p_aout->sys;
1359 int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1360 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1362 /* Pull audio from buffer */
1363 int32_t availableBytes;
1364 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1366 /* check if we have enough data */
1367 if (!availableBytes) {
1368 /* return an empty buffer so silence is played until we have data */
1369 for (UInt32 j = 0; j < inNumberFrames; j++)
1370 targetBuffer[j] = 0.;
1372 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1373 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1374 VLC_UNUSED(inNumberFrames);
1375 vlc_mutex_lock(&p_sys->lock);
1376 p_sys->i_last_sample_time = inTimeStamp->mSampleTime;
1377 vlc_mutex_unlock(&p_sys->lock);
1383 /*****************************************************************************
1384 * RenderCallbackSPDIF: callback for SPDIF audio output
1385 *****************************************************************************/
1386 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1387 const AudioTimeStamp * inNow,
1388 const void * inInputData,
1389 const AudioTimeStamp * inInputTime,
1390 AudioBufferList * outOutputData,
1391 const AudioTimeStamp * inOutputTime,
1392 void * threadGlobals)
1395 VLC_UNUSED(inDevice);
1396 VLC_UNUSED(inInputData);
1397 VLC_UNUSED(inInputTime);
1399 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1400 struct aout_sys_t * p_sys = p_aout->sys;
1402 int bytesToCopy = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1403 Float32 *targetBuffer = (Float32*)outOutputData->mBuffers[p_sys->i_stream_index].mData;
1405 /* Pull audio from buffer */
1406 int32_t availableBytes;
1407 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1409 /* check if we have enough data */
1410 if (!availableBytes) {
1411 /* return an empty buffer so silence is played until we have data */
1412 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1414 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1415 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1416 vlc_mutex_lock(&p_sys->lock);
1417 p_sys->i_last_sample_time = inOutputTime->mSampleTime;
1418 vlc_mutex_unlock(&p_sys->lock);
1424 /*****************************************************************************
1425 * HardwareListener: Warns us of changes in the list of registered devices
1426 *****************************************************************************/
1427 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1429 OSStatus err = noErr;
1430 audio_output_t *p_aout = (audio_output_t *)inClientData;
1431 VLC_UNUSED(inObjectID);
1432 VLC_UNUSED(inNumberAddresses);
1433 VLC_UNUSED(inAddresses);
1439 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1440 switch (inAddresses[i].mSelector) {
1441 case kAudioHardwarePropertyDevices:
1442 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1445 case kAudioDevicePropertyDeviceIsAlive:
1446 msg_Warn(p_aout, "audio device died, resetting aout");
1449 case kAudioStreamPropertyAvailablePhysicalFormats:
1450 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1454 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1460 RebuildDeviceList(p_aout);
1465 /*****************************************************************************
1467 *****************************************************************************/
1468 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1470 OSStatus err = noErr;
1471 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1473 VLC_UNUSED(inObjectID);
1475 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1476 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1477 vlc_mutex_lock(&w->lock);
1478 vlc_cond_signal(&w->cond);
1479 vlc_mutex_unlock(&w->lock);
1486 /*****************************************************************************
1487 * VolumeSet: Implements volume_set(). Update the CoreAudio AU volume immediately.
1488 *****************************************************************************/
1489 static int VolumeSet(audio_output_t * p_aout, float volume)
1491 struct aout_sys_t *p_sys = p_aout->sys;
1494 aout_VolumeReport(p_aout, volume);
1496 /* Set volume for output unit */
1497 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1498 kHALOutputParam_Volume,
1499 kAudioUnitScope_Global,
1501 volume * volume * volume,
1504 if (var_InheritBool(p_aout, "volume-save"))
1505 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1510 static int MuteSet(audio_output_t * p_aout, bool mute)
1512 struct aout_sys_t *p_sys = p_aout->sys;
1515 aout_MuteReport(p_aout, mute);
1520 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1522 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1523 kHALOutputParam_Volume,
1524 kAudioUnitScope_Global,
1526 volume * volume * volume,
1532 static int Open(vlc_object_t *obj)
1534 audio_output_t *aout = (audio_output_t *)obj;
1535 aout_sys_t *sys = malloc(sizeof (*sys));
1537 if (unlikely(sys == NULL))
1540 vlc_mutex_init(&sys->lock);
1543 aout->start = Start;
1545 aout->volume_set = VolumeSet;
1546 aout->mute_set = MuteSet;
1547 aout->device_enum = DeviceList;
1548 aout->sys->devices = NULL;
1549 aout->device_select = SwitchAudioDevice;
1551 RebuildDeviceList(aout);
1553 /* remember the volume */
1554 aout_VolumeReport(aout, var_InheritInteger(aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
1555 MuteSet(aout, var_InheritBool(aout, "mute"));
1560 static void Close(vlc_object_t *obj)
1562 audio_output_t *aout = (audio_output_t *)obj;
1563 aout_sys_t *sys = aout->sys;
1565 for (struct audio_device_t * device = sys->devices, *next; device != NULL; device = next) {
1566 next = device->next;
1571 vlc_mutex_destroy(&sys->lock);