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 stream_format; /* The format we changed the stream to */
102 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
103 bool b_revert; /* Whether we need to revert the stream format */
104 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
106 int i_rate; /* media sample rate */
107 int i_bytes_per_sample;
109 CFArrayRef device_list;
111 vlc_mutex_t var_lock; /* protects access to device_list and i_selected_dev */
120 bool b_ignore_streams_changed_callback;
124 #pragma mark local prototypes & module descriptor
126 static int Open (vlc_object_t *);
127 static void Close (vlc_object_t *);
128 static int Start (audio_output_t *, audio_sample_format_t *);
129 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
130 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
131 static void Stop (audio_output_t *);
133 static void RebuildDeviceList (audio_output_t *);
134 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
135 static int VolumeSet (audio_output_t *, float);
136 static int MuteSet (audio_output_t *, bool);
138 static void Play (audio_output_t *, block_t *);
139 static void Pause (audio_output_t *, bool, mtime_t);
140 static void Flush (audio_output_t *, bool);
141 static int TimeGet (audio_output_t *, mtime_t *);
142 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
143 UInt32 , UInt32, AudioBufferList *);
145 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
146 AudioBufferList *, const AudioTimeStamp *, void *);
148 static OSStatus DevicesListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
149 static OSStatus DeviceAliveListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
150 static OSStatus DefaultDeviceChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
151 static OSStatus StreamsChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
153 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
155 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register);
156 static int AudioDeviceHasOutput (AudioDeviceID);
157 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
158 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
159 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
163 set_shortname("auhal")
164 set_description(N_("HAL AudioUnit output"))
165 set_capability("audio output", 101)
166 set_category(CAT_AUDIO)
167 set_subcategory(SUBCAT_AUDIO_AOUT)
168 set_callbacks(Open, Close)
169 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
170 VOLUME_TEXT, VOLUME_LONGTEXT, true)
171 change_integer_range(0, AOUT_VOLUME_MAX)
172 add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
173 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
177 #pragma mark initialization
179 static int Open(vlc_object_t *obj)
181 audio_output_t *p_aout = (audio_output_t *)obj;
182 aout_sys_t *p_sys = malloc(sizeof (*p_sys));
183 if (unlikely(p_sys == NULL))
186 OSStatus err = noErr;
188 vlc_mutex_init(&p_sys->var_lock);
189 vlc_mutex_init(&p_sys->lock);
190 vlc_cond_init(&p_sys->cond);
191 p_sys->b_digital = false;
192 p_sys->b_ignore_streams_changed_callback = false;
193 p_sys->b_selected_dev_is_default = false;
194 p_sys->b_paused = false;
197 p_aout->start = Start;
199 p_aout->volume_set = VolumeSet;
200 p_aout->mute_set = MuteSet;
201 p_aout->device_select = SwitchAudioDevice;
202 p_sys->device_list = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL);
205 * Force an own run loop for callbacks.
207 * According to rtaudio, this is absolutely necessary since 10.6 to get correct notifications.
208 * It might fix issues when using the module as a library where a proper loop is not setup already.
210 CFRunLoopRef theRunLoop = NULL;
211 AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal,kAudioObjectPropertyElementMaster };
212 err = AudioObjectSetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
214 msg_Err(p_aout, "failed to set the run loop property [%4.4s]", (char *)&err);
217 /* Attach a listener so that we are notified of a change in the device setup */
218 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
219 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
221 msg_Err(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
223 /* Attach a listener to be notified about changes in default audio device */
224 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
225 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
227 msg_Err(p_aout, "failed to add listener for default audio device [%4.4s]", (char *)&err);
229 RebuildDeviceList(p_aout);
231 /* remember the volume */
232 p_sys->f_volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
233 aout_VolumeReport(p_aout, p_sys->f_volume);
234 p_sys->b_mute = var_InheritBool(p_aout, "mute");
235 aout_MuteReport(p_aout, p_sys->b_mute);
237 char *psz_audio_device = var_InheritString(p_aout, "auhal-audio-device");
238 SwitchAudioDevice(p_aout, psz_audio_device);
239 free(psz_audio_device);
244 static void Close(vlc_object_t *obj)
246 audio_output_t *p_aout = (audio_output_t *)obj;
247 aout_sys_t *p_sys = p_aout->sys;
249 OSStatus err = noErr;
251 /* remove audio devices callback */
252 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
253 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
255 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed [%4.4s]", (char *)&err);
257 /* remove listener to be notified about changes in default audio device */
258 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
259 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
261 msg_Err(p_aout, "failed to remove listener for default audio device [%4.4s]", (char *)&err);
263 vlc_mutex_lock(&p_sys->var_lock);
264 /* remove streams callbacks */
265 CFIndex count = CFArrayGetCount(p_sys->device_list);
267 for (CFIndex x = 0; x < count; x++) {
268 AudioDeviceID deviceId = 0;
269 CFNumberRef cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
273 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &deviceId);
274 if (!(deviceId & AOUT_VAR_SPDIF_FLAG)) {
275 ManageAudioStreamsCallback(p_aout, deviceId, false);
280 CFRelease(p_sys->device_list);
281 vlc_mutex_unlock(&p_sys->var_lock);
283 char *psz_device = aout_DeviceGet(p_aout);
284 config_PutPsz(p_aout, "auhal-audio-device", psz_device);
287 vlc_mutex_destroy(&p_sys->var_lock);
288 vlc_mutex_destroy(&p_sys->lock);
289 vlc_cond_destroy(&p_sys->cond);
294 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
296 OSStatus err = noErr;
297 UInt32 i_param_size = 0;
298 struct aout_sys_t *p_sys = NULL;
300 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
304 bool b_start_digital = false;
307 p_sys->b_digital = false;
308 p_sys->au_component = NULL;
309 p_sys->au_unit = NULL;
310 p_sys->i_hog_pid = -1;
311 p_sys->i_stream_id = 0;
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 AudioChannelLayout new_layout;
443 AURenderCallbackStruct input;
444 p_aout->sys->chans_to_reorder = 0;
446 SInt32 currentMinorSystemVersion;
447 if(Gestalt(gestaltSystemVersionMinor, ¤tMinorSystemVersion) != noErr)
448 msg_Err(p_aout, "failed to check OSX version");
450 /* Lets go find our Component */
451 desc.componentType = kAudioUnitType_Output;
452 desc.componentSubType = kAudioUnitSubType_HALOutput;
453 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
454 desc.componentFlags = 0;
455 desc.componentFlagsMask = 0;
457 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
458 if (p_sys->au_component == NULL) {
459 msg_Err(p_aout, "cannot find any HAL component, PCM output failed");
463 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
465 msg_Err(p_aout, "cannot open HAL component, PCM output failed [%4.4s]", (char *)&err);
469 /* Set the device we will use for this output unit */
470 err = AudioUnitSetProperty(p_sys->au_unit,
471 kAudioOutputUnitProperty_CurrentDevice,
472 kAudioUnitScope_Global,
474 &p_sys->i_selected_dev,
475 sizeof(AudioObjectID));
478 msg_Err(p_aout, "cannot select audio output device, PCM output failed [%4.4s]", (char *)&err);
482 /* Get the current format */
483 i_param_size = sizeof(AudioStreamBasicDescription);
485 err = AudioUnitGetProperty(p_sys->au_unit,
486 kAudioUnitProperty_StreamFormat,
487 kAudioUnitScope_Output,
493 msg_Err(p_aout, "failed to detect supported stream formats [%4.4s]", (char *)&err);
496 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
498 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
499 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
500 kAudioDevicePropertyPreferredChannelLayout,
501 kAudioUnitScope_Output,
507 layout = (AudioChannelLayout *)malloc(i_param_size);
509 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
510 kAudioDevicePropertyPreferredChannelLayout,
511 kAudioUnitScope_Output,
516 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
517 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
518 /* bitmap defined channellayout */
519 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
520 sizeof(UInt32), &layout->mChannelBitmap,
523 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
525 /* layouttags defined channellayout */
526 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
527 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
532 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
534 if (layout->mNumberChannelDescriptions == 0) {
535 msg_Err(p_aout, "insufficient number of output channels");
539 /* Initialize the VLC core channel count */
540 fmt->i_physical_channels = 0;
541 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
543 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
544 /* We only need Mono or cannot output more than 1 channel */
545 fmt->i_physical_channels = AOUT_CHAN_CENTER;
546 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
547 /* We only need Stereo or cannot output more than 2 channels */
548 fmt->i_physical_channels = AOUT_CHANS_STEREO;
550 /* We want more than stereo and we can do that */
551 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
553 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
556 switch(layout->mChannelDescriptions[i].mChannelLabel) {
557 case kAudioChannelLabel_Left:
558 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
560 case kAudioChannelLabel_Right:
561 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
563 case kAudioChannelLabel_Center:
564 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
566 case kAudioChannelLabel_LFEScreen:
567 fmt->i_physical_channels |= AOUT_CHAN_LFE;
569 case kAudioChannelLabel_LeftSurround:
570 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
572 case kAudioChannelLabel_RightSurround:
573 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
575 case kAudioChannelLabel_RearSurroundLeft:
576 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
578 case kAudioChannelLabel_RearSurroundRight:
579 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
581 case kAudioChannelLabel_CenterSurround:
582 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
585 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
588 if (fmt->i_physical_channels == 0) {
589 fmt->i_physical_channels = AOUT_CHANS_STEREO;
590 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup in /Applications/Utilities. VLC will output Stereo only.");
591 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
592 _("You should configure your speaker layout with "
593 "\"Audio Midi Setup\" in /Applications/"
594 "Utilities. VLC will output Stereo only."));
599 msg_Warn(p_aout, "device driver does not support kAudioDevicePropertyPreferredChannelLayout - using stereo fallback [%4.4s]", (char *)&err);
600 fmt->i_physical_channels = AOUT_CHANS_STEREO;
603 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
604 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
606 memset (&new_layout, 0, sizeof(new_layout));
607 uint32_t chans_out[AOUT_CHAN_MAX];
608 memset(&chans_out, 0, sizeof(chans_out));
610 /* Some channel abbreviations used below:
615 * Rs - right surround
616 * Cs - center surround
617 * Rls - rear left surround
618 * Rrs - rear right surround
621 * Lsd - left surround direct
622 * Rsd - right surround direct
626 * Vhl - vertical height left
627 * Vhc - vertical height center
628 * Vhr - vertical height right
629 * Lt - left matrix total. for matrix encoded stereo.
630 * Rt - right matrix total. for matrix encoded stereo. */
632 switch(aout_FormatNbChannels(fmt)) {
634 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
637 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
640 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
641 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
642 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
643 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
646 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
647 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
648 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
649 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
650 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
651 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
654 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
655 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
656 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
657 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
660 if (fmt->i_physical_channels & (AOUT_CHAN_LFE)) {
661 /* note: for some reason, kAudioChannelLayoutTag_DVD_20, which would not require channel reordering,
662 does not work anymore */
663 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_5_1; // L R C LFE Ls Rs
665 chans_out[0] = AOUT_CHAN_LEFT;
666 chans_out[1] = AOUT_CHAN_RIGHT;
667 chans_out[2] = AOUT_CHAN_CENTER;
668 chans_out[3] = AOUT_CHAN_LFE;
669 chans_out[4] = AOUT_CHAN_REARLEFT;
670 chans_out[5] = AOUT_CHAN_REARRIGHT;
672 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
673 if (p_aout->sys->chans_to_reorder)
674 msg_Dbg(p_aout, "channel reordering needed for 5.1 output");
676 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
678 chans_out[0] = AOUT_CHAN_LEFT;
679 chans_out[1] = AOUT_CHAN_RIGHT;
680 chans_out[2] = AOUT_CHAN_REARLEFT;
681 chans_out[3] = AOUT_CHAN_REARRIGHT;
682 chans_out[4] = AOUT_CHAN_CENTER;
683 chans_out[5] = AOUT_CHAN_REARCENTER;
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 6.0 output");
691 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
693 chans_out[0] = AOUT_CHAN_LEFT;
694 chans_out[1] = AOUT_CHAN_RIGHT;
695 chans_out[2] = AOUT_CHAN_CENTER;
696 chans_out[3] = AOUT_CHAN_LFE;
697 chans_out[4] = AOUT_CHAN_REARLEFT;
698 chans_out[5] = AOUT_CHAN_REARRIGHT;
699 chans_out[6] = AOUT_CHAN_REARCENTER;
701 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
702 if (p_aout->sys->chans_to_reorder)
703 msg_Dbg(p_aout, "channel reordering needed for 6.1 output");
707 if (fmt->i_physical_channels & (AOUT_CHAN_LFE) || currentMinorSystemVersion < 7) {
708 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
710 chans_out[0] = AOUT_CHAN_LEFT;
711 chans_out[1] = AOUT_CHAN_RIGHT;
712 chans_out[2] = AOUT_CHAN_CENTER;
713 chans_out[3] = AOUT_CHAN_LFE;
714 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
715 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
716 chans_out[6] = AOUT_CHAN_REARLEFT;
717 chans_out[7] = AOUT_CHAN_REARRIGHT;
719 if (!(fmt->i_physical_channels & (AOUT_CHAN_LFE)))
720 msg_Warn(p_aout, "8.0 audio output not supported on OS X 10.%i, layout will be incorrect", currentMinorSystemVersion);
722 #ifdef MAC_OS_X_VERSION_10_7
724 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_0_B; // Lc C Rc L R Ls Cs Rs
726 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
727 chans_out[1] = AOUT_CHAN_CENTER;
728 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
729 chans_out[3] = AOUT_CHAN_LEFT;
730 chans_out[4] = AOUT_CHAN_RIGHT;
731 chans_out[5] = AOUT_CHAN_REARLEFT;
732 chans_out[6] = AOUT_CHAN_REARCENTER;
733 chans_out[7] = AOUT_CHAN_REARRIGHT;
736 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
737 if (p_aout->sys->chans_to_reorder)
738 msg_Dbg(p_aout, "channel reordering needed for 7.1 / 8.0 output");
742 if (currentMinorSystemVersion < 7) {
743 msg_Warn(p_aout, "8.1 audio output not supported on OS X 10.%i", currentMinorSystemVersion);
747 #ifdef MAC_OS_X_VERSION_10_7
748 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_1_B; // Lc C Rc L R Ls Cs Rs LFE
749 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
750 chans_out[1] = AOUT_CHAN_CENTER;
751 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
752 chans_out[3] = AOUT_CHAN_LEFT;
753 chans_out[4] = AOUT_CHAN_RIGHT;
754 chans_out[5] = AOUT_CHAN_REARLEFT;
755 chans_out[6] = AOUT_CHAN_REARCENTER;
756 chans_out[7] = AOUT_CHAN_REARRIGHT;
757 chans_out[8] = AOUT_CHAN_LFE;
759 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
760 if (p_aout->sys->chans_to_reorder)
761 msg_Dbg(p_aout, "channel reordering needed for 8.1 output");
766 /* Set up the format to be used */
767 DeviceFormat.mSampleRate = fmt->i_rate;
768 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
769 p_sys->i_rate = fmt->i_rate;
771 /* We use float 32 since this is VLC's endorsed format */
772 fmt->i_format = VLC_CODEC_FL32;
773 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
774 DeviceFormat.mBitsPerChannel = 32;
775 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
777 /* Calculate framesizes and stuff */
778 DeviceFormat.mFramesPerPacket = 1;
779 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
780 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
782 /* Set the desired format */
783 i_param_size = sizeof(AudioStreamBasicDescription);
784 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
785 kAudioUnitProperty_StreamFormat,
786 kAudioUnitScope_Input,
791 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
793 /* Retrieve actual format */
794 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
795 kAudioUnitProperty_StreamFormat,
796 kAudioUnitScope_Input,
801 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
803 /* Do the last VLC aout setups */
804 aout_FormatPrepare(fmt);
806 /* set the IOproc callback */
807 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
808 input.inputProcRefCon = p_aout;
810 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
811 kAudioUnitProperty_SetRenderCallback,
812 kAudioUnitScope_Input,
813 0, &input, sizeof(input)));
815 /* Set the new_layout as the layout VLC will use to feed the AU unit */
816 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
817 kAudioUnitProperty_AudioChannelLayout,
818 kAudioUnitScope_Output,
819 0, &new_layout, sizeof(new_layout)));
821 if (new_layout.mNumberChannelDescriptions > 0)
822 free(new_layout.mChannelDescriptions);
825 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
827 /* setup circular buffer */
828 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
829 fmt->i_rate * fmt->i_bytes_per_frame);
831 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
833 /* Set volume for output unit */
834 VolumeSet(p_aout, p_sys->f_volume);
835 MuteSet(p_aout, p_sys->b_mute);
841 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
843 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
845 struct aout_sys_t *p_sys = p_aout->sys;
846 OSStatus err = noErr;
847 UInt32 i_param_size = 0, b_mix = 0;
848 Boolean b_writeable = false;
849 AudioStreamID *p_streams = NULL;
850 unsigned i_streams = 0;
852 /* Start doing the SPDIF setup proces */
853 p_sys->b_digital = true;
856 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
857 i_param_size = sizeof(p_sys->i_hog_pid);
858 p_sys->i_hog_pid = getpid() ;
861 * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
862 * directly in the same thread. This call needs to be ignored to avoid endless restarting.
864 p_sys->b_ignore_streams_changed_callback = true;
865 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
866 p_sys->b_ignore_streams_changed_callback = false;
869 msg_Err(p_aout, "failed to set hogmode [%4.4s]", (char *)&err);
873 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
875 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
876 /* Set mixable to false if we are allowed to */
877 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
878 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
879 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
881 if (err == noErr && b_writeable) {
883 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
884 p_sys->b_changed_mixing = true;
888 msg_Err(p_aout, "failed to set mixmode [%4.4s]", (char *)&err);
893 /* Get a list of all the streams on this device */
894 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
895 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
897 msg_Err(p_aout, "could not get size of stream description packet [%4.4s]", (char *)&err);
901 i_streams = i_param_size / sizeof(AudioStreamID);
902 p_streams = (AudioStreamID *)malloc(i_param_size);
903 if (p_streams == NULL)
906 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
909 msg_Err(p_aout, "could not fetch stream descriptions [%4.4s]", (char *)&err);
914 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
915 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
916 /* Find a stream with a cac3 stream */
917 AudioStreamRangedDescription *p_format_list = NULL;
919 bool b_digital = false;
921 /* Retrieve all the stream formats supported by each output stream */
922 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
924 msg_Err(p_aout, "could not get number of streamformats: [%4.4s] (%i)", (char *)&err, (int32_t)err);
928 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
929 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
930 if (p_format_list == NULL)
933 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
935 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
940 /* Check if one of the supported formats is a digital format */
941 for (int j = 0; j < i_formats; j++) {
942 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
943 p_format_list[j].mFormat.mFormatID == 'iac3' ||
944 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
945 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
952 /* if this stream supports a digital (cac3) format, then go set it. */
953 int i_requested_rate_format = -1;
954 int i_current_rate_format = -1;
955 int i_backup_rate_format = -1;
957 p_sys->i_stream_id = p_streams[i];
958 p_sys->i_stream_index = i;
960 if (!p_sys->b_revert) {
961 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
962 /* Retrieve the original format of this stream first if not done so already */
963 i_param_size = sizeof(p_sys->sfmt_revert);
964 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
966 msg_Err(p_aout, "could not retrieve the original streamformat [%4.4s]", (char *)&err);
969 p_sys->b_revert = true;
972 for (int j = 0; j < i_formats; j++) {
973 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
974 p_format_list[j].mFormat.mFormatID == 'iac3' ||
975 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
976 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
977 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
978 i_requested_rate_format = j;
980 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
981 i_current_rate_format = j;
983 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
984 i_backup_rate_format = j;
990 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
991 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
992 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
993 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
995 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) */
1001 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
1003 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format)) {
1004 msg_Err(p_aout, "failed to change stream format for SPDIF output");
1008 /* Set the format flags */
1009 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
1010 fmt->i_format = VLC_CODEC_SPDIFB;
1012 fmt->i_format = VLC_CODEC_SPDIFL;
1013 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
1014 fmt->i_frame_length = A52_FRAME_NB;
1015 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
1016 p_sys->i_rate = fmt->i_rate;
1017 aout_FormatPrepare(fmt);
1019 /* Add IOProc callback */
1020 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
1021 (AudioDeviceIOProc)RenderCallbackSPDIF,
1025 msg_Err(p_aout, "Failed to create Process ID [%4.4s]", (char *)&err);
1030 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1032 msg_Err(p_aout, "Failed to start audio device [%4.4s]", (char *)&err);
1034 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
1036 msg_Err(p_aout, "Failed to destroy process ID [%4.4s]", (char *)&err);
1041 /* setup circular buffer */
1042 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
1047 static void Stop(audio_output_t *p_aout)
1049 struct aout_sys_t *p_sys = p_aout->sys;
1050 OSStatus err = noErr;
1051 UInt32 i_param_size = 0;
1053 if (p_sys->au_unit) {
1054 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
1055 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
1056 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
1059 if (p_sys->b_digital) {
1061 err = AudioDeviceStop(p_sys->i_selected_dev,
1064 msg_Err(p_aout, "Failed to stop audio device [%4.4s]", (char *)&err);
1066 /* Remove IOProc callback */
1067 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
1070 msg_Err(p_aout, "Failed to destroy Process ID [%4.4s]", (char *)&err);
1072 if (p_sys->b_revert)
1073 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
1075 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
1077 Boolean b_writeable = false;
1078 i_param_size = sizeof(int);
1079 /* Revert mixable to true if we are allowed to */
1080 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1081 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
1082 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
1084 if (err == noErr && b_writeable) {
1085 msg_Dbg(p_aout, "mixable is: %d", b_mix);
1087 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
1091 msg_Err(p_aout, "failed to re-set mixmode [%4.4s]", (char *)&err);
1095 if (p_sys->i_hog_pid == getpid()) {
1096 p_sys->i_hog_pid = -1;
1097 i_param_size = sizeof(p_sys->i_hog_pid);
1098 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
1099 kAudioDevicePropertyScopeOutput,
1100 kAudioObjectPropertyElementMaster };
1103 * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
1104 * directly in the same thread. This call needs to be ignored to avoid endless restarting.
1106 p_sys->b_ignore_streams_changed_callback = true;
1107 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
1108 p_sys->b_ignore_streams_changed_callback = false;
1110 msg_Err(p_aout, "Failed to release hogmode [%4.4s]", (char *)&err);
1113 /* remove audio device alive callback */
1114 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1115 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, DeviceAliveListener, (void *)p_aout);
1117 /* Be tolerant, only give a warning here */
1118 msg_Warn(p_aout, "failed to remove audio device life checker [%4.4s]", (char *)&err);
1121 p_sys->i_bytes_per_sample = 0;
1122 p_sys->b_digital = false;
1124 /* clean-up circular buffer */
1125 TPCircularBufferCleanup(&p_sys->circular_buffer);
1129 #pragma mark core interaction
1131 static void ReportDevice(audio_output_t *p_aout, UInt32 i_id, char *name)
1134 sprintf(deviceid, "%i", i_id);
1136 aout_HotplugReport(p_aout, deviceid, name);
1139 static void RebuildDeviceList(audio_output_t * p_aout)
1141 OSStatus err = noErr;
1142 UInt32 propertySize = 0;
1143 AudioObjectID *deviceIDs;
1144 UInt32 numberOfDevices;
1145 CFMutableArrayRef currentListOfDevices;
1147 struct aout_sys_t *p_sys = p_aout->sys;
1149 ReportDevice(p_aout, 0, _("System Sound Output Device"));
1151 /* setup local array */
1152 currentListOfDevices = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
1154 /* Get number of devices */
1155 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1156 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1158 msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
1162 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1164 if (numberOfDevices < 1) {
1165 msg_Err(p_aout, "No audio output devices found.");
1168 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1170 /* Allocate DeviceID array */
1171 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1172 if (deviceIDs == NULL)
1175 /* Populate DeviceID array */
1176 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1178 msg_Err(p_aout, "could not get the device IDs [%4.4s]", (char *)&err);
1182 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1184 for (unsigned int i = 0; i < numberOfDevices; i++) {
1185 CFStringRef device_name_ref;
1188 bool b_digital = false;
1189 UInt32 i_id = deviceIDs[i];
1191 /* Retrieve the length of the device name */
1192 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1194 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1198 /* Retrieve the name of the device */
1199 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1201 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1204 length = CFStringGetLength(device_name_ref);
1206 psz_name = (char *)malloc(length);
1207 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1209 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1211 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1212 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1217 ReportDevice(p_aout, i_id, psz_name);
1218 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1220 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1222 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1223 char *psz_encoded_name = nil;
1224 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1225 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1226 ReportDevice(p_aout, i_id, psz_encoded_name);
1227 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1228 free(psz_encoded_name);
1231 // TODO: only register once for each device
1232 ManageAudioStreamsCallback(p_aout, deviceIDs[i], true);
1234 CFRelease(device_name_ref);
1238 vlc_mutex_lock(&p_sys->var_lock);
1240 if (p_sys->device_list)
1241 count = CFArrayGetCount(p_sys->device_list);
1244 CFNumberRef cfn_device_id;
1245 int i_device_id = 0;
1246 for (CFIndex x = 0; x < count; x++) {
1247 if (!CFArrayContainsValue(currentListOfDevices, CFRangeMake(0, count), CFArrayGetValueAtIndex(p_sys->device_list, x))) {
1248 cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
1250 if (cfn_device_id) {
1251 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &i_device_id);
1252 ReportDevice(p_aout, i_device_id, NULL);
1257 CFRelease(p_sys->device_list);
1258 p_sys->device_list = CFArrayCreateCopy(kCFAllocatorDefault, currentListOfDevices);
1259 CFRelease(currentListOfDevices);
1260 vlc_mutex_unlock(&p_sys->var_lock);
1265 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1267 struct aout_sys_t *p_sys = p_aout->sys;
1270 p_sys->i_new_selected_dev = atoi(name);
1272 p_sys->i_new_selected_dev = 0;
1274 bool b_supports_digital = (p_sys->i_new_selected_dev & AOUT_VAR_SPDIF_FLAG);
1275 if (b_supports_digital)
1276 p_sys->b_selected_dev_is_digital = true;
1278 p_sys->b_selected_dev_is_digital = false;
1280 p_sys->i_new_selected_dev = p_sys->i_new_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1282 aout_DeviceReport(p_aout, name);
1283 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1288 static int VolumeSet(audio_output_t * p_aout, float volume)
1290 struct aout_sys_t *p_sys = p_aout->sys;
1291 OSStatus ostatus = 0;
1293 if(p_sys->b_digital)
1294 return VLC_EGENERIC;
1296 p_sys->f_volume = volume;
1297 aout_VolumeReport(p_aout, volume);
1299 /* Set volume for output unit */
1300 if(!p_sys->b_mute) {
1301 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1302 kHALOutputParam_Volume,
1303 kAudioUnitScope_Global,
1305 volume * volume * volume,
1309 if (var_InheritBool(p_aout, "volume-save"))
1310 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1315 static int MuteSet(audio_output_t * p_aout, bool mute)
1317 struct aout_sys_t *p_sys = p_aout->sys;
1320 if(p_sys->b_digital)
1321 return VLC_EGENERIC;
1323 p_sys->b_mute = mute;
1324 aout_MuteReport(p_aout, mute);
1328 volume = p_sys->f_volume;
1330 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1331 kHALOutputParam_Volume,
1332 kAudioUnitScope_Global,
1334 volume * volume * volume,
1341 #pragma mark actual playback
1343 static void Play(audio_output_t * p_aout, block_t * p_block)
1345 struct aout_sys_t *p_sys = p_aout->sys;
1347 if (p_block->i_nb_samples > 0) {
1348 /* Do the channel reordering */
1349 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1350 aout_ChannelReorder(p_block->p_buffer,
1352 p_sys->chans_to_reorder,
1357 /* move data to buffer */
1358 if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1359 msg_Warn(p_aout, "dropped buffer");
1361 if (!p_sys->i_bytes_per_sample)
1362 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1365 block_Release(p_block);
1368 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1370 struct aout_sys_t * p_sys = p_aout->sys;
1373 vlc_mutex_lock(&p_sys->lock);
1374 p_sys->b_paused = pause;
1375 vlc_mutex_unlock(&p_sys->lock);
1378 static void Flush(audio_output_t *p_aout, bool wait)
1380 struct aout_sys_t *p_sys = p_aout->sys;
1382 int32_t availableBytes;
1383 vlc_mutex_lock(&p_sys->lock);
1384 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1387 while (availableBytes > 0) {
1388 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1389 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1392 /* flush circular buffer if data is left */
1393 if (availableBytes > 0)
1394 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1397 vlc_mutex_unlock(&p_sys->lock);
1400 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1402 struct aout_sys_t * p_sys = p_aout->sys;
1404 if (!p_sys->i_bytes_per_sample)
1407 int32_t availableBytes;
1408 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1410 *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1415 /*****************************************************************************
1416 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1417 * us to provide some more audio data.
1418 * Don't print anything during normal playback, calling blocking function from
1419 * this callback is not allowed.
1420 *****************************************************************************/
1421 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1422 AudioUnitRenderActionFlags *ioActionFlags,
1423 const AudioTimeStamp *inTimeStamp,
1425 UInt32 inNumberFrames,
1426 AudioBufferList *ioData) {
1427 VLC_UNUSED(ioActionFlags);
1428 VLC_UNUSED(inTimeStamp);
1429 VLC_UNUSED(inBusNumber);
1430 VLC_UNUSED(inNumberFrames);
1432 audio_output_t * p_aout = (audio_output_t *)p_obj;
1433 struct aout_sys_t * p_sys = p_aout->sys;
1435 int bytesRequested = ioData->mBuffers[0].mDataByteSize;
1436 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1438 vlc_mutex_lock(&p_sys->lock);
1439 /* Pull audio from buffer */
1440 int32_t availableBytes;
1441 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1443 /* check if we have enough data */
1444 if (!availableBytes || p_sys->b_paused) {
1445 /* return an empty buffer so silence is played until we have data */
1446 memset(targetBuffer, 0, bytesRequested);
1448 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1449 assert(bytesToCopy > 0);
1451 memcpy(targetBuffer, buffer, bytesToCopy);
1452 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1453 ioData->mBuffers[0].mDataByteSize = bytesToCopy;
1456 vlc_cond_signal(&p_sys->cond);
1457 vlc_mutex_unlock(&p_sys->lock);
1463 * RenderCallbackSPDIF: callback for SPDIF audio output
1465 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1466 const AudioTimeStamp * inNow,
1467 const void * inInputData,
1468 const AudioTimeStamp * inInputTime,
1469 AudioBufferList * outOutputData,
1470 const AudioTimeStamp * inOutputTime,
1471 void * threadGlobals)
1474 VLC_UNUSED(inDevice);
1475 VLC_UNUSED(inInputData);
1476 VLC_UNUSED(inInputTime);
1477 VLC_UNUSED(inOutputTime);
1479 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1480 struct aout_sys_t * p_sys = p_aout->sys;
1482 int bytesRequested = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1483 char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1485 vlc_mutex_lock(&p_sys->lock);
1486 /* Pull audio from buffer */
1487 int32_t availableBytes;
1488 char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1490 /* check if we have enough data */
1491 if (!availableBytes || p_sys->b_paused) {
1492 /* return an empty buffer so silence is played until we have data */
1493 memset(targetBuffer, 0, bytesRequested);
1495 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1496 assert(bytesToCopy > 0);
1498 memcpy(targetBuffer, buffer, bytesToCopy);
1499 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1500 outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize = bytesToCopy;
1503 vlc_cond_signal(&p_sys->cond);
1504 vlc_mutex_unlock(&p_sys->lock);
1510 #pragma mark Stream / Hardware Listeners
1513 * Callback when device list changed
1515 static OSStatus DevicesListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1517 VLC_UNUSED(inObjectID);
1518 VLC_UNUSED(inNumberAddresses);
1519 VLC_UNUSED(inAddresses);
1521 audio_output_t *p_aout = (audio_output_t *)inClientData;
1524 aout_sys_t *p_sys = p_aout->sys;
1526 msg_Dbg(p_aout, "audio device configuration changed, resetting cache");
1527 RebuildDeviceList(p_aout);
1529 vlc_mutex_lock(&p_sys->var_lock);
1530 if(!CFArrayContainsValue(p_sys->device_list, CFRangeMake(0, CFArrayGetCount(p_sys->device_list)),CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &p_sys->i_selected_dev)))
1531 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1532 vlc_mutex_unlock(&p_sys->var_lock);
1538 * Callback when current device is not alive anymore
1540 static OSStatus DeviceAliveListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1542 VLC_UNUSED(inObjectID);
1543 VLC_UNUSED(inNumberAddresses);
1544 VLC_UNUSED(inAddresses);
1546 audio_output_t *p_aout = (audio_output_t *)inClientData;
1550 msg_Warn(p_aout, "audio device died, resetting aout");
1551 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1557 * Callback when default audio device changed
1559 static OSStatus DefaultDeviceChangedListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1561 VLC_UNUSED(inObjectID);
1562 VLC_UNUSED(inNumberAddresses);
1563 VLC_UNUSED(inAddresses);
1565 audio_output_t *p_aout = (audio_output_t *)inClientData;
1569 if (!p_aout->sys->b_selected_dev_is_default)
1572 AudioObjectID defaultDeviceID = 0;
1573 UInt32 propertySize = sizeof(AudioObjectID);
1574 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1575 propertySize = sizeof(AudioObjectID);
1576 OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1578 msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
1582 msg_Dbg(p_aout, "default device changed to %i", defaultDeviceID);
1584 /* Default device is changed by the os to allow other apps to play sound while in digital
1585 mode. But this should not affect ourself. */
1586 if (p_aout->sys->b_digital) {
1587 msg_Dbg(p_aout, "ignore, as digital mode is active");
1591 /* Also ignore events which announce the same device id */
1592 if(defaultDeviceID == p_aout->sys->i_selected_dev)
1595 msg_Dbg(p_aout, "default device actually changed, resetting aout");
1596 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1602 * Callback when physical formats for device change
1604 static OSStatus StreamsChangedListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1606 OSStatus err = noErr;
1607 UInt32 i_param_size = 0;
1608 AudioStreamID *p_streams = NULL;
1611 VLC_UNUSED(inNumberAddresses);
1612 VLC_UNUSED(inAddresses);
1614 audio_output_t *p_aout = (audio_output_t *)inClientData;
1618 aout_sys_t *p_sys = p_aout->sys;
1619 if(unlikely(p_sys->b_ignore_streams_changed_callback == true))
1622 msg_Dbg(p_aout, "available physical formats for audio device changed");
1623 RebuildDeviceList(p_aout);
1626 * check if changed stream id belongs to current device
1628 vlc_mutex_lock(&p_sys->var_lock);
1629 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1630 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
1632 msg_Err(p_aout, "could not get number of streams [%4.4s]", (char *)&err);
1633 return VLC_EGENERIC;
1636 i_streams = i_param_size / sizeof(AudioStreamID);
1637 p_streams = (AudioStreamID *)malloc(i_param_size);
1638 if (p_streams == NULL)
1641 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1643 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1644 return VLC_EGENERIC;
1646 vlc_mutex_unlock(&p_sys->var_lock);
1648 for (int i = 0; i < i_streams; i++) {
1649 if (p_streams[i] == inObjectID) {
1650 msg_Dbg(p_aout, "Restart aout as this affects current device");
1651 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1661 * StreamListener: check whether the device's physical format change is complete
1663 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1665 OSStatus err = noErr;
1666 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1668 VLC_UNUSED(inObjectID);
1670 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1671 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1672 vlc_mutex_lock(&w->lock);
1673 vlc_cond_signal(&w->cond);
1674 vlc_mutex_unlock(&w->lock);
1682 #pragma mark helpers
1684 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register)
1686 OSStatus err = noErr;
1687 UInt32 i_param_size = 0;
1688 AudioStreamID *p_streams = NULL;
1691 /* Retrieve all the output streams */
1692 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1693 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1695 msg_Err(p_aout, "could not get number of streams for device id %i [%4.4s]", i_dev_id, (char *)&err);
1696 return VLC_EGENERIC;
1699 i_streams = i_param_size / sizeof(AudioStreamID);
1700 p_streams = (AudioStreamID *)malloc(i_param_size);
1701 if (p_streams == NULL)
1704 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1706 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1707 return VLC_EGENERIC;
1710 for (int i = 0; i < i_streams; i++) {
1711 /* get notified when physical formats change */
1712 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1715 err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1717 // nope just means that we already have a callback
1718 if (err == kAudioHardwareIllegalOperationError) {
1719 msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i, callback already set? [%4.4s]", p_streams[i],
1722 msg_Err(p_aout, "could not set audio stream formats property callback on stream id %i [%4.4s]", p_streams[i],
1727 } else { /* unregister callback */
1728 err = AudioObjectRemovePropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1730 msg_Err(p_aout, "failed to remove audio device property streams callback [%4.4s]", (char *)&err);
1740 * AudioDeviceHasOutput: Checks if the device is actually an output device
1742 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1744 UInt32 dataSize = 0;
1747 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1748 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1750 if (dataSize == 0 || status != noErr)
1757 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1759 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1761 OSStatus err = noErr;
1762 UInt32 i_param_size = 0;
1763 AudioStreamID *p_streams = NULL;
1765 bool b_return = false;
1767 /* Retrieve all the output streams */
1768 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1769 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1771 msg_Err(p_aout, "could not get number of streams [%4.4s] (%i)", (char *)&err, (int32_t)err);
1775 i_streams = i_param_size / sizeof(AudioStreamID);
1776 p_streams = (AudioStreamID *)malloc(i_param_size);
1777 if (p_streams == NULL)
1780 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1782 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1786 for (int i = 0; i < i_streams; i++) {
1787 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1796 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1798 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1800 OSStatus err = noErr;
1801 UInt32 i_param_size = 0;
1802 AudioStreamRangedDescription *p_format_list = NULL;
1804 bool b_return = false;
1806 /* Retrieve all the stream formats supported by each output stream */
1807 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1808 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1810 msg_Err(p_aout, "could not get number of streamformats [%4.4s] (%i)", (char *)&err, (int32_t)err);
1814 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1815 msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1817 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1818 if (p_format_list == NULL)
1821 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1823 msg_Err(p_aout, "could not get the list of streamformats [%4.4s]", (char *)&err);
1824 free(p_format_list);
1825 p_format_list = NULL;
1829 for (int i = 0; i < i_formats; i++) {
1831 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1834 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1835 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1836 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1837 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1841 free(p_format_list);
1846 * AudioStreamChangeFormat: switch stream format based on the provided description
1848 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1850 OSStatus err = noErr;
1851 UInt32 i_param_size = 0;
1853 int retValue = true;
1855 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1857 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1859 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1861 /* Condition because SetProperty is asynchronious */
1862 vlc_cond_init(&w.cond);
1863 vlc_mutex_init(&w.lock);
1864 vlc_mutex_lock(&w.lock);
1866 /* Install the callback */
1867 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1869 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed [%4.4s]", (char *)&err);
1874 /* change the format */
1875 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1878 msg_Err(p_aout, "could not set the stream format [%4.4s]", (char *)&err);
1883 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1884 * it is also not atomic in its behaviour.
1885 * Therefore we check 5 times before we really give up.
1886 * FIXME: failing isn't actually implemented yet. */
1887 for (int i = 0; i < 5; i++) {
1888 AudioStreamBasicDescription actual_format;
1889 mtime_t timeout = mdate() + 500000;
1891 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1892 msg_Dbg(p_aout, "reached timeout");
1894 i_param_size = sizeof(AudioStreamBasicDescription);
1895 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1897 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1898 if (actual_format.mSampleRate == change_format.mSampleRate &&
1899 actual_format.mFormatID == change_format.mFormatID &&
1900 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1901 /* The right format is now active */
1904 /* We need to check again */
1908 /* Removing the property listener */
1909 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1911 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed [%4.4s]", (char *)&err);
1915 /* Destroy the lock and condition */
1916 vlc_mutex_unlock(&w.lock);
1917 vlc_mutex_destroy(&w.lock);
1918 vlc_cond_destroy(&w.cond);