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_selected_dev; /* DeviceID of the selected device */
81 AudioObjectID i_new_selected_dev; /* DeviceID of device which will be selected on start */
82 bool b_selected_dev_is_digital;
83 bool b_selected_dev_is_default; /* true if the user selected the default audio device (id 0) */
85 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
86 bool b_digital; /* Are we running in digital mode? */
88 uint8_t chans_to_reorder; /* do we need channel reordering */
89 uint8_t chan_table[AOUT_CHAN_MAX];
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 sfmt_revert; /* The original format of the stream */
102 bool b_revert; /* Whether we need to revert the stream format */
103 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
105 int i_rate; /* media sample rate */
106 int i_bytes_per_sample;
108 CFArrayRef device_list;
110 vlc_mutex_t var_lock; /* protects access to device_list and i_selected_dev */
119 bool b_ignore_streams_changed_callback;
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 DevicesListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
148 static OSStatus DeviceAliveListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
149 static OSStatus DefaultDeviceChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
150 static OSStatus StreamsChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
152 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
154 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register);
155 static int AudioDeviceHasOutput (AudioDeviceID);
156 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
157 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
158 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
162 set_shortname("auhal")
163 set_description(N_("HAL AudioUnit output"))
164 set_capability("audio output", 101)
165 set_category(CAT_AUDIO)
166 set_subcategory(SUBCAT_AUDIO_AOUT)
167 set_callbacks(Open, Close)
168 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
169 VOLUME_TEXT, VOLUME_LONGTEXT, true)
170 change_integer_range(0, AOUT_VOLUME_MAX)
171 add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
172 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
176 #pragma mark initialization
178 static int Open(vlc_object_t *obj)
180 audio_output_t *p_aout = (audio_output_t *)obj;
181 aout_sys_t *p_sys = malloc(sizeof (*p_sys));
182 if (unlikely(p_sys == NULL))
185 OSStatus err = noErr;
187 vlc_mutex_init(&p_sys->var_lock);
188 vlc_mutex_init(&p_sys->lock);
189 vlc_cond_init(&p_sys->cond);
190 p_sys->b_digital = false;
191 p_sys->b_ignore_streams_changed_callback = false;
192 p_sys->b_selected_dev_is_default = false;
193 p_sys->b_paused = false;
194 memset(&p_sys->sfmt_revert, 0, sizeof(p_sys->sfmt_revert));
195 p_sys->i_stream_id = 0;
198 p_aout->start = Start;
200 p_aout->volume_set = VolumeSet;
201 p_aout->mute_set = MuteSet;
202 p_aout->device_select = SwitchAudioDevice;
203 p_sys->device_list = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL);
206 * Force an own run loop for callbacks.
208 * According to rtaudio, this is absolutely necessary since 10.6 to get correct notifications.
209 * It might fix issues when using the module as a library where a proper loop is not setup already.
211 CFRunLoopRef theRunLoop = NULL;
212 AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal,kAudioObjectPropertyElementMaster };
213 err = AudioObjectSetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
215 msg_Err(p_aout, "failed to set the run loop property [%4.4s]", (char *)&err);
218 /* Attach a listener so that we are notified of a change in the device setup */
219 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
220 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
222 msg_Err(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
224 /* Attach a listener to be notified about changes in default audio device */
225 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
226 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
228 msg_Err(p_aout, "failed to add listener for default audio device [%4.4s]", (char *)&err);
230 RebuildDeviceList(p_aout);
232 /* remember the volume */
233 p_sys->f_volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
234 aout_VolumeReport(p_aout, p_sys->f_volume);
235 p_sys->b_mute = var_InheritBool(p_aout, "mute");
236 aout_MuteReport(p_aout, p_sys->b_mute);
238 char *psz_audio_device = var_InheritString(p_aout, "auhal-audio-device");
239 SwitchAudioDevice(p_aout, psz_audio_device);
240 free(psz_audio_device);
245 static void Close(vlc_object_t *obj)
247 audio_output_t *p_aout = (audio_output_t *)obj;
248 aout_sys_t *p_sys = p_aout->sys;
250 OSStatus err = noErr;
252 /* remove audio devices callback */
253 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
254 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
256 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed [%4.4s]", (char *)&err);
258 /* remove listener to be notified about changes in default audio device */
259 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
260 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
262 msg_Err(p_aout, "failed to remove listener for default audio device [%4.4s]", (char *)&err);
264 vlc_mutex_lock(&p_sys->var_lock);
265 /* remove streams callbacks */
266 CFIndex count = CFArrayGetCount(p_sys->device_list);
268 for (CFIndex x = 0; x < count; x++) {
269 AudioDeviceID deviceId = 0;
270 CFNumberRef cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
274 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &deviceId);
275 if (!(deviceId & AOUT_VAR_SPDIF_FLAG)) {
276 ManageAudioStreamsCallback(p_aout, deviceId, false);
281 CFRelease(p_sys->device_list);
282 vlc_mutex_unlock(&p_sys->var_lock);
284 char *psz_device = aout_DeviceGet(p_aout);
285 config_PutPsz(p_aout, "auhal-audio-device", psz_device);
288 vlc_mutex_destroy(&p_sys->var_lock);
289 vlc_mutex_destroy(&p_sys->lock);
290 vlc_cond_destroy(&p_sys->cond);
295 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
297 OSStatus err = noErr;
298 UInt32 i_param_size = 0;
299 struct aout_sys_t *p_sys = NULL;
301 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
305 bool b_start_digital = false;
308 p_sys->b_digital = false;
309 p_sys->au_component = NULL;
310 p_sys->au_unit = NULL;
311 p_sys->i_hog_pid = -1;
312 p_sys->i_stream_index = -1;
313 p_sys->b_revert = false;
314 p_sys->b_changed_mixing = false;
315 p_sys->i_bytes_per_sample = 0;
316 p_sys->b_paused = false;
318 vlc_mutex_lock(&p_sys->var_lock);
319 p_sys->i_selected_dev = p_sys->i_new_selected_dev;
321 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
323 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
325 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
326 if (p_sys->i_selected_dev > 0) {
327 /* Check if the desired device is alive and usable */
328 i_param_size = sizeof(b_alive);
329 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
331 /* Be tolerant, only give a warning here */
332 msg_Warn(p_aout, "could not check whether device [0x%x] is alive [%4.4s]",
333 (unsigned int)p_sys->i_selected_dev, (char *)&err);
338 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
341 p_sys->b_selected_dev_is_default = false;
342 if (!b_alive || p_sys->i_selected_dev == 0) {
343 p_sys->b_selected_dev_is_default = true;
345 AudioObjectID defaultDeviceID = 0;
346 UInt32 propertySize = sizeof(AudioObjectID);
347 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
348 propertySize = sizeof(AudioObjectID);
349 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
351 msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
352 vlc_mutex_unlock(&p_sys->var_lock);
356 msg_Dbg(p_aout, "using default audio device %i", defaultDeviceID);
358 p_sys->i_selected_dev = defaultDeviceID;
359 p_sys->b_selected_dev_is_digital = var_InheritBool(p_aout, "spdif");
361 vlc_mutex_unlock(&p_sys->var_lock);
363 // recheck if device still supports digital
364 b_start_digital = p_sys->b_selected_dev_is_digital;
365 if(!AudioDeviceSupportsDigital(p_aout, p_sys->i_selected_dev))
366 b_start_digital = false;
369 msg_Dbg(p_aout, "Using audio device for digital output");
371 msg_Dbg(p_aout, "Audio device supports PCM mode only");
373 /* add a callback to see if the device dies later on */
374 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, DeviceAliveListener, (void *)p_aout);
376 /* Be tolerant, only give a warning here */
377 msg_Warn(p_aout, "could not set alive check callback on device [0x%x] [%4.4s]",
378 (unsigned int)p_sys->i_selected_dev, (char *)&err);
381 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
382 kAudioDevicePropertyScopeOutput,
383 kAudioObjectPropertyElementMaster };
384 i_param_size = sizeof(p_sys->i_hog_pid);
385 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
387 /* This is not a fatal error. Some drivers simply don't support this property */
388 msg_Warn(p_aout, "could not check whether device is hogged [%4.4s]",
390 p_sys->i_hog_pid = -1;
393 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
394 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
395 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
396 _("The selected audio output device is exclusively in "
397 "use by another program."));
401 bool b_success = false;
403 /* Check for Digital mode or Analog output mode */
404 if (AOUT_FMT_SPDIF (fmt) && b_start_digital) {
405 if (StartSPDIF (p_aout, fmt)) {
406 msg_Dbg(p_aout, "digital output successfully opened");
410 if (StartAnalog(p_aout, fmt)) {
411 msg_Dbg(p_aout, "analog output successfully opened");
418 p_aout->flush = Flush;
419 p_aout->time_get = TimeGet;
420 p_aout->pause = Pause;
425 /* If we reach this, this aout has failed */
426 msg_Err(p_aout, "opening auhal output failed");
431 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
433 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
435 struct aout_sys_t *p_sys = p_aout->sys;
436 OSStatus err = noErr;
437 UInt32 i_param_size = 0;
439 AudioComponentDescription desc;
440 AudioStreamBasicDescription DeviceFormat;
441 AudioChannelLayout *layout;
442 AURenderCallbackStruct input;
443 p_aout->sys->chans_to_reorder = 0;
445 SInt32 currentMinorSystemVersion;
446 if(Gestalt(gestaltSystemVersionMinor, ¤tMinorSystemVersion) != noErr)
447 msg_Err(p_aout, "failed to check OSX version");
449 /* Lets go find our Component */
450 desc.componentType = kAudioUnitType_Output;
451 desc.componentSubType = kAudioUnitSubType_HALOutput;
452 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
453 desc.componentFlags = 0;
454 desc.componentFlagsMask = 0;
456 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
457 if (p_sys->au_component == NULL) {
458 msg_Err(p_aout, "cannot find any HAL component, PCM output failed");
462 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
464 msg_Err(p_aout, "cannot open HAL component, PCM output failed [%4.4s]", (char *)&err);
468 /* Set the device we will use for this output unit */
469 err = AudioUnitSetProperty(p_sys->au_unit,
470 kAudioOutputUnitProperty_CurrentDevice,
471 kAudioUnitScope_Global,
473 &p_sys->i_selected_dev,
474 sizeof(AudioObjectID));
477 msg_Err(p_aout, "cannot select audio output device, PCM output failed [%4.4s]", (char *)&err);
481 /* Get the current format */
482 i_param_size = sizeof(AudioStreamBasicDescription);
484 err = AudioUnitGetProperty(p_sys->au_unit,
485 kAudioUnitProperty_StreamFormat,
486 kAudioUnitScope_Output,
492 msg_Err(p_aout, "failed to detect supported stream formats [%4.4s]", (char *)&err);
495 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
497 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
498 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
499 kAudioDevicePropertyPreferredChannelLayout,
500 kAudioUnitScope_Output,
506 layout = (AudioChannelLayout *)malloc(i_param_size);
508 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
509 kAudioDevicePropertyPreferredChannelLayout,
510 kAudioUnitScope_Output,
515 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
516 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
517 /* bitmap defined channellayout */
518 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
519 sizeof(UInt32), &layout->mChannelBitmap,
522 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
524 /* layouttags defined channellayout */
525 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
526 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
531 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
533 if (layout->mNumberChannelDescriptions == 0) {
534 msg_Err(p_aout, "insufficient number of output channels");
538 /* Initialize the VLC core channel count */
539 fmt->i_physical_channels = 0;
540 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
542 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
543 /* We only need Mono or cannot output more than 1 channel */
544 fmt->i_physical_channels = AOUT_CHAN_CENTER;
545 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
546 /* We only need Stereo or cannot output more than 2 channels */
547 fmt->i_physical_channels = AOUT_CHANS_STEREO;
550 // maps auhal channels to vlc ones
551 static const unsigned i_auhal_channel_mapping[] = {
552 [kAudioChannelLabel_Left] = AOUT_CHAN_LEFT,
553 [kAudioChannelLabel_Right] = AOUT_CHAN_RIGHT,
554 [kAudioChannelLabel_Center] = AOUT_CHAN_CENTER,
555 [kAudioChannelLabel_LFEScreen] = AOUT_CHAN_LFE,
556 [kAudioChannelLabel_LeftSurround] = AOUT_CHAN_REARLEFT,
557 [kAudioChannelLabel_RightSurround] = AOUT_CHAN_REARRIGHT,
558 [kAudioChannelLabel_RearSurroundLeft] = AOUT_CHAN_MIDDLELEFT, // needs to be swapped with rear
559 [kAudioChannelLabel_RearSurroundRight] = AOUT_CHAN_MIDDLERIGHT,// needs to be swapped with rear
560 [kAudioChannelLabel_CenterSurround] = AOUT_CHAN_REARCENTER
563 /* We want more than stereo and we can do that */
564 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
566 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
569 AudioChannelLabel chan = layout->mChannelDescriptions[i].mChannelLabel;
570 if(chan < sizeof(i_auhal_channel_mapping) / sizeof(i_auhal_channel_mapping[0])
571 && i_auhal_channel_mapping[chan] > 0) {
572 fmt->i_physical_channels |= i_auhal_channel_mapping[chan];
574 msg_Dbg(p_aout, "found nonrecognized channel %d at index %d", chan, i);
577 if (fmt->i_physical_channels == 0) {
578 fmt->i_physical_channels = AOUT_CHANS_STEREO;
579 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup in /Applications/Utilities. VLC will output Stereo only.");
580 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
581 _("You should configure your speaker layout with "
582 "\"Audio Midi Setup\" in /Applications/"
583 "Utilities. VLC will output Stereo only."));
588 msg_Warn(p_aout, "device driver does not support kAudioDevicePropertyPreferredChannelLayout - using stereo fallback [%4.4s]", (char *)&err);
589 fmt->i_physical_channels = AOUT_CHANS_STEREO;
592 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
593 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
595 /* Now we set the INPUT layout of the AU */
596 AudioChannelLayout input_layout;
597 memset (&input_layout, 0, sizeof(input_layout));
598 uint32_t chans_out[AOUT_CHAN_MAX];
600 /* Some channel abbreviations used below:
605 * Rs - right surround
606 * Cs - center surround
607 * Rls - rear left surround
608 * Rrs - rear right surround
611 * Lsd - left surround direct
612 * Rsd - right surround direct
616 * Vhl - vertical height left
617 * Vhc - vertical height center
618 * Vhr - vertical height right
619 * Lt - left matrix total. for matrix encoded stereo.
620 * Rt - right matrix total. for matrix encoded stereo. */
622 switch(aout_FormatNbChannels(fmt)) {
624 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
627 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
630 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
631 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
632 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
633 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
636 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
637 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
638 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
639 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
640 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
641 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
644 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
645 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
646 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
647 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
650 if (fmt->i_physical_channels & (AOUT_CHAN_LFE)) {
651 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
653 chans_out[0] = AOUT_CHAN_LEFT;
654 chans_out[1] = AOUT_CHAN_RIGHT;
655 chans_out[2] = AOUT_CHAN_REARLEFT;
656 chans_out[3] = AOUT_CHAN_REARRIGHT;
657 chans_out[4] = AOUT_CHAN_CENTER;
658 chans_out[5] = AOUT_CHAN_LFE;
660 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
661 if (p_aout->sys->chans_to_reorder)
662 msg_Dbg(p_aout, "channel reordering needed for 5.1 output");
664 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
666 chans_out[0] = AOUT_CHAN_LEFT;
667 chans_out[1] = AOUT_CHAN_RIGHT;
668 chans_out[2] = AOUT_CHAN_REARLEFT;
669 chans_out[3] = AOUT_CHAN_REARRIGHT;
670 chans_out[4] = AOUT_CHAN_CENTER;
671 chans_out[5] = AOUT_CHAN_REARCENTER;
673 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
674 if (p_aout->sys->chans_to_reorder)
675 msg_Dbg(p_aout, "channel reordering needed for 6.0 output");
679 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
681 chans_out[0] = AOUT_CHAN_LEFT;
682 chans_out[1] = AOUT_CHAN_RIGHT;
683 chans_out[2] = AOUT_CHAN_CENTER;
684 chans_out[3] = AOUT_CHAN_LFE;
685 chans_out[4] = AOUT_CHAN_REARLEFT;
686 chans_out[5] = AOUT_CHAN_REARRIGHT;
687 chans_out[6] = AOUT_CHAN_REARCENTER;
689 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
690 if (p_aout->sys->chans_to_reorder)
691 msg_Dbg(p_aout, "channel reordering needed for 6.1 output");
695 if (fmt->i_physical_channels & (AOUT_CHAN_LFE) || currentMinorSystemVersion < 7) {
696 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
698 chans_out[0] = AOUT_CHAN_LEFT;
699 chans_out[1] = AOUT_CHAN_RIGHT;
700 chans_out[2] = AOUT_CHAN_CENTER;
701 chans_out[3] = AOUT_CHAN_LFE;
702 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
703 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
704 chans_out[6] = AOUT_CHAN_REARLEFT;
705 chans_out[7] = AOUT_CHAN_REARRIGHT;
707 if (!(fmt->i_physical_channels & (AOUT_CHAN_LFE)))
708 msg_Warn(p_aout, "8.0 audio output not supported on OS X 10.%i, layout will be incorrect", currentMinorSystemVersion);
710 #ifdef MAC_OS_X_VERSION_10_7
712 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_0_B; // Lc C Rc L R Ls Cs Rs
714 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
715 chans_out[1] = AOUT_CHAN_CENTER;
716 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
717 chans_out[3] = AOUT_CHAN_LEFT;
718 chans_out[4] = AOUT_CHAN_RIGHT;
719 chans_out[5] = AOUT_CHAN_REARLEFT;
720 chans_out[6] = AOUT_CHAN_REARCENTER;
721 chans_out[7] = AOUT_CHAN_REARRIGHT;
724 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
725 if (p_aout->sys->chans_to_reorder)
726 msg_Dbg(p_aout, "channel reordering needed for 7.1 / 8.0 output");
730 if (currentMinorSystemVersion < 7) {
731 msg_Warn(p_aout, "8.1 audio output not supported on OS X 10.%i", currentMinorSystemVersion);
735 #ifdef MAC_OS_X_VERSION_10_7
736 input_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_1_B; // Lc C Rc L R Ls Cs Rs LFE
737 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
738 chans_out[1] = AOUT_CHAN_CENTER;
739 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
740 chans_out[3] = AOUT_CHAN_LEFT;
741 chans_out[4] = AOUT_CHAN_RIGHT;
742 chans_out[5] = AOUT_CHAN_REARLEFT;
743 chans_out[6] = AOUT_CHAN_REARCENTER;
744 chans_out[7] = AOUT_CHAN_REARRIGHT;
745 chans_out[8] = AOUT_CHAN_LFE;
747 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
748 if (p_aout->sys->chans_to_reorder)
749 msg_Dbg(p_aout, "channel reordering needed for 8.1 output");
754 /* Set up the format to be used */
755 DeviceFormat.mSampleRate = fmt->i_rate;
756 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
757 p_sys->i_rate = fmt->i_rate;
759 /* We use float 32 since this is VLC's endorsed format */
760 fmt->i_format = VLC_CODEC_FL32;
761 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
762 DeviceFormat.mBitsPerChannel = 32;
763 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
765 /* Calculate framesizes and stuff */
766 DeviceFormat.mFramesPerPacket = 1;
767 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
768 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
770 /* Set the desired format */
771 i_param_size = sizeof(AudioStreamBasicDescription);
772 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
773 kAudioUnitProperty_StreamFormat,
774 kAudioUnitScope_Input,
779 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
781 /* Retrieve actual format */
782 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
783 kAudioUnitProperty_StreamFormat,
784 kAudioUnitScope_Input,
789 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
791 /* Do the last VLC aout setups */
792 aout_FormatPrepare(fmt);
794 /* set the IOproc callback */
795 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
796 input.inputProcRefCon = p_aout;
798 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
799 kAudioUnitProperty_SetRenderCallback,
800 kAudioUnitScope_Input,
801 0, &input, sizeof(input)));
803 /* Set the input_layout as the layout VLC will use to feed the AU unit */
804 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
805 kAudioUnitProperty_AudioChannelLayout,
806 kAudioUnitScope_Input, /* yes, it must be the INPUT scope */
807 0, &input_layout, sizeof(input_layout)));
810 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
812 /* setup circular buffer */
813 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
814 fmt->i_rate * fmt->i_bytes_per_frame);
816 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
818 /* Set volume for output unit */
819 VolumeSet(p_aout, p_sys->f_volume);
820 MuteSet(p_aout, p_sys->b_mute);
826 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
828 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
830 struct aout_sys_t *p_sys = p_aout->sys;
831 OSStatus err = noErr;
832 UInt32 i_param_size = 0, b_mix = 0;
833 Boolean b_writeable = false;
834 AudioStreamID *p_streams = NULL;
835 unsigned i_streams = 0;
836 AudioStreamBasicDescription desired_stream_format;
837 memset(&desired_stream_format, 0, sizeof(desired_stream_format));
839 /* Start doing the SPDIF setup proces */
840 p_sys->b_digital = true;
843 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
844 i_param_size = sizeof(p_sys->i_hog_pid);
845 p_sys->i_hog_pid = getpid() ;
848 * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
849 * directly in the same thread. This call needs to be ignored to avoid endless restarting.
851 p_sys->b_ignore_streams_changed_callback = true;
852 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
853 p_sys->b_ignore_streams_changed_callback = false;
856 msg_Err(p_aout, "failed to set hogmode [%4.4s]", (char *)&err);
860 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
862 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
863 /* Set mixable to false if we are allowed to */
864 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
865 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
866 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
868 if (err == noErr && b_writeable) {
870 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
871 p_sys->b_changed_mixing = true;
875 msg_Err(p_aout, "failed to set mixmode [%4.4s]", (char *)&err);
880 /* Get a list of all the streams on this device */
881 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
882 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
884 msg_Err(p_aout, "could not get size of stream description packet [%4.4s]", (char *)&err);
888 i_streams = i_param_size / sizeof(AudioStreamID);
889 p_streams = (AudioStreamID *)malloc(i_param_size);
890 if (p_streams == NULL)
893 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
896 msg_Err(p_aout, "could not fetch stream descriptions [%4.4s]", (char *)&err);
901 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
902 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
903 /* Find a stream with a cac3 stream */
904 AudioStreamRangedDescription *p_format_list = NULL;
906 bool b_digital = false;
908 /* Retrieve all the stream formats supported by each output stream */
909 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
911 msg_Err(p_aout, "could not get number of streamformats: [%4.4s] (%i)", (char *)&err, (int32_t)err);
915 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
916 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
917 if (p_format_list == NULL)
920 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
922 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
927 /* Check if one of the supported formats is a digital format */
928 for (int j = 0; j < i_formats; j++) {
929 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
930 p_format_list[j].mFormat.mFormatID == 'iac3' ||
931 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
932 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
939 /* if this stream supports a digital (cac3) format, then go set it. */
940 int i_requested_rate_format = -1;
941 int i_current_rate_format = -1;
942 int i_backup_rate_format = -1;
944 if (!p_sys->b_revert) {
945 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
946 /* Retrieve the original format of this stream first if not done so already */
947 AudioStreamBasicDescription current_streamformat;
948 i_param_size = sizeof(current_streamformat);
949 err = AudioObjectGetPropertyData(p_streams[i], ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, ¤t_streamformat);
951 msg_Err(p_aout, "could not retrieve the original streamformat [%4.4s]", (char *)&err);
956 * Only the first found format id is accepted. In case of another id later on, we still use the
957 * already saved one. This can happen if the user plugs in a spdif cable while a stream is already
958 * playing. Then, auhal already misleadingly reports an ac3 format here whereas the original format
959 * should be still pcm.
961 if (p_sys->sfmt_revert.mFormatID > 0 && p_sys->sfmt_revert.mFormatID != current_streamformat.mFormatID &&
962 p_streams[i] == p_sys->i_stream_id) {
963 msg_Warn(p_aout, STREAM_FORMAT_MSG("Detected current stream format: ", current_streamformat));
964 msg_Warn(p_aout, "... there is another stream format already stored, the current one is ignored");
966 p_sys->sfmt_revert = current_streamformat;
969 p_sys->b_revert = true;
972 p_sys->i_stream_id = p_streams[i];
973 p_sys->i_stream_index = i;
975 for (int j = 0; j < i_formats; j++) {
976 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
977 p_format_list[j].mFormat.mFormatID == 'iac3' ||
978 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
979 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
980 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
981 i_requested_rate_format = j;
983 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
984 i_current_rate_format = j;
986 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
987 i_backup_rate_format = j;
993 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
994 desired_stream_format = p_format_list[i_requested_rate_format].mFormat;
995 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
996 desired_stream_format = p_format_list[i_current_rate_format].mFormat;
998 desired_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) */
1000 free(p_format_list);
1004 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
1006 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, desired_stream_format)) {
1007 msg_Err(p_aout, "failed to change stream format for SPDIF output");
1011 /* Set the format flags */
1012 if (desired_stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
1013 fmt->i_format = VLC_CODEC_SPDIFB;
1015 fmt->i_format = VLC_CODEC_SPDIFL;
1016 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
1017 fmt->i_frame_length = A52_FRAME_NB;
1018 fmt->i_rate = (unsigned int)desired_stream_format.mSampleRate;
1019 p_sys->i_rate = fmt->i_rate;
1020 aout_FormatPrepare(fmt);
1022 /* Add IOProc callback */
1023 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
1024 (AudioDeviceIOProc)RenderCallbackSPDIF,
1028 msg_Err(p_aout, "Failed to create Process ID [%4.4s]", (char *)&err);
1033 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1035 msg_Err(p_aout, "Failed to start audio device [%4.4s]", (char *)&err);
1037 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
1039 msg_Err(p_aout, "Failed to destroy process ID [%4.4s]", (char *)&err);
1044 /* setup circular buffer */
1045 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
1050 static void Stop(audio_output_t *p_aout)
1052 struct aout_sys_t *p_sys = p_aout->sys;
1053 OSStatus err = noErr;
1054 UInt32 i_param_size = 0;
1056 if (p_sys->au_unit) {
1057 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
1058 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
1059 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
1062 if (p_sys->b_digital) {
1064 err = AudioDeviceStop(p_sys->i_selected_dev,
1067 msg_Err(p_aout, "Failed to stop audio device [%4.4s]", (char *)&err);
1069 /* Remove IOProc callback */
1070 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
1073 msg_Err(p_aout, "Failed to destroy Process ID [%4.4s]", (char *)&err);
1075 if (p_sys->b_revert)
1076 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
1078 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
1080 Boolean b_writeable = false;
1081 i_param_size = sizeof(int);
1082 /* Revert mixable to true if we are allowed to */
1083 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1084 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
1085 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
1087 if (err == noErr && b_writeable) {
1088 msg_Dbg(p_aout, "mixable is: %d", b_mix);
1090 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
1094 msg_Err(p_aout, "failed to re-set mixmode [%4.4s]", (char *)&err);
1098 if (p_sys->i_hog_pid == getpid()) {
1099 p_sys->i_hog_pid = -1;
1100 i_param_size = sizeof(p_sys->i_hog_pid);
1101 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
1102 kAudioDevicePropertyScopeOutput,
1103 kAudioObjectPropertyElementMaster };
1106 * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
1107 * directly in the same thread. This call needs to be ignored to avoid endless restarting.
1109 p_sys->b_ignore_streams_changed_callback = true;
1110 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
1111 p_sys->b_ignore_streams_changed_callback = false;
1113 msg_Err(p_aout, "Failed to release hogmode [%4.4s]", (char *)&err);
1116 /* remove audio device alive callback */
1117 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1118 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, DeviceAliveListener, (void *)p_aout);
1120 /* Be tolerant, only give a warning here */
1121 msg_Warn(p_aout, "failed to remove audio device life checker [%4.4s]", (char *)&err);
1124 p_sys->i_bytes_per_sample = 0;
1125 p_sys->b_digital = false;
1127 /* clean-up circular buffer */
1128 TPCircularBufferCleanup(&p_sys->circular_buffer);
1132 #pragma mark core interaction
1134 static void ReportDevice(audio_output_t *p_aout, UInt32 i_id, char *name)
1137 sprintf(deviceid, "%i", i_id);
1139 aout_HotplugReport(p_aout, deviceid, name);
1142 static void RebuildDeviceList(audio_output_t * p_aout)
1144 OSStatus err = noErr;
1145 UInt32 propertySize = 0;
1146 AudioObjectID *deviceIDs;
1147 UInt32 numberOfDevices;
1148 CFMutableArrayRef currentListOfDevices;
1150 struct aout_sys_t *p_sys = p_aout->sys;
1152 ReportDevice(p_aout, 0, _("System Sound Output Device"));
1154 /* setup local array */
1155 currentListOfDevices = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
1157 /* Get number of devices */
1158 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1159 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1161 msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
1165 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1167 if (numberOfDevices < 1) {
1168 msg_Err(p_aout, "No audio output devices found.");
1171 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1173 /* Allocate DeviceID array */
1174 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1175 if (deviceIDs == NULL)
1178 /* Populate DeviceID array */
1179 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1181 msg_Err(p_aout, "could not get the device IDs [%4.4s]", (char *)&err);
1185 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1187 for (unsigned int i = 0; i < numberOfDevices; i++) {
1188 CFStringRef device_name_ref;
1191 bool b_digital = false;
1192 UInt32 i_id = deviceIDs[i];
1194 /* Retrieve the length of the device name */
1195 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1197 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1201 /* Retrieve the name of the device */
1202 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1204 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1207 length = CFStringGetLength(device_name_ref);
1209 psz_name = (char *)malloc(length);
1210 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1212 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1214 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1215 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1220 ReportDevice(p_aout, i_id, psz_name);
1221 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1223 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1225 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1226 char *psz_encoded_name = nil;
1227 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1228 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1229 ReportDevice(p_aout, i_id, psz_encoded_name);
1230 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1231 free(psz_encoded_name);
1234 // TODO: only register once for each device
1235 ManageAudioStreamsCallback(p_aout, deviceIDs[i], true);
1237 CFRelease(device_name_ref);
1241 vlc_mutex_lock(&p_sys->var_lock);
1243 if (p_sys->device_list)
1244 count = CFArrayGetCount(p_sys->device_list);
1247 CFNumberRef cfn_device_id;
1248 int i_device_id = 0;
1249 for (CFIndex x = 0; x < count; x++) {
1250 if (!CFArrayContainsValue(currentListOfDevices, CFRangeMake(0, count), CFArrayGetValueAtIndex(p_sys->device_list, x))) {
1251 cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
1253 if (cfn_device_id) {
1254 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &i_device_id);
1255 ReportDevice(p_aout, i_device_id, NULL);
1260 CFRelease(p_sys->device_list);
1261 p_sys->device_list = CFArrayCreateCopy(kCFAllocatorDefault, currentListOfDevices);
1262 CFRelease(currentListOfDevices);
1263 vlc_mutex_unlock(&p_sys->var_lock);
1268 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1270 struct aout_sys_t *p_sys = p_aout->sys;
1273 p_sys->i_new_selected_dev = atoi(name);
1275 p_sys->i_new_selected_dev = 0;
1277 bool b_supports_digital = (p_sys->i_new_selected_dev & AOUT_VAR_SPDIF_FLAG);
1278 if (b_supports_digital)
1279 p_sys->b_selected_dev_is_digital = true;
1281 p_sys->b_selected_dev_is_digital = false;
1283 p_sys->i_new_selected_dev = p_sys->i_new_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1285 aout_DeviceReport(p_aout, name);
1286 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1291 static int VolumeSet(audio_output_t * p_aout, float volume)
1293 struct aout_sys_t *p_sys = p_aout->sys;
1294 OSStatus ostatus = 0;
1296 if(p_sys->b_digital)
1297 return VLC_EGENERIC;
1299 p_sys->f_volume = volume;
1300 aout_VolumeReport(p_aout, volume);
1302 /* Set volume for output unit */
1303 if(!p_sys->b_mute) {
1304 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1305 kHALOutputParam_Volume,
1306 kAudioUnitScope_Global,
1308 volume * volume * volume,
1312 if (var_InheritBool(p_aout, "volume-save"))
1313 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1318 static int MuteSet(audio_output_t * p_aout, bool mute)
1320 struct aout_sys_t *p_sys = p_aout->sys;
1323 if(p_sys->b_digital)
1324 return VLC_EGENERIC;
1326 p_sys->b_mute = mute;
1327 aout_MuteReport(p_aout, mute);
1331 volume = p_sys->f_volume;
1333 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1334 kHALOutputParam_Volume,
1335 kAudioUnitScope_Global,
1337 volume * volume * volume,
1344 #pragma mark actual playback
1346 static void Play(audio_output_t * p_aout, block_t * p_block)
1348 struct aout_sys_t *p_sys = p_aout->sys;
1350 if (p_block->i_nb_samples > 0) {
1351 /* Do the channel reordering */
1352 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1353 aout_ChannelReorder(p_block->p_buffer,
1355 p_sys->chans_to_reorder,
1360 /* move data to buffer */
1361 if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1362 msg_Warn(p_aout, "dropped buffer");
1364 if (!p_sys->i_bytes_per_sample)
1365 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1368 block_Release(p_block);
1371 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1373 struct aout_sys_t * p_sys = p_aout->sys;
1376 vlc_mutex_lock(&p_sys->lock);
1377 p_sys->b_paused = pause;
1378 vlc_mutex_unlock(&p_sys->lock);
1381 static void Flush(audio_output_t *p_aout, bool wait)
1383 struct aout_sys_t *p_sys = p_aout->sys;
1385 int32_t availableBytes;
1386 vlc_mutex_lock(&p_sys->lock);
1387 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1390 while (availableBytes > 0) {
1391 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1392 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1395 /* flush circular buffer if data is left */
1396 if (availableBytes > 0)
1397 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1400 vlc_mutex_unlock(&p_sys->lock);
1403 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1405 struct aout_sys_t * p_sys = p_aout->sys;
1407 if (!p_sys->i_bytes_per_sample)
1410 int32_t availableBytes;
1411 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1413 *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1418 /*****************************************************************************
1419 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1420 * us to provide some more audio data.
1421 * Don't print anything during normal playback, calling blocking function from
1422 * this callback is not allowed.
1423 *****************************************************************************/
1424 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1425 AudioUnitRenderActionFlags *ioActionFlags,
1426 const AudioTimeStamp *inTimeStamp,
1428 UInt32 inNumberFrames,
1429 AudioBufferList *ioData) {
1430 VLC_UNUSED(ioActionFlags);
1431 VLC_UNUSED(inTimeStamp);
1432 VLC_UNUSED(inBusNumber);
1433 VLC_UNUSED(inNumberFrames);
1435 audio_output_t * p_aout = (audio_output_t *)p_obj;
1436 struct aout_sys_t * p_sys = p_aout->sys;
1438 int bytesRequested = ioData->mBuffers[0].mDataByteSize;
1439 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1440 if (unlikely(bytesRequested == 0)) /* cannot be negative */
1443 vlc_mutex_lock(&p_sys->lock);
1444 /* Pull audio from buffer */
1445 int32_t availableBytes;
1446 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1448 /* check if we have enough data */
1449 if (!availableBytes || p_sys->b_paused) {
1450 /* return an empty buffer so silence is played until we have data */
1451 memset(targetBuffer, 0, bytesRequested);
1453 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1455 memcpy(targetBuffer, buffer, bytesToCopy);
1456 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1457 ioData->mBuffers[0].mDataByteSize = bytesToCopy;
1460 vlc_cond_signal(&p_sys->cond);
1461 vlc_mutex_unlock(&p_sys->lock);
1467 * RenderCallbackSPDIF: callback for SPDIF audio output
1469 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1470 const AudioTimeStamp * inNow,
1471 const void * inInputData,
1472 const AudioTimeStamp * inInputTime,
1473 AudioBufferList * outOutputData,
1474 const AudioTimeStamp * inOutputTime,
1475 void * threadGlobals)
1478 VLC_UNUSED(inDevice);
1479 VLC_UNUSED(inInputData);
1480 VLC_UNUSED(inInputTime);
1481 VLC_UNUSED(inOutputTime);
1483 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1484 struct aout_sys_t * p_sys = p_aout->sys;
1486 int bytesRequested = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1487 char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1488 if (unlikely(bytesRequested == 0)) /* cannot be negative */
1491 vlc_mutex_lock(&p_sys->lock);
1492 /* Pull audio from buffer */
1493 int32_t availableBytes;
1494 char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1496 /* check if we have enough data */
1497 if (!availableBytes || p_sys->b_paused) {
1498 /* return an empty buffer so silence is played until we have data */
1499 memset(targetBuffer, 0, bytesRequested);
1501 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1503 memcpy(targetBuffer, buffer, bytesToCopy);
1504 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1505 outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize = bytesToCopy;
1508 vlc_cond_signal(&p_sys->cond);
1509 vlc_mutex_unlock(&p_sys->lock);
1515 #pragma mark Stream / Hardware Listeners
1518 * Callback when device list changed
1520 static OSStatus DevicesListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1522 VLC_UNUSED(inObjectID);
1523 VLC_UNUSED(inNumberAddresses);
1524 VLC_UNUSED(inAddresses);
1526 audio_output_t *p_aout = (audio_output_t *)inClientData;
1529 aout_sys_t *p_sys = p_aout->sys;
1531 msg_Dbg(p_aout, "audio device configuration changed, resetting cache");
1532 RebuildDeviceList(p_aout);
1534 vlc_mutex_lock(&p_sys->var_lock);
1535 if(!CFArrayContainsValue(p_sys->device_list, CFRangeMake(0, CFArrayGetCount(p_sys->device_list)),CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &p_sys->i_selected_dev)))
1536 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1537 vlc_mutex_unlock(&p_sys->var_lock);
1543 * Callback when current device is not alive anymore
1545 static OSStatus DeviceAliveListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1547 VLC_UNUSED(inObjectID);
1548 VLC_UNUSED(inNumberAddresses);
1549 VLC_UNUSED(inAddresses);
1551 audio_output_t *p_aout = (audio_output_t *)inClientData;
1555 msg_Warn(p_aout, "audio device died, resetting aout");
1556 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1562 * Callback when default audio device changed
1564 static OSStatus DefaultDeviceChangedListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1566 VLC_UNUSED(inObjectID);
1567 VLC_UNUSED(inNumberAddresses);
1568 VLC_UNUSED(inAddresses);
1570 audio_output_t *p_aout = (audio_output_t *)inClientData;
1574 if (!p_aout->sys->b_selected_dev_is_default)
1577 AudioObjectID defaultDeviceID = 0;
1578 UInt32 propertySize = sizeof(AudioObjectID);
1579 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1580 propertySize = sizeof(AudioObjectID);
1581 OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1583 msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
1587 msg_Dbg(p_aout, "default device changed to %i", defaultDeviceID);
1589 /* Default device is changed by the os to allow other apps to play sound while in digital
1590 mode. But this should not affect ourself. */
1591 if (p_aout->sys->b_digital) {
1592 msg_Dbg(p_aout, "ignore, as digital mode is active");
1596 /* Also ignore events which announce the same device id */
1597 if(defaultDeviceID == p_aout->sys->i_selected_dev)
1600 msg_Dbg(p_aout, "default device actually changed, resetting aout");
1601 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1607 * Callback when physical formats for device change
1609 static OSStatus StreamsChangedListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1611 OSStatus err = noErr;
1612 UInt32 i_param_size = 0;
1613 AudioStreamID *p_streams = NULL;
1616 VLC_UNUSED(inNumberAddresses);
1617 VLC_UNUSED(inAddresses);
1619 audio_output_t *p_aout = (audio_output_t *)inClientData;
1623 aout_sys_t *p_sys = p_aout->sys;
1624 if(unlikely(p_sys->b_ignore_streams_changed_callback == true))
1627 msg_Dbg(p_aout, "available physical formats for audio device changed");
1628 RebuildDeviceList(p_aout);
1630 /* In this case audio has not yet started. Below code will not work and is not needed here. */
1631 if (p_sys->i_selected_dev == 0)
1635 * check if changed stream id belongs to current device
1637 vlc_mutex_lock(&p_sys->var_lock);
1638 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1639 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
1641 msg_Err(p_aout, "could not get number of streams for device %i [%4.4s]", p_sys->i_selected_dev, (char *)&err);
1642 vlc_mutex_unlock(&p_sys->var_lock);
1643 return VLC_EGENERIC;
1646 i_streams = i_param_size / sizeof(AudioStreamID);
1647 p_streams = (AudioStreamID *)malloc(i_param_size);
1648 if (p_streams == NULL) {
1649 vlc_mutex_unlock(&p_sys->var_lock);
1653 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1655 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1656 vlc_mutex_unlock(&p_sys->var_lock);
1657 return VLC_EGENERIC;
1659 vlc_mutex_unlock(&p_sys->var_lock);
1661 for (int i = 0; i < i_streams; i++) {
1662 if (p_streams[i] == inObjectID) {
1663 msg_Dbg(p_aout, "Restart aout as this affects current device");
1664 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1674 * StreamListener: check whether the device's physical format change is complete
1676 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1678 OSStatus err = noErr;
1679 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1681 VLC_UNUSED(inObjectID);
1683 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1684 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1685 vlc_mutex_lock(&w->lock);
1686 vlc_cond_signal(&w->cond);
1687 vlc_mutex_unlock(&w->lock);
1695 #pragma mark helpers
1697 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register)
1699 OSStatus err = noErr;
1700 UInt32 i_param_size = 0;
1701 AudioStreamID *p_streams = NULL;
1704 /* Retrieve all the output streams */
1705 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1706 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1708 msg_Err(p_aout, "could not get number of streams for device id %i [%4.4s]", i_dev_id, (char *)&err);
1709 return VLC_EGENERIC;
1712 i_streams = i_param_size / sizeof(AudioStreamID);
1713 p_streams = (AudioStreamID *)malloc(i_param_size);
1714 if (p_streams == NULL)
1717 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1719 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1720 return VLC_EGENERIC;
1723 for (int i = 0; i < i_streams; i++) {
1724 /* get notified when physical formats change */
1725 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1728 err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1730 // nope just means that we already have a callback
1731 if (err == kAudioHardwareIllegalOperationError) {
1732 msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i, callback already set? [%4.4s]", p_streams[i],
1735 msg_Err(p_aout, "could not set audio stream formats property callback on stream id %i [%4.4s]", p_streams[i],
1740 } else { /* unregister callback */
1741 err = AudioObjectRemovePropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1743 msg_Err(p_aout, "failed to remove audio device property streams callback [%4.4s]", (char *)&err);
1753 * AudioDeviceHasOutput: Checks if the device is actually an output device
1755 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1757 UInt32 dataSize = 0;
1760 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1761 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1763 if (dataSize == 0 || status != noErr)
1770 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1772 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1774 OSStatus err = noErr;
1775 UInt32 i_param_size = 0;
1776 AudioStreamID *p_streams = NULL;
1778 bool b_return = false;
1780 /* Retrieve all the output streams */
1781 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1782 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1784 msg_Err(p_aout, "could not get number of streams [%4.4s] (%i)", (char *)&err, (int32_t)err);
1788 i_streams = i_param_size / sizeof(AudioStreamID);
1789 p_streams = (AudioStreamID *)malloc(i_param_size);
1790 if (p_streams == NULL)
1793 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1795 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1799 for (int i = 0; i < i_streams; i++) {
1800 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1809 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1811 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1813 OSStatus err = noErr;
1814 UInt32 i_param_size = 0;
1815 AudioStreamRangedDescription *p_format_list = NULL;
1817 bool b_return = false;
1819 /* Retrieve all the stream formats supported by each output stream */
1820 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1821 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1823 msg_Err(p_aout, "could not get number of streamformats [%4.4s] (%i)", (char *)&err, (int32_t)err);
1827 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1828 msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1830 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1831 if (p_format_list == NULL)
1834 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1836 msg_Err(p_aout, "could not get the list of streamformats [%4.4s]", (char *)&err);
1837 free(p_format_list);
1838 p_format_list = NULL;
1842 for (int i = 0; i < i_formats; i++) {
1844 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1847 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1848 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1849 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1850 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1854 free(p_format_list);
1859 * AudioStreamChangeFormat: switch stream format based on the provided description
1861 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1863 OSStatus err = noErr;
1864 int retValue = true;
1866 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1868 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1870 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1872 /* Condition because SetProperty is asynchronious */
1873 vlc_cond_init(&w.cond);
1874 vlc_mutex_init(&w.lock);
1875 vlc_mutex_lock(&w.lock);
1877 /* Install the callback */
1878 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1880 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed [%4.4s]", (char *)&err);
1885 /* change the format */
1886 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1889 msg_Err(p_aout, "could not set the stream format [%4.4s]", (char *)&err);
1894 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1895 * it is also not atomic in its behaviour.
1896 * Therefore we check 5 times before we really give up.
1897 * FIXME: failing isn't actually implemented yet. */
1898 AudioStreamBasicDescription actual_format;
1899 UInt32 i_param_size = sizeof(AudioStreamBasicDescription);
1900 for (int i = 0; i < 5; i++) {
1901 /* Callback is not always invoked. So first check if format is already set. */
1902 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1904 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1905 if (actual_format.mSampleRate == change_format.mSampleRate &&
1906 actual_format.mFormatID == change_format.mFormatID &&
1907 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1908 /* The right format is now active */
1912 /* We need to check again */
1913 mtime_t timeout = mdate() + 500000;
1914 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1915 msg_Dbg(p_aout, "reached timeout");
1919 /* Removing the property listener */
1920 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1922 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed [%4.4s]", (char *)&err);
1926 /* Destroy the lock and condition */
1927 vlc_mutex_unlock(&w.lock);
1928 vlc_mutex_destroy(&w.lock);
1929 vlc_cond_destroy(&w.cond);