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 *****************************************************************************/
31 #import <vlc_common.h>
32 #import <vlc_plugin.h>
33 #import <vlc_dialog.h> // dialog_Fatal
34 #import <vlc_aout.h> // aout_*
36 #import <AudioUnit/AudioUnit.h> // AudioUnit
37 #import <CoreAudio/CoreAudio.h> // AudioDeviceID
38 #import <AudioToolbox/AudioFormat.h> // AudioFormatGetProperty
39 #import <CoreServices/CoreServices.h>
41 #import "TPCircularBuffer.h"
44 #pragma mark private declarations
47 # define verify_noerr(a) assert((a) == noErr)
50 #define STREAM_FORMAT_MSG(pre, sfm) \
51 pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
52 sfm.mSampleRate, (char *)&sfm.mFormatID, \
53 (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
54 (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
55 (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
57 #define AOUT_VAR_SPDIF_FLAG 0xf00000
59 #define kBufferLength 2048 * 8 * 8 * 4
61 #define AOUT_VOLUME_DEFAULT 256
62 #define AOUT_VOLUME_MAX 512
64 #define VOLUME_TEXT N_("Audio volume")
65 #define VOLUME_LONGTEXT VOLUME_TEXT
67 /*****************************************************************************
68 * aout_sys_t: private audio output method descriptor
69 *****************************************************************************
70 * This structure is part of the audio output thread descriptor.
71 * It describes the CoreAudio specific properties of an output thread.
72 *****************************************************************************/
75 AudioObjectID i_default_dev; /* DeviceID of defaultOutputDevice */
76 AudioObjectID i_selected_dev; /* DeviceID of the selected device */
77 bool b_selected_dev_is_digital;
78 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
79 bool b_digital; /* Are we running in digital mode? */
80 mtime_t clock_diff; /* Difference between VLC clock and Device clock */
82 uint8_t chans_to_reorder; /* do we need channel reordering */
83 uint8_t chan_table[AOUT_CHAN_MAX];
85 UInt32 i_numberOfChannels;
86 TPCircularBuffer circular_buffer; /* circular buffer to swap the audio data */
89 AudioComponent au_component; /* The AudioComponent we use */
90 AudioUnit au_unit; /* The AudioUnit we use */
92 /* CoreAudio SPDIF mode specific */
93 pid_t i_hog_pid; /* The keep the pid of our hog status */
94 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
95 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
96 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
97 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
98 bool b_revert; /* Whether we need to revert the stream format */
99 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
100 bool b_got_first_sample; /* did the aout core provide something to render? */
102 int i_rate; /* media sample rate */
103 mtime_t i_played_length; /* how much did we play already */
104 mtime_t i_last_sample_time; /* last sample time played by the AudioUnit */
106 struct audio_device_t *devices;
111 struct audio_device_t
113 struct audio_device_t *next;
120 #pragma mark local prototypes & module descriptor
122 static int Open (vlc_object_t *);
123 static void Close (vlc_object_t *);
124 static int Start (audio_output_t *, audio_sample_format_t *);
125 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
126 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
127 static void Stop (audio_output_t *);
129 static int DeviceList (audio_output_t *p_aout, char ***namesp, char ***descsp);
130 static void RebuildDeviceList (audio_output_t *);
131 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
132 static int VolumeSet (audio_output_t *, float);
133 static int MuteSet (audio_output_t *, bool);
135 static void Play (audio_output_t *, block_t *);
136 static void Pause (audio_output_t *, bool, mtime_t);
137 static void Flush (audio_output_t *, bool);
138 static int TimeGet (audio_output_t *, mtime_t *);
139 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
140 UInt32 , UInt32, AudioBufferList *);
142 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
143 AudioBufferList *, const AudioTimeStamp *, void *);
145 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
146 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
148 static int AudioDeviceHasOutput (AudioDeviceID);
149 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
150 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
151 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
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 */
168 #pragma mark initialization
170 static int Open(vlc_object_t *obj)
172 audio_output_t *aout = (audio_output_t *)obj;
173 aout_sys_t *sys = malloc(sizeof (*sys));
175 if (unlikely(sys == NULL))
178 vlc_mutex_init(&sys->lock);
183 aout->volume_set = VolumeSet;
184 aout->mute_set = MuteSet;
185 aout->device_enum = DeviceList;
186 aout->sys->devices = NULL;
187 aout->device_select = SwitchAudioDevice;
189 RebuildDeviceList(aout);
191 /* remember the volume */
192 aout_VolumeReport(aout, var_InheritInteger(aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
193 MuteSet(aout, var_InheritBool(aout, "mute"));
198 static void Close(vlc_object_t *obj)
200 audio_output_t *aout = (audio_output_t *)obj;
201 aout_sys_t *sys = aout->sys;
203 for (struct audio_device_t * device = sys->devices, *next; device != NULL; device = next) {
209 vlc_mutex_destroy(&sys->lock);
214 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
216 OSStatus err = noErr;
217 UInt32 i_param_size = 0;
218 struct aout_sys_t *p_sys = NULL;
220 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
225 p_sys->b_digital = false;
226 p_sys->au_component = NULL;
227 p_sys->au_unit = NULL;
228 p_sys->clock_diff = (mtime_t) 0;
229 p_sys->i_hog_pid = -1;
230 p_sys->i_stream_id = 0;
231 p_sys->i_stream_index = -1;
232 p_sys->b_revert = false;
233 p_sys->b_changed_mixing = false;
235 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
237 if (p_sys->b_selected_dev_is_digital)
238 msg_Dbg(p_aout, "audio device supports digital output");
240 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
242 /* Check if the desired device is alive and usable */
243 i_param_size = sizeof(b_alive);
244 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
245 kAudioObjectPropertyScopeGlobal,
246 kAudioObjectPropertyElementMaster };
247 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
250 /* Be tolerant, only give a warning here */
251 msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
252 (unsigned int)p_sys->i_selected_dev, (char *)&err);
257 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
258 p_sys->i_selected_dev = p_sys->i_default_dev;
261 /* add a callback to see if the device dies later on */
262 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
264 /* Be tolerant, only give a warning here */
265 msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
266 (unsigned int)p_sys->i_selected_dev, (char *)&err);
269 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
270 kAudioDevicePropertyScopeOutput,
271 kAudioObjectPropertyElementMaster };
272 i_param_size = sizeof(p_sys->i_hog_pid);
273 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
275 /* This is not a fatal error. Some drivers simply don't support this property */
276 msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
278 p_sys->i_hog_pid = -1;
281 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
282 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
283 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
284 _("The selected audio output device is exclusively in "
285 "use by another program."));
289 bool b_success = false;
291 /* Check for Digital mode or Analog output mode */
292 if (AOUT_FMT_SPDIF (fmt) && p_sys->b_selected_dev_is_digital) {
293 if (StartSPDIF (p_aout, fmt)) {
294 msg_Dbg(p_aout, "digital output successfully opened");
298 if (StartAnalog(p_aout, fmt)) {
299 msg_Dbg(p_aout, "analog output successfully opened");
306 p_aout->flush = Flush;
307 p_aout->time_get = TimeGet;
308 p_aout->pause = Pause;
313 /* If we reach this, this aout has failed */
314 msg_Err(p_aout, "opening auhal output failed");
319 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
321 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
323 struct aout_sys_t *p_sys = p_aout->sys;
324 OSStatus err = noErr;
325 UInt32 i_param_size = 0;
327 AudioComponentDescription desc;
328 AudioStreamBasicDescription DeviceFormat;
329 AudioChannelLayout *layout;
330 AudioChannelLayout new_layout;
331 AURenderCallbackStruct input;
332 p_aout->sys->chans_to_reorder = 0;
334 /* Lets go find our Component */
335 desc.componentType = kAudioUnitType_Output;
336 desc.componentSubType = kAudioUnitSubType_HALOutput;
337 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
338 desc.componentFlags = 0;
339 desc.componentFlagsMask = 0;
341 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
342 if (p_sys->au_component == NULL) {
343 msg_Warn(p_aout, "we cannot find our HAL component");
347 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
349 msg_Warn(p_aout, "we cannot open our HAL component");
353 /* Set the device we will use for this output unit */
354 err = AudioUnitSetProperty(p_sys->au_unit,
355 kAudioOutputUnitProperty_CurrentDevice,
356 kAudioUnitScope_Global,
358 &p_sys->i_selected_dev,
359 sizeof(AudioObjectID));
362 msg_Warn(p_aout, "we cannot select the audio device");
366 /* Get the current format */
367 i_param_size = sizeof(AudioStreamBasicDescription);
369 err = AudioUnitGetProperty(p_sys->au_unit,
370 kAudioUnitProperty_StreamFormat,
371 kAudioUnitScope_Output,
379 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
381 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
382 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
383 kAudioDevicePropertyPreferredChannelLayout,
384 kAudioUnitScope_Output,
390 layout = (AudioChannelLayout *)malloc(i_param_size);
392 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
393 kAudioDevicePropertyPreferredChannelLayout,
394 kAudioUnitScope_Output,
399 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
400 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
401 /* bitmap defined channellayout */
402 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
403 sizeof(UInt32), &layout->mChannelBitmap,
406 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
408 /* layouttags defined channellayout */
409 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
410 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
415 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
417 if (layout->mNumberChannelDescriptions == 0) {
418 msg_Err(p_aout, "insufficient number of output channels");
422 /* Initialize the VLC core channel count */
423 fmt->i_physical_channels = 0;
424 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
426 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
427 /* We only need Mono or cannot output more than 1 channel */
428 fmt->i_physical_channels = AOUT_CHAN_CENTER;
429 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
430 /* We only need Stereo or cannot output more than 2 channels */
431 fmt->i_physical_channels = AOUT_CHANS_STEREO;
433 /* We want more than stereo and we can do that */
434 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
436 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
439 switch(layout->mChannelDescriptions[i].mChannelLabel) {
440 case kAudioChannelLabel_Left:
441 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
443 case kAudioChannelLabel_Right:
444 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
446 case kAudioChannelLabel_Center:
447 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
449 case kAudioChannelLabel_LFEScreen:
450 fmt->i_physical_channels |= AOUT_CHAN_LFE;
452 case kAudioChannelLabel_LeftSurround:
453 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
455 case kAudioChannelLabel_RightSurround:
456 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
458 case kAudioChannelLabel_RearSurroundLeft:
459 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
461 case kAudioChannelLabel_RearSurroundRight:
462 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
464 case kAudioChannelLabel_CenterSurround:
465 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
468 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
471 if (fmt->i_physical_channels == 0) {
472 fmt->i_physical_channels = AOUT_CHANS_STEREO;
473 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
474 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
475 _("You should configure your speaker layout with "
476 "the \"Audio Midi Setup\" utility in /Applications/"
477 "Utilities. Stereo mode is being used now."));
482 msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
483 fmt->i_physical_channels = AOUT_CHANS_STEREO;
486 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
487 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
488 p_sys->i_numberOfChannels = aout_FormatNbChannels(fmt);
490 memset (&new_layout, 0, sizeof(new_layout));
491 uint32_t chans_out[AOUT_CHAN_MAX];
493 switch(aout_FormatNbChannels(fmt)) {
495 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
498 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
501 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
502 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
503 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
504 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
507 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
508 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
509 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
510 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
511 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
512 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
515 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
516 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
517 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
518 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
521 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
522 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
524 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
527 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
529 chans_out[0] = AOUT_CHAN_LEFT;
530 chans_out[1] = AOUT_CHAN_RIGHT;
531 chans_out[2] = AOUT_CHAN_CENTER;
532 chans_out[3] = AOUT_CHAN_LFE;
533 chans_out[4] = AOUT_CHAN_REARLEFT;
534 chans_out[5] = AOUT_CHAN_REARRIGHT;
535 chans_out[6] = AOUT_CHAN_REARCENTER;
537 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
538 if (p_aout->sys->chans_to_reorder)
539 msg_Dbg(p_aout, "channel reordering needed");
543 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
545 chans_out[0] = AOUT_CHAN_LEFT;
546 chans_out[1] = AOUT_CHAN_RIGHT;
547 chans_out[2] = AOUT_CHAN_CENTER;
548 chans_out[3] = AOUT_CHAN_LFE;
549 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
550 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
551 chans_out[6] = AOUT_CHAN_REARLEFT;
552 chans_out[7] = AOUT_CHAN_REARRIGHT;
554 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
555 if (p_aout->sys->chans_to_reorder)
556 msg_Dbg(p_aout, "channel reordering needed");
561 /* Set up the format to be used */
562 DeviceFormat.mSampleRate = fmt->i_rate;
563 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
564 p_sys->i_rate = fmt->i_rate;
566 /* We use float 32 since this is VLC's endorsed format */
567 fmt->i_format = VLC_CODEC_FL32;
568 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
569 DeviceFormat.mBitsPerChannel = 32;
570 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
572 /* Calculate framesizes and stuff */
573 DeviceFormat.mFramesPerPacket = 1;
574 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
575 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
577 /* Set the desired format */
578 i_param_size = sizeof(AudioStreamBasicDescription);
579 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
580 kAudioUnitProperty_StreamFormat,
581 kAudioUnitScope_Input,
586 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
588 /* Retrieve actual format */
589 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
590 kAudioUnitProperty_StreamFormat,
591 kAudioUnitScope_Input,
596 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
598 /* Do the last VLC aout setups */
599 aout_FormatPrepare(fmt);
601 /* set the IOproc callback */
602 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
603 input.inputProcRefCon = p_aout;
605 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
606 kAudioUnitProperty_SetRenderCallback,
607 kAudioUnitScope_Input,
608 0, &input, sizeof(input)));
610 /* Set the new_layout as the layout VLC will use to feed the AU unit */
611 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
612 kAudioUnitProperty_AudioChannelLayout,
613 kAudioUnitScope_Output,
614 0, &new_layout, sizeof(new_layout)));
616 if (new_layout.mNumberChannelDescriptions > 0)
617 free(new_layout.mChannelDescriptions);
620 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
622 /* Find the difference between device clock and mdate clock */
623 p_sys->clock_diff = - (mtime_t)
624 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
625 p_sys->clock_diff += mdate();
627 /* setup circular buffer */
628 TPCircularBufferInit(&p_sys->circular_buffer, kBufferLength);
630 p_sys->b_got_first_sample = false;
631 p_sys->i_played_length = 0;
632 p_sys->i_last_sample_time = 0;
634 /* Set volume for output unit */
635 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
636 volume = volume * volume * volume;
637 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
638 kHALOutputParam_Volume,
639 kAudioUnitScope_Global,
648 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
650 static int StartSPDIF (audio_output_t * p_aout, audio_sample_format_t *fmt)
652 struct aout_sys_t *p_sys = p_aout->sys;
653 OSStatus err = noErr;
654 UInt32 i_param_size = 0, b_mix = 0;
655 Boolean b_writeable = false;
656 AudioStreamID *p_streams = NULL;
657 unsigned i_streams = 0;
659 /* Start doing the SPDIF setup proces */
660 p_sys->b_digital = true;
663 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
664 i_param_size = sizeof(p_sys->i_hog_pid);
665 p_sys->i_hog_pid = getpid() ;
667 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
670 msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
674 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
676 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
677 /* Set mixable to false if we are allowed to */
678 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
679 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
680 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
682 if (err == noErr && b_writeable) {
684 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
685 p_sys->b_changed_mixing = true;
689 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
694 /* Get a list of all the streams on this device */
695 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
696 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
698 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
702 i_streams = i_param_size / sizeof(AudioStreamID);
703 p_streams = (AudioStreamID *)malloc(i_param_size);
704 if (p_streams == NULL)
707 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
710 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
715 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
716 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
717 /* Find a stream with a cac3 stream */
718 AudioStreamRangedDescription *p_format_list = NULL;
720 bool b_digital = false;
722 /* Retrieve all the stream formats supported by each output stream */
723 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
725 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
729 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
730 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
731 if (p_format_list == NULL)
734 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
736 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
741 /* Check if one of the supported formats is a digital format */
742 for (int j = 0; j < i_formats; j++) {
743 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
744 p_format_list[j].mFormat.mFormatID == 'iac3' ||
745 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
746 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
753 /* if this stream supports a digital (cac3) format, then go set it. */
754 int i_requested_rate_format = -1;
755 int i_current_rate_format = -1;
756 int i_backup_rate_format = -1;
758 p_sys->i_stream_id = p_streams[i];
759 p_sys->i_stream_index = i;
761 if (!p_sys->b_revert) {
762 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
763 /* Retrieve the original format of this stream first if not done so already */
764 i_param_size = sizeof(p_sys->sfmt_revert);
765 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
767 msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
770 p_sys->b_revert = true;
773 for (int j = 0; j < i_formats; j++) {
774 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
775 p_format_list[j].mFormat.mFormatID == 'iac3' ||
776 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
777 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
778 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
779 i_requested_rate_format = j;
781 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
782 i_current_rate_format = j;
784 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
785 i_backup_rate_format = j;
791 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
792 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
793 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
794 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
796 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) */
802 /* get notified when we don't have spdif-output anymore */
803 err = AudioObjectAddPropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
805 msg_Warn(p_aout, "could not set audio device property streams callback on device: %4.4s",
809 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
811 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
814 /* Set the format flags */
815 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
816 fmt->i_format = VLC_CODEC_SPDIFB;
818 fmt->i_format = VLC_CODEC_SPDIFL;
819 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
820 fmt->i_frame_length = A52_FRAME_NB;
821 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
822 p_sys->i_rate = fmt->i_rate;
823 aout_FormatPrepare(fmt);
825 /* Add IOProc callback */
826 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
827 (AudioDeviceIOProc)RenderCallbackSPDIF,
831 msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
835 /* Check for the difference between the Device clock and mdate */
836 p_sys->clock_diff = - (mtime_t)
837 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
838 p_sys->clock_diff += mdate();
841 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
843 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
845 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
847 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
855 static void Stop(audio_output_t *p_aout)
857 struct aout_sys_t *p_sys = p_aout->sys;
858 OSStatus err = noErr;
859 UInt32 i_param_size = 0;
861 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
862 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
864 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
866 if (p_sys->b_digital) {
867 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
868 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
870 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
873 if (p_sys->au_unit) {
874 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
875 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
876 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
879 if (p_sys->b_digital) {
881 err = AudioDeviceStop(p_sys->i_selected_dev,
884 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
886 /* Remove IOProc callback */
887 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
890 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
893 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
895 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
897 Boolean b_writeable = false;
898 /* Revert mixable to true if we are allowed to */
899 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
900 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
901 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
903 if (err == noErr && b_writeable) {
904 msg_Dbg(p_aout, "mixable is: %d", b_mix);
906 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
910 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
914 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
915 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
918 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
920 if (p_sys->i_hog_pid == getpid()) {
921 p_sys->i_hog_pid = -1;
922 i_param_size = sizeof(p_sys->i_hog_pid);
923 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
924 kAudioDevicePropertyScopeOutput,
925 kAudioObjectPropertyElementMaster };
926 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
928 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
931 p_sys->i_played_length = 0;
932 p_sys->i_last_sample_time = 0;
934 /* clean-up circular buffer */
935 TPCircularBufferCleanup(&p_sys->circular_buffer);
939 #pragma mark core interaction
941 static int DeviceList(audio_output_t *p_aout, char ***namesp, char ***descsp)
943 struct aout_sys_t *p_sys = p_aout->sys;
944 char **names, **descs;
947 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next)
950 *namesp = names = xmalloc(sizeof(*names) * n);
951 *descsp = descs = xmalloc(sizeof(*descs) * n);
954 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next) {
955 sprintf(deviceid, "%i", device->deviceid);
956 *(names++) = strdup(deviceid);
957 *(descs++) = strdup(device->name);
963 static void add_device_to_list(audio_output_t * p_aout, UInt32 i_id, char *name)
965 struct aout_sys_t *p_sys = p_aout->sys;
967 struct audio_device_t *device = malloc(sizeof(*device));
968 if (unlikely(device == NULL))
971 device->next = p_sys->devices;
972 device->deviceid = i_id;
973 device->name = strdup(name);
975 p_sys->devices = device;
978 static void RebuildDeviceList(audio_output_t * p_aout)
980 OSStatus err = noErr;
981 UInt32 propertySize = 0;
982 AudioObjectID defaultDeviceID = 0;
983 AudioObjectID *deviceIDs;
984 UInt32 numberOfDevices;
986 struct aout_sys_t *p_sys = p_aout->sys;
988 if (p_sys->devices) {
989 for (struct audio_device_t * device = p_sys->devices, *next; device != NULL; device = next) {
996 /* Get number of devices */
997 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
998 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1000 msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
1004 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1006 if (numberOfDevices < 1) {
1007 msg_Err(p_aout, "No audio output devices were found.");
1010 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1012 /* Allocate DeviceID array */
1013 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1014 if (deviceIDs == NULL)
1017 /* Populate DeviceID array */
1018 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1020 msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
1024 /* Find the ID of the default Device */
1025 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1026 propertySize = sizeof(AudioObjectID);
1027 err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1029 msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
1032 p_sys->i_default_dev = defaultDeviceID;
1034 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1036 for (unsigned int i = 0; i < numberOfDevices; i++) {
1037 CFStringRef device_name_ref;
1040 bool b_digital = false;
1041 UInt32 i_id = deviceIDs[i];
1043 /* Retrieve the length of the device name */
1044 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1046 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1050 /* Retrieve the name of the device */
1051 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1053 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1056 length = CFStringGetLength(device_name_ref);
1058 psz_name = (char *)malloc(length);
1059 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1061 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1063 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1064 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1069 add_device_to_list(p_aout, i_id, psz_name);
1071 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1073 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1074 char *psz_encoded_name = nil;
1075 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1076 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1077 add_device_to_list(p_aout, i_id, psz_encoded_name);
1078 free(psz_encoded_name);
1081 CFRelease(device_name_ref);
1085 add_device_to_list(p_aout, 0, _("System Sound Output Device"));
1087 /* Attach a Listener so that we are notified of a change in the Device setup */
1088 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
1090 msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
1095 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1097 struct aout_sys_t *p_sys = p_aout->sys;
1100 p_sys->i_selected_dev = atoi(name);
1102 p_sys->i_selected_dev = 0;
1104 bool b_supports_digital = (p_sys->i_selected_dev & AOUT_VAR_SPDIF_FLAG);
1105 if (b_supports_digital)
1106 p_sys->b_selected_dev_is_digital = true;
1108 p_sys->b_selected_dev_is_digital = false;
1110 p_sys->i_selected_dev = p_sys->i_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1112 aout_DeviceReport(p_aout, name);
1113 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1118 static int VolumeSet(audio_output_t * p_aout, float volume)
1120 struct aout_sys_t *p_sys = p_aout->sys;
1123 aout_VolumeReport(p_aout, volume);
1125 /* Set volume for output unit */
1126 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1127 kHALOutputParam_Volume,
1128 kAudioUnitScope_Global,
1130 volume * volume * volume,
1133 if (var_InheritBool(p_aout, "volume-save"))
1134 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1139 static int MuteSet(audio_output_t * p_aout, bool mute)
1141 struct aout_sys_t *p_sys = p_aout->sys;
1144 aout_MuteReport(p_aout, mute);
1149 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1151 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1152 kHALOutputParam_Volume,
1153 kAudioUnitScope_Global,
1155 volume * volume * volume,
1162 #pragma mark actual playback
1164 static void Play (audio_output_t * p_aout, block_t * p_block)
1166 struct aout_sys_t *p_sys = p_aout->sys;
1168 if (p_block->i_nb_samples > 0) {
1169 if (!p_sys->b_got_first_sample) {
1171 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1172 p_sys->b_got_first_sample = true;
1175 /* Do the channel reordering */
1176 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1177 aout_ChannelReorder(p_block->p_buffer,
1179 p_sys->chans_to_reorder,
1184 /* keep track of the played data */
1185 p_aout->sys->i_played_length += p_block->i_length;
1187 /* move data to buffer */
1188 TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer);
1191 block_Release(p_block);
1194 static void Pause (audio_output_t *p_aout, bool pause, mtime_t date)
1196 struct aout_sys_t * p_sys = p_aout->sys;
1199 if (p_aout->sys->b_digital) {
1201 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1203 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1206 AudioOutputUnitStop(p_sys->au_unit);
1208 AudioOutputUnitStart(p_sys->au_unit);
1212 static void Flush(audio_output_t *p_aout, bool wait)
1214 struct aout_sys_t * p_sys = p_aout->sys;
1217 p_sys->b_got_first_sample = false;
1219 /* flush circular buffer */
1220 AudioOutputUnitStop(p_aout->sys->au_unit);
1221 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1223 p_sys->i_played_length = 0;
1224 p_sys->i_last_sample_time = 0;
1227 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1229 struct aout_sys_t * p_sys = p_aout->sys;
1231 vlc_mutex_lock(&p_sys->lock);
1232 mtime_t i_pos = p_sys->i_last_sample_time * CLOCK_FREQ / p_sys->i_rate;
1233 vlc_mutex_unlock(&p_sys->lock);
1236 *delay = p_aout->sys->i_played_length - i_pos;
1243 /*****************************************************************************
1244 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1245 * us to provide some more audio data.
1246 * Don't print anything during normal playback, calling blocking function from
1247 * this callback is not allowed.
1248 *****************************************************************************/
1249 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1250 AudioUnitRenderActionFlags *ioActionFlags,
1251 const AudioTimeStamp *inTimeStamp,
1253 UInt32 inNumberFrames,
1254 AudioBufferList *ioData) {
1255 VLC_UNUSED(ioActionFlags);
1256 VLC_UNUSED(inTimeStamp);
1257 VLC_UNUSED(inBusNumber);
1259 audio_output_t * p_aout = (audio_output_t *)p_obj;
1260 struct aout_sys_t * p_sys = p_aout->sys;
1262 int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1263 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1265 /* Pull audio from buffer */
1266 int32_t availableBytes;
1267 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1269 /* check if we have enough data */
1270 if (!availableBytes) {
1271 /* return an empty buffer so silence is played until we have data */
1272 for (UInt32 j = 0; j < inNumberFrames; j++)
1273 targetBuffer[j] = 0.;
1275 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1276 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1277 VLC_UNUSED(inNumberFrames);
1278 vlc_mutex_lock(&p_sys->lock);
1279 p_sys->i_last_sample_time = inTimeStamp->mSampleTime;
1280 vlc_mutex_unlock(&p_sys->lock);
1287 * RenderCallbackSPDIF: callback for SPDIF audio output
1289 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1290 const AudioTimeStamp * inNow,
1291 const void * inInputData,
1292 const AudioTimeStamp * inInputTime,
1293 AudioBufferList * outOutputData,
1294 const AudioTimeStamp * inOutputTime,
1295 void * threadGlobals)
1298 VLC_UNUSED(inDevice);
1299 VLC_UNUSED(inInputData);
1300 VLC_UNUSED(inInputTime);
1302 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1303 struct aout_sys_t * p_sys = p_aout->sys;
1305 int bytesToCopy = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1306 Float32 *targetBuffer = (Float32*)outOutputData->mBuffers[p_sys->i_stream_index].mData;
1308 /* Pull audio from buffer */
1309 int32_t availableBytes;
1310 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1312 /* check if we have enough data */
1313 if (!availableBytes) {
1314 /* return an empty buffer so silence is played until we have data */
1315 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1317 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1318 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1319 vlc_mutex_lock(&p_sys->lock);
1320 p_sys->i_last_sample_time = inOutputTime->mSampleTime;
1321 vlc_mutex_unlock(&p_sys->lock);
1328 #pragma mark Stream / Hardware Listeners
1331 * HardwareListener: Warns us of changes in the list of registered devices
1333 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1335 OSStatus err = noErr;
1336 audio_output_t *p_aout = (audio_output_t *)inClientData;
1337 VLC_UNUSED(inObjectID);
1338 VLC_UNUSED(inNumberAddresses);
1339 VLC_UNUSED(inAddresses);
1345 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1346 switch (inAddresses[i].mSelector) {
1347 case kAudioHardwarePropertyDevices:
1348 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1351 case kAudioDevicePropertyDeviceIsAlive:
1352 msg_Warn(p_aout, "audio device died, resetting aout");
1355 case kAudioStreamPropertyAvailablePhysicalFormats:
1356 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1360 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1366 RebuildDeviceList(p_aout);
1372 * StreamListener: check whether the device's physical format changes on-the-fly (unlikely)
1374 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1376 OSStatus err = noErr;
1377 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1379 VLC_UNUSED(inObjectID);
1381 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1382 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1383 vlc_mutex_lock(&w->lock);
1384 vlc_cond_signal(&w->cond);
1385 vlc_mutex_unlock(&w->lock);
1393 #pragma mark helpers
1396 * AudioDeviceHasOutput: Checks if the device is actually an output device
1398 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1400 UInt32 dataSize = 0;
1403 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1404 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1406 if (dataSize == 0 || status != noErr)
1413 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1415 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1417 OSStatus err = noErr;
1418 UInt32 i_param_size = 0;
1419 AudioStreamID *p_streams = NULL;
1421 bool b_return = false;
1423 /* Retrieve all the output streams */
1424 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1425 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1427 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1431 i_streams = i_param_size / sizeof(AudioStreamID);
1432 p_streams = (AudioStreamID *)malloc(i_param_size);
1433 if (p_streams == NULL)
1436 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1438 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1442 for (int i = 0; i < i_streams; i++) {
1443 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1452 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1454 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1456 OSStatus err = noErr;
1457 UInt32 i_param_size = 0;
1458 AudioStreamRangedDescription *p_format_list = NULL;
1460 bool b_return = false;
1462 /* Retrieve all the stream formats supported by each output stream */
1463 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1464 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1466 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1470 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1471 msg_Dbg(p_aout, "found %i stream formats", i_formats);
1473 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1474 if (p_format_list == NULL)
1477 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1479 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1480 free(p_format_list);
1481 p_format_list = NULL;
1485 for (int i = 0; i < i_formats; i++) {
1487 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1490 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1491 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1492 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1493 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1497 free(p_format_list);
1502 * AudioStreamChangeFormat: switch stream format based on the provided description
1504 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1506 OSStatus err = noErr;
1507 UInt32 i_param_size = 0;
1509 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1511 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1513 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1515 /* Condition because SetProperty is asynchronious */
1516 vlc_cond_init(&w.cond);
1517 vlc_mutex_init(&w.lock);
1518 vlc_mutex_lock(&w.lock);
1520 /* Install the callback */
1521 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1523 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1527 /* change the format */
1528 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1531 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1535 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1536 * it is also not atomic in its behaviour.
1537 * Therefore we check 5 times before we really give up.
1538 * FIXME: failing isn't actually implemented yet. */
1539 for (int i = 0; i < 5; i++) {
1540 AudioStreamBasicDescription actual_format;
1541 mtime_t timeout = mdate() + 500000;
1543 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1544 msg_Dbg(p_aout, "reached timeout");
1546 i_param_size = sizeof(AudioStreamBasicDescription);
1547 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1549 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1550 if (actual_format.mSampleRate == change_format.mSampleRate &&
1551 actual_format.mFormatID == change_format.mFormatID &&
1552 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1553 /* The right format is now active */
1556 /* We need to check again */
1559 /* Removing the property listener */
1560 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1562 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1566 /* Destroy the lock and condition */
1567 vlc_mutex_unlock(&w.lock);
1568 vlc_mutex_destroy(&w.lock);
1569 vlc_cond_destroy(&w.cond);