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 AudioObjectID i_new_selected_dev; /* DeviceID of device which will be selected on start */
83 bool b_selected_dev_is_digital;
84 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
85 bool b_digital; /* Are we running in digital mode? */
86 mtime_t clock_diff; /* Difference between VLC clock and Device clock */
88 uint8_t chans_to_reorder; /* do we need channel reordering */
89 uint8_t chan_table[AOUT_CHAN_MAX];
91 UInt32 i_numberOfChannels;
92 TPCircularBuffer circular_buffer; /* circular buffer to swap the audio data */
95 AudioComponent au_component; /* The AudioComponent we use */
96 AudioUnit au_unit; /* The AudioUnit we use */
98 /* CoreAudio SPDIF mode specific */
99 pid_t i_hog_pid; /* The keep the pid of our hog status */
100 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
101 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
102 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
103 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
104 bool b_revert; /* Whether we need to revert the stream format */
105 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
108 bool b_got_first_sample; /* did the aout core provide something to render? */
110 int i_rate; /* media sample rate */
111 int i_bytes_per_sample;
113 CFArrayRef device_list;
123 #pragma mark local prototypes & module descriptor
125 static int Open (vlc_object_t *);
126 static void Close (vlc_object_t *);
127 static int Start (audio_output_t *, audio_sample_format_t *);
128 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
129 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
130 static void Stop (audio_output_t *);
132 static void RebuildDeviceList (audio_output_t *);
133 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
134 static int VolumeSet (audio_output_t *, float);
135 static int MuteSet (audio_output_t *, bool);
137 static void Play (audio_output_t *, block_t *);
138 static void Pause (audio_output_t *, bool, mtime_t);
139 static void Flush (audio_output_t *, bool);
140 static int TimeGet (audio_output_t *, mtime_t *);
141 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
142 UInt32 , UInt32, AudioBufferList *);
144 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
145 AudioBufferList *, const AudioTimeStamp *, void *);
147 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
148 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
150 static int RegisterAudioStreamsCallback(audio_output_t *, AudioDeviceID);
151 static int AudioDeviceHasOutput (AudioDeviceID);
152 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
153 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
154 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
158 set_shortname("auhal")
159 set_description(N_("HAL AudioUnit output"))
160 set_capability("audio output", 101)
161 set_category(CAT_AUDIO)
162 set_subcategory(SUBCAT_AUDIO_AOUT)
163 set_callbacks(Open, Close)
164 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
165 VOLUME_TEXT, VOLUME_LONGTEXT, true)
166 change_integer_range(0, AOUT_VOLUME_MAX)
167 add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
168 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
172 #pragma mark initialization
174 static int Open(vlc_object_t *obj)
176 audio_output_t *p_aout = (audio_output_t *)obj;
177 aout_sys_t *p_sys = malloc(sizeof (*p_sys));
178 if (unlikely(p_sys == NULL))
181 OSStatus err = noErr;
183 vlc_mutex_init(&p_sys->lock);
184 vlc_cond_init(&p_sys->cond);
185 p_sys->b_digital = false;
188 p_aout->start = Start;
190 p_aout->volume_set = VolumeSet;
191 p_aout->mute_set = MuteSet;
192 p_aout->device_select = SwitchAudioDevice;
193 p_sys->device_list = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL);
195 /* Attach a Listener so that we are notified of a change in the Device setup */
196 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
197 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
199 msg_Warn(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
201 RebuildDeviceList(p_aout);
203 /* remember the volume */
204 p_sys->f_volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
205 aout_VolumeReport(p_aout, p_sys->f_volume);
206 p_sys->b_mute = var_InheritBool(p_aout, "mute");
207 aout_MuteReport(p_aout, p_sys->b_mute);
209 SwitchAudioDevice(p_aout, config_GetPsz(p_aout, "auhal-audio-device"));
214 static void Close(vlc_object_t *obj)
216 audio_output_t *p_aout = (audio_output_t *)obj;
217 aout_sys_t *p_sys = p_aout->sys;
219 OSStatus err = noErr;
221 /* remove audio devices callback */
222 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
223 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
225 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed [%4.4s]", (char *)&err);
228 /* remove audio device alive callback */
229 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
230 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
232 msg_Err(p_aout, "failed to remove audio device life checker [%4.4s]", (char *)&err);
234 /* remove audio streams callback */
235 if (p_sys->i_stream_id > 0) {
236 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
237 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
239 msg_Err(p_aout, "failed to remove audio device property streams callback [%4.4s]", (char *)&err);
242 config_PutPsz(p_aout, "auhal-audio-device", aout_DeviceGet(p_aout));
244 CFRelease(p_sys->device_list);
246 vlc_mutex_destroy(&p_sys->lock);
247 vlc_cond_destroy(&p_sys->cond);
252 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
254 OSStatus err = noErr;
255 UInt32 i_param_size = 0;
256 struct aout_sys_t *p_sys = NULL;
258 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
262 bool b_start_digital = false;
265 p_sys->b_digital = false;
266 p_sys->au_component = NULL;
267 p_sys->au_unit = NULL;
268 p_sys->clock_diff = (mtime_t) 0;
269 p_sys->i_hog_pid = -1;
270 p_sys->i_stream_id = 0;
271 p_sys->i_stream_index = -1;
272 p_sys->b_revert = false;
273 p_sys->b_changed_mixing = false;
274 p_sys->i_bytes_per_sample = 0;
276 p_sys->i_selected_dev = p_sys->i_new_selected_dev;
278 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
280 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
282 /* Check if the desired device is alive and usable */
283 i_param_size = sizeof(b_alive);
284 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
285 kAudioObjectPropertyScopeGlobal,
286 kAudioObjectPropertyElementMaster };
287 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
290 /* Be tolerant, only give a warning here */
291 msg_Warn(p_aout, "could not check whether device [0x%x] is alive [%4.4s]",
292 (unsigned int)p_sys->i_selected_dev, (char *)&err);
296 if (!b_alive || p_sys->i_selected_dev == 0) {
297 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
299 AudioObjectID defaultDeviceID = 0;
300 UInt32 propertySize = 0;
301 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
302 propertySize = sizeof(AudioObjectID);
303 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
305 msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
309 msg_Dbg(p_aout, "using default audio device %i", defaultDeviceID);
311 p_sys->i_selected_dev = defaultDeviceID;
314 // recheck if device still supports digital
315 b_start_digital = p_sys->b_selected_dev_is_digital;
316 if(!AudioDeviceSupportsDigital(p_aout, p_sys->i_selected_dev))
317 b_start_digital = false;
320 msg_Dbg(p_aout, "Using audio device for digital output");
322 msg_Dbg(p_aout, "Audio device supports PCM mode only");
324 /* add a callback to see if the device dies later on */
325 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
327 /* Be tolerant, only give a warning here */
328 msg_Warn(p_aout, "could not set alive check callback on device [0x%x] [%4.4s]",
329 (unsigned int)p_sys->i_selected_dev, (char *)&err);
332 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
333 kAudioDevicePropertyScopeOutput,
334 kAudioObjectPropertyElementMaster };
335 i_param_size = sizeof(p_sys->i_hog_pid);
336 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
338 /* This is not a fatal error. Some drivers simply don't support this property */
339 msg_Warn(p_aout, "could not check whether device is hogged [%4.4s]",
341 p_sys->i_hog_pid = -1;
344 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
345 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
346 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
347 _("The selected audio output device is exclusively in "
348 "use by another program."));
352 bool b_success = false;
354 /* Check for Digital mode or Analog output mode */
355 if (AOUT_FMT_SPDIF (fmt) && b_start_digital) {
356 if (StartSPDIF (p_aout, fmt)) {
357 msg_Dbg(p_aout, "digital output successfully opened");
361 if (StartAnalog(p_aout, fmt)) {
362 msg_Dbg(p_aout, "analog output successfully opened");
369 p_aout->flush = Flush;
370 p_aout->time_get = TimeGet;
371 p_aout->pause = Pause;
376 /* If we reach this, this aout has failed */
377 msg_Err(p_aout, "opening auhal output failed");
382 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
384 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
386 struct aout_sys_t *p_sys = p_aout->sys;
387 OSStatus err = noErr;
388 UInt32 i_param_size = 0;
390 AudioComponentDescription desc;
391 AudioStreamBasicDescription DeviceFormat;
392 AudioChannelLayout *layout;
393 AudioChannelLayout new_layout;
394 AURenderCallbackStruct input;
395 p_aout->sys->chans_to_reorder = 0;
397 SInt32 currentMinorSystemVersion;
398 if(Gestalt(gestaltSystemVersionMinor, ¤tMinorSystemVersion) != noErr)
399 msg_Err(p_aout, "failed to check OSX version");
401 /* Lets go find our Component */
402 desc.componentType = kAudioUnitType_Output;
403 desc.componentSubType = kAudioUnitSubType_HALOutput;
404 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
405 desc.componentFlags = 0;
406 desc.componentFlagsMask = 0;
408 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
409 if (p_sys->au_component == NULL) {
410 msg_Err(p_aout, "cannot find any HAL component, PCM output failed");
414 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
416 msg_Err(p_aout, "cannot open HAL component, PCM output failed [%4.4s]", (char *)&err);
420 /* Set the device we will use for this output unit */
421 err = AudioUnitSetProperty(p_sys->au_unit,
422 kAudioOutputUnitProperty_CurrentDevice,
423 kAudioUnitScope_Global,
425 &p_sys->i_selected_dev,
426 sizeof(AudioObjectID));
429 msg_Err(p_aout, "cannot select audio output device, PCM output failed [%4.4s]", (char *)&err);
433 /* Get the current format */
434 i_param_size = sizeof(AudioStreamBasicDescription);
436 err = AudioUnitGetProperty(p_sys->au_unit,
437 kAudioUnitProperty_StreamFormat,
438 kAudioUnitScope_Output,
444 msg_Err(p_aout, "failed to detect supported stream formats [%4.4s]", (char *)&err);
447 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
449 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
450 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
451 kAudioDevicePropertyPreferredChannelLayout,
452 kAudioUnitScope_Output,
458 layout = (AudioChannelLayout *)malloc(i_param_size);
460 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
461 kAudioDevicePropertyPreferredChannelLayout,
462 kAudioUnitScope_Output,
467 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
468 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
469 /* bitmap defined channellayout */
470 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
471 sizeof(UInt32), &layout->mChannelBitmap,
474 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
476 /* layouttags defined channellayout */
477 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
478 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
483 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
485 if (layout->mNumberChannelDescriptions == 0) {
486 msg_Err(p_aout, "insufficient number of output channels");
490 /* Initialize the VLC core channel count */
491 fmt->i_physical_channels = 0;
492 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
494 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
495 /* We only need Mono or cannot output more than 1 channel */
496 fmt->i_physical_channels = AOUT_CHAN_CENTER;
497 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
498 /* We only need Stereo or cannot output more than 2 channels */
499 fmt->i_physical_channels = AOUT_CHANS_STEREO;
501 /* We want more than stereo and we can do that */
502 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
504 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
507 switch(layout->mChannelDescriptions[i].mChannelLabel) {
508 case kAudioChannelLabel_Left:
509 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
511 case kAudioChannelLabel_Right:
512 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
514 case kAudioChannelLabel_Center:
515 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
517 case kAudioChannelLabel_LFEScreen:
518 fmt->i_physical_channels |= AOUT_CHAN_LFE;
520 case kAudioChannelLabel_LeftSurround:
521 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
523 case kAudioChannelLabel_RightSurround:
524 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
526 case kAudioChannelLabel_RearSurroundLeft:
527 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
529 case kAudioChannelLabel_RearSurroundRight:
530 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
532 case kAudioChannelLabel_CenterSurround:
533 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
536 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
539 if (fmt->i_physical_channels == 0) {
540 fmt->i_physical_channels = AOUT_CHANS_STEREO;
541 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup in /Applications/Utilities. VLC will output Stereo only.");
542 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
543 _("You should configure your speaker layout with "
544 "\"Audio Midi Setup\" in /Applications/"
545 "Utilities. VLC will output Stereo only."));
550 msg_Warn(p_aout, "device driver does not support kAudioDevicePropertyPreferredChannelLayout - using stereo fallback [%4.4s]", (char *)&err);
551 fmt->i_physical_channels = AOUT_CHANS_STEREO;
554 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
555 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
556 p_sys->i_numberOfChannels = aout_FormatNbChannels(fmt);
558 memset (&new_layout, 0, sizeof(new_layout));
559 uint32_t chans_out[AOUT_CHAN_MAX];
561 /* Some channel abbreviations used below:
566 * Rs - right surround
567 * Cs - center surround
568 * Rls - rear left surround
569 * Rrs - rear right surround
572 * Lsd - left surround direct
573 * Rsd - right surround direct
577 * Vhl - vertical height left
578 * Vhc - vertical height center
579 * Vhr - vertical height right
580 * Lt - left matrix total. for matrix encoded stereo.
581 * Rt - right matrix total. for matrix encoded stereo. */
583 switch(aout_FormatNbChannels(fmt)) {
585 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
588 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
591 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
592 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
593 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
594 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
597 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
598 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
599 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
600 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
601 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
602 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
605 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
606 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
607 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
608 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
611 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
612 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
614 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
617 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
619 chans_out[0] = AOUT_CHAN_LEFT;
620 chans_out[1] = AOUT_CHAN_RIGHT;
621 chans_out[2] = AOUT_CHAN_CENTER;
622 chans_out[3] = AOUT_CHAN_LFE;
623 chans_out[4] = AOUT_CHAN_REARLEFT;
624 chans_out[5] = AOUT_CHAN_REARRIGHT;
625 chans_out[6] = AOUT_CHAN_REARCENTER;
627 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
628 if (p_aout->sys->chans_to_reorder)
629 msg_Dbg(p_aout, "channel reordering needed for 6.1 output");
633 if (fmt->i_physical_channels & (AOUT_CHAN_LFE) || currentMinorSystemVersion < 7) {
634 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
636 chans_out[0] = AOUT_CHAN_LEFT;
637 chans_out[1] = AOUT_CHAN_RIGHT;
638 chans_out[2] = AOUT_CHAN_CENTER;
639 chans_out[3] = AOUT_CHAN_LFE;
640 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
641 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
642 chans_out[6] = AOUT_CHAN_REARLEFT;
643 chans_out[7] = AOUT_CHAN_REARRIGHT;
645 if (!(fmt->i_physical_channels & (AOUT_CHAN_LFE)))
646 msg_Warn(p_aout, "8.0 audio output not supported on OS X 10.%i, layout will be incorrect", currentMinorSystemVersion);
648 #ifdef MAC_OS_X_VERSION_10_7
650 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_0_B; // Lc C Rc L R Ls Cs Rs
652 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
653 chans_out[1] = AOUT_CHAN_CENTER;
654 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
655 chans_out[3] = AOUT_CHAN_LEFT;
656 chans_out[4] = AOUT_CHAN_RIGHT;
657 chans_out[5] = AOUT_CHAN_REARLEFT;
658 chans_out[6] = AOUT_CHAN_REARCENTER;
659 chans_out[7] = AOUT_CHAN_REARRIGHT;
662 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
663 if (p_aout->sys->chans_to_reorder)
664 msg_Dbg(p_aout, "channel reordering needed for 7.1 / 8.0 output");
668 if (currentMinorSystemVersion < 7) {
669 msg_Warn(p_aout, "8.1 audio output not supported on OS X 10.%i", currentMinorSystemVersion);
673 #ifdef MAC_OS_X_VERSION_10_7
674 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_1_B; // Lc C Rc L R Ls Cs Rs LFE
675 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
676 chans_out[1] = AOUT_CHAN_CENTER;
677 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
678 chans_out[3] = AOUT_CHAN_LEFT;
679 chans_out[4] = AOUT_CHAN_RIGHT;
680 chans_out[5] = AOUT_CHAN_REARLEFT;
681 chans_out[6] = AOUT_CHAN_REARCENTER;
682 chans_out[7] = AOUT_CHAN_REARRIGHT;
683 chans_out[8] = AOUT_CHAN_LFE;
685 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
686 if (p_aout->sys->chans_to_reorder)
687 msg_Dbg(p_aout, "channel reordering needed for 8.1 output");
692 /* Set up the format to be used */
693 DeviceFormat.mSampleRate = fmt->i_rate;
694 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
695 p_sys->i_rate = fmt->i_rate;
697 /* We use float 32 since this is VLC's endorsed format */
698 fmt->i_format = VLC_CODEC_FL32;
699 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
700 DeviceFormat.mBitsPerChannel = 32;
701 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
703 /* Calculate framesizes and stuff */
704 DeviceFormat.mFramesPerPacket = 1;
705 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
706 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
708 /* Set the desired format */
709 i_param_size = sizeof(AudioStreamBasicDescription);
710 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
711 kAudioUnitProperty_StreamFormat,
712 kAudioUnitScope_Input,
717 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
719 /* Retrieve actual format */
720 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
721 kAudioUnitProperty_StreamFormat,
722 kAudioUnitScope_Input,
727 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
729 /* Do the last VLC aout setups */
730 aout_FormatPrepare(fmt);
732 /* set the IOproc callback */
733 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
734 input.inputProcRefCon = p_aout;
736 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
737 kAudioUnitProperty_SetRenderCallback,
738 kAudioUnitScope_Input,
739 0, &input, sizeof(input)));
741 /* Set the new_layout as the layout VLC will use to feed the AU unit */
742 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
743 kAudioUnitProperty_AudioChannelLayout,
744 kAudioUnitScope_Output,
745 0, &new_layout, sizeof(new_layout)));
747 if (new_layout.mNumberChannelDescriptions > 0)
748 free(new_layout.mChannelDescriptions);
751 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
753 /* Find the difference between device clock and mdate clock */
754 p_sys->clock_diff = - (mtime_t)
755 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
756 p_sys->clock_diff += mdate();
758 /* setup circular buffer */
759 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
760 fmt->i_rate * fmt->i_bytes_per_frame);
762 p_sys->b_got_first_sample = false;
764 /* Set volume for output unit */
765 VolumeSet(p_aout, p_sys->f_volume);
766 MuteSet(p_aout, p_sys->b_mute);
772 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
774 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
776 struct aout_sys_t *p_sys = p_aout->sys;
777 OSStatus err = noErr;
778 UInt32 i_param_size = 0, b_mix = 0;
779 Boolean b_writeable = false;
780 AudioStreamID *p_streams = NULL;
781 unsigned i_streams = 0;
783 /* Start doing the SPDIF setup proces */
784 p_sys->b_digital = true;
787 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
788 i_param_size = sizeof(p_sys->i_hog_pid);
789 p_sys->i_hog_pid = getpid() ;
791 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
794 msg_Err(p_aout, "failed to set hogmode [%4.4s]", (char *)&err);
798 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
800 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
801 /* Set mixable to false if we are allowed to */
802 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
803 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
804 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
806 if (err == noErr && b_writeable) {
808 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
809 p_sys->b_changed_mixing = true;
813 msg_Err(p_aout, "failed to set mixmode [%4.4s]", (char *)&err);
818 /* Get a list of all the streams on this device */
819 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
820 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
822 msg_Err(p_aout, "could not get size of stream description packet [%4.4s]", (char *)&err);
826 i_streams = i_param_size / sizeof(AudioStreamID);
827 p_streams = (AudioStreamID *)malloc(i_param_size);
828 if (p_streams == NULL)
831 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
834 msg_Err(p_aout, "could not fetch stream descriptions [%4.4s]", (char *)&err);
839 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
840 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
841 /* Find a stream with a cac3 stream */
842 AudioStreamRangedDescription *p_format_list = NULL;
844 bool b_digital = false;
846 /* Retrieve all the stream formats supported by each output stream */
847 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
849 msg_Err(p_aout, "could not get number of streamformats: [%4.4s] (%i)", (char *)&err, (int32_t)err);
853 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
854 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
855 if (p_format_list == NULL)
858 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
860 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
865 /* Check if one of the supported formats is a digital format */
866 for (int j = 0; j < i_formats; j++) {
867 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
868 p_format_list[j].mFormat.mFormatID == 'iac3' ||
869 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
870 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
877 /* if this stream supports a digital (cac3) format, then go set it. */
878 int i_requested_rate_format = -1;
879 int i_current_rate_format = -1;
880 int i_backup_rate_format = -1;
882 p_sys->i_stream_id = p_streams[i];
883 p_sys->i_stream_index = i;
885 if (!p_sys->b_revert) {
886 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
887 /* Retrieve the original format of this stream first if not done so already */
888 i_param_size = sizeof(p_sys->sfmt_revert);
889 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
891 msg_Err(p_aout, "could not retrieve the original streamformat [%4.4s]", (char *)&err);
894 p_sys->b_revert = true;
897 for (int j = 0; j < i_formats; j++) {
898 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
899 p_format_list[j].mFormat.mFormatID == 'iac3' ||
900 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
901 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
902 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
903 i_requested_rate_format = j;
905 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
906 i_current_rate_format = j;
908 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
909 i_backup_rate_format = j;
915 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
916 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
917 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
918 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
920 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) */
926 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
928 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format)) {
929 msg_Err(p_aout, "failed to change stream format for SPDIF output");
933 /* Set the format flags */
934 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
935 fmt->i_format = VLC_CODEC_SPDIFB;
937 fmt->i_format = VLC_CODEC_SPDIFL;
938 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
939 fmt->i_frame_length = A52_FRAME_NB;
940 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
941 p_sys->i_rate = fmt->i_rate;
942 aout_FormatPrepare(fmt);
944 /* Add IOProc callback */
945 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
946 (AudioDeviceIOProc)RenderCallbackSPDIF,
950 msg_Err(p_aout, "Failed to create Process ID [%4.4s]", (char *)&err);
954 /* Check for the difference between the Device clock and mdate */
955 p_sys->clock_diff = - (mtime_t)
956 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
957 p_sys->clock_diff += mdate();
960 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
962 msg_Err(p_aout, "Failed to start audio device [%4.4s]", (char *)&err);
964 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
966 msg_Err(p_aout, "Failed to destroy process ID [%4.4s]", (char *)&err);
971 /* setup circular buffer */
972 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
977 static void Stop(audio_output_t *p_aout)
979 struct aout_sys_t *p_sys = p_aout->sys;
980 OSStatus err = noErr;
981 UInt32 i_param_size = 0;
983 if (p_sys->au_unit) {
984 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
985 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
986 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
989 if (p_sys->b_digital) {
991 err = AudioDeviceStop(p_sys->i_selected_dev,
994 msg_Err(p_aout, "Failed to stop audio device [%4.4s]", (char *)&err);
996 /* Remove IOProc callback */
997 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
1000 msg_Err(p_aout, "Failed to destroy Process ID [%4.4s]", (char *)&err);
1002 if (p_sys->b_revert)
1003 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
1005 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
1007 Boolean b_writeable = false;
1008 /* Revert mixable to true if we are allowed to */
1009 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1010 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
1011 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
1013 if (err == noErr && b_writeable) {
1014 msg_Dbg(p_aout, "mixable is: %d", b_mix);
1016 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
1020 msg_Err(p_aout, "failed to re-set mixmode [%4.4s]", (char *)&err);
1024 if (p_sys->i_hog_pid == getpid()) {
1025 p_sys->i_hog_pid = -1;
1026 i_param_size = sizeof(p_sys->i_hog_pid);
1027 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
1028 kAudioDevicePropertyScopeOutput,
1029 kAudioObjectPropertyElementMaster };
1030 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
1032 msg_Err(p_aout, "Failed to release hogmode [%4.4s]", (char *)&err);
1035 p_sys->i_bytes_per_sample = 0;
1036 p_sys->b_digital = false;
1038 /* clean-up circular buffer */
1039 TPCircularBufferCleanup(&p_sys->circular_buffer);
1043 #pragma mark core interaction
1045 static void ReportDevice(audio_output_t *p_aout, UInt32 i_id, char *name)
1048 sprintf(deviceid, "%i", i_id);
1050 aout_HotplugReport(p_aout, deviceid, name);
1053 static void RebuildDeviceList(audio_output_t * p_aout)
1055 OSStatus err = noErr;
1056 UInt32 propertySize = 0;
1057 AudioObjectID *deviceIDs;
1058 UInt32 numberOfDevices;
1059 CFMutableArrayRef currentListOfDevices;
1061 struct aout_sys_t *p_sys = p_aout->sys;
1063 /* setup local array */
1064 currentListOfDevices = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
1066 /* Get number of devices */
1067 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1068 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1070 msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
1074 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1076 if (numberOfDevices < 1) {
1077 msg_Err(p_aout, "No audio output devices found.");
1080 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1082 /* Allocate DeviceID array */
1083 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1084 if (deviceIDs == NULL)
1087 /* Populate DeviceID array */
1088 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1090 msg_Err(p_aout, "could not get the device IDs [%4.4s]", (char *)&err);
1094 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1096 for (unsigned int i = 0; i < numberOfDevices; i++) {
1097 CFStringRef device_name_ref;
1100 bool b_digital = false;
1101 UInt32 i_id = deviceIDs[i];
1103 /* Retrieve the length of the device name */
1104 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1106 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1110 /* Retrieve the name of the device */
1111 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1113 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1116 length = CFStringGetLength(device_name_ref);
1118 psz_name = (char *)malloc(length);
1119 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1121 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1123 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1124 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1129 ReportDevice(p_aout, i_id, psz_name);
1130 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1132 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1134 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1135 char *psz_encoded_name = nil;
1136 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1137 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1138 ReportDevice(p_aout, i_id, psz_encoded_name);
1139 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1140 free(psz_encoded_name);
1143 // TODO: only register once for each device
1144 RegisterAudioStreamsCallback(p_aout, deviceIDs[i]);
1146 CFRelease(device_name_ref);
1151 if (p_sys->device_list)
1152 count = CFArrayGetCount(p_sys->device_list);
1155 CFNumberRef cfn_device_id;
1156 int i_device_id = 0;
1157 for (CFIndex x = 0; x < count; x++) {
1158 if (!CFArrayContainsValue(currentListOfDevices, CFRangeMake(0, count), CFArrayGetValueAtIndex(p_sys->device_list, x))) {
1159 cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
1161 if (cfn_device_id) {
1162 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &i_device_id);
1163 ReportDevice(p_aout, i_device_id, NULL);
1168 CFRelease(p_sys->device_list);
1169 p_sys->device_list = CFArrayCreateCopy(kCFAllocatorDefault, currentListOfDevices);
1170 CFRelease(currentListOfDevices);
1172 ReportDevice(p_aout, 0, _("System Sound Output Device"));
1177 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1179 struct aout_sys_t *p_sys = p_aout->sys;
1182 p_sys->i_new_selected_dev = atoi(name);
1184 p_sys->i_new_selected_dev = 0;
1186 bool b_supports_digital = (p_sys->i_new_selected_dev & AOUT_VAR_SPDIF_FLAG);
1187 if (b_supports_digital)
1188 p_sys->b_selected_dev_is_digital = true;
1190 p_sys->b_selected_dev_is_digital = false;
1192 p_sys->i_new_selected_dev = p_sys->i_new_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1194 aout_DeviceReport(p_aout, name);
1195 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1200 static int VolumeSet(audio_output_t * p_aout, float volume)
1202 struct aout_sys_t *p_sys = p_aout->sys;
1205 if(p_sys->b_digital)
1206 return VLC_EGENERIC;
1208 p_sys->f_volume = volume;
1209 aout_VolumeReport(p_aout, volume);
1211 /* Set volume for output unit */
1212 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1213 kHALOutputParam_Volume,
1214 kAudioUnitScope_Global,
1216 volume * volume * volume,
1219 if (var_InheritBool(p_aout, "volume-save"))
1220 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1225 static int MuteSet(audio_output_t * p_aout, bool mute)
1227 struct aout_sys_t *p_sys = p_aout->sys;
1230 if(p_sys->b_digital)
1231 return VLC_EGENERIC;
1233 p_sys->b_mute = mute;
1234 aout_MuteReport(p_aout, mute);
1238 volume = p_sys->f_volume;
1240 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1241 kHALOutputParam_Volume,
1242 kAudioUnitScope_Global,
1244 volume * volume * volume,
1251 #pragma mark actual playback
1253 static void Play(audio_output_t * p_aout, block_t * p_block)
1255 struct aout_sys_t *p_sys = p_aout->sys;
1257 if (p_block->i_nb_samples > 0) {
1258 if (!p_sys->b_got_first_sample) {
1260 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1261 p_sys->b_got_first_sample = true;
1264 /* Do the channel reordering */
1265 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1266 aout_ChannelReorder(p_block->p_buffer,
1268 p_sys->chans_to_reorder,
1273 /* move data to buffer */
1274 if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1275 msg_Warn(p_aout, "dropped buffer");
1277 if (!p_sys->i_bytes_per_sample)
1278 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1281 block_Release(p_block);
1284 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1286 struct aout_sys_t * p_sys = p_aout->sys;
1289 if (p_aout->sys->b_digital) {
1291 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1293 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1296 AudioOutputUnitStop(p_sys->au_unit);
1298 AudioOutputUnitStart(p_sys->au_unit);
1302 static void Flush(audio_output_t *p_aout, bool wait)
1304 struct aout_sys_t *p_sys = p_aout->sys;
1307 int32_t availableBytes;
1308 vlc_mutex_lock(&p_sys->lock);
1309 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1310 while (availableBytes > 0) {
1311 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1312 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1314 vlc_mutex_unlock(&p_sys->lock);
1317 p_sys->b_got_first_sample = false;
1319 /* flush circular buffer */
1320 AudioOutputUnitStop(p_aout->sys->au_unit);
1321 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1325 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1327 struct aout_sys_t * p_sys = p_aout->sys;
1329 if (!p_sys->i_bytes_per_sample)
1332 int32_t availableBytes;
1333 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1335 *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1340 /*****************************************************************************
1341 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1342 * us to provide some more audio data.
1343 * Don't print anything during normal playback, calling blocking function from
1344 * this callback is not allowed.
1345 *****************************************************************************/
1346 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1347 AudioUnitRenderActionFlags *ioActionFlags,
1348 const AudioTimeStamp *inTimeStamp,
1350 UInt32 inNumberFrames,
1351 AudioBufferList *ioData) {
1352 VLC_UNUSED(ioActionFlags);
1353 VLC_UNUSED(inTimeStamp);
1354 VLC_UNUSED(inBusNumber);
1355 VLC_UNUSED(inNumberFrames);
1357 audio_output_t * p_aout = (audio_output_t *)p_obj;
1358 struct aout_sys_t * p_sys = p_aout->sys;
1360 int bytesRequested = ioData->mBuffers[0].mDataByteSize;
1361 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1363 vlc_mutex_lock(&p_sys->lock);
1364 /* Pull audio from buffer */
1365 int32_t availableBytes;
1366 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1368 /* check if we have enough data */
1369 if (!availableBytes) {
1370 /* return an empty buffer so silence is played until we have data */
1371 memset(targetBuffer, 0, ioData->mBuffers[0].mDataByteSize);
1373 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1375 memcpy(targetBuffer, buffer, bytesToCopy);
1376 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1377 ioData->mBuffers[0].mDataByteSize = bytesToCopy;
1380 vlc_cond_signal(&p_sys->cond);
1381 vlc_mutex_unlock(&p_sys->lock);
1387 * RenderCallbackSPDIF: callback for SPDIF audio output
1389 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1390 const AudioTimeStamp * inNow,
1391 const void * inInputData,
1392 const AudioTimeStamp * inInputTime,
1393 AudioBufferList * outOutputData,
1394 const AudioTimeStamp * inOutputTime,
1395 void * threadGlobals)
1398 VLC_UNUSED(inDevice);
1399 VLC_UNUSED(inInputData);
1400 VLC_UNUSED(inInputTime);
1401 VLC_UNUSED(inOutputTime);
1403 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1404 struct aout_sys_t * p_sys = p_aout->sys;
1406 int bytesRequested = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1407 char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1409 vlc_mutex_lock(&p_sys->lock);
1410 /* Pull audio from buffer */
1411 int32_t availableBytes;
1412 char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1414 /* check if we have enough data */
1415 if (!availableBytes) {
1416 /* return an empty buffer so silence is played until we have data */
1417 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1419 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1421 memcpy(targetBuffer, buffer, bytesToCopy);
1422 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1423 outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize = bytesToCopy;
1426 vlc_cond_signal(&p_sys->cond);
1427 vlc_mutex_unlock(&p_sys->lock);
1433 #pragma mark Stream / Hardware Listeners
1436 * HardwareListener: Warns us of changes in the list of registered devices
1438 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1440 OSStatus err = noErr;
1441 audio_output_t *p_aout = (audio_output_t *)inClientData;
1442 VLC_UNUSED(inObjectID);
1443 VLC_UNUSED(inNumberAddresses);
1444 VLC_UNUSED(inAddresses);
1449 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1450 switch (inAddresses[i].mSelector) {
1451 case kAudioHardwarePropertyDevices:
1452 msg_Dbg(p_aout, "audio device configuration changed, resetting cache");
1455 case kAudioDevicePropertyDeviceIsAlive:
1456 msg_Warn(p_aout, "audio device died, resetting aout");
1459 case kAudioStreamPropertyAvailablePhysicalFormats:
1460 msg_Dbg(p_aout, "available physical formats for audio device changed, resetting aout");
1464 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1469 RebuildDeviceList(p_aout);
1470 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1476 * StreamListener: check whether the device's physical format changes on-the-fly (unlikely)
1478 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1480 OSStatus err = noErr;
1481 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1483 VLC_UNUSED(inObjectID);
1485 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1486 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1487 vlc_mutex_lock(&w->lock);
1488 vlc_cond_signal(&w->cond);
1489 vlc_mutex_unlock(&w->lock);
1497 #pragma mark helpers
1499 static int RegisterAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1501 OSStatus err = noErr;
1502 UInt32 i_param_size = 0;
1503 AudioStreamID *p_streams = NULL;
1506 /* Retrieve all the output streams */
1507 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1508 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1510 msg_Err(p_aout, "could not get number of streams [%4.4s] (%i)", (char *)&err, (int32_t)err);
1511 return VLC_EGENERIC;
1514 i_streams = i_param_size / sizeof(AudioStreamID);
1515 p_streams = (AudioStreamID *)malloc(i_param_size);
1516 if (p_streams == NULL)
1519 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1521 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1522 return VLC_EGENERIC;
1525 for (int i = 0; i < i_streams; i++) {
1526 /* get notified when physical formats change */
1527 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1528 err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, HardwareListener, (void *)p_aout);
1530 // nope just means that we already have a callback
1531 if (err == kAudioHardwareIllegalOperationError) {
1532 msg_Dbg(p_aout, "could not set audio stream formats property callback on stream id %i, callback already set? [%4.4s]", p_streams[i],
1535 msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i [%4.4s]", p_streams[i],
1546 * AudioDeviceHasOutput: Checks if the device is actually an output device
1548 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1550 UInt32 dataSize = 0;
1553 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1554 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1556 if (dataSize == 0 || status != noErr)
1563 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1565 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1567 OSStatus err = noErr;
1568 UInt32 i_param_size = 0;
1569 AudioStreamID *p_streams = NULL;
1571 bool b_return = false;
1573 /* Retrieve all the output streams */
1574 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1575 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1577 msg_Err(p_aout, "could not get number of streams [%4.4s] (%i)", (char *)&err, (int32_t)err);
1581 i_streams = i_param_size / sizeof(AudioStreamID);
1582 p_streams = (AudioStreamID *)malloc(i_param_size);
1583 if (p_streams == NULL)
1586 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1588 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1592 for (int i = 0; i < i_streams; i++) {
1593 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1602 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1604 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1606 OSStatus err = noErr;
1607 UInt32 i_param_size = 0;
1608 AudioStreamRangedDescription *p_format_list = NULL;
1610 bool b_return = false;
1612 /* Retrieve all the stream formats supported by each output stream */
1613 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1614 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1616 msg_Err(p_aout, "could not get number of streamformats [%4.4s] (%i)", (char *)&err, (int32_t)err);
1620 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1621 msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1623 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1624 if (p_format_list == NULL)
1627 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1629 msg_Err(p_aout, "could not get the list of streamformats [%4.4s]", (char *)&err);
1630 free(p_format_list);
1631 p_format_list = NULL;
1635 for (int i = 0; i < i_formats; i++) {
1637 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1640 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1641 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1642 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1643 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1647 free(p_format_list);
1652 * AudioStreamChangeFormat: switch stream format based on the provided description
1654 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1656 OSStatus err = noErr;
1657 UInt32 i_param_size = 0;
1659 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1661 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1663 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1665 /* Condition because SetProperty is asynchronious */
1666 vlc_cond_init(&w.cond);
1667 vlc_mutex_init(&w.lock);
1668 vlc_mutex_lock(&w.lock);
1670 /* Install the callback */
1671 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1673 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed [%4.4s]", (char *)&err);
1677 /* change the format */
1678 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1681 msg_Err(p_aout, "could not set the stream format [%4.4s]", (char *)&err);
1685 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1686 * it is also not atomic in its behaviour.
1687 * Therefore we check 5 times before we really give up.
1688 * FIXME: failing isn't actually implemented yet. */
1689 for (int i = 0; i < 5; i++) {
1690 AudioStreamBasicDescription actual_format;
1691 mtime_t timeout = mdate() + 500000;
1693 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1694 msg_Dbg(p_aout, "reached timeout");
1696 i_param_size = sizeof(AudioStreamBasicDescription);
1697 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1699 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1700 if (actual_format.mSampleRate == change_format.mSampleRate &&
1701 actual_format.mFormatID == change_format.mFormatID &&
1702 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1703 /* The right format is now active */
1706 /* We need to check again */
1709 /* Removing the property listener */
1710 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1712 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed [%4.4s]", (char *)&err);
1716 /* Destroy the lock and condition */
1717 vlc_mutex_unlock(&w.lock);
1718 vlc_mutex_destroy(&w.lock);
1719 vlc_cond_destroy(&w.cond);