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;
117 #pragma mark local prototypes & module descriptor
119 static int Open (vlc_object_t *);
120 static void Close (vlc_object_t *);
121 static int Start (audio_output_t *, audio_sample_format_t *);
122 static int StartAnalog (audio_output_t *, audio_sample_format_t *);
123 static int StartSPDIF (audio_output_t *, audio_sample_format_t *);
124 static void Stop (audio_output_t *);
126 static void RebuildDeviceList (audio_output_t *);
127 static int SwitchAudioDevice (audio_output_t *p_aout, const char *name);
128 static int VolumeSet (audio_output_t *, float);
129 static int MuteSet (audio_output_t *, bool);
131 static void Play (audio_output_t *, block_t *);
132 static void Pause (audio_output_t *, bool, mtime_t);
133 static void Flush (audio_output_t *, bool);
134 static int TimeGet (audio_output_t *, mtime_t *);
135 static OSStatus RenderCallbackAnalog (vlc_object_t *, AudioUnitRenderActionFlags *, const AudioTimeStamp *,
136 UInt32 , UInt32, AudioBufferList *);
138 static OSStatus RenderCallbackSPDIF (AudioDeviceID, const AudioTimeStamp *, const void *, const AudioTimeStamp *,
139 AudioBufferList *, const AudioTimeStamp *, void *);
141 static OSStatus HardwareListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
142 static OSStatus StreamListener (AudioObjectID, UInt32, const AudioObjectPropertyAddress *, void *);
144 static int RegisterAudioStreamsCallback(audio_output_t *, AudioDeviceID);
145 static int AudioDeviceHasOutput (AudioDeviceID);
146 static int AudioDeviceSupportsDigital(audio_output_t *, AudioDeviceID);
147 static int AudioStreamSupportsDigital(audio_output_t *, AudioStreamID);
148 static int AudioStreamChangeFormat (audio_output_t *, AudioStreamID, AudioStreamBasicDescription);
152 set_shortname("auhal")
153 set_description(N_("HAL AudioUnit output"))
154 set_capability("audio output", 101)
155 set_category(CAT_AUDIO)
156 set_subcategory(SUBCAT_AUDIO_AOUT)
157 set_callbacks(Open, Close)
158 add_integer("auhal-volume", AOUT_VOLUME_DEFAULT,
159 VOLUME_TEXT, VOLUME_LONGTEXT, true)
160 change_integer_range(0, AOUT_VOLUME_MAX)
161 add_string("auhal-audio-device", "", DEVICE_TEXT, DEVICE_LONGTEXT, true)
162 add_obsolete_integer("macosx-audio-device") /* since 2.1.0 */
166 #pragma mark initialization
168 static int Open(vlc_object_t *obj)
170 audio_output_t *p_aout = (audio_output_t *)obj;
171 aout_sys_t *p_sys = malloc(sizeof (*p_sys));
172 if (unlikely(p_sys == NULL))
175 OSStatus err = noErr;
177 vlc_mutex_init(&p_sys->lock);
178 vlc_cond_init(&p_sys->cond);
181 p_aout->start = Start;
183 p_aout->volume_set = VolumeSet;
184 p_aout->mute_set = MuteSet;
185 p_aout->device_select = SwitchAudioDevice;
187 /* Attach a Listener so that we are notified of a change in the Device setup */
188 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
189 err = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
191 msg_Warn(p_aout, "failed to add listener for audio device configuration [%4.4s]", (char *)&err);
193 RebuildDeviceList(p_aout);
195 /* remember the volume */
196 aout_VolumeReport(p_aout, var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT);
197 MuteSet(p_aout, var_InheritBool(p_aout, "mute"));
199 SwitchAudioDevice(p_aout, config_GetPsz(p_aout, "auhal-audio-device"));
204 static void Close(vlc_object_t *obj)
206 audio_output_t *p_aout = (audio_output_t *)obj;
207 aout_sys_t *p_sys = p_aout->sys;
209 OSStatus err = noErr;
211 /* remove audio device callback */
212 AudioObjectPropertyAddress deviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
213 err = AudioObjectRemovePropertyListener(p_sys->i_selected_dev, &deviceAliveAddress, HardwareListener, (void *)p_aout);
215 msg_Err(p_aout, "failed to remove audio device life checker: [%4.4s]", (char *)&err);
217 /* remove audio streams callback */
218 if (p_sys->i_stream_id > 0) {
219 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
220 err = AudioObjectRemovePropertyListener(p_sys->i_stream_id, &physicalFormatsAddress, HardwareListener, (void *)p_aout);
222 msg_Err(p_aout, "failed to remove audio device property streams callback: [%4.4s]", (char *)&err);
225 config_PutPsz(p_aout, "auhal-audio-device", aout_DeviceGet(p_aout));
227 vlc_mutex_destroy(&p_sys->lock);
228 vlc_cond_destroy(&p_sys->cond);
233 static int Start(audio_output_t *p_aout, audio_sample_format_t *restrict fmt)
235 OSStatus err = noErr;
236 UInt32 i_param_size = 0;
237 struct aout_sys_t *p_sys = NULL;
239 /* Use int here, to match kAudioDevicePropertyDeviceIsAlive
243 bool b_start_digital = false;
246 p_sys->b_digital = false;
247 p_sys->au_component = NULL;
248 p_sys->au_unit = NULL;
249 p_sys->clock_diff = (mtime_t) 0;
250 p_sys->i_hog_pid = -1;
251 p_sys->i_stream_id = 0;
252 p_sys->i_stream_index = -1;
253 p_sys->b_revert = false;
254 p_sys->b_changed_mixing = false;
255 p_sys->i_bytes_per_sample = 0;
257 aout_FormatPrint(p_aout, "VLC is looking for:", fmt);
259 msg_Dbg(p_aout, "attempting to use device %i", p_sys->i_selected_dev);
261 /* Check if the desired device is alive and usable */
262 i_param_size = sizeof(b_alive);
263 AudioObjectPropertyAddress audioDeviceAliveAddress = { kAudioDevicePropertyDeviceIsAlive,
264 kAudioObjectPropertyScopeGlobal,
265 kAudioObjectPropertyElementMaster };
266 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceAliveAddress, 0, NULL, &i_param_size, &b_alive);
269 /* Be tolerant, only give a warning here */
270 msg_Warn(p_aout, "could not check whether device [0x%x] is alive: %4.4s",
271 (unsigned int)p_sys->i_selected_dev, (char *)&err);
276 msg_Warn(p_aout, "selected audio device is not alive, switching to default device with id %i", p_sys->i_default_dev);
277 p_sys->i_selected_dev = p_sys->i_default_dev;
278 p_sys->b_selected_dev_is_digital = false;
281 // recheck if device still supports digital
282 b_start_digital = p_sys->b_selected_dev_is_digital;
283 if(!AudioDeviceSupportsDigital(p_aout, p_sys->i_selected_dev))
284 b_start_digital = false;
287 msg_Dbg(p_aout, "Use audio device for digital output");
289 /* add a callback to see if the device dies later on */
290 err = AudioObjectAddPropertyListener(p_sys->i_selected_dev, &audioDeviceAliveAddress, HardwareListener, (void *)p_aout);
292 /* Be tolerant, only give a warning here */
293 msg_Warn(p_aout, "could not set alive check callback on device [0x%x]: %4.4s",
294 (unsigned int)p_sys->i_selected_dev, (char *)&err);
297 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
298 kAudioDevicePropertyScopeOutput,
299 kAudioObjectPropertyElementMaster };
300 i_param_size = sizeof(p_sys->i_hog_pid);
301 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, &i_param_size, &p_sys->i_hog_pid);
303 /* This is not a fatal error. Some drivers simply don't support this property */
304 msg_Warn(p_aout, "could not check whether device is hogged: %4.4s",
306 p_sys->i_hog_pid = -1;
309 if (p_sys->i_hog_pid != -1 && p_sys->i_hog_pid != getpid()) {
310 msg_Err(p_aout, "Selected audio device is exclusively in use by another program.");
311 dialog_Fatal(p_aout, _("Audio output failed"), "%s",
312 _("The selected audio output device is exclusively in "
313 "use by another program."));
317 bool b_success = false;
319 /* Check for Digital mode or Analog output mode */
320 if (AOUT_FMT_SPDIF (fmt) && b_start_digital) {
321 if (StartSPDIF (p_aout, fmt)) {
322 msg_Dbg(p_aout, "digital output successfully opened");
326 if (StartAnalog(p_aout, fmt)) {
327 msg_Dbg(p_aout, "analog output successfully opened");
334 p_aout->flush = Flush;
335 p_aout->time_get = TimeGet;
336 p_aout->pause = Pause;
341 /* If we reach this, this aout has failed */
342 msg_Err(p_aout, "opening auhal output failed");
347 * StartAnalog: open and setup a HAL AudioUnit to do PCM audio output
349 static int StartAnalog(audio_output_t *p_aout, audio_sample_format_t *fmt)
351 struct aout_sys_t *p_sys = p_aout->sys;
352 OSStatus err = noErr;
353 UInt32 i_param_size = 0;
355 AudioComponentDescription desc;
356 AudioStreamBasicDescription DeviceFormat;
357 AudioChannelLayout *layout;
358 AudioChannelLayout new_layout;
359 AURenderCallbackStruct input;
360 p_aout->sys->chans_to_reorder = 0;
362 /* Lets go find our Component */
363 desc.componentType = kAudioUnitType_Output;
364 desc.componentSubType = kAudioUnitSubType_HALOutput;
365 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
366 desc.componentFlags = 0;
367 desc.componentFlagsMask = 0;
369 p_sys->au_component = AudioComponentFindNext(NULL, &desc);
370 if (p_sys->au_component == NULL) {
371 msg_Warn(p_aout, "we cannot find our HAL component");
375 err = AudioComponentInstanceNew(p_sys->au_component, &p_sys->au_unit);
377 msg_Warn(p_aout, "we cannot open our HAL component");
381 /* Set the device we will use for this output unit */
382 err = AudioUnitSetProperty(p_sys->au_unit,
383 kAudioOutputUnitProperty_CurrentDevice,
384 kAudioUnitScope_Global,
386 &p_sys->i_selected_dev,
387 sizeof(AudioObjectID));
390 msg_Warn(p_aout, "we cannot select the audio device");
394 /* Get the current format */
395 i_param_size = sizeof(AudioStreamBasicDescription);
397 err = AudioUnitGetProperty(p_sys->au_unit,
398 kAudioUnitProperty_StreamFormat,
399 kAudioUnitScope_Output,
407 msg_Dbg(p_aout, STREAM_FORMAT_MSG("current format is: ", DeviceFormat));
409 /* Get the channel layout of the device side of the unit (vlc -> unit -> device) */
410 err = AudioUnitGetPropertyInfo(p_sys->au_unit,
411 kAudioDevicePropertyPreferredChannelLayout,
412 kAudioUnitScope_Output,
418 layout = (AudioChannelLayout *)malloc(i_param_size);
420 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
421 kAudioDevicePropertyPreferredChannelLayout,
422 kAudioUnitScope_Output,
427 /* We need to "fill out" the ChannelLayout, because there are multiple ways that it can be set */
428 if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
429 /* bitmap defined channellayout */
430 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
431 sizeof(UInt32), &layout->mChannelBitmap,
434 } else if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_UseChannelDescriptions)
436 /* layouttags defined channellayout */
437 verify_noerr(AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
438 sizeof(AudioChannelLayoutTag), &layout->mChannelLayoutTag,
443 msg_Dbg(p_aout, "layout of AUHAL has %i channels" , layout->mNumberChannelDescriptions);
445 if (layout->mNumberChannelDescriptions == 0) {
446 msg_Err(p_aout, "insufficient number of output channels");
450 /* Initialize the VLC core channel count */
451 fmt->i_physical_channels = 0;
452 i_original = fmt->i_original_channels & AOUT_CHAN_PHYSMASK;
454 if (i_original == AOUT_CHAN_CENTER || layout->mNumberChannelDescriptions < 2) {
455 /* We only need Mono or cannot output more than 1 channel */
456 fmt->i_physical_channels = AOUT_CHAN_CENTER;
457 } else if (i_original == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) || layout->mNumberChannelDescriptions < 3) {
458 /* We only need Stereo or cannot output more than 2 channels */
459 fmt->i_physical_channels = AOUT_CHANS_STEREO;
461 /* We want more than stereo and we can do that */
462 for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; i++) {
464 msg_Dbg(p_aout, "this is channel: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
467 switch(layout->mChannelDescriptions[i].mChannelLabel) {
468 case kAudioChannelLabel_Left:
469 fmt->i_physical_channels |= AOUT_CHAN_LEFT;
471 case kAudioChannelLabel_Right:
472 fmt->i_physical_channels |= AOUT_CHAN_RIGHT;
474 case kAudioChannelLabel_Center:
475 fmt->i_physical_channels |= AOUT_CHAN_CENTER;
477 case kAudioChannelLabel_LFEScreen:
478 fmt->i_physical_channels |= AOUT_CHAN_LFE;
480 case kAudioChannelLabel_LeftSurround:
481 fmt->i_physical_channels |= AOUT_CHAN_REARLEFT;
483 case kAudioChannelLabel_RightSurround:
484 fmt->i_physical_channels |= AOUT_CHAN_REARRIGHT;
486 case kAudioChannelLabel_RearSurroundLeft:
487 fmt->i_physical_channels |= AOUT_CHAN_MIDDLELEFT;
489 case kAudioChannelLabel_RearSurroundRight:
490 fmt->i_physical_channels |= AOUT_CHAN_MIDDLERIGHT;
492 case kAudioChannelLabel_CenterSurround:
493 fmt->i_physical_channels |= AOUT_CHAN_REARCENTER;
496 msg_Warn(p_aout, "unrecognized channel form provided by driver: %d", (int)layout->mChannelDescriptions[i].mChannelLabel);
499 if (fmt->i_physical_channels == 0) {
500 fmt->i_physical_channels = AOUT_CHANS_STEREO;
501 msg_Err(p_aout, "You should configure your speaker layout with Audio Midi Setup Utility in /Applications/Utilities. Now using Stereo mode.");
502 dialog_Fatal(p_aout, _("Audio device is not configured"), "%s",
503 _("You should configure your speaker layout with "
504 "the \"Audio Midi Setup\" utility in /Applications/"
505 "Utilities. Stereo mode is being used now."));
510 msg_Warn(p_aout, "this driver does not support kAudioDevicePropertyPreferredChannelLayout. BAD DRIVER AUTHOR !!!");
511 fmt->i_physical_channels = AOUT_CHANS_STEREO;
514 msg_Dbg(p_aout, "selected %d physical channels for device output", aout_FormatNbChannels(fmt));
515 msg_Dbg(p_aout, "VLC will output: %s", aout_FormatPrintChannels(fmt));
516 p_sys->i_numberOfChannels = aout_FormatNbChannels(fmt);
518 memset (&new_layout, 0, sizeof(new_layout));
519 uint32_t chans_out[AOUT_CHAN_MAX];
521 switch(aout_FormatNbChannels(fmt)) {
523 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
526 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
529 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
530 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_7; // L R C
531 else if (fmt->i_physical_channels & AOUT_CHAN_LFE)
532 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; // L R LFE
535 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_LFE))
536 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_10; // L R C LFE
537 else if (fmt->i_physical_channels & (AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT))
538 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R Ls Rs
539 else if (fmt->i_physical_channels & (AOUT_CHAN_CENTER | AOUT_CHAN_REARCENTER))
540 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_3; // L R C Cs
543 if (fmt->i_physical_channels & (AOUT_CHAN_CENTER))
544 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_19; // L R Ls Rs C
545 else if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
546 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_18; // L R Ls Rs LFE
549 if (fmt->i_physical_channels & (AOUT_CHAN_LFE))
550 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_20; // L R Ls Rs C LFE
552 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_AudioUnit_6_0; // L R Ls Rs C Cs
555 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
557 chans_out[0] = AOUT_CHAN_LEFT;
558 chans_out[1] = AOUT_CHAN_RIGHT;
559 chans_out[2] = AOUT_CHAN_CENTER;
560 chans_out[3] = AOUT_CHAN_LFE;
561 chans_out[4] = AOUT_CHAN_REARLEFT;
562 chans_out[5] = AOUT_CHAN_REARRIGHT;
563 chans_out[6] = AOUT_CHAN_REARCENTER;
565 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
566 if (p_aout->sys->chans_to_reorder)
567 msg_Dbg(p_aout, "channel reordering needed");
571 new_layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
573 chans_out[0] = AOUT_CHAN_LEFT;
574 chans_out[1] = AOUT_CHAN_RIGHT;
575 chans_out[2] = AOUT_CHAN_CENTER;
576 chans_out[3] = AOUT_CHAN_LFE;
577 chans_out[4] = AOUT_CHAN_MIDDLELEFT;
578 chans_out[5] = AOUT_CHAN_MIDDLERIGHT;
579 chans_out[6] = AOUT_CHAN_REARLEFT;
580 chans_out[7] = AOUT_CHAN_REARRIGHT;
582 p_aout->sys->chans_to_reorder = aout_CheckChannelReorder(NULL, chans_out, fmt->i_physical_channels, p_aout->sys->chan_table);
583 if (p_aout->sys->chans_to_reorder)
584 msg_Dbg(p_aout, "channel reordering needed");
589 /* Set up the format to be used */
590 DeviceFormat.mSampleRate = fmt->i_rate;
591 DeviceFormat.mFormatID = kAudioFormatLinearPCM;
592 p_sys->i_rate = fmt->i_rate;
594 /* We use float 32 since this is VLC's endorsed format */
595 fmt->i_format = VLC_CODEC_FL32;
596 DeviceFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
597 DeviceFormat.mBitsPerChannel = 32;
598 DeviceFormat.mChannelsPerFrame = aout_FormatNbChannels(fmt);
600 /* Calculate framesizes and stuff */
601 DeviceFormat.mFramesPerPacket = 1;
602 DeviceFormat.mBytesPerFrame = DeviceFormat.mBitsPerChannel * DeviceFormat.mChannelsPerFrame / 8;
603 DeviceFormat.mBytesPerPacket = DeviceFormat.mBytesPerFrame * DeviceFormat.mFramesPerPacket;
605 /* Set the desired format */
606 i_param_size = sizeof(AudioStreamBasicDescription);
607 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
608 kAudioUnitProperty_StreamFormat,
609 kAudioUnitScope_Input,
614 msg_Dbg(p_aout, STREAM_FORMAT_MSG("we set the AU format: " , DeviceFormat));
616 /* Retrieve actual format */
617 verify_noerr(AudioUnitGetProperty(p_sys->au_unit,
618 kAudioUnitProperty_StreamFormat,
619 kAudioUnitScope_Input,
624 msg_Dbg(p_aout, STREAM_FORMAT_MSG("the actual set AU format is " , DeviceFormat));
626 /* Do the last VLC aout setups */
627 aout_FormatPrepare(fmt);
629 /* set the IOproc callback */
630 input.inputProc = (AURenderCallback) RenderCallbackAnalog;
631 input.inputProcRefCon = p_aout;
633 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
634 kAudioUnitProperty_SetRenderCallback,
635 kAudioUnitScope_Input,
636 0, &input, sizeof(input)));
638 /* Set the new_layout as the layout VLC will use to feed the AU unit */
639 verify_noerr(AudioUnitSetProperty(p_sys->au_unit,
640 kAudioUnitProperty_AudioChannelLayout,
641 kAudioUnitScope_Output,
642 0, &new_layout, sizeof(new_layout)));
644 if (new_layout.mNumberChannelDescriptions > 0)
645 free(new_layout.mChannelDescriptions);
648 verify_noerr(AudioUnitInitialize(p_sys->au_unit));
650 /* Find the difference between device clock and mdate clock */
651 p_sys->clock_diff = - (mtime_t)
652 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
653 p_sys->clock_diff += mdate();
655 /* setup circular buffer */
656 TPCircularBufferInit(&p_sys->circular_buffer, AUDIO_BUFFER_SIZE_IN_SECONDS *
657 fmt->i_rate * fmt->i_bytes_per_frame);
659 p_sys->b_got_first_sample = false;
661 /* Set volume for output unit */
662 float volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
663 volume = volume * volume * volume;
664 verify_noerr(AudioUnitSetParameter(p_sys->au_unit,
665 kHALOutputParam_Volume,
666 kAudioUnitScope_Global,
675 * StartSPDIF: Setup an encoded digital stream (SPDIF) output
677 static int StartSPDIF(audio_output_t * p_aout, audio_sample_format_t *fmt)
679 struct aout_sys_t *p_sys = p_aout->sys;
680 OSStatus err = noErr;
681 UInt32 i_param_size = 0, b_mix = 0;
682 Boolean b_writeable = false;
683 AudioStreamID *p_streams = NULL;
684 unsigned i_streams = 0;
686 /* Start doing the SPDIF setup proces */
687 p_sys->b_digital = true;
690 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
691 i_param_size = sizeof(p_sys->i_hog_pid);
692 p_sys->i_hog_pid = getpid() ;
694 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
697 msg_Err(p_aout, "failed to set hogmode: [%4.4s]", (char *)&err);
701 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
703 if (AudioObjectHasProperty(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress)) {
704 /* Set mixable to false if we are allowed to */
705 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
706 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size);
707 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
709 if (err == noErr && b_writeable) {
711 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
712 p_sys->b_changed_mixing = true;
716 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
721 /* Get a list of all the streams on this device */
722 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
723 err = AudioObjectGetPropertyDataSize(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size);
725 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
729 i_streams = i_param_size / sizeof(AudioStreamID);
730 p_streams = (AudioStreamID *)malloc(i_param_size);
731 if (p_streams == NULL)
734 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &streamsAddress, 0, NULL, &i_param_size, p_streams);
737 msg_Err(p_aout, "could not get number of streams: [%4.4s]", (char *)&err);
742 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
743 for (unsigned i = 0; i < i_streams && p_sys->i_stream_index < 0 ; i++) {
744 /* Find a stream with a cac3 stream */
745 AudioStreamRangedDescription *p_format_list = NULL;
747 bool b_digital = false;
749 /* Retrieve all the stream formats supported by each output stream */
750 err = AudioObjectGetPropertyDataSize(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size);
752 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
756 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
757 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
758 if (p_format_list == NULL)
761 err = AudioObjectGetPropertyData(p_streams[i], &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
763 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
768 /* Check if one of the supported formats is a digital format */
769 for (int j = 0; j < i_formats; j++) {
770 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
771 p_format_list[j].mFormat.mFormatID == 'iac3' ||
772 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
773 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
780 /* if this stream supports a digital (cac3) format, then go set it. */
781 int i_requested_rate_format = -1;
782 int i_current_rate_format = -1;
783 int i_backup_rate_format = -1;
785 p_sys->i_stream_id = p_streams[i];
786 p_sys->i_stream_index = i;
788 if (!p_sys->b_revert) {
789 AudioObjectPropertyAddress currentPhysicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
790 /* Retrieve the original format of this stream first if not done so already */
791 i_param_size = sizeof(p_sys->sfmt_revert);
792 err = AudioObjectGetPropertyData(p_sys->i_stream_id, ¤tPhysicalFormatAddress, 0, NULL, &i_param_size, &p_sys->sfmt_revert);
794 msg_Err(p_aout, "could not retrieve the original streamformat: [%4.4s]", (char *)&err);
797 p_sys->b_revert = true;
800 for (int j = 0; j < i_formats; j++) {
801 if (p_format_list[j].mFormat.mFormatID == 'IAC3' ||
802 p_format_list[j].mFormat.mFormatID == 'iac3' ||
803 p_format_list[j].mFormat.mFormatID == kAudioFormat60958AC3 ||
804 p_format_list[j].mFormat.mFormatID == kAudioFormatAC3) {
805 if (p_format_list[j].mFormat.mSampleRate == fmt->i_rate) {
806 i_requested_rate_format = j;
808 } else if (p_format_list[j].mFormat.mSampleRate == p_sys->sfmt_revert.mSampleRate)
809 i_current_rate_format = j;
811 if (i_backup_rate_format < 0 || p_format_list[j].mFormat.mSampleRate > p_format_list[i_backup_rate_format].mFormat.mSampleRate)
812 i_backup_rate_format = j;
818 if (i_requested_rate_format >= 0) /* We prefer to output at the samplerate of the original audio */
819 p_sys->stream_format = p_format_list[i_requested_rate_format].mFormat;
820 else if (i_current_rate_format >= 0) /* If not possible, we will try to use the current samplerate of the device */
821 p_sys->stream_format = p_format_list[i_current_rate_format].mFormat;
823 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) */
829 msg_Dbg(p_aout, STREAM_FORMAT_MSG("original stream format: ", p_sys->sfmt_revert));
831 if (!AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->stream_format))
834 /* Set the format flags */
835 if (p_sys->stream_format.mFormatFlags & kAudioFormatFlagIsBigEndian)
836 fmt->i_format = VLC_CODEC_SPDIFB;
838 fmt->i_format = VLC_CODEC_SPDIFL;
839 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
840 fmt->i_frame_length = A52_FRAME_NB;
841 fmt->i_rate = (unsigned int)p_sys->stream_format.mSampleRate;
842 p_sys->i_rate = fmt->i_rate;
843 aout_FormatPrepare(fmt);
845 /* Add IOProc callback */
846 err = AudioDeviceCreateIOProcID(p_sys->i_selected_dev,
847 (AudioDeviceIOProc)RenderCallbackSPDIF,
851 msg_Err(p_aout, "AudioDeviceCreateIOProcID failed: [%4.4s]", (char *)&err);
855 /* Check for the difference between the Device clock and mdate */
856 p_sys->clock_diff = - (mtime_t)
857 AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) / 1000;
858 p_sys->clock_diff += mdate();
861 err = AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
863 msg_Err(p_aout, "AudioDeviceStart failed: [%4.4s]", (char *)&err);
865 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev, p_sys->i_procID);
867 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
872 /* setup circular buffer */
873 TPCircularBufferInit(&p_sys->circular_buffer, 200 * AOUT_SPDIF_SIZE);
878 static void Stop(audio_output_t *p_aout)
880 struct aout_sys_t *p_sys = p_aout->sys;
881 OSStatus err = noErr;
882 UInt32 i_param_size = 0;
884 if (p_sys->au_unit) {
885 verify_noerr(AudioOutputUnitStop(p_sys->au_unit));
886 verify_noerr(AudioUnitUninitialize(p_sys->au_unit));
887 verify_noerr(AudioComponentInstanceDispose(p_sys->au_unit));
890 if (p_sys->b_digital) {
892 err = AudioDeviceStop(p_sys->i_selected_dev,
895 msg_Err(p_aout, "AudioDeviceStop failed: [%4.4s]", (char *)&err);
897 /* Remove IOProc callback */
898 err = AudioDeviceDestroyIOProcID(p_sys->i_selected_dev,
901 msg_Err(p_aout, "AudioDeviceDestroyIOProcID failed: [%4.4s]", (char *)&err);
904 AudioStreamChangeFormat(p_aout, p_sys->i_stream_id, p_sys->sfmt_revert);
906 if (p_sys->b_changed_mixing && p_sys->sfmt_revert.mFormatID != kAudioFormat60958AC3) {
908 Boolean b_writeable = false;
909 /* Revert mixable to true if we are allowed to */
910 AudioObjectPropertyAddress audioDeviceSupportsMixingAddress = { kAudioDevicePropertySupportsMixing , kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
911 err = AudioObjectIsPropertySettable(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, &b_writeable);
912 err = AudioObjectGetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, &i_param_size, &b_mix);
914 if (err == noErr && b_writeable) {
915 msg_Dbg(p_aout, "mixable is: %d", b_mix);
917 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceSupportsMixingAddress, 0, NULL, i_param_size, &b_mix);
921 msg_Err(p_aout, "failed to set mixmode: [%4.4s]", (char *)&err);
925 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
926 err = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &audioDevicesAddress, HardwareListener, (void *)p_aout);
929 msg_Err(p_aout, "AudioHardwareRemovePropertyListener failed: [%4.4s]", (char *)&err);
931 if (p_sys->i_hog_pid == getpid()) {
932 p_sys->i_hog_pid = -1;
933 i_param_size = sizeof(p_sys->i_hog_pid);
934 AudioObjectPropertyAddress audioDeviceHogModeAddress = { kAudioDevicePropertyHogMode,
935 kAudioDevicePropertyScopeOutput,
936 kAudioObjectPropertyElementMaster };
937 err = AudioObjectSetPropertyData(p_sys->i_selected_dev, &audioDeviceHogModeAddress, 0, NULL, i_param_size, &p_sys->i_hog_pid);
939 msg_Err(p_aout, "Could not release hogmode: [%4.4s]", (char *)&err);
942 p_sys->i_bytes_per_sample = 0;
944 /* clean-up circular buffer */
945 TPCircularBufferCleanup(&p_sys->circular_buffer);
949 #pragma mark core interaction
951 static void ReportDevice(audio_output_t *p_aout, UInt32 i_id, char *name)
954 sprintf(deviceid, "%i", i_id);
956 aout_HotplugReport(p_aout, deviceid, name);
959 static void RebuildDeviceList(audio_output_t * p_aout)
961 OSStatus err = noErr;
962 UInt32 propertySize = 0;
963 AudioObjectID defaultDeviceID = 0;
964 AudioObjectID *deviceIDs;
965 UInt32 numberOfDevices;
967 struct aout_sys_t *p_sys = p_aout->sys;
969 /* Get number of devices */
970 AudioObjectPropertyAddress audioDevicesAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
971 err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize);
973 msg_Err(p_aout, "Could not get number of devices: [%4.4s]", (char *)&err);
977 numberOfDevices = propertySize / sizeof(AudioDeviceID);
979 if (numberOfDevices < 1) {
980 msg_Err(p_aout, "No audio output devices were found.");
983 msg_Dbg(p_aout, "found %i audio device(s)", numberOfDevices);
985 /* Allocate DeviceID array */
986 deviceIDs = (AudioDeviceID *)calloc(numberOfDevices, sizeof(AudioDeviceID));
987 if (deviceIDs == NULL)
990 /* Populate DeviceID array */
991 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &audioDevicesAddress, 0, NULL, &propertySize, deviceIDs);
993 msg_Err(p_aout, "could not get the device IDs: [%4.4s]", (char *)&err);
997 /* Find the ID of the default Device */
998 AudioObjectPropertyAddress defaultDeviceAddress = { kAudioHardwarePropertyDefaultOutputDevice, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
999 propertySize = sizeof(AudioObjectID);
1000 err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultDeviceAddress, 0, NULL, &propertySize, &defaultDeviceID);
1002 msg_Err(p_aout, "could not get default audio device: [%4.4s]", (char *)&err);
1005 p_sys->i_default_dev = defaultDeviceID;
1007 AudioObjectPropertyAddress deviceNameAddress = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1009 for (unsigned int i = 0; i < numberOfDevices; i++) {
1010 CFStringRef device_name_ref;
1013 bool b_digital = false;
1014 UInt32 i_id = deviceIDs[i];
1016 /* Retrieve the length of the device name */
1017 err = AudioObjectGetPropertyDataSize(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize);
1019 msg_Dbg(p_aout, "failed to get name size for device %i", deviceIDs[i]);
1023 /* Retrieve the name of the device */
1024 err = AudioObjectGetPropertyData(deviceIDs[i], &deviceNameAddress, 0, NULL, &propertySize, &device_name_ref);
1026 msg_Dbg(p_aout, "failed to get name for device %i", deviceIDs[i]);
1029 length = CFStringGetLength(device_name_ref);
1031 psz_name = (char *)malloc(length);
1032 CFStringGetCString(device_name_ref, psz_name, length, kCFStringEncodingUTF8);
1034 msg_Dbg(p_aout, "DevID: %i DevName: %s", deviceIDs[i], psz_name);
1036 if (!AudioDeviceHasOutput(deviceIDs[i])) {
1037 msg_Dbg(p_aout, "this '%s' is INPUT only. skipping...", psz_name);
1042 ReportDevice(p_aout, i_id, psz_name);
1044 if (AudioDeviceSupportsDigital(p_aout, deviceIDs[i])) {
1046 msg_Dbg(p_aout, "'%s' supports digital output", psz_name);
1047 char *psz_encoded_name = nil;
1048 asprintf(&psz_encoded_name, _("%s (Encoded Output)"), psz_name);
1049 i_id = i_id | AOUT_VAR_SPDIF_FLAG;
1050 ReportDevice(p_aout, i_id, psz_encoded_name);
1051 free(psz_encoded_name);
1054 // TODO: only register once for each device
1055 RegisterAudioStreamsCallback(p_aout, deviceIDs[i]);
1057 CFRelease(device_name_ref);
1061 // TODO: fix default audio device
1062 ReportDevice(p_aout, 0, _("System Sound Output Device"));
1067 static int SwitchAudioDevice(audio_output_t *p_aout, const char *name)
1069 struct aout_sys_t *p_sys = p_aout->sys;
1072 p_sys->i_selected_dev = atoi(name);
1074 p_sys->i_selected_dev = 0;
1076 bool b_supports_digital = (p_sys->i_selected_dev & AOUT_VAR_SPDIF_FLAG);
1077 if (b_supports_digital)
1078 p_sys->b_selected_dev_is_digital = true;
1080 p_sys->b_selected_dev_is_digital = false;
1082 p_sys->i_selected_dev = p_sys->i_selected_dev & ~AOUT_VAR_SPDIF_FLAG;
1084 aout_DeviceReport(p_aout, name);
1085 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1090 static int VolumeSet(audio_output_t * p_aout, float volume)
1092 struct aout_sys_t *p_sys = p_aout->sys;
1095 aout_VolumeReport(p_aout, volume);
1097 /* Set volume for output unit */
1098 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1099 kHALOutputParam_Volume,
1100 kAudioUnitScope_Global,
1102 volume * volume * volume,
1105 if (var_InheritBool(p_aout, "volume-save"))
1106 config_PutInt(p_aout, "auhal-volume", lroundf(volume * AOUT_VOLUME_DEFAULT));
1111 static int MuteSet(audio_output_t * p_aout, bool mute)
1113 struct aout_sys_t *p_sys = p_aout->sys;
1116 aout_MuteReport(p_aout, mute);
1121 volume = var_InheritInteger(p_aout, "auhal-volume") / (float)AOUT_VOLUME_DEFAULT;
1123 ostatus = AudioUnitSetParameter(p_sys->au_unit,
1124 kHALOutputParam_Volume,
1125 kAudioUnitScope_Global,
1127 volume * volume * volume,
1134 #pragma mark actual playback
1136 static void Play(audio_output_t * p_aout, block_t * p_block)
1138 struct aout_sys_t *p_sys = p_aout->sys;
1140 if (p_block->i_nb_samples > 0) {
1141 if (!p_sys->b_got_first_sample) {
1143 verify_noerr(AudioOutputUnitStart(p_sys->au_unit));
1144 p_sys->b_got_first_sample = true;
1147 /* Do the channel reordering */
1148 if (p_sys->chans_to_reorder && !p_sys->b_digital) {
1149 aout_ChannelReorder(p_block->p_buffer,
1151 p_sys->chans_to_reorder,
1156 /* move data to buffer */
1157 if (unlikely(!TPCircularBufferProduceBytes(&p_sys->circular_buffer, p_block->p_buffer, p_block->i_buffer)))
1158 msg_Warn(p_aout, "dropped buffer");
1160 if (!p_sys->i_bytes_per_sample)
1161 p_sys->i_bytes_per_sample = p_block->i_buffer / p_block->i_nb_samples;
1164 block_Release(p_block);
1167 static void Pause(audio_output_t *p_aout, bool pause, mtime_t date)
1169 struct aout_sys_t * p_sys = p_aout->sys;
1172 if (p_aout->sys->b_digital) {
1174 AudioDeviceStop(p_sys->i_selected_dev, p_sys->i_procID);
1176 AudioDeviceStart(p_sys->i_selected_dev, p_sys->i_procID);
1179 AudioOutputUnitStop(p_sys->au_unit);
1181 AudioOutputUnitStart(p_sys->au_unit);
1185 static void Flush(audio_output_t *p_aout, bool wait)
1187 struct aout_sys_t *p_sys = p_aout->sys;
1190 int32_t availableBytes;
1191 vlc_mutex_lock(&p_sys->lock);
1192 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1193 while (availableBytes > 0) {
1194 vlc_cond_wait(&p_sys->cond, &p_sys->lock);
1195 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1197 vlc_mutex_unlock(&p_sys->lock);
1200 p_sys->b_got_first_sample = false;
1202 /* flush circular buffer */
1203 AudioOutputUnitStop(p_aout->sys->au_unit);
1204 TPCircularBufferClear(&p_aout->sys->circular_buffer);
1208 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
1210 struct aout_sys_t * p_sys = p_aout->sys;
1212 if (!p_sys->i_bytes_per_sample)
1215 int32_t availableBytes;
1216 TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1218 *delay = (availableBytes / p_sys->i_bytes_per_sample) * CLOCK_FREQ / p_sys->i_rate;
1223 /*****************************************************************************
1224 * RenderCallbackAnalog: This function is called everytime the AudioUnit wants
1225 * us to provide some more audio data.
1226 * Don't print anything during normal playback, calling blocking function from
1227 * this callback is not allowed.
1228 *****************************************************************************/
1229 static OSStatus RenderCallbackAnalog(vlc_object_t *p_obj,
1230 AudioUnitRenderActionFlags *ioActionFlags,
1231 const AudioTimeStamp *inTimeStamp,
1233 UInt32 inNumberFrames,
1234 AudioBufferList *ioData) {
1235 VLC_UNUSED(ioActionFlags);
1236 VLC_UNUSED(inTimeStamp);
1237 VLC_UNUSED(inBusNumber);
1238 VLC_UNUSED(inNumberFrames);
1240 audio_output_t * p_aout = (audio_output_t *)p_obj;
1241 struct aout_sys_t * p_sys = p_aout->sys;
1243 int bytesToCopy = ioData->mBuffers[0].mDataByteSize;
1244 Float32 *targetBuffer = (Float32*)ioData->mBuffers[0].mData;
1246 vlc_mutex_lock(&p_sys->lock);
1247 /* Pull audio from buffer */
1248 int32_t availableBytes;
1249 Float32 *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1251 /* check if we have enough data */
1252 if (!availableBytes) {
1253 /* return an empty buffer so silence is played until we have data */
1254 for (UInt32 j = 0; j < inNumberFrames; j++)
1255 targetBuffer[j] = 0.;
1257 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1258 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1261 vlc_cond_signal(&p_sys->cond);
1262 vlc_mutex_unlock(&p_sys->lock);
1268 * RenderCallbackSPDIF: callback for SPDIF audio output
1270 static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
1271 const AudioTimeStamp * inNow,
1272 const void * inInputData,
1273 const AudioTimeStamp * inInputTime,
1274 AudioBufferList * outOutputData,
1275 const AudioTimeStamp * inOutputTime,
1276 void * threadGlobals)
1279 VLC_UNUSED(inDevice);
1280 VLC_UNUSED(inInputData);
1281 VLC_UNUSED(inInputTime);
1282 VLC_UNUSED(inOutputTime);
1284 audio_output_t * p_aout = (audio_output_t *)threadGlobals;
1285 struct aout_sys_t * p_sys = p_aout->sys;
1287 int bytesToCopy = outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize;
1288 char *targetBuffer = outOutputData->mBuffers[p_sys->i_stream_index].mData;
1290 vlc_mutex_lock(&p_sys->lock);
1291 /* Pull audio from buffer */
1292 int32_t availableBytes;
1293 char *buffer = TPCircularBufferTail(&p_sys->circular_buffer, &availableBytes);
1295 /* check if we have enough data */
1296 if (!availableBytes) {
1297 /* return an empty buffer so silence is played until we have data */
1298 memset(targetBuffer, 0, outOutputData->mBuffers[p_sys->i_stream_index].mDataByteSize);
1300 memcpy(targetBuffer, buffer, __MIN(bytesToCopy, availableBytes));
1301 TPCircularBufferConsume(&p_sys->circular_buffer, __MIN(bytesToCopy, availableBytes));
1304 vlc_cond_signal(&p_sys->cond);
1305 vlc_mutex_unlock(&p_sys->lock);
1311 #pragma mark Stream / Hardware Listeners
1314 * HardwareListener: Warns us of changes in the list of registered devices
1316 static OSStatus HardwareListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1318 OSStatus err = noErr;
1319 audio_output_t *p_aout = (audio_output_t *)inClientData;
1320 VLC_UNUSED(inObjectID);
1321 VLC_UNUSED(inNumberAddresses);
1322 VLC_UNUSED(inAddresses);
1328 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1329 switch (inAddresses[i].mSelector) {
1330 case kAudioHardwarePropertyDevices:
1331 msg_Warn(p_aout, "audio device configuration changed, resetting cache");
1334 case kAudioDevicePropertyDeviceIsAlive:
1335 msg_Warn(p_aout, "audio device died, resetting aout");
1338 case kAudioStreamPropertyAvailablePhysicalFormats:
1339 msg_Warn(p_aout, "available physical formats for audio device changed, resetting aout");
1343 msg_Warn(p_aout, "device reset for unknown reason (%i)", inAddresses[i].mSelector);
1349 RebuildDeviceList(p_aout);
1350 aout_RestartRequest(p_aout, AOUT_RESTART_OUTPUT);
1356 * StreamListener: check whether the device's physical format changes on-the-fly (unlikely)
1358 static OSStatus StreamListener(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void*inClientData)
1360 OSStatus err = noErr;
1361 struct { vlc_mutex_t lock; vlc_cond_t cond; } * w = inClientData;
1363 VLC_UNUSED(inObjectID);
1365 for (unsigned int i = 0; i < inNumberAddresses; i++) {
1366 if (inAddresses[i].mSelector == kAudioStreamPropertyPhysicalFormat) {
1367 vlc_mutex_lock(&w->lock);
1368 vlc_cond_signal(&w->cond);
1369 vlc_mutex_unlock(&w->lock);
1377 #pragma mark helpers
1379 static int RegisterAudioStreamsCallback(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1381 OSStatus err = noErr;
1382 UInt32 i_param_size = 0;
1383 AudioStreamID *p_streams = NULL;
1386 /* Retrieve all the output streams */
1387 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1388 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1390 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1391 return VLC_EGENERIC;
1394 i_streams = i_param_size / sizeof(AudioStreamID);
1395 p_streams = (AudioStreamID *)malloc(i_param_size);
1396 if (p_streams == NULL)
1399 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1401 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1402 return VLC_EGENERIC;
1405 for (int i = 0; i < i_streams; i++) {
1406 /* get notified when physical formats change */
1407 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1408 err = AudioObjectAddPropertyListener(p_streams[i], &physicalFormatsAddress, HardwareListener, (void *)p_aout);
1410 // nope just means that we already have a callback
1411 if (err == kAudioHardwareIllegalOperationError) {
1412 msg_Dbg(p_aout, "could not set audio stream formats property callback on stream id %i, already have callback: %4.4s", p_streams[i],
1415 msg_Warn(p_aout, "could not set audio stream formats property callback on stream id %i: %4.4s", p_streams[i],
1426 * AudioDeviceHasOutput: Checks if the device is actually an output device
1428 static int AudioDeviceHasOutput(AudioDeviceID i_dev_id)
1430 UInt32 dataSize = 0;
1433 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1434 status = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &dataSize);
1436 if (dataSize == 0 || status != noErr)
1443 * AudioDeviceSupportsDigital: Checks if device supports raw bitstreams
1445 static int AudioDeviceSupportsDigital(audio_output_t *p_aout, AudioDeviceID i_dev_id)
1447 OSStatus err = noErr;
1448 UInt32 i_param_size = 0;
1449 AudioStreamID *p_streams = NULL;
1451 bool b_return = false;
1453 /* Retrieve all the output streams */
1454 AudioObjectPropertyAddress streamsAddress = { kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster };
1455 err = AudioObjectGetPropertyDataSize(i_dev_id, &streamsAddress, 0, NULL, &i_param_size);
1457 msg_Err(p_aout, "could not get number of streams: [%s] (%i)", (char *)&err, (int32_t)err);
1461 i_streams = i_param_size / sizeof(AudioStreamID);
1462 p_streams = (AudioStreamID *)malloc(i_param_size);
1463 if (p_streams == NULL)
1466 err = AudioObjectGetPropertyData(i_dev_id, &streamsAddress, 0, NULL, &i_param_size, p_streams);
1468 msg_Err(p_aout, "could not get list of streams: [%s]", (char *)&err);
1472 for (int i = 0; i < i_streams; i++) {
1473 if (AudioStreamSupportsDigital(p_aout, p_streams[i]))
1482 * AudioStreamSupportsDigital: Checks if audio stream is compatible with raw bitstreams
1484 static int AudioStreamSupportsDigital(audio_output_t *p_aout, AudioStreamID i_stream_id)
1486 OSStatus err = noErr;
1487 UInt32 i_param_size = 0;
1488 AudioStreamRangedDescription *p_format_list = NULL;
1490 bool b_return = false;
1492 /* Retrieve all the stream formats supported by each output stream */
1493 AudioObjectPropertyAddress physicalFormatsAddress = { kAudioStreamPropertyAvailablePhysicalFormats, kAudioObjectPropertyScopeGlobal, 0 };
1494 err = AudioObjectGetPropertyDataSize(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size);
1496 msg_Err(p_aout, "could not get number of streamformats: [%s] (%i)", (char *)&err, (int32_t)err);
1500 i_formats = i_param_size / sizeof(AudioStreamRangedDescription);
1501 msg_Dbg(p_aout, "found %i stream formats for stream id %i", i_formats, i_stream_id);
1503 p_format_list = (AudioStreamRangedDescription *)malloc(i_param_size);
1504 if (p_format_list == NULL)
1507 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatsAddress, 0, NULL, &i_param_size, p_format_list);
1509 msg_Err(p_aout, "could not get the list of streamformats: [%4.4s]", (char *)&err);
1510 free(p_format_list);
1511 p_format_list = NULL;
1515 for (int i = 0; i < i_formats; i++) {
1517 msg_Dbg(p_aout, STREAM_FORMAT_MSG("supported format: ", p_format_list[i].mFormat));
1520 if (p_format_list[i].mFormat.mFormatID == 'IAC3' ||
1521 p_format_list[i].mFormat.mFormatID == 'iac3' ||
1522 p_format_list[i].mFormat.mFormatID == kAudioFormat60958AC3 ||
1523 p_format_list[i].mFormat.mFormatID == kAudioFormatAC3)
1527 free(p_format_list);
1532 * AudioStreamChangeFormat: switch stream format based on the provided description
1534 static int AudioStreamChangeFormat(audio_output_t *p_aout, AudioStreamID i_stream_id, AudioStreamBasicDescription change_format)
1536 OSStatus err = noErr;
1537 UInt32 i_param_size = 0;
1539 AudioObjectPropertyAddress physicalFormatAddress = { kAudioStreamPropertyPhysicalFormat, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1541 struct { vlc_mutex_t lock; vlc_cond_t cond; } w;
1543 msg_Dbg(p_aout, STREAM_FORMAT_MSG("setting stream format: ", change_format));
1545 /* Condition because SetProperty is asynchronious */
1546 vlc_cond_init(&w.cond);
1547 vlc_mutex_init(&w.lock);
1548 vlc_mutex_lock(&w.lock);
1550 /* Install the callback */
1551 err = AudioObjectAddPropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1553 msg_Err(p_aout, "AudioObjectAddPropertyListener for kAudioStreamPropertyPhysicalFormat failed: [%4.4s]", (char *)&err);
1557 /* change the format */
1558 err = AudioObjectSetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, sizeof(AudioStreamBasicDescription),
1561 msg_Err(p_aout, "could not set the stream format: [%4.4s]", (char *)&err);
1565 /* The AudioStreamSetProperty is not only asynchronious (requiring the locks)
1566 * it is also not atomic in its behaviour.
1567 * Therefore we check 5 times before we really give up.
1568 * FIXME: failing isn't actually implemented yet. */
1569 for (int i = 0; i < 5; i++) {
1570 AudioStreamBasicDescription actual_format;
1571 mtime_t timeout = mdate() + 500000;
1573 if (vlc_cond_timedwait(&w.cond, &w.lock, timeout))
1574 msg_Dbg(p_aout, "reached timeout");
1576 i_param_size = sizeof(AudioStreamBasicDescription);
1577 err = AudioObjectGetPropertyData(i_stream_id, &physicalFormatAddress, 0, NULL, &i_param_size, &actual_format);
1579 msg_Dbg(p_aout, STREAM_FORMAT_MSG("actual format in use: ", actual_format));
1580 if (actual_format.mSampleRate == change_format.mSampleRate &&
1581 actual_format.mFormatID == change_format.mFormatID &&
1582 actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
1583 /* The right format is now active */
1586 /* We need to check again */
1589 /* Removing the property listener */
1590 err = AudioObjectRemovePropertyListener(i_stream_id, &physicalFormatAddress, StreamListener, (void *)&w);
1592 msg_Err(p_aout, "AudioStreamRemovePropertyListener failed: [%4.4s]", (char *)&err);
1596 /* Destroy the lock and condition */
1597 vlc_mutex_unlock(&w.lock);
1598 vlc_mutex_destroy(&w.lock);
1599 vlc_cond_destroy(&w.cond);