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 */
107 bool b_got_first_sample; /* did the aout core provide something to render? */
109 int i_rate; /* media sample rate */
110 int i_bytes_per_sample;
112 CFArrayRef device_list;
114 vlc_mutex_t var_lock; /* protects access to device_list and i_selected_dev */
122 bool b_ignore_streams_changed_callback;
126 #pragma mark local prototypes & module descriptor
128 static int Open (vlc_object_t *);
129 static void Close (vlc_object_t *);
130 static int Start (audio_output_t *, audio_sample_format_t *);
131 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
132 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
133 static void Stop (audio_output_t *);
135 static void RebuildDeviceList (audio_output_t *);
136 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
137 static int VolumeSet (audio_output_t *, float);
138 static int MuteSet (audio_output_t *, bool);
140 static void Play (audio_output_t *, block_t *);
141 static void Pause (audio_output_t *, bool, mtime_t);
142 static void Flush (audio_output_t *, bool);
143 static int TimeGet (audio_output_t *, mtime_t *);
144 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
145 UInt32 , UInt32, AudioBufferList *);
147 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
148 AudioBufferList *, const AudioTimeStamp *, void *);
150 static OSStatus DevicesListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
151 static OSStatus DeviceAliveListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
152 static OSStatus DefaultDeviceChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
153 static OSStatus StreamsChangedListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
155 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
157 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register);
158 static int AudioDeviceHasOutput (AudioDeviceID);
159 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
160 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
161 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
165 set_shortname("auhal")
166 set_description(N_("HAL AudioUnit output"))
167 set_capability("audio output", 101)
168 set_category(CAT_AUDIO)
169 set_subcategory(SUBCAT_AUDIO_AOUT)
170 set_callbacks(Open, Close)
171 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
172 VOLUME_TEXT, VOLUME_LONGTEXT, true)
173 change_integer_range(0, AOUT_VOLUME_MAX)
174 add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
175 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
179 #pragma mark initialization
181 static int Open(vlc_object_t *obj)
183 audio_output_t *p_aout = (audio_output_t *)obj;
184 aout_sys_t *p_sys = malloc(sizeof (*p_sys));
185 if (unlikely(p_sys == NULL))
188 OSStatus err = noErr;
190 vlc_mutex_init(&p_sys->var_lock);
191 vlc_mutex_init(&p_sys->lock);
192 vlc_cond_init(&p_sys->cond);
193 p_sys->b_digital = false;
194 p_sys->b_ignore_streams_changed_callback = false;
195 p_sys->b_selected_dev_is_default = false;
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);
205 /* Attach a listener so that we are notified of a change in the device setup */
206 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
207 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
209 msg_Err(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
211 /* Attach a listener to be notified about changes in default audio device */
212 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
213 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
215 msg_Err(p_aout, "failed to add listener for default audio device [%4.4s]", (char *)&err);
217 RebuildDeviceList(p_aout);
219 /* remember the volume */
220 p_sys->f_volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
221 aout_VolumeReport(p_aout, p_sys->f_volume);
222 p_sys->b_mute = var_InheritBool(p_aout, "mute");
223 aout_MuteReport(p_aout, p_sys->b_mute);
225 char *psz_audio_device = config_GetPsz(p_aout, "auhal-audio-device");
226 SwitchAudioDevice(p_aout, psz_audio_device);
227 free(psz_audio_device);
232 static void Close(vlc_object_t *obj)
234 audio_output_t *p_aout = (audio_output_t *)obj;
235 aout_sys_t *p_sys = p_aout->sys;
237 OSStatus err = noErr;
239 /* remove audio devices callback */
240 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
241 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, DevicesListener, (void *)p_aout);
243 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed [%4.4s]", (char *)&err);
245 /* remove listener to be notified about changes in default audio device */
246 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
247 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &defaultDeviceAddress, DefaultDeviceChangedListener, (void *)p_aout);
249 msg_Err(p_aout, "failed to remove listener for default audio device [%4.4s]", (char *)&err);
251 vlc_mutex_lock(&p_sys->var_lock);
252 /* remove streams callbacks */
253 CFIndex count = CFArrayGetCount(p_sys->device_list);
255 for (CFIndex x = 0; x < count; x++) {
256 AudioDeviceID deviceId = 0;
257 CFNumberRef cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
261 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &deviceId);
262 if (!(deviceId & AOUT_VAR_SPDIF_FLAG)) {
263 ManageAudioStreamsCallback(p_aout, deviceId, false);
268 CFRelease(p_sys->device_list);
269 vlc_mutex_unlock(&p_sys->var_lock);
271 char *psz_device = aout_DeviceGet(p_aout);
272 config_PutPsz(p_aout, "auhal-audio-device", psz_device);
275 vlc_mutex_destroy(&p_sys->var_lock);
276 vlc_mutex_destroy(&p_sys->lock);
277 vlc_cond_destroy(&p_sys->cond);
282 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
284 OSStatus err = noErr;
285 UInt32 i_param_size = 0;
286 struct aout_sys_t *p_sys = NULL;
288 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
292 bool b_start_digital = false;
295 p_sys->b_digital = false;
296 p_sys->au_component = NULL;
297 p_sys->au_unit = NULL;
298 p_sys->i_hog_pid = -1;
299 p_sys->i_stream_id = 0;
300 p_sys->i_stream_index = -1;
301 p_sys->b_revert = false;
302 p_sys->b_changed_mixing = false;
303 p_sys->i_bytes_per_sample = 0;
305 vlc_mutex_lock(&p_sys->var_lock);
306 p_sys->i_selected_dev = p_sys->i_new_selected_dev;
308 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
310 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
312 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
313 if (p_sys->i_selected_dev > 0) {
314 /* Check if the desired device is alive and usable */
315 i_param_size = sizeof(b_alive);
316 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
318 /* Be tolerant, only give a warning here */
319 msg_Warn(p_aout, "could not check whether device [0x%x] is alive [%4.4s]",
320 (unsigned int)p_sys->i_selected_dev, (char *)&err);
325 msg_Warn(p_aout, "selected audio device is not alive, switching to default device");
328 p_sys->b_selected_dev_is_default = false;
329 if (!b_alive || p_sys->i_selected_dev == 0) {
330 p_sys->b_selected_dev_is_default = true;
332 AudioObjectID defaultDeviceID = 0;
333 UInt32 propertySize = sizeof(AudioObjectID);
334 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
335 propertySize = sizeof(AudioObjectID);
336 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
338 msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
339 vlc_mutex_unlock(&p_sys->var_lock);
343 msg_Dbg(p_aout, "using default audio device %i", defaultDeviceID);
345 p_sys->i_selected_dev = defaultDeviceID;
346 p_sys->b_selected_dev_is_digital = var_InheritBool(p_aout, "spdif");
348 vlc_mutex_unlock(&p_sys->var_lock);
350 // recheck if device still supports digital
351 b_start_digital = p_sys->b_selected_dev_is_digital;
352 if(!AudioDeviceSupportsDigital(p_aout, p_sys->i_selected_dev))
353 b_start_digital = false;
356 msg_Dbg(p_aout, "Using audio device for digital output");
358 msg_Dbg(p_aout, "Audio device supports PCM mode only");
360 /* add a callback to see if the device dies later on */
361 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, DeviceAliveListener, (void *)p_aout);
363 /* Be tolerant, only give a warning here */
364 msg_Warn(p_aout, "could not set alive check callback on device [0x%x] [%4.4s]",
365 (unsigned int)p_sys->i_selected_dev, (char *)&err);
368 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
369 kAudioDevicePropertyScopeOutput,
370 kAudioObjectPropertyElementMaster };
371 i_param_size = sizeof(p_sys->i_hog_pid);
372 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
374 /* This is not a fatal error. Some drivers simply don't support this property */
375 msg_Warn(p_aout, "could not check whether device is hogged [%4.4s]",
377 p_sys->i_hog_pid = -1;
380 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
381 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
382 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
383 _("The selected audio output device is exclusively in "
384 "use by another program."));
388 bool b_success = false;
390 /* Check for Digital mode or Analog output mode */
391 if (AOUT_FMT_SPDIF (fmt) && b_start_digital) {
392 if (StartSPDIF (p_aout, fmt)) {
393 msg_Dbg(p_aout, "digital output successfully opened");
397 if (StartAnalog(p_aout, fmt)) {
398 msg_Dbg(p_aout, "analog output successfully opened");
405 p_aout->flush = Flush;
406 p_aout->time_get = TimeGet;
407 p_aout->pause = Pause;
412 /* If we reach this, this aout has failed */
413 msg_Err(p_aout, "opening auhal output failed");
418 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
420 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
422 struct aout_sys_t *p_sys = p_aout->sys;
423 OSStatus err = noErr;
424 UInt32 i_param_size = 0;
426 AudioComponentDescription desc;
427 AudioStreamBasicDescription DeviceFormat;
428 AudioChannelLayout *layout;
429 AudioChannelLayout new_layout;
430 AURenderCallbackStruct input;
431 p_aout->sys->chans_to_reorder = 0;
433 SInt32 currentMinorSystemVersion;
434 if(Gestalt(gestaltSystemVersionMinor, ¤tMinorSystemVersion) != noErr)
435 msg_Err(p_aout, "failed to check OSX version");
437 /* Lets go find our Component */
438 desc.componentType = kAudioUnitType_Output;
439 desc.componentSubType = kAudioUnitSubType_HALOutput;
440 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
441 desc.componentFlags = 0;
442 desc.componentFlagsMask = 0;
444 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
445 if (p_sys->au_component == NULL) {
446 msg_Err(p_aout, "cannot find any HAL component, PCM output failed");
450 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
452 msg_Err(p_aout, "cannot open HAL component, PCM output failed [%4.4s]", (char *)&err);
456 /* Set the device we will use for this output unit */
457 err = AudioUnitSetProperty(p_sys->au_unit,
458 kAudioOutputUnitProperty_CurrentDevice,
459 kAudioUnitScope_Global,
461 &p_sys->i_selected_dev,
462 sizeof(AudioObjectID));
465 msg_Err(p_aout, "cannot select audio output device, PCM output failed [%4.4s]", (char *)&err);
469 /* Get the current format */
470 i_param_size = sizeof(AudioStreamBasicDescription);
472 err = AudioUnitGetProperty(p_sys->au_unit,
473 kAudioUnitProperty_StreamFormat,
474 kAudioUnitScope_Output,
480 msg_Err(p_aout, "failed to detect supported stream formats [%4.4s]", (char *)&err);
483 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
485 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
486 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
487 kAudioDevicePropertyPreferredChannelLayout,
488 kAudioUnitScope_Output,
494 layout = (AudioChannelLayout *)malloc(i_param_size);
496 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
497 kAudioDevicePropertyPreferredChannelLayout,
498 kAudioUnitScope_Output,
503 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
504 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
505 /* bitmap defined channellayout */
506 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
507 sizeof(UInt32), &layout->mChannelBitmap,
510 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
512 /* layouttags defined channellayout */
513 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
514 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
519 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
521 if (layout->mNumberChannelDescriptions == 0) {
522 msg_Err(p_aout, "insufficient number of output channels");
526 /* Initialize the VLC core channel count */
527 fmt->i_physical_channels = 0;
528 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
530 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
531 /* We only need Mono or cannot output more than 1 channel */
532 fmt->i_physical_channels = AOUT_CHAN_CENTER;
533 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
534 /* We only need Stereo or cannot output more than 2 channels */
535 fmt->i_physical_channels = AOUT_CHANS_STEREO;
537 /* We want more than stereo and we can do that */
538 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
540 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
543 switch(layout->mChannelDescriptions[i].mChannelLabel) {
544 case kAudioChannelLabel_Left:
545 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
547 case kAudioChannelLabel_Right:
548 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
550 case kAudioChannelLabel_Center:
551 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
553 case kAudioChannelLabel_LFEScreen:
554 fmt->i_physical_channels |= AOUT_CHAN_LFE;
556 case kAudioChannelLabel_LeftSurround:
557 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
559 case kAudioChannelLabel_RightSurround:
560 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
562 case kAudioChannelLabel_RearSurroundLeft:
563 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
565 case kAudioChannelLabel_RearSurroundRight:
566 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
568 case kAudioChannelLabel_CenterSurround:
569 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
572 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
575 if (fmt->i_physical_channels == 0) {
576 fmt->i_physical_channels = AOUT_CHANS_STEREO;
577 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup in /Applications/Utilities. VLC will output Stereo only.");
578 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
579 _("You should configure your speaker layout with "
580 "\"Audio Midi Setup\" in /Applications/"
581 "Utilities. VLC will output Stereo only."));
586 msg_Warn(p_aout, "device driver does not support kAudioDevicePropertyPreferredChannelLayout - using stereo fallback [%4.4s]", (char *)&err);
587 fmt->i_physical_channels = AOUT_CHANS_STEREO;
590 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
591 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
593 memset (&new_layout, 0, sizeof(new_layout));
594 uint32_t chans_out[AOUT_CHAN_MAX];
595 memset(&chans_out, 0, sizeof(chans_out));
597 /* Some channel abbreviations used below:
602 * Rs - right surround
603 * Cs - center surround
604 * Rls - rear left surround
605 * Rrs - rear right surround
608 * Lsd - left surround direct
609 * Rsd - right surround direct
613 * Vhl - vertical height left
614 * Vhc - vertical height center
615 * Vhr - vertical height right
616 * Lt - left matrix total. for matrix encoded stereo.
617 * Rt - right matrix total. for matrix encoded stereo. */
619 switch(aout_FormatNbChannels(fmt)) {
621 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
624 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
627 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
628 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
629 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
630 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
633 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
634 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
635 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
636 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
637 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
638 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
641 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
642 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
643 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
644 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
647 if (fmt->i_physical_channels & (AOUT_CHAN_LFE)) {
648 /* note: for some reason, kAudioChannelLayoutTag_DVD_20, which would not require channel reordering,
649 does not work anymore */
650 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_5_1; // L R C LFE Ls Rs
652 chans_out[0] = AOUT_CHAN_LEFT;
653 chans_out[1] = AOUT_CHAN_RIGHT;
654 chans_out[2] = AOUT_CHAN_CENTER;
655 chans_out[3] = AOUT_CHAN_LFE;
656 chans_out[4] = AOUT_CHAN_REARLEFT;
657 chans_out[5] = AOUT_CHAN_REARRIGHT;
659 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
660 if (p_aout->sys->chans_to_reorder)
661 msg_Dbg(p_aout, "channel reordering needed for 5.1 output");
663 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
665 chans_out[0] = AOUT_CHAN_LEFT;
666 chans_out[1] = AOUT_CHAN_RIGHT;
667 chans_out[2] = AOUT_CHAN_REARLEFT;
668 chans_out[3] = AOUT_CHAN_REARRIGHT;
669 chans_out[4] = AOUT_CHAN_CENTER;
670 chans_out[5] = AOUT_CHAN_REARCENTER;
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 6.0 output");
678 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; // L R C LFE Ls Rs Cs
680 chans_out[0] = AOUT_CHAN_LEFT;
681 chans_out[1] = AOUT_CHAN_RIGHT;
682 chans_out[2] = AOUT_CHAN_CENTER;
683 chans_out[3] = AOUT_CHAN_LFE;
684 chans_out[4] = AOUT_CHAN_REARLEFT;
685 chans_out[5] = AOUT_CHAN_REARRIGHT;
686 chans_out[6] = AOUT_CHAN_REARCENTER;
688 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
689 if (p_aout->sys->chans_to_reorder)
690 msg_Dbg(p_aout, "channel reordering needed for 6.1 output");
694 if (fmt->i_physical_channels & (AOUT_CHAN_LFE) || currentMinorSystemVersion < 7) {
695 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; // L R C LFE Ls Rs Lc Rc
697 chans_out[0] = AOUT_CHAN_LEFT;
698 chans_out[1] = AOUT_CHAN_RIGHT;
699 chans_out[2] = AOUT_CHAN_CENTER;
700 chans_out[3] = AOUT_CHAN_LFE;
701 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
702 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
703 chans_out[6] = AOUT_CHAN_REARLEFT;
704 chans_out[7] = AOUT_CHAN_REARRIGHT;
706 if (!(fmt->i_physical_channels & (AOUT_CHAN_LFE)))
707 msg_Warn(p_aout, "8.0 audio output not supported on OS X 10.%i, layout will be incorrect", currentMinorSystemVersion);
709 #ifdef MAC_OS_X_VERSION_10_7
711 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_0_B; // Lc C Rc L R Ls Cs Rs
713 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
714 chans_out[1] = AOUT_CHAN_CENTER;
715 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
716 chans_out[3] = AOUT_CHAN_LEFT;
717 chans_out[4] = AOUT_CHAN_RIGHT;
718 chans_out[5] = AOUT_CHAN_REARLEFT;
719 chans_out[6] = AOUT_CHAN_REARCENTER;
720 chans_out[7] = AOUT_CHAN_REARRIGHT;
723 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
724 if (p_aout->sys->chans_to_reorder)
725 msg_Dbg(p_aout, "channel reordering needed for 7.1 / 8.0 output");
729 if (currentMinorSystemVersion < 7) {
730 msg_Warn(p_aout, "8.1 audio output not supported on OS X 10.%i", currentMinorSystemVersion);
734 #ifdef MAC_OS_X_VERSION_10_7
735 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DTS_8_1_B; // Lc C Rc L R Ls Cs Rs LFE
736 chans_out[0] = AOUT_CHAN_MIDDLELEFT;
737 chans_out[1] = AOUT_CHAN_CENTER;
738 chans_out[2] = AOUT_CHAN_MIDDLERIGHT;
739 chans_out[3] = AOUT_CHAN_LEFT;
740 chans_out[4] = AOUT_CHAN_RIGHT;
741 chans_out[5] = AOUT_CHAN_REARLEFT;
742 chans_out[6] = AOUT_CHAN_REARCENTER;
743 chans_out[7] = AOUT_CHAN_REARRIGHT;
744 chans_out[8] = AOUT_CHAN_LFE;
746 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
747 if (p_aout->sys->chans_to_reorder)
748 msg_Dbg(p_aout, "channel reordering needed for 8.1 output");
753 /* Set up the format to be used */
754 DeviceFormat.mSampleRate = fmt->i_rate;
755 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
756 p_sys->i_rate = fmt->i_rate;
758 /* We use float 32 since this is VLC's endorsed format */
759 fmt->i_format = VLC_CODEC_FL32;
760 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
761 DeviceFormat.mBitsPerChannel = 32;
762 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
764 /* Calculate framesizes and stuff */
765 DeviceFormat.mFramesPerPacket = 1;
766 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
767 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
769 /* Set the desired format */
770 i_param_size = sizeof(AudioStreamBasicDescription);
771 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
772 kAudioUnitProperty_StreamFormat,
773 kAudioUnitScope_Input,
778 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
780 /* Retrieve actual format */
781 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
782 kAudioUnitProperty_StreamFormat,
783 kAudioUnitScope_Input,
788 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
790 /* Do the last VLC aout setups */
791 aout_FormatPrepare(fmt);
793 /* set the IOproc callback */
794 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
795 input.inputProcRefCon = p_aout;
797 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
798 kAudioUnitProperty_SetRenderCallback,
799 kAudioUnitScope_Input,
800 0, &input, sizeof(input)));
802 /* Set the new_layout as the layout VLC will use to feed the AU unit */
803 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
804 kAudioUnitProperty_AudioChannelLayout,
805 kAudioUnitScope_Output,
806 0, &new_layout, sizeof(new_layout)));
808 if (new_layout.mNumberChannelDescriptions > 0)
809 free(new_layout.mChannelDescriptions);
812 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
814 /* setup circular buffer */
815 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
816 fmt->i_rate * fmt->i_bytes_per_frame);
818 p_sys->b_got_first_sample = false;
820 /* Set volume for output unit */
821 VolumeSet(p_aout, p_sys->f_volume);
822 MuteSet(p_aout, p_sys->b_mute);
828 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
830 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
832 struct aout_sys_t *p_sys = p_aout->sys;
833 OSStatus err = noErr;
834 UInt32 i_param_size = 0, b_mix = 0;
835 Boolean b_writeable = false;
836 AudioStreamID *p_streams = NULL;
837 unsigned i_streams = 0;
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 p_sys->i_stream_id = p_streams[i];
945 p_sys->i_stream_index = i;
947 if (!p_sys->b_revert) {
948 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
949 /* Retrieve the original format of this stream first if not done so already */
950 i_param_size = sizeof(p_sys->sfmt_revert);
951 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
953 msg_Err(p_aout, "could not retrieve the original streamformat [%4.4s]", (char *)&err);
956 p_sys->b_revert = true;
959 for (int j = 0; j < i_formats; j++) {
960 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
961 p_format_list[j].mFormat.mFormatID == 'iac3' ||
962 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
963 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
964 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
965 i_requested_rate_format = j;
967 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
968 i_current_rate_format = j;
970 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
971 i_backup_rate_format = j;
977 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
978 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
979 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
980 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
982 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) */
988 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
990 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format)) {
991 msg_Err(p_aout, "failed to change stream format for SPDIF output");
995 /* Set the format flags */
996 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
997 fmt->i_format = VLC_CODEC_SPDIFB;
999 fmt->i_format = VLC_CODEC_SPDIFL;
1000 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
1001 fmt->i_frame_length = A52_FRAME_NB;
1002 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
1003 p_sys->i_rate = fmt->i_rate;
1004 aout_FormatPrepare(fmt);
1006 /* Add IOProc callback */
1007 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
1008 (AudioDeviceIOProc)RenderCallbackSPDIF,
1012 msg_Err(p_aout, "Failed to create Process ID [%4.4s]", (char *)&err);
1017 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1019 msg_Err(p_aout, "Failed to start audio device [%4.4s]", (char *)&err);
1021 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
1023 msg_Err(p_aout, "Failed to destroy process ID [%4.4s]", (char *)&err);
1028 /* setup circular buffer */
1029 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
1034 static void Stop(audio_output_t *p_aout)
1036 struct aout_sys_t *p_sys = p_aout->sys;
1037 OSStatus err = noErr;
1038 UInt32 i_param_size = 0;
1040 if (p_sys->au_unit) {
1041 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
1042 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
1043 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
1046 if (p_sys->b_digital) {
1048 err = AudioDeviceStop(p_sys->i_selected_dev,
1051 msg_Err(p_aout, "Failed to stop audio device [%4.4s]", (char *)&err);
1053 /* Remove IOProc callback */
1054 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
1057 msg_Err(p_aout, "Failed to destroy Process ID [%4.4s]", (char *)&err);
1059 if (p_sys->b_revert)
1060 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
1062 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
1064 Boolean b_writeable = false;
1065 i_param_size = sizeof(int);
1066 /* Revert mixable to true if we are allowed to */
1067 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1068 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
1069 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
1071 if (err == noErr && b_writeable) {
1072 msg_Dbg(p_aout, "mixable is: %d", b_mix);
1074 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
1078 msg_Err(p_aout, "failed to re-set mixmode [%4.4s]", (char *)&err);
1082 if (p_sys->i_hog_pid == getpid()) {
1083 p_sys->i_hog_pid = -1;
1084 i_param_size = sizeof(p_sys->i_hog_pid);
1085 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
1086 kAudioDevicePropertyScopeOutput,
1087 kAudioObjectPropertyElementMaster };
1090 * HACK: On 10.6, auhal will trigger the streams changed callback when calling below line,
1091 * directly in the same thread. This call needs to be ignored to avoid endless restarting.
1093 p_sys->b_ignore_streams_changed_callback = true;
1094 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
1095 p_sys->b_ignore_streams_changed_callback = false;
1097 msg_Err(p_aout, "Failed to release hogmode [%4.4s]", (char *)&err);
1100 /* remove audio device alive callback */
1101 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1102 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, DeviceAliveListener, (void *)p_aout);
1104 /* Be tolerant, only give a warning here */
1105 msg_Warn(p_aout, "failed to remove audio device life checker [%4.4s]", (char *)&err);
1108 p_sys->i_bytes_per_sample = 0;
1109 p_sys->b_digital = false;
1111 /* clean-up circular buffer */
1112 TPCircularBufferCleanup(&p_sys->circular_buffer);
1116 #pragma mark core interaction
1118 static void ReportDevice(audio_output_t *p_aout, UInt32 i_id, char *name)
1121 sprintf(deviceid, "%i", i_id);
1123 aout_HotplugReport(p_aout, deviceid, name);
1126 static void RebuildDeviceList(audio_output_t * p_aout)
1128 OSStatus err = noErr;
1129 UInt32 propertySize = 0;
1130 AudioObjectID *deviceIDs;
1131 UInt32 numberOfDevices;
1132 CFMutableArrayRef currentListOfDevices;
1134 struct aout_sys_t *p_sys = p_aout->sys;
1136 ReportDevice(p_aout, 0, _("System Sound Output Device"));
1138 /* setup local array */
1139 currentListOfDevices = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
1141 /* Get number of devices */
1142 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1143 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1145 msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
1149 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1151 if (numberOfDevices < 1) {
1152 msg_Err(p_aout, "No audio output devices found.");
1155 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1157 /* Allocate DeviceID array */
1158 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1159 if (deviceIDs == NULL)
1162 /* Populate DeviceID array */
1163 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1165 msg_Err(p_aout, "could not get the device IDs [%4.4s]", (char *)&err);
1169 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1171 for (unsigned int i = 0; i < numberOfDevices; i++) {
1172 CFStringRef device_name_ref;
1175 bool b_digital = false;
1176 UInt32 i_id = deviceIDs[i];
1178 /* Retrieve the length of the device name */
1179 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1181 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1185 /* Retrieve the name of the device */
1186 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1188 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1191 length = CFStringGetLength(device_name_ref);
1193 psz_name = (char *)malloc(length);
1194 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1196 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1198 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1199 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1204 ReportDevice(p_aout, i_id, psz_name);
1205 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1207 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1209 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1210 char *psz_encoded_name = nil;
1211 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1212 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1213 ReportDevice(p_aout, i_id, psz_encoded_name);
1214 CFArrayAppendValue(currentListOfDevices, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i_id));
1215 free(psz_encoded_name);
1218 // TODO: only register once for each device
1219 ManageAudioStreamsCallback(p_aout, deviceIDs[i], true);
1221 CFRelease(device_name_ref);
1225 vlc_mutex_lock(&p_sys->var_lock);
1227 if (p_sys->device_list)
1228 count = CFArrayGetCount(p_sys->device_list);
1231 CFNumberRef cfn_device_id;
1232 int i_device_id = 0;
1233 for (CFIndex x = 0; x < count; x++) {
1234 if (!CFArrayContainsValue(currentListOfDevices, CFRangeMake(0, count), CFArrayGetValueAtIndex(p_sys->device_list, x))) {
1235 cfn_device_id = CFArrayGetValueAtIndex(p_sys->device_list, x);
1237 if (cfn_device_id) {
1238 CFNumberGetValue(cfn_device_id, kCFNumberSInt32Type, &i_device_id);
1239 ReportDevice(p_aout, i_device_id, NULL);
1244 CFRelease(p_sys->device_list);
1245 p_sys->device_list = CFArrayCreateCopy(kCFAllocatorDefault, currentListOfDevices);
1246 CFRelease(currentListOfDevices);
1247 vlc_mutex_unlock(&p_sys->var_lock);
1252 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1254 struct aout_sys_t *p_sys = p_aout->sys;
1257 p_sys->i_new_selected_dev = atoi(name);
1259 p_sys->i_new_selected_dev = 0;
1261 bool b_supports_digital = (p_sys->i_new_selected_dev & AOUT_VAR_SPDIF_FLAG);
1262 if (b_supports_digital)
1263 p_sys->b_selected_dev_is_digital = true;
1265 p_sys->b_selected_dev_is_digital = false;
1267 p_sys->i_new_selected_dev = p_sys->i_new_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1269 aout_DeviceReport(p_aout, name);
1270 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1275 static int VolumeSet(audio_output_t * p_aout, float volume)
1277 struct aout_sys_t *p_sys = p_aout->sys;
1280 if(p_sys->b_digital)
1281 return VLC_EGENERIC;
1283 p_sys->f_volume = volume;
1284 aout_VolumeReport(p_aout, volume);
1286 /* Set volume for output unit */
1287 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1288 kHALOutputParam_Volume,
1289 kAudioUnitScope_Global,
1291 volume * volume * volume,
1294 if (var_InheritBool(p_aout, "volume-save"))
1295 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1300 static int MuteSet(audio_output_t * p_aout, bool mute)
1302 struct aout_sys_t *p_sys = p_aout->sys;
1305 if(p_sys->b_digital)
1306 return VLC_EGENERIC;
1308 p_sys->b_mute = mute;
1309 aout_MuteReport(p_aout, mute);
1313 volume = p_sys->f_volume;
1315 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1316 kHALOutputParam_Volume,
1317 kAudioUnitScope_Global,
1319 volume * volume * volume,
1326 #pragma mark actual playback
1328 static void Play(audio_output_t * p_aout, block_t * p_block)
1330 struct aout_sys_t *p_sys = p_aout->sys;
1332 if (p_block->i_nb_samples > 0) {
1333 if (!p_sys->b_got_first_sample) {
1335 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1336 p_sys->b_got_first_sample = true;
1339 /* Do the channel reordering */
1340 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1341 aout_ChannelReorder(p_block->p_buffer,
1343 p_sys->chans_to_reorder,
1348 /* move data to buffer */
1349 if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1350 msg_Warn(p_aout, "dropped buffer");
1352 if (!p_sys->i_bytes_per_sample)
1353 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1356 block_Release(p_block);
1359 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1361 struct aout_sys_t * p_sys = p_aout->sys;
1364 if (p_aout->sys->b_digital) {
1366 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1368 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1371 AudioOutputUnitStop(p_sys->au_unit);
1373 AudioOutputUnitStart(p_sys->au_unit);
1377 static void Flush(audio_output_t *p_aout, bool wait)
1379 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);
1385 while (availableBytes > 0) {
1386 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1387 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1389 vlc_mutex_unlock(&p_sys->lock);
1392 p_sys->b_got_first_sample = false;
1394 /* flush circular buffer */
1395 AudioOutputUnitStop(p_aout->sys->au_unit);
1396 TPCircularBufferClear(&p_aout->sys->circular_buffer);
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) {
1445 /* return an empty buffer so silence is played until we have data */
1446 memset(targetBuffer, 0, ioData->mBuffers[0].mDataByteSize);
1448 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1450 memcpy(targetBuffer, buffer, bytesToCopy);
1451 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1452 ioData->mBuffers[0].mDataByteSize = bytesToCopy;
1455 vlc_cond_signal(&p_sys->cond);
1456 vlc_mutex_unlock(&p_sys->lock);
1462 * RenderCallbackSPDIF: callback for SPDIF audio output
1464 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1465 const AudioTimeStamp * inNow,
1466 const void * inInputData,
1467 const AudioTimeStamp * inInputTime,
1468 AudioBufferList * outOutputData,
1469 const AudioTimeStamp * inOutputTime,
1470 void * threadGlobals)
1473 VLC_UNUSED(inDevice);
1474 VLC_UNUSED(inInputData);
1475 VLC_UNUSED(inInputTime);
1476 VLC_UNUSED(inOutputTime);
1478 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1479 struct aout_sys_t * p_sys = p_aout->sys;
1481 int bytesRequested = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1482 char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1484 vlc_mutex_lock(&p_sys->lock);
1485 /* Pull audio from buffer */
1486 int32_t availableBytes;
1487 char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1489 /* check if we have enough data */
1490 if (!availableBytes) {
1491 /* return an empty buffer so silence is played until we have data */
1492 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1494 int32_t bytesToCopy = __MIN(bytesRequested, availableBytes);
1496 memcpy(targetBuffer, buffer, bytesToCopy);
1497 TPCircularBufferConsume(&p_sys->circular_buffer, bytesToCopy);
1498 outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize = bytesToCopy;
1501 vlc_cond_signal(&p_sys->cond);
1502 vlc_mutex_unlock(&p_sys->lock);
1508 #pragma mark Stream / Hardware Listeners
1511 * Callback when device list changed
1513 static OSStatus DevicesListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1515 VLC_UNUSED(inObjectID);
1516 VLC_UNUSED(inNumberAddresses);
1517 VLC_UNUSED(inAddresses);
1519 audio_output_t *p_aout = (audio_output_t *)inClientData;
1522 aout_sys_t *p_sys = p_aout->sys;
1524 msg_Dbg(p_aout, "audio device configuration changed, resetting cache");
1525 RebuildDeviceList(p_aout);
1527 vlc_mutex_lock(&p_sys->var_lock);
1528 if(!CFArrayContainsValue(p_sys->device_list, CFRangeMake(0, CFArrayGetCount(p_sys->device_list)),CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &p_sys->i_selected_dev)))
1529 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1530 vlc_mutex_unlock(&p_sys->var_lock);
1536 * Callback when current device is not alive anymore
1538 static OSStatus DeviceAliveListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1540 VLC_UNUSED(inObjectID);
1541 VLC_UNUSED(inNumberAddresses);
1542 VLC_UNUSED(inAddresses);
1544 audio_output_t *p_aout = (audio_output_t *)inClientData;
1548 msg_Warn(p_aout, "audio device died, resetting aout");
1549 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1555 * Callback when current device is not alive anymore
1557 static OSStatus DefaultDeviceChangedListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1559 VLC_UNUSED(inObjectID);
1560 VLC_UNUSED(inNumberAddresses);
1561 VLC_UNUSED(inAddresses);
1563 audio_output_t *p_aout = (audio_output_t *)inClientData;
1567 if (!p_aout->sys->b_selected_dev_is_default)
1570 AudioObjectID defaultDeviceID = 0;
1571 UInt32 propertySize = sizeof(AudioObjectID);
1572 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1573 propertySize = sizeof(AudioObjectID);
1574 OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1576 msg_Err(p_aout, "could not get default audio device [%4.4s]", (char *)&err);
1580 msg_Dbg(p_aout, "default device changed to %i", defaultDeviceID);
1583 * The default device id changes to 0 when switching to SPDIF for whatever reason.
1584 * We need to ignore that.
1586 if(defaultDeviceID == 0)
1589 /* Also ignore events which announce the same device id */
1590 if(defaultDeviceID == p_aout->sys->i_selected_dev)
1593 msg_Dbg(p_aout, "default device actually changed, resetting aout");
1594 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1601 * Callback when default audio device changed
1603 static OSStatus StreamsChangedListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1605 OSStatus err = noErr;
1606 UInt32 i_param_size = 0;
1607 AudioStreamID *p_streams = NULL;
1610 VLC_UNUSED(inNumberAddresses);
1611 VLC_UNUSED(inAddresses);
1613 audio_output_t *p_aout = (audio_output_t *)inClientData;
1617 aout_sys_t *p_sys = p_aout->sys;
1618 if(unlikely(p_sys->b_ignore_streams_changed_callback == true))
1621 msg_Dbg(p_aout, "available physical formats for audio device changed");
1622 RebuildDeviceList(p_aout);
1625 * check if changed stream id belongs to current device
1627 vlc_mutex_lock(&p_sys->var_lock);
1628 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1629 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
1631 msg_Err(p_aout, "could not get number of streams [%4.4s]", (char *)&err);
1632 return VLC_EGENERIC;
1635 i_streams = i_param_size / sizeof(AudioStreamID);
1636 p_streams = (AudioStreamID *)malloc(i_param_size);
1637 if (p_streams == NULL)
1640 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1642 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1643 return VLC_EGENERIC;
1645 vlc_mutex_unlock(&p_sys->var_lock);
1647 for (int i = 0; i < i_streams; i++) {
1648 if (p_streams[i] == inObjectID) {
1649 msg_Dbg(p_aout, "Restart aout as this affects current device");
1650 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1660 * StreamListener: check whether the device's physical format changes on-the-fly (unlikely)
1662 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void *inClientData)
1664 OSStatus err = noErr;
1665 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1667 VLC_UNUSED(inObjectID);
1669 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1670 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1671 vlc_mutex_lock(&w->lock);
1672 vlc_cond_signal(&w->cond);
1673 vlc_mutex_unlock(&w->lock);
1681 #pragma mark helpers
1683 static int ManageAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id, bool b_register)
1685 OSStatus err = noErr;
1686 UInt32 i_param_size = 0;
1687 AudioStreamID *p_streams = NULL;
1690 /* Retrieve all the output streams */
1691 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1692 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1694 msg_Err(p_aout, "could not get number of streams for device id %i [%4.4s]", i_dev_id, (char *)&err);
1695 return VLC_EGENERIC;
1698 i_streams = i_param_size / sizeof(AudioStreamID);
1699 p_streams = (AudioStreamID *)malloc(i_param_size);
1700 if (p_streams == NULL)
1703 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1705 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1706 return VLC_EGENERIC;
1709 for (int i = 0; i < i_streams; i++) {
1710 /* get notified when physical formats change */
1711 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1714 err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1716 // nope just means that we already have a callback
1717 if (err == kAudioHardwareIllegalOperationError) {
1718 msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i, callback already set? [%4.4s]", p_streams[i],
1721 msg_Err(p_aout, "could not set audio stream formats property callback on stream id %i [%4.4s]", p_streams[i],
1726 } else { /* unregister callback */
1727 err = AudioObjectRemovePropertyListener(p_streams[i], &physicalFormatsAddress, StreamsChangedListener, (void *)p_aout);
1729 msg_Err(p_aout, "failed to remove audio device property streams callback [%4.4s]", (char *)&err);
1739 * AudioDeviceHasOutput: Checks if the device is actually an output device
1741 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1743 UInt32 dataSize = 0;
1746 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1747 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1749 if (dataSize == 0 || status != noErr)
1756 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1758 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1760 OSStatus err = noErr;
1761 UInt32 i_param_size = 0;
1762 AudioStreamID *p_streams = NULL;
1764 bool b_return = false;
1766 /* Retrieve all the output streams */
1767 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1768 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1770 msg_Err(p_aout, "could not get number of streams [%4.4s] (%i)", (char *)&err, (int32_t)err);
1774 i_streams = i_param_size / sizeof(AudioStreamID);
1775 p_streams = (AudioStreamID *)malloc(i_param_size);
1776 if (p_streams == NULL)
1779 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1781 msg_Err(p_aout, "could not get list of streams [%4.4s]", (char *)&err);
1785 for (int i = 0; i < i_streams; i++) {
1786 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1795 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1797 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1799 OSStatus err = noErr;
1800 UInt32 i_param_size = 0;
1801 AudioStreamRangedDescription *p_format_list = NULL;
1803 bool b_return = false;
1805 /* Retrieve all the stream formats supported by each output stream */
1806 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1807 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1809 msg_Err(p_aout, "could not get number of streamformats [%4.4s] (%i)", (char *)&err, (int32_t)err);
1813 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1814 msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1816 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1817 if (p_format_list == NULL)
1820 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1822 msg_Err(p_aout, "could not get the list of streamformats [%4.4s]", (char *)&err);
1823 free(p_format_list);
1824 p_format_list = NULL;
1828 for (int i = 0; i < i_formats; i++) {
1830 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1833 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1834 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1835 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1836 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1840 free(p_format_list);
1845 * AudioStreamChangeFormat: switch stream format based on the provided description
1847 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1849 OSStatus err = noErr;
1850 UInt32 i_param_size = 0;
1852 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1854 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1856 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1858 /* Condition because SetProperty is asynchronious */
1859 vlc_cond_init(&w.cond);
1860 vlc_mutex_init(&w.lock);
1861 vlc_mutex_lock(&w.lock);
1863 /* Install the callback */
1864 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1866 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed [%4.4s]", (char *)&err);
1870 /* change the format */
1871 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1874 msg_Err(p_aout, "could not set the stream format [%4.4s]", (char *)&err);
1878 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1879 * it is also not atomic in its behaviour.
1880 * Therefore we check 5 times before we really give up.
1881 * FIXME: failing isn't actually implemented yet. */
1882 for (int i = 0; i < 5; i++) {
1883 AudioStreamBasicDescription actual_format;
1884 mtime_t timeout = mdate() + 500000;
1886 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1887 msg_Dbg(p_aout, "reached timeout");
1889 i_param_size = sizeof(AudioStreamBasicDescription);
1890 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1892 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1893 if (actual_format.mSampleRate == change_format.mSampleRate &&
1894 actual_format.mFormatID == change_format.mFormatID &&
1895 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1896 /* The right format is now active */
1899 /* We need to check again */
1902 /* Removing the property listener */
1903 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1905 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed [%4.4s]", (char *)&err);
1909 /* Destroy the lock and condition */
1910 vlc_mutex_unlock(&w.lock);
1911 vlc_mutex_destroy(&w.lock);
1912 vlc_cond_destroy(&w.cond);