1 /*****************************************************************************
2 * auhal.c: AUHAL and Coreaudio output plugin
3 *****************************************************************************
4 * Copyright (C) 2005 - 2013 VLC authors and VideoLAN
7 * Authors: Derk-Jan Hartman <hartman at videolan dot org>
8 * Felix Paul Kühne <fkuehne at videolan dot org>
9 * David Fuhrmann <david dot fuhrmann at googlemail dot com>
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation; either version 2.1 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this program; if not, write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 *****************************************************************************/
32 #import <vlc_common.h>
33 #import <vlc_plugin.h>
34 #import <vlc_dialog.h> // dialog_Fatal
35 #import <vlc_aout.h> // aout_*
37 #import <AudioUnit/AudioUnit.h> // AudioUnit
38 #import <CoreAudio/CoreAudio.h> // AudioDeviceID
39 #import <AudioToolbox/AudioFormat.h> // AudioFormatGetProperty
40 #import <CoreServices/CoreServices.h>
42 #import "TPCircularBuffer.h"
45 #pragma mark private declarations
48 # define verify_noerr(a) assert((a) == noErr)
51 #define STREAM_FORMAT_MSG(pre, sfm) \
52 pre "[%f][%4.4s][%u][%u][%u][%u][%u][%u]", \
53 sfm.mSampleRate, (char *)&sfm.mFormatID, \
54 (unsigned int)sfm.mFormatFlags, (unsigned int)sfm.mBytesPerPacket, \
55 (unsigned int)sfm.mFramesPerPacket, (unsigned int)sfm.mBytesPerFrame, \
56 (unsigned int)sfm.mChannelsPerFrame, (unsigned int)sfm.mBitsPerChannel
58 #define AOUT_VAR_SPDIF_FLAG 0xf00000
60 #define AUDIO_BUFFER_SIZE_IN_SECONDS (AOUT_MAX_ADVANCE_TIME / CLOCK_FREQ)
63 #define AOUT_VOLUME_DEFAULT 256
64 #define AOUT_VOLUME_MAX 512
66 #define VOLUME_TEXT N_("Audio volume")
67 #define VOLUME_LONGTEXT VOLUME_TEXT
69 #define DEVICE_TEXT N_("Last audio device")
70 #define DEVICE_LONGTEXT DEVICE_TEXT
72 /*****************************************************************************
73 * aout_sys_t: private audio output method descriptor
74 *****************************************************************************
75 * This structure is part of the audio output thread descriptor.
76 * It describes the CoreAudio specific properties of an output thread.
77 *****************************************************************************/
80 AudioObjectID i_default_dev; /* DeviceID of defaultOutputDevice */
81 AudioObjectID i_selected_dev; /* DeviceID of the selected device */
82 bool b_selected_dev_is_digital;
83 AudioDeviceIOProcID i_procID; /* DeviceID of current device */
84 bool b_digital; /* Are we running in digital mode? */
85 mtime_t clock_diff; /* Difference between VLC clock and Device clock */
87 uint8_t chans_to_reorder; /* do we need channel reordering */
88 uint8_t chan_table[AOUT_CHAN_MAX];
90 UInt32 i_numberOfChannels;
91 TPCircularBuffer circular_buffer; /* circular buffer to swap the audio data */
94 AudioComponent au_component; /* The AudioComponent we use */
95 AudioUnit au_unit; /* The AudioUnit we use */
97 /* CoreAudio SPDIF mode specific */
98 pid_t i_hog_pid; /* The keep the pid of our hog status */
99 AudioStreamID i_stream_id; /* The StreamID that has a cac3 streamformat */
100 int i_stream_index; /* The index of i_stream_id in an AudioBufferList */
101 AudioStreamBasicDescription stream_format; /* The format we changed the stream to */
102 AudioStreamBasicDescription sfmt_revert; /* The original format of the stream */
103 bool b_revert; /* Whether we need to revert the stream format */
104 bool b_changed_mixing; /* Whether we need to set the mixing mode back */
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 struct audio_device_t *devices;
118 struct audio_device_t
120 struct audio_device_t *next;
127 #pragma mark local prototypes & module descriptor
129 static int Open (vlc_object_t *);
130 static void Close (vlc_object_t *);
131 static int Start (audio_output_t *, audio_sample_format_t *);
132 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
133 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
134 static void Stop (audio_output_t *);
136 static int DeviceList (audio_output_t *p_aout, char ***namesp, char ***descsp);
137 static void RebuildDeviceList (audio_output_t *);
138 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
139 static int VolumeSet (audio_output_t *, float);
140 static int MuteSet (audio_output_t *, bool);
142 static void Play (audio_output_t *, block_t *);
143 static void Pause (audio_output_t *, bool, mtime_t);
144 static void Flush (audio_output_t *, bool);
145 static int TimeGet (audio_output_t *, mtime_t *);
146 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
147 UInt32 , UInt32, AudioBufferList *);
149 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
150 AudioBufferList *, const AudioTimeStamp *, void *);
152 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
153 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
155 static int RegisterAudioStreamsCallback(audio_output_t *, AudioDeviceID);
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->lock);
189 vlc_cond_init(&p_sys->cond);
192 p_aout->start = Start;
194 p_aout->volume_set = VolumeSet;
195 p_aout->mute_set = MuteSet;
196 p_aout->device_enum = DeviceList;
197 p_aout->sys->devices = NULL;
198 p_aout->device_select = SwitchAudioDevice;
200 /* Attach a Listener so that we are notified of a change in the Device setup */
201 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
202 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
204 msg_Warn(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
206 RebuildDeviceList(p_aout);
208 /* remember the volume */
209 aout_VolumeReport(p_aout, var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
210 MuteSet(p_aout, var_InheritBool(p_aout, "mute"));
212 SwitchAudioDevice(p_aout, config_GetPsz(p_aout, "auhal-audio-device"));
217 static void Close(vlc_object_t *obj)
219 audio_output_t *p_aout = (audio_output_t *)obj;
220 aout_sys_t *p_sys = p_aout->sys;
222 OSStatus err = noErr;
224 /* remove audio device callback */
225 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
226 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
228 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
230 /* remove audio streams callback */
231 if (p_sys->i_stream_id > 0) {
232 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
233 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
235 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
238 config_PutPsz(p_aout, "auhal-audio-device", aout_DeviceGet(p_aout));
240 for (struct audio_device_t * device = p_sys->devices, *next; device != NULL; device = next) {
246 vlc_mutex_destroy(&p_sys->lock);
247 vlc_cond_destroy(&p_sys->cond);
252 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
254 OSStatus err = noErr;
255 UInt32 i_param_size = 0;
256 struct aout_sys_t *p_sys = NULL;
258 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
262 bool b_start_digital = false;
265 p_sys->b_digital = false;
266 p_sys->au_component = NULL;
267 p_sys->au_unit = NULL;
268 p_sys->clock_diff = (mtime_t) 0;
269 p_sys->i_hog_pid = -1;
270 p_sys->i_stream_id = 0;
271 p_sys->i_stream_index = -1;
272 p_sys->b_revert = false;
273 p_sys->b_changed_mixing = false;
274 p_sys->i_bytes_per_sample = 0;
276 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
278 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
280 /* Check if the desired device is alive and usable */
281 i_param_size = sizeof(b_alive);
282 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
283 kAudioObjectPropertyScopeGlobal,
284 kAudioObjectPropertyElementMaster };
285 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
288 /* Be tolerant, only give a warning here */
289 msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
290 (unsigned int)p_sys->i_selected_dev, (char *)&err);
295 msg_Warn(p_aout, "selected audio device is not alive, switching to default device with id %i", p_sys->i_default_dev);
296 p_sys->i_selected_dev = p_sys->i_default_dev;
297 p_sys->b_selected_dev_is_digital = false;
300 // recheck if device still supports digital
301 b_start_digital = p_sys->b_selected_dev_is_digital;
302 if(!AudioDeviceSupportsDigital(p_aout, p_sys->i_selected_dev))
303 b_start_digital = false;
306 msg_Dbg(p_aout, "Use audio device for digital output");
308 /* add a callback to see if the device dies later on */
309 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
311 /* Be tolerant, only give a warning here */
312 msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
313 (unsigned int)p_sys->i_selected_dev, (char *)&err);
316 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
317 kAudioDevicePropertyScopeOutput,
318 kAudioObjectPropertyElementMaster };
319 i_param_size = sizeof(p_sys->i_hog_pid);
320 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
322 /* This is not a fatal error. Some drivers simply don't support this property */
323 msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
325 p_sys->i_hog_pid = -1;
328 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
329 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
330 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
331 _("The selected audio output device is exclusively in "
332 "use by another program."));
336 bool b_success = false;
338 /* Check for Digital mode or Analog output mode */
339 if (AOUT_FMT_SPDIF (fmt) && b_start_digital) {
340 if (StartSPDIF (p_aout, fmt)) {
341 msg_Dbg(p_aout, "digital output successfully opened");
345 if (StartAnalog(p_aout, fmt)) {
346 msg_Dbg(p_aout, "analog output successfully opened");
353 p_aout->flush = Flush;
354 p_aout->time_get = TimeGet;
355 p_aout->pause = Pause;
360 /* If we reach this, this aout has failed */
361 msg_Err(p_aout, "opening auhal output failed");
366 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
368 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
370 struct aout_sys_t *p_sys = p_aout->sys;
371 OSStatus err = noErr;
372 UInt32 i_param_size = 0;
374 AudioComponentDescription desc;
375 AudioStreamBasicDescription DeviceFormat;
376 AudioChannelLayout *layout;
377 AudioChannelLayout new_layout;
378 AURenderCallbackStruct input;
379 p_aout->sys->chans_to_reorder = 0;
381 /* Lets go find our Component */
382 desc.componentType = kAudioUnitType_Output;
383 desc.componentSubType = kAudioUnitSubType_HALOutput;
384 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
385 desc.componentFlags = 0;
386 desc.componentFlagsMask = 0;
388 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
389 if (p_sys->au_component == NULL) {
390 msg_Warn(p_aout, "we cannot find our HAL component");
394 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
396 msg_Warn(p_aout, "we cannot open our HAL component");
400 /* Set the device we will use for this output unit */
401 err = AudioUnitSetProperty(p_sys->au_unit,
402 kAudioOutputUnitProperty_CurrentDevice,
403 kAudioUnitScope_Global,
405 &p_sys->i_selected_dev,
406 sizeof(AudioObjectID));
409 msg_Warn(p_aout, "we cannot select the audio device");
413 /* Get the current format */
414 i_param_size = sizeof(AudioStreamBasicDescription);
416 err = AudioUnitGetProperty(p_sys->au_unit,
417 kAudioUnitProperty_StreamFormat,
418 kAudioUnitScope_Output,
426 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
428 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
429 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
430 kAudioDevicePropertyPreferredChannelLayout,
431 kAudioUnitScope_Output,
437 layout = (AudioChannelLayout *)malloc(i_param_size);
439 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
440 kAudioDevicePropertyPreferredChannelLayout,
441 kAudioUnitScope_Output,
446 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
447 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
448 /* bitmap defined channellayout */
449 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
450 sizeof(UInt32), &layout->mChannelBitmap,
453 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
455 /* layouttags defined channellayout */
456 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
457 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
462 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
464 if (layout->mNumberChannelDescriptions == 0) {
465 msg_Err(p_aout, "insufficient number of output channels");
469 /* Initialize the VLC core channel count */
470 fmt->i_physical_channels = 0;
471 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
473 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
474 /* We only need Mono or cannot output more than 1 channel */
475 fmt->i_physical_channels = AOUT_CHAN_CENTER;
476 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
477 /* We only need Stereo or cannot output more than 2 channels */
478 fmt->i_physical_channels = AOUT_CHANS_STEREO;
480 /* We want more than stereo and we can do that */
481 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
483 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
486 switch(layout->mChannelDescriptions[i].mChannelLabel) {
487 case kAudioChannelLabel_Left:
488 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
490 case kAudioChannelLabel_Right:
491 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
493 case kAudioChannelLabel_Center:
494 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
496 case kAudioChannelLabel_LFEScreen:
497 fmt->i_physical_channels |= AOUT_CHAN_LFE;
499 case kAudioChannelLabel_LeftSurround:
500 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
502 case kAudioChannelLabel_RightSurround:
503 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
505 case kAudioChannelLabel_RearSurroundLeft:
506 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
508 case kAudioChannelLabel_RearSurroundRight:
509 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
511 case kAudioChannelLabel_CenterSurround:
512 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
515 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
518 if (fmt->i_physical_channels == 0) {
519 fmt->i_physical_channels = AOUT_CHANS_STEREO;
520 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
521 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
522 _("You should configure your speaker layout with "
523 "the \"Audio Midi Setup\" utility in /Applications/"
524 "Utilities. Stereo mode is being used now."));
529 msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
530 fmt->i_physical_channels = AOUT_CHANS_STEREO;
533 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
534 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
535 p_sys->i_numberOfChannels = aout_FormatNbChannels(fmt);
537 memset (&new_layout, 0, sizeof(new_layout));
538 uint32_t chans_out[AOUT_CHAN_MAX];
540 switch(aout_FormatNbChannels(fmt)) {
542 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
545 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
548 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
549 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
550 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
551 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
554 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
555 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
556 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
557 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
558 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
559 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
562 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
563 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
564 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
565 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
568 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
569 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
571 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
574 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
576 chans_out[0] = AOUT_CHAN_LEFT;
577 chans_out[1] = AOUT_CHAN_RIGHT;
578 chans_out[2] = AOUT_CHAN_CENTER;
579 chans_out[3] = AOUT_CHAN_LFE;
580 chans_out[4] = AOUT_CHAN_REARLEFT;
581 chans_out[5] = AOUT_CHAN_REARRIGHT;
582 chans_out[6] = AOUT_CHAN_REARCENTER;
584 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
585 if (p_aout->sys->chans_to_reorder)
586 msg_Dbg(p_aout, "channel reordering needed");
590 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
592 chans_out[0] = AOUT_CHAN_LEFT;
593 chans_out[1] = AOUT_CHAN_RIGHT;
594 chans_out[2] = AOUT_CHAN_CENTER;
595 chans_out[3] = AOUT_CHAN_LFE;
596 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
597 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
598 chans_out[6] = AOUT_CHAN_REARLEFT;
599 chans_out[7] = AOUT_CHAN_REARRIGHT;
601 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
602 if (p_aout->sys->chans_to_reorder)
603 msg_Dbg(p_aout, "channel reordering needed");
608 /* Set up the format to be used */
609 DeviceFormat.mSampleRate = fmt->i_rate;
610 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
611 p_sys->i_rate = fmt->i_rate;
613 /* We use float 32 since this is VLC's endorsed format */
614 fmt->i_format = VLC_CODEC_FL32;
615 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
616 DeviceFormat.mBitsPerChannel = 32;
617 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
619 /* Calculate framesizes and stuff */
620 DeviceFormat.mFramesPerPacket = 1;
621 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
622 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
624 /* Set the desired format */
625 i_param_size = sizeof(AudioStreamBasicDescription);
626 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
627 kAudioUnitProperty_StreamFormat,
628 kAudioUnitScope_Input,
633 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
635 /* Retrieve actual format */
636 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
637 kAudioUnitProperty_StreamFormat,
638 kAudioUnitScope_Input,
643 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
645 /* Do the last VLC aout setups */
646 aout_FormatPrepare(fmt);
648 /* set the IOproc callback */
649 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
650 input.inputProcRefCon = p_aout;
652 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
653 kAudioUnitProperty_SetRenderCallback,
654 kAudioUnitScope_Input,
655 0, &input, sizeof(input)));
657 /* Set the new_layout as the layout VLC will use to feed the AU unit */
658 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
659 kAudioUnitProperty_AudioChannelLayout,
660 kAudioUnitScope_Output,
661 0, &new_layout, sizeof(new_layout)));
663 if (new_layout.mNumberChannelDescriptions > 0)
664 free(new_layout.mChannelDescriptions);
667 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
669 /* Find the difference between device clock and mdate clock */
670 p_sys->clock_diff = - (mtime_t)
671 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
672 p_sys->clock_diff += mdate();
674 /* setup circular buffer */
675 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
676 fmt->i_rate * fmt->i_bytes_per_frame);
678 p_sys->b_got_first_sample = false;
680 /* Set volume for output unit */
681 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
682 volume = volume * volume * volume;
683 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
684 kHALOutputParam_Volume,
685 kAudioUnitScope_Global,
694 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
696 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
698 struct aout_sys_t *p_sys = p_aout->sys;
699 OSStatus err = noErr;
700 UInt32 i_param_size = 0, b_mix = 0;
701 Boolean b_writeable = false;
702 AudioStreamID *p_streams = NULL;
703 unsigned i_streams = 0;
705 /* Start doing the SPDIF setup proces */
706 p_sys->b_digital = true;
709 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
710 i_param_size = sizeof(p_sys->i_hog_pid);
711 p_sys->i_hog_pid = getpid() ;
713 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
716 msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
720 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
722 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
723 /* Set mixable to false if we are allowed to */
724 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
725 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
726 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
728 if (err == noErr && b_writeable) {
730 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
731 p_sys->b_changed_mixing = true;
735 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
740 /* Get a list of all the streams on this device */
741 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
742 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
744 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
748 i_streams = i_param_size / sizeof(AudioStreamID);
749 p_streams = (AudioStreamID *)malloc(i_param_size);
750 if (p_streams == NULL)
753 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
756 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
761 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
762 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
763 /* Find a stream with a cac3 stream */
764 AudioStreamRangedDescription *p_format_list = NULL;
766 bool b_digital = false;
768 /* Retrieve all the stream formats supported by each output stream */
769 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
771 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
775 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
776 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
777 if (p_format_list == NULL)
780 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
782 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
787 /* Check if one of the supported formats is a digital format */
788 for (int j = 0; j < i_formats; j++) {
789 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
790 p_format_list[j].mFormat.mFormatID == 'iac3' ||
791 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
792 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
799 /* if this stream supports a digital (cac3) format, then go set it. */
800 int i_requested_rate_format = -1;
801 int i_current_rate_format = -1;
802 int i_backup_rate_format = -1;
804 p_sys->i_stream_id = p_streams[i];
805 p_sys->i_stream_index = i;
807 if (!p_sys->b_revert) {
808 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
809 /* Retrieve the original format of this stream first if not done so already */
810 i_param_size = sizeof(p_sys->sfmt_revert);
811 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
813 msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
816 p_sys->b_revert = true;
819 for (int j = 0; j < i_formats; j++) {
820 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
821 p_format_list[j].mFormat.mFormatID == 'iac3' ||
822 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
823 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
824 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
825 i_requested_rate_format = j;
827 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
828 i_current_rate_format = j;
830 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
831 i_backup_rate_format = j;
837 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
838 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
839 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
840 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
842 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) */
848 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
850 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
853 /* Set the format flags */
854 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
855 fmt->i_format = VLC_CODEC_SPDIFB;
857 fmt->i_format = VLC_CODEC_SPDIFL;
858 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
859 fmt->i_frame_length = A52_FRAME_NB;
860 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
861 p_sys->i_rate = fmt->i_rate;
862 aout_FormatPrepare(fmt);
864 /* Add IOProc callback */
865 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
866 (AudioDeviceIOProc)RenderCallbackSPDIF,
870 msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
874 /* Check for the difference between the Device clock and mdate */
875 p_sys->clock_diff = - (mtime_t)
876 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
877 p_sys->clock_diff += mdate();
880 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
882 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
884 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
886 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
891 /* setup circular buffer */
892 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
897 static void Stop(audio_output_t *p_aout)
899 struct aout_sys_t *p_sys = p_aout->sys;
900 OSStatus err = noErr;
901 UInt32 i_param_size = 0;
903 if (p_sys->au_unit) {
904 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
905 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
906 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
909 if (p_sys->b_digital) {
911 err = AudioDeviceStop(p_sys->i_selected_dev,
914 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
916 /* Remove IOProc callback */
917 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
920 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
923 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
925 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
927 Boolean b_writeable = false;
928 /* Revert mixable to true if we are allowed to */
929 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
930 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
931 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
933 if (err == noErr && b_writeable) {
934 msg_Dbg(p_aout, "mixable is: %d", b_mix);
936 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
940 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
944 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
945 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
948 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
950 if (p_sys->i_hog_pid == getpid()) {
951 p_sys->i_hog_pid = -1;
952 i_param_size = sizeof(p_sys->i_hog_pid);
953 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
954 kAudioDevicePropertyScopeOutput,
955 kAudioObjectPropertyElementMaster };
956 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
958 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
961 p_sys->i_bytes_per_sample = 0;
963 /* clean-up circular buffer */
964 TPCircularBufferCleanup(&p_sys->circular_buffer);
968 #pragma mark core interaction
970 static int DeviceList(audio_output_t *p_aout, char ***namesp, char ***descsp)
972 struct aout_sys_t *p_sys = p_aout->sys;
973 char **names, **descs;
976 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next)
979 *namesp = names = xmalloc(sizeof(*names) * n);
980 *descsp = descs = xmalloc(sizeof(*descs) * n);
983 for (struct audio_device_t *device = p_sys->devices; device != NULL; device = device->next) {
984 sprintf(deviceid, "%i", device->deviceid);
985 *(names++) = strdup(deviceid);
986 *(descs++) = strdup(device->name);
992 static void add_device_to_list(audio_output_t * p_aout, UInt32 i_id, char *name)
994 struct aout_sys_t *p_sys = p_aout->sys;
996 struct audio_device_t *device = malloc(sizeof(*device));
997 if (unlikely(device == NULL))
1000 device->next = p_sys->devices;
1001 device->deviceid = i_id;
1002 device->name = strdup(name);
1004 p_sys->devices = device;
1007 static void RebuildDeviceList(audio_output_t * p_aout)
1009 OSStatus err = noErr;
1010 UInt32 propertySize = 0;
1011 AudioObjectID defaultDeviceID = 0;
1012 AudioObjectID *deviceIDs;
1013 UInt32 numberOfDevices;
1015 struct aout_sys_t *p_sys = p_aout->sys;
1017 if (p_sys->devices) {
1018 for (struct audio_device_t * device = p_sys->devices, *next; device != NULL; device = next) {
1019 next = device->next;
1024 p_sys->devices = NULL;
1026 /* Get number of devices */
1027 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1028 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
1030 msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
1034 numberOfDevices = propertySize / sizeof(AudioDeviceID);
1036 if (numberOfDevices < 1) {
1037 msg_Err(p_aout, "No audio output devices were found.");
1040 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
1042 /* Allocate DeviceID array */
1043 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
1044 if (deviceIDs == NULL)
1047 /* Populate DeviceID array */
1048 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
1050 msg_Err(p_aout, "could not get the device IDs: [%4.4s]", (char *)&err);
1054 /* Find the ID of the default Device */
1055 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1056 propertySize = sizeof(AudioObjectID);
1057 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1059 msg_Err(p_aout, "could not get default audio device: [%4.4s]", (char *)&err);
1062 p_sys->i_default_dev = defaultDeviceID;
1064 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1066 for (unsigned int i = 0; i < numberOfDevices; i++) {
1067 CFStringRef device_name_ref;
1070 bool b_digital = false;
1071 UInt32 i_id = deviceIDs[i];
1073 /* Retrieve the length of the device name */
1074 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1076 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1080 /* Retrieve the name of the device */
1081 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1083 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1086 length = CFStringGetLength(device_name_ref);
1088 psz_name = (char *)malloc(length);
1089 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1091 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1093 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1094 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1099 add_device_to_list(p_aout, i_id, psz_name);
1101 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1103 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1104 char *psz_encoded_name = nil;
1105 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1106 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1107 add_device_to_list(p_aout, i_id, psz_encoded_name);
1108 free(psz_encoded_name);
1111 // TODO: only register once for each device
1112 RegisterAudioStreamsCallback(p_aout, deviceIDs[i]);
1114 CFRelease(device_name_ref);
1118 // TODO: fix default audio device
1119 add_device_to_list(p_aout, 0, _("System Sound Output Device"));
1124 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1126 struct aout_sys_t *p_sys = p_aout->sys;
1129 p_sys->i_selected_dev = atoi(name);
1131 p_sys->i_selected_dev = 0;
1133 bool b_supports_digital = (p_sys->i_selected_dev & AOUT_VAR_SPDIF_FLAG);
1134 if (b_supports_digital)
1135 p_sys->b_selected_dev_is_digital = true;
1137 p_sys->b_selected_dev_is_digital = false;
1139 p_sys->i_selected_dev = p_sys->i_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1141 aout_DeviceReport(p_aout, name);
1142 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1147 static int VolumeSet(audio_output_t * p_aout, float volume)
1149 struct aout_sys_t *p_sys = p_aout->sys;
1152 aout_VolumeReport(p_aout, volume);
1154 /* Set volume for output unit */
1155 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1156 kHALOutputParam_Volume,
1157 kAudioUnitScope_Global,
1159 volume * volume * volume,
1162 if (var_InheritBool(p_aout, "volume-save"))
1163 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1168 static int MuteSet(audio_output_t * p_aout, bool mute)
1170 struct aout_sys_t *p_sys = p_aout->sys;
1173 aout_MuteReport(p_aout, mute);
1178 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1180 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1181 kHALOutputParam_Volume,
1182 kAudioUnitScope_Global,
1184 volume * volume * volume,
1191 #pragma mark actual playback
1193 static void Play(audio_output_t * p_aout, block_t * p_block)
1195 struct aout_sys_t *p_sys = p_aout->sys;
1197 if (p_block->i_nb_samples > 0) {
1198 if (!p_sys->b_got_first_sample) {
1200 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1201 p_sys->b_got_first_sample = true;
1204 /* Do the channel reordering */
1205 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1206 aout_ChannelReorder(p_block->p_buffer,
1208 p_sys->chans_to_reorder,
1213 /* move data to buffer */
1214 if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1215 msg_Warn(p_aout, "dropped buffer");
1217 if (!p_sys->i_bytes_per_sample)
1218 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1221 block_Release(p_block);
1224 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1226 struct aout_sys_t * p_sys = p_aout->sys;
1229 if (p_aout->sys->b_digital) {
1231 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1233 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1236 AudioOutputUnitStop(p_sys->au_unit);
1238 AudioOutputUnitStart(p_sys->au_unit);
1242 static void Flush(audio_output_t *p_aout, bool wait)
1244 struct aout_sys_t *p_sys = p_aout->sys;
1247 int32_t availableBytes;
1248 vlc_mutex_lock(&p_sys->lock);
1249 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1250 while (availableBytes > 0) {
1251 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1252 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1254 vlc_mutex_unlock(&p_sys->lock);
1257 p_sys->b_got_first_sample = false;
1259 /* flush circular buffer */
1260 AudioOutputUnitStop(p_aout->sys->au_unit);
1261 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1265 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1267 struct aout_sys_t * p_sys = p_aout->sys;
1269 if (!p_sys->i_bytes_per_sample)
1272 int32_t availableBytes;
1273 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1275 *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1280 /*****************************************************************************
1281 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1282 * us to provide some more audio data.
1283 * Don't print anything during normal playback, calling blocking function from
1284 * this callback is not allowed.
1285 *****************************************************************************/
1286 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1287 AudioUnitRenderActionFlags *ioActionFlags,
1288 const AudioTimeStamp *inTimeStamp,
1290 UInt32 inNumberFrames,
1291 AudioBufferList *ioData) {
1292 VLC_UNUSED(ioActionFlags);
1293 VLC_UNUSED(inTimeStamp);
1294 VLC_UNUSED(inBusNumber);
1295 VLC_UNUSED(inNumberFrames);
1297 audio_output_t * p_aout = (audio_output_t *)p_obj;
1298 struct aout_sys_t * p_sys = p_aout->sys;
1300 int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1301 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1303 vlc_mutex_lock(&p_sys->lock);
1304 /* Pull audio from buffer */
1305 int32_t availableBytes;
1306 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1308 /* check if we have enough data */
1309 if (!availableBytes) {
1310 /* return an empty buffer so silence is played until we have data */
1311 for (UInt32 j = 0; j < inNumberFrames; j++)
1312 targetBuffer[j] = 0.;
1314 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1315 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1318 vlc_cond_signal(&p_sys->cond);
1319 vlc_mutex_unlock(&p_sys->lock);
1325 * RenderCallbackSPDIF: callback for SPDIF audio output
1327 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1328 const AudioTimeStamp * inNow,
1329 const void * inInputData,
1330 const AudioTimeStamp * inInputTime,
1331 AudioBufferList * outOutputData,
1332 const AudioTimeStamp * inOutputTime,
1333 void * threadGlobals)
1336 VLC_UNUSED(inDevice);
1337 VLC_UNUSED(inInputData);
1338 VLC_UNUSED(inInputTime);
1339 VLC_UNUSED(inOutputTime);
1341 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1342 struct aout_sys_t * p_sys = p_aout->sys;
1344 int bytesToCopy = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1345 char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1347 vlc_mutex_lock(&p_sys->lock);
1348 /* Pull audio from buffer */
1349 int32_t availableBytes;
1350 char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1352 /* check if we have enough data */
1353 if (!availableBytes) {
1354 /* return an empty buffer so silence is played until we have data */
1355 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1357 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1358 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1361 vlc_cond_signal(&p_sys->cond);
1362 vlc_mutex_unlock(&p_sys->lock);
1368 #pragma mark Stream / Hardware Listeners
1371 * HardwareListener: Warns us of changes in the list of registered devices
1373 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1375 OSStatus err = noErr;
1376 audio_output_t *p_aout = (audio_output_t *)inClientData;
1377 VLC_UNUSED(inObjectID);
1378 VLC_UNUSED(inNumberAddresses);
1379 VLC_UNUSED(inAddresses);
1385 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1386 switch (inAddresses[i].mSelector) {
1387 case kAudioHardwarePropertyDevices:
1388 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1391 case kAudioDevicePropertyDeviceIsAlive:
1392 msg_Warn(p_aout, "audio device died, resetting aout");
1395 case kAudioStreamPropertyAvailablePhysicalFormats:
1396 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1400 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1406 RebuildDeviceList(p_aout);
1407 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1413 * StreamListener: check whether the device's physical format changes on-the-fly (unlikely)
1415 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1417 OSStatus err = noErr;
1418 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1420 VLC_UNUSED(inObjectID);
1422 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1423 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1424 vlc_mutex_lock(&w->lock);
1425 vlc_cond_signal(&w->cond);
1426 vlc_mutex_unlock(&w->lock);
1434 #pragma mark helpers
1436 static int RegisterAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1438 OSStatus err = noErr;
1439 UInt32 i_param_size = 0;
1440 AudioStreamID *p_streams = NULL;
1443 /* Retrieve all the output streams */
1444 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1445 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1447 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1448 return VLC_EGENERIC;
1451 i_streams = i_param_size / sizeof(AudioStreamID);
1452 p_streams = (AudioStreamID *)malloc(i_param_size);
1453 if (p_streams == NULL)
1456 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1458 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1459 return VLC_EGENERIC;
1462 for (int i = 0; i < i_streams; i++) {
1463 /* get notified when physical formats change */
1464 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1465 err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, HardwareListener, (void *)p_aout);
1467 // nope just means that we already have a callback
1468 if (err == kAudioHardwareIllegalOperationError) {
1469 msg_Dbg(p_aout, "could not set audio stream formats property callback on stream id %i, already have callback: %4.4s", p_streams[i],
1472 msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i: %4.4s", p_streams[i],
1483 * AudioDeviceHasOutput: Checks if the device is actually an output device
1485 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1487 UInt32 dataSize = 0;
1490 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1491 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1493 if (dataSize == 0 || status != noErr)
1500 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1502 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1504 OSStatus err = noErr;
1505 UInt32 i_param_size = 0;
1506 AudioStreamID *p_streams = NULL;
1508 bool b_return = false;
1510 /* Retrieve all the output streams */
1511 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1512 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1514 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1518 i_streams = i_param_size / sizeof(AudioStreamID);
1519 p_streams = (AudioStreamID *)malloc(i_param_size);
1520 if (p_streams == NULL)
1523 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1525 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1529 for (int i = 0; i < i_streams; i++) {
1530 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1539 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1541 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1543 OSStatus err = noErr;
1544 UInt32 i_param_size = 0;
1545 AudioStreamRangedDescription *p_format_list = NULL;
1547 bool b_return = false;
1549 /* Retrieve all the stream formats supported by each output stream */
1550 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1551 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1553 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1557 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1558 msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1560 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1561 if (p_format_list == NULL)
1564 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1566 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1567 free(p_format_list);
1568 p_format_list = NULL;
1572 for (int i = 0; i < i_formats; i++) {
1574 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1577 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1578 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1579 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1580 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1584 free(p_format_list);
1589 * AudioStreamChangeFormat: switch stream format based on the provided description
1591 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1593 OSStatus err = noErr;
1594 UInt32 i_param_size = 0;
1596 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1598 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1600 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1602 /* Condition because SetProperty is asynchronious */
1603 vlc_cond_init(&w.cond);
1604 vlc_mutex_init(&w.lock);
1605 vlc_mutex_lock(&w.lock);
1607 /* Install the callback */
1608 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1610 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1614 /* change the format */
1615 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1618 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1622 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1623 * it is also not atomic in its behaviour.
1624 * Therefore we check 5 times before we really give up.
1625 * FIXME: failing isn't actually implemented yet. */
1626 for (int i = 0; i < 5; i++) {
1627 AudioStreamBasicDescription actual_format;
1628 mtime_t timeout = mdate() + 500000;
1630 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1631 msg_Dbg(p_aout, "reached timeout");
1633 i_param_size = sizeof(AudioStreamBasicDescription);
1634 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1636 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1637 if (actual_format.mSampleRate == change_format.mSampleRate &&
1638 actual_format.mFormatID == change_format.mFormatID &&
1639 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1640 /* The right format is now active */
1643 /* We need to check again */
1646 /* Removing the property listener */
1647 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1649 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1653 /* Destroy the lock and condition */
1654 vlc_mutex_unlock(&w.lock);
1655 vlc_mutex_destroy(&w.lock);
1656 vlc_cond_destroy(&w.cond);