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>
9 * David Fuhrmann <david dot fuhrmann at googlemail dot com>
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation; either version 2.1 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this program; if not, write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 *****************************************************************************/
32 #import <vlc_common.h>
33 #import <vlc_plugin.h>
34 #import <vlc_dialog.h> // dialog_Fatal
35 #import <vlc_aout.h> // aout_*
37 #import <AudioUnit/AudioUnit.h> // AudioUnit
38 #import <CoreAudio/CoreAudio.h> // AudioDeviceID
39 #import <AudioToolbox/AudioFormat.h> // AudioFormatGetProperty
40 #import <CoreServices/CoreServices.h>
42 #import "TPCircularBuffer.h"
45 #pragma mark private declarations
48 # define verify_noerr(a) assert((a) == noErr)
51 #define STREAM_FORMAT_MSG(pre, sfm) \
52 pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
53 sfm.mSampleRate, (char *)&sfm.mFormatID, \
54 (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
55 (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
56 (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
58 #define AOUT_VAR_SPDIF_FLAG 0xf00000
60 #define AUDIO_BUFFER_SIZE_IN_SECONDS (AOUT_MAX_ADVANCE_TIME / CLOCK_FREQ)
63 #define AOUT_VOLUME_DEFAULT 256
64 #define AOUT_VOLUME_MAX 512
66 #define VOLUME_TEXT N_("Audio volume")
67 #define VOLUME_LONGTEXT VOLUME_TEXT
69 #define DEVICE_TEXT N_("Last audio device")
70 #define DEVICE_LONGTEXT DEVICE_TEXT
72 /*****************************************************************************
73 * aout_sys_t: private audio output method descriptor
74 *****************************************************************************
75 * This structure is part of the audio output thread descriptor.
76 * It describes the CoreAudio specific properties of an output thread.
77 *****************************************************************************/
80 AudioObjectID i_default_dev; /* DeviceID of defaultOutputDevice */
81 AudioObjectID i_selected_dev; /* DeviceID of the selected device */
82 bool b_selected_dev_is_digital;
83 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
84 bool b_digital; /* Are we running in digital mode? */
85 mtime_t clock_diff; /* Difference between VLC clock and Device clock */
87 uint8_t chans_to_reorder; /* do we need channel reordering */
88 uint8_t chan_table[AOUT_CHAN_MAX];
90 UInt32 i_numberOfChannels;
91 TPCircularBuffer circular_buffer; /* circular buffer to swap the audio data */
94 AudioComponent au_component; /* The AudioComponent we use */
95 AudioUnit au_unit; /* The AudioUnit we use */
97 /* CoreAudio SPDIF mode specific */
98 pid_t i_hog_pid; /* The keep the pid of our hog status */
99 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
100 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
101 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
102 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
103 bool b_revert; /* Whether we need to revert the stream format */
104 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
105 bool b_got_first_sample; /* did the aout core provide something to render? */
107 int i_rate; /* media sample rate */
108 int i_bytes_per_sample;
110 struct audio_device_t *devices;
116 struct audio_device_t
118 struct audio_device_t *next;
125 #pragma mark local prototypes & module descriptor
127 static int Open (vlc_object_t *);
128 static void Close (vlc_object_t *);
129 static int Start (audio_output_t *, audio_sample_format_t *);
130 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
131 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
132 static void Stop (audio_output_t *);
134 static int DeviceList (audio_output_t *p_aout, char ***namesp, char ***descsp);
135 static void RebuildDeviceList (audio_output_t *);
136 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
137 static int VolumeSet (audio_output_t *, float);
138 static int MuteSet (audio_output_t *, bool);
140 static void Play (audio_output_t *, block_t *);
141 static void Pause (audio_output_t *, bool, mtime_t);
142 static void Flush (audio_output_t *, bool);
143 static int TimeGet (audio_output_t *, mtime_t *);
144 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
145 UInt32 , UInt32, AudioBufferList *);
147 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
148 AudioBufferList *, const AudioTimeStamp *, void *);
150 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
151 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
153 static int AudioDeviceHasOutput (AudioDeviceID);
154 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
155 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
156 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
160 set_shortname("auhal")
161 set_description(N_("HAL AudioUnit output"))
162 set_capability("audio output", 101)
163 set_category(CAT_AUDIO)
164 set_subcategory(SUBCAT_AUDIO_AOUT)
165 set_callbacks(Open, Close)
166 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
167 VOLUME_TEXT, VOLUME_LONGTEXT, true)
168 change_integer_range(0, AOUT_VOLUME_MAX)
169 add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
170 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
174 #pragma mark initialization
176 static int Open(vlc_object_t *obj)
178 audio_output_t *aout = (audio_output_t *)obj;
179 aout_sys_t *sys = malloc(sizeof (*sys));
181 if (unlikely(sys == NULL))
184 vlc_mutex_init(&sys->lock);
185 vlc_cond_init(&sys->cond);
190 aout->volume_set = VolumeSet;
191 aout->mute_set = MuteSet;
192 aout->device_enum = DeviceList;
193 aout->sys->devices = NULL;
194 aout->device_select = SwitchAudioDevice;
196 RebuildDeviceList(aout);
198 /* remember the volume */
199 aout_VolumeReport(aout, var_InheritInteger(aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
200 MuteSet(aout, var_InheritBool(aout, "mute"));
202 SwitchAudioDevice(aout, config_GetPsz(aout, "auhal-audio-device"));
207 static void Close(vlc_object_t *obj)
209 audio_output_t *aout = (audio_output_t *)obj;
210 aout_sys_t *sys = aout->sys;
212 config_PutPsz(aout, "auhal-audio-device", aout_DeviceGet(aout));
214 for (struct audio_device_t * device = sys->devices, *next; device != NULL; device = next) {
220 vlc_mutex_destroy(&sys->lock);
221 vlc_cond_destroy(&sys->cond);
226 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
228 OSStatus err = noErr;
229 UInt32 i_param_size = 0;
230 struct aout_sys_t *p_sys = NULL;
232 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
237 p_sys->b_digital = false;
238 p_sys->au_component = NULL;
239 p_sys->au_unit = NULL;
240 p_sys->clock_diff = (mtime_t) 0;
241 p_sys->i_hog_pid = -1;
242 p_sys->i_stream_id = 0;
243 p_sys->i_stream_index = -1;
244 p_sys->b_revert = false;
245 p_sys->b_changed_mixing = false;
246 p_sys->i_bytes_per_sample = 0;
248 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
250 if (p_sys->b_selected_dev_is_digital)
251 msg_Dbg(p_aout, "audio device supports digital output");
253 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
255 /* Check if the desired device is alive and usable */
256 i_param_size = sizeof(b_alive);
257 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
258 kAudioObjectPropertyScopeGlobal,
259 kAudioObjectPropertyElementMaster };
260 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
263 /* Be tolerant, only give a warning here */
264 msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
265 (unsigned int)p_sys->i_selected_dev, (char *)&err);
270 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
271 p_sys->i_selected_dev = p_sys->i_default_dev;
274 /* add a callback to see if the device dies later on */
275 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
277 /* Be tolerant, only give a warning here */
278 msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
279 (unsigned int)p_sys->i_selected_dev, (char *)&err);
282 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
283 kAudioDevicePropertyScopeOutput,
284 kAudioObjectPropertyElementMaster };
285 i_param_size = sizeof(p_sys->i_hog_pid);
286 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
288 /* This is not a fatal error. Some drivers simply don't support this property */
289 msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
291 p_sys->i_hog_pid = -1;
294 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
295 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
296 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
297 _("The selected audio output device is exclusively in "
298 "use by another program."));
302 bool b_success = false;
304 /* Check for Digital mode or Analog output mode */
305 if (AOUT_FMT_SPDIF (fmt) && p_sys->b_selected_dev_is_digital) {
306 if (StartSPDIF (p_aout, fmt)) {
307 msg_Dbg(p_aout, "digital output successfully opened");
311 if (StartAnalog(p_aout, fmt)) {
312 msg_Dbg(p_aout, "analog output successfully opened");
319 p_aout->flush = Flush;
320 p_aout->time_get = TimeGet;
321 p_aout->pause = Pause;
326 /* If we reach this, this aout has failed */
327 msg_Err(p_aout, "opening auhal output failed");
332 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
334 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
336 struct aout_sys_t *p_sys = p_aout->sys;
337 OSStatus err = noErr;
338 UInt32 i_param_size = 0;
340 AudioComponentDescription desc;
341 AudioStreamBasicDescription DeviceFormat;
342 AudioChannelLayout *layout;
343 AudioChannelLayout new_layout;
344 AURenderCallbackStruct input;
345 p_aout->sys->chans_to_reorder = 0;
347 /* Lets go find our Component */
348 desc.componentType = kAudioUnitType_Output;
349 desc.componentSubType = kAudioUnitSubType_HALOutput;
350 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
351 desc.componentFlags = 0;
352 desc.componentFlagsMask = 0;
354 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
355 if (p_sys->au_component == NULL) {
356 msg_Warn(p_aout, "we cannot find our HAL component");
360 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
362 msg_Warn(p_aout, "we cannot open our HAL component");
366 /* Set the device we will use for this output unit */
367 err = AudioUnitSetProperty(p_sys->au_unit,
368 kAudioOutputUnitProperty_CurrentDevice,
369 kAudioUnitScope_Global,
371 &p_sys->i_selected_dev,
372 sizeof(AudioObjectID));
375 msg_Warn(p_aout, "we cannot select the audio device");
379 /* Get the current format */
380 i_param_size = sizeof(AudioStreamBasicDescription);
382 err = AudioUnitGetProperty(p_sys->au_unit,
383 kAudioUnitProperty_StreamFormat,
384 kAudioUnitScope_Output,
392 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
394 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
395 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
396 kAudioDevicePropertyPreferredChannelLayout,
397 kAudioUnitScope_Output,
403 layout = (AudioChannelLayout *)malloc(i_param_size);
405 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
406 kAudioDevicePropertyPreferredChannelLayout,
407 kAudioUnitScope_Output,
412 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
413 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
414 /* bitmap defined channellayout */
415 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
416 sizeof(UInt32), &layout->mChannelBitmap,
419 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
421 /* layouttags defined channellayout */
422 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
423 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
428 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
430 if (layout->mNumberChannelDescriptions == 0) {
431 msg_Err(p_aout, "insufficient number of output channels");
435 /* Initialize the VLC core channel count */
436 fmt->i_physical_channels = 0;
437 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
439 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
440 /* We only need Mono or cannot output more than 1 channel */
441 fmt->i_physical_channels = AOUT_CHAN_CENTER;
442 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
443 /* We only need Stereo or cannot output more than 2 channels */
444 fmt->i_physical_channels = AOUT_CHANS_STEREO;
446 /* We want more than stereo and we can do that */
447 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
449 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
452 switch(layout->mChannelDescriptions[i].mChannelLabel) {
453 case kAudioChannelLabel_Left:
454 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
456 case kAudioChannelLabel_Right:
457 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
459 case kAudioChannelLabel_Center:
460 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
462 case kAudioChannelLabel_LFEScreen:
463 fmt->i_physical_channels |= AOUT_CHAN_LFE;
465 case kAudioChannelLabel_LeftSurround:
466 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
468 case kAudioChannelLabel_RightSurround:
469 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
471 case kAudioChannelLabel_RearSurroundLeft:
472 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
474 case kAudioChannelLabel_RearSurroundRight:
475 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
477 case kAudioChannelLabel_CenterSurround:
478 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
481 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
484 if (fmt->i_physical_channels == 0) {
485 fmt->i_physical_channels = AOUT_CHANS_STEREO;
486 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
487 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
488 _("You should configure your speaker layout with "
489 "the \"Audio Midi Setup\" utility in /Applications/"
490 "Utilities. Stereo mode is being used now."));
495 msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
496 fmt->i_physical_channels = AOUT_CHANS_STEREO;
499 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
500 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
501 p_sys->i_numberOfChannels = aout_FormatNbChannels(fmt);
503 memset (&new_layout, 0, sizeof(new_layout));
504 uint32_t chans_out[AOUT_CHAN_MAX];
506 switch(aout_FormatNbChannels(fmt)) {
508 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
511 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
514 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
515 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
516 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
517 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
520 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
521 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
522 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
523 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
524 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
525 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
528 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
529 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
530 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
531 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
534 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
535 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
537 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
540 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
542 chans_out[0] = AOUT_CHAN_LEFT;
543 chans_out[1] = AOUT_CHAN_RIGHT;
544 chans_out[2] = AOUT_CHAN_CENTER;
545 chans_out[3] = AOUT_CHAN_LFE;
546 chans_out[4] = AOUT_CHAN_REARLEFT;
547 chans_out[5] = AOUT_CHAN_REARRIGHT;
548 chans_out[6] = AOUT_CHAN_REARCENTER;
550 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
551 if (p_aout->sys->chans_to_reorder)
552 msg_Dbg(p_aout, "channel reordering needed");
556 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
558 chans_out[0] = AOUT_CHAN_LEFT;
559 chans_out[1] = AOUT_CHAN_RIGHT;
560 chans_out[2] = AOUT_CHAN_CENTER;
561 chans_out[3] = AOUT_CHAN_LFE;
562 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
563 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
564 chans_out[6] = AOUT_CHAN_REARLEFT;
565 chans_out[7] = AOUT_CHAN_REARRIGHT;
567 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
568 if (p_aout->sys->chans_to_reorder)
569 msg_Dbg(p_aout, "channel reordering needed");
574 /* Set up the format to be used */
575 DeviceFormat.mSampleRate = fmt->i_rate;
576 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
577 p_sys->i_rate = fmt->i_rate;
579 /* We use float 32 since this is VLC's endorsed format */
580 fmt->i_format = VLC_CODEC_FL32;
581 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
582 DeviceFormat.mBitsPerChannel = 32;
583 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
585 /* Calculate framesizes and stuff */
586 DeviceFormat.mFramesPerPacket = 1;
587 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
588 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
590 /* Set the desired format */
591 i_param_size = sizeof(AudioStreamBasicDescription);
592 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
593 kAudioUnitProperty_StreamFormat,
594 kAudioUnitScope_Input,
599 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
601 /* Retrieve actual format */
602 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
603 kAudioUnitProperty_StreamFormat,
604 kAudioUnitScope_Input,
609 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
611 /* Do the last VLC aout setups */
612 aout_FormatPrepare(fmt);
614 /* set the IOproc callback */
615 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
616 input.inputProcRefCon = p_aout;
618 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
619 kAudioUnitProperty_SetRenderCallback,
620 kAudioUnitScope_Input,
621 0, &input, sizeof(input)));
623 /* Set the new_layout as the layout VLC will use to feed the AU unit */
624 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
625 kAudioUnitProperty_AudioChannelLayout,
626 kAudioUnitScope_Output,
627 0, &new_layout, sizeof(new_layout)));
629 if (new_layout.mNumberChannelDescriptions > 0)
630 free(new_layout.mChannelDescriptions);
633 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
635 /* Find the difference between device clock and mdate clock */
636 p_sys->clock_diff = - (mtime_t)
637 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
638 p_sys->clock_diff += mdate();
640 /* setup circular buffer */
641 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
642 fmt->i_rate * fmt->i_bytes_per_frame);
644 p_sys->b_got_first_sample = false;
646 /* Set volume for output unit */
647 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
648 volume = volume * volume * volume;
649 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
650 kHALOutputParam_Volume,
651 kAudioUnitScope_Global,
660 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
662 static int StartSPDIF (audio_output_t * p_aout, audio_sample_format_t *fmt)
664 struct aout_sys_t *p_sys = p_aout->sys;
665 OSStatus err = noErr;
666 UInt32 i_param_size = 0, b_mix = 0;
667 Boolean b_writeable = false;
668 AudioStreamID *p_streams = NULL;
669 unsigned i_streams = 0;
671 /* Start doing the SPDIF setup proces */
672 p_sys->b_digital = true;
675 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
676 i_param_size = sizeof(p_sys->i_hog_pid);
677 p_sys->i_hog_pid = getpid() ;
679 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
682 msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
686 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
688 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
689 /* Set mixable to false if we are allowed to */
690 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
691 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
692 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
694 if (err == noErr && b_writeable) {
696 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
697 p_sys->b_changed_mixing = true;
701 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
706 /* Get a list of all the streams on this device */
707 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
708 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
710 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
714 i_streams = i_param_size / sizeof(AudioStreamID);
715 p_streams = (AudioStreamID *)malloc(i_param_size);
716 if (p_streams == NULL)
719 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
722 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
727 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
728 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
729 /* Find a stream with a cac3 stream */
730 AudioStreamRangedDescription *p_format_list = NULL;
732 bool b_digital = false;
734 /* Retrieve all the stream formats supported by each output stream */
735 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
737 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
741 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
742 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
743 if (p_format_list == NULL)
746 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
748 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
753 /* Check if one of the supported formats is a digital format */
754 for (int j = 0; j < i_formats; j++) {
755 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
756 p_format_list[j].mFormat.mFormatID == 'iac3' ||
757 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
758 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
765 /* if this stream supports a digital (cac3) format, then go set it. */
766 int i_requested_rate_format = -1;
767 int i_current_rate_format = -1;
768 int i_backup_rate_format = -1;
770 p_sys->i_stream_id = p_streams[i];
771 p_sys->i_stream_index = i;
773 if (!p_sys->b_revert) {
774 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
775 /* Retrieve the original format of this stream first if not done so already */
776 i_param_size = sizeof(p_sys->sfmt_revert);
777 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
779 msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
782 p_sys->b_revert = true;
785 for (int j = 0; j < i_formats; j++) {
786 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
787 p_format_list[j].mFormat.mFormatID == 'iac3' ||
788 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
789 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
790 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
791 i_requested_rate_format = j;
793 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
794 i_current_rate_format = j;
796 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
797 i_backup_rate_format = j;
803 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
804 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
805 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
806 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
808 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) */
814 /* get notified when we don't have spdif-output anymore */
815 err = AudioObjectAddPropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
817 msg_Warn(p_aout, "could not set audio device property streams callback on device: %4.4s",
821 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
823 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
826 /* Set the format flags */
827 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
828 fmt->i_format = VLC_CODEC_SPDIFB;
830 fmt->i_format = VLC_CODEC_SPDIFL;
831 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
832 fmt->i_frame_length = A52_FRAME_NB;
833 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
834 p_sys->i_rate = fmt->i_rate;
835 aout_FormatPrepare(fmt);
837 /* Add IOProc callback */
838 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
839 (AudioDeviceIOProc)RenderCallbackSPDIF,
843 msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
847 /* Check for the difference between the Device clock and mdate */
848 p_sys->clock_diff = - (mtime_t)
849 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
850 p_sys->clock_diff += mdate();
853 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
855 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
857 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
859 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
864 /* setup circular buffer */
865 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
870 static void Stop(audio_output_t *p_aout)
872 struct aout_sys_t *p_sys = p_aout->sys;
873 OSStatus err = noErr;
874 UInt32 i_param_size = 0;
876 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
877 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
879 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
881 if (p_sys->b_digital) {
882 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
883 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
885 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
888 if (p_sys->au_unit) {
889 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
890 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
891 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
894 if (p_sys->b_digital) {
896 err = AudioDeviceStop(p_sys->i_selected_dev,
899 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
901 /* Remove IOProc callback */
902 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
905 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
908 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
910 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
912 Boolean b_writeable = false;
913 /* Revert mixable to true if we are allowed to */
914 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
915 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
916 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
918 if (err == noErr && b_writeable) {
919 msg_Dbg(p_aout, "mixable is: %d", b_mix);
921 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
925 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
929 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
930 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
933 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
935 if (p_sys->i_hog_pid == getpid()) {
936 p_sys->i_hog_pid = -1;
937 i_param_size = sizeof(p_sys->i_hog_pid);
938 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
939 kAudioDevicePropertyScopeOutput,
940 kAudioObjectPropertyElementMaster };
941 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
943 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
946 p_sys->i_bytes_per_sample = 0;
948 /* clean-up circular buffer */
949 TPCircularBufferCleanup(&p_sys->circular_buffer);
953 #pragma mark core interaction
955 static int DeviceList(audio_output_t *p_aout, char ***namesp, char ***descsp)
957 struct aout_sys_t *p_sys = p_aout->sys;
958 char **names, **descs;
961 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next)
964 *namesp = names = xmalloc(sizeof(*names) * n);
965 *descsp = descs = xmalloc(sizeof(*descs) * n);
968 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next) {
969 sprintf(deviceid, "%i", device->deviceid);
970 *(names++) = strdup(deviceid);
971 *(descs++) = strdup(device->name);
977 static void add_device_to_list(audio_output_t * p_aout, UInt32 i_id, char *name)
979 struct aout_sys_t *p_sys = p_aout->sys;
981 struct audio_device_t *device = malloc(sizeof(*device));
982 if (unlikely(device == NULL))
985 device->next = p_sys->devices;
986 device->deviceid = i_id;
987 device->name = strdup(name);
989 p_sys->devices = device;
992 static void RebuildDeviceList(audio_output_t * p_aout)
994 OSStatus err = noErr;
995 UInt32 propertySize = 0;
996 AudioObjectID defaultDeviceID = 0;
997 AudioObjectID *deviceIDs;
998 UInt32 numberOfDevices;
1000 struct aout_sys_t *p_sys = p_aout->sys;
1002 if (p_sys->devices) {
1003 for (struct audio_device_t * device = p_sys->devices, *next; device != NULL; device = next) {
1004 next = device->next;
1009 p_sys->devices = NULL;
1011 /* Get number of devices */
1012 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1013 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1015 msg_Err(p_aout, "Could not get number of devices: [%s]", (char *)&err);
1019 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1021 if (numberOfDevices < 1) {
1022 msg_Err(p_aout, "No audio output devices were found.");
1025 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1027 /* Allocate DeviceID array */
1028 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1029 if (deviceIDs == NULL)
1032 /* Populate DeviceID array */
1033 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1035 msg_Err(p_aout, "could not get the device IDs: [%s]", (char *)&err);
1039 /* Find the ID of the default Device */
1040 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1041 propertySize = sizeof(AudioObjectID);
1042 err= AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1044 msg_Err(p_aout, "could not get default audio device: [%s]", (char *)&err);
1047 p_sys->i_default_dev = defaultDeviceID;
1049 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1051 for (unsigned int i = 0; i < numberOfDevices; i++) {
1052 CFStringRef device_name_ref;
1055 bool b_digital = false;
1056 UInt32 i_id = deviceIDs[i];
1058 /* Retrieve the length of the device name */
1059 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1061 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1065 /* Retrieve the name of the device */
1066 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1068 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1071 length = CFStringGetLength(device_name_ref);
1073 psz_name = (char *)malloc(length);
1074 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1076 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1078 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1079 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1084 add_device_to_list(p_aout, i_id, psz_name);
1086 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1088 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1089 char *psz_encoded_name = nil;
1090 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1091 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1092 add_device_to_list(p_aout, i_id, psz_encoded_name);
1093 free(psz_encoded_name);
1096 CFRelease(device_name_ref);
1100 add_device_to_list(p_aout, 0, _("System Sound Output Device"));
1102 /* Attach a Listener so that we are notified of a change in the Device setup */
1103 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
1105 msg_Warn(p_aout, "failed to add listener for audio device configuration (%i)", err);
1110 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1112 struct aout_sys_t *p_sys = p_aout->sys;
1115 p_sys->i_selected_dev = atoi(name);
1117 p_sys->i_selected_dev = 0;
1119 bool b_supports_digital = (p_sys->i_selected_dev & AOUT_VAR_SPDIF_FLAG);
1120 if (b_supports_digital)
1121 p_sys->b_selected_dev_is_digital = true;
1123 p_sys->b_selected_dev_is_digital = false;
1125 p_sys->i_selected_dev = p_sys->i_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1127 aout_DeviceReport(p_aout, name);
1128 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1133 static int VolumeSet(audio_output_t * p_aout, float volume)
1135 struct aout_sys_t *p_sys = p_aout->sys;
1138 aout_VolumeReport(p_aout, volume);
1140 /* Set volume for output unit */
1141 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1142 kHALOutputParam_Volume,
1143 kAudioUnitScope_Global,
1145 volume * volume * volume,
1148 if (var_InheritBool(p_aout, "volume-save"))
1149 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1154 static int MuteSet(audio_output_t * p_aout, bool mute)
1156 struct aout_sys_t *p_sys = p_aout->sys;
1159 aout_MuteReport(p_aout, mute);
1164 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1166 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1167 kHALOutputParam_Volume,
1168 kAudioUnitScope_Global,
1170 volume * volume * volume,
1177 #pragma mark actual playback
1179 static void Play (audio_output_t * p_aout, block_t * p_block)
1181 struct aout_sys_t *p_sys = p_aout->sys;
1183 if (p_block->i_nb_samples > 0) {
1184 if (!p_sys->b_got_first_sample) {
1186 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1187 p_sys->b_got_first_sample = true;
1190 /* Do the channel reordering */
1191 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1192 aout_ChannelReorder(p_block->p_buffer,
1194 p_sys->chans_to_reorder,
1199 /* move data to buffer */
1200 if (unlikely(TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer) == 0)) {
1201 msg_Warn(p_aout, "Audio buffer was dropped");
1204 if (!p_sys->i_bytes_per_sample)
1205 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1208 block_Release(p_block);
1211 static void Pause (audio_output_t *p_aout, bool pause, mtime_t date)
1213 struct aout_sys_t * p_sys = p_aout->sys;
1216 if (p_aout->sys->b_digital) {
1218 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1220 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1223 AudioOutputUnitStop(p_sys->au_unit);
1225 AudioOutputUnitStart(p_sys->au_unit);
1229 static void Flush(audio_output_t *p_aout, bool wait)
1231 struct aout_sys_t *p_sys = p_aout->sys;
1234 int32_t availableBytes;
1235 vlc_mutex_lock(&p_sys->lock);
1236 while (TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes) != NULL) {
1237 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1239 vlc_mutex_unlock(&p_sys->lock);
1242 p_sys->b_got_first_sample = false;
1244 /* flush circular buffer */
1245 AudioOutputUnitStop(p_aout->sys->au_unit);
1246 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1250 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1252 struct aout_sys_t * p_sys = p_aout->sys;
1254 if (!p_sys->i_bytes_per_sample)
1257 int32_t availableBytes;
1258 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1260 *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1265 /*****************************************************************************
1266 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1267 * us to provide some more audio data.
1268 * Don't print anything during normal playback, calling blocking function from
1269 * this callback is not allowed.
1270 *****************************************************************************/
1271 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1272 AudioUnitRenderActionFlags *ioActionFlags,
1273 const AudioTimeStamp *inTimeStamp,
1275 UInt32 inNumberFrames,
1276 AudioBufferList *ioData) {
1277 VLC_UNUSED(ioActionFlags);
1278 VLC_UNUSED(inTimeStamp);
1279 VLC_UNUSED(inBusNumber);
1281 audio_output_t * p_aout = (audio_output_t *)p_obj;
1282 struct aout_sys_t * p_sys = p_aout->sys;
1284 int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1285 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1287 /* Pull audio from buffer */
1288 int32_t availableBytes;
1289 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1291 /* check if we have enough data */
1292 if (!availableBytes) {
1293 /* return an empty buffer so silence is played until we have data */
1294 for (UInt32 j = 0; j < inNumberFrames; j++)
1295 targetBuffer[j] = 0.;
1297 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1298 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1299 VLC_UNUSED(inNumberFrames);
1302 vlc_mutex_lock(&p_sys->lock);
1303 vlc_cond_signal(&p_sys->cond);
1304 vlc_mutex_unlock(&p_sys->lock);
1310 * RenderCallbackSPDIF: callback for SPDIF audio output
1312 static OSStatus RenderCallbackSPDIF (AudioDeviceID inDevice,
1313 const AudioTimeStamp * inNow,
1314 const void * inInputData,
1315 const AudioTimeStamp * inInputTime,
1316 AudioBufferList * outOutputData,
1317 const AudioTimeStamp * inOutputTime,
1318 void * threadGlobals)
1321 VLC_UNUSED(inDevice);
1322 VLC_UNUSED(inInputData);
1323 VLC_UNUSED(inInputTime);
1324 VLC_UNUSED(inOutputTime);
1326 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1327 struct aout_sys_t * p_sys = p_aout->sys;
1329 int bytesToCopy = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1330 Float32 *targetBuffer = (Float32*)outOutputData->mBuffers[p_sys->i_stream_index].mData;
1332 /* Pull audio from buffer */
1333 int32_t availableBytes;
1334 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1336 /* check if we have enough data */
1337 if (!availableBytes) {
1338 /* return an empty buffer so silence is played until we have data */
1339 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1341 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1342 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1345 vlc_mutex_lock(&p_sys->lock);
1346 vlc_cond_signal(&p_sys->cond);
1347 vlc_mutex_unlock(&p_sys->lock);
1353 #pragma mark Stream / Hardware Listeners
1356 * HardwareListener: Warns us of changes in the list of registered devices
1358 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1360 OSStatus err = noErr;
1361 audio_output_t *p_aout = (audio_output_t *)inClientData;
1362 VLC_UNUSED(inObjectID);
1363 VLC_UNUSED(inNumberAddresses);
1364 VLC_UNUSED(inAddresses);
1370 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1371 switch (inAddresses[i].mSelector) {
1372 case kAudioHardwarePropertyDevices:
1373 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1376 case kAudioDevicePropertyDeviceIsAlive:
1377 msg_Warn(p_aout, "audio device died, resetting aout");
1380 case kAudioStreamPropertyAvailablePhysicalFormats:
1381 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1385 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1391 RebuildDeviceList(p_aout);
1392 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1398 * StreamListener: check whether the device's physical format changes on-the-fly (unlikely)
1400 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1402 OSStatus err = noErr;
1403 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1405 VLC_UNUSED(inObjectID);
1407 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1408 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1409 vlc_mutex_lock(&w->lock);
1410 vlc_cond_signal(&w->cond);
1411 vlc_mutex_unlock(&w->lock);
1419 #pragma mark helpers
1422 * AudioDeviceHasOutput: Checks if the device is actually an output device
1424 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1426 UInt32 dataSize = 0;
1429 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1430 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1432 if (dataSize == 0 || status != noErr)
1439 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1441 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1443 OSStatus err = noErr;
1444 UInt32 i_param_size = 0;
1445 AudioStreamID *p_streams = NULL;
1447 bool b_return = false;
1449 /* Retrieve all the output streams */
1450 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1451 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1453 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1457 i_streams = i_param_size / sizeof(AudioStreamID);
1458 p_streams = (AudioStreamID *)malloc(i_param_size);
1459 if (p_streams == NULL)
1462 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1464 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1468 for (int i = 0; i < i_streams; i++) {
1469 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1478 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1480 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1482 OSStatus err = noErr;
1483 UInt32 i_param_size = 0;
1484 AudioStreamRangedDescription *p_format_list = NULL;
1486 bool b_return = false;
1488 /* Retrieve all the stream formats supported by each output stream */
1489 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1490 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1492 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1496 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1497 msg_Dbg(p_aout, "found %i stream formats", i_formats);
1499 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1500 if (p_format_list == NULL)
1503 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1505 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1506 free(p_format_list);
1507 p_format_list = NULL;
1511 for (int i = 0; i < i_formats; i++) {
1513 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1516 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1517 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1518 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1519 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1523 free(p_format_list);
1528 * AudioStreamChangeFormat: switch stream format based on the provided description
1530 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1532 OSStatus err = noErr;
1533 UInt32 i_param_size = 0;
1535 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1537 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1539 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1541 /* Condition because SetProperty is asynchronious */
1542 vlc_cond_init(&w.cond);
1543 vlc_mutex_init(&w.lock);
1544 vlc_mutex_lock(&w.lock);
1546 /* Install the callback */
1547 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1549 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1553 /* change the format */
1554 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1557 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1561 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1562 * it is also not atomic in its behaviour.
1563 * Therefore we check 5 times before we really give up.
1564 * FIXME: failing isn't actually implemented yet. */
1565 for (int i = 0; i < 5; i++) {
1566 AudioStreamBasicDescription actual_format;
1567 mtime_t timeout = mdate() + 500000;
1569 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1570 msg_Dbg(p_aout, "reached timeout");
1572 i_param_size = sizeof(AudioStreamBasicDescription);
1573 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1575 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1576 if (actual_format.mSampleRate == change_format.mSampleRate &&
1577 actual_format.mFormatID == change_format.mFormatID &&
1578 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1579 /* The right format is now active */
1582 /* We need to check again */
1585 /* Removing the property listener */
1586 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1588 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1592 /* Destroy the lock and condition */
1593 vlc_mutex_unlock(&w.lock);
1594 vlc_mutex_destroy(&w.lock);
1595 vlc_cond_destroy(&w.cond);