2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include <pbd/transmitter.h>
28 #include <pbd/xml++.h>
29 #include <pbd/whitespace.h>
30 #include <pbd/pathscanner.h>
31 #include <pbd/localeguard.h>
33 #include <glibmm/thread.h>
34 #include <glibmm/fileutils.h>
35 #include <glibmm/miscutils.h>
37 #include <ardour/ardour.h>
38 #include <ardour/audioengine.h>
39 #include <ardour/io.h>
40 #include <ardour/audio_unit.h>
41 #include <ardour/session.h>
42 #include <ardour/tempo.h>
43 #include <ardour/utils.h>
45 #include <appleutility/CAAudioUnit.h>
46 #include <appleutility/CAAUParameter.h>
48 #include <CoreFoundation/CoreFoundation.h>
49 #include <CoreServices/CoreServices.h>
50 #include <AudioUnit/AudioUnit.h>
51 #include <AudioToolbox/AudioUnitUtilities.h>
57 using namespace ARDOUR
;
59 //#define TRACE_AU_API
61 #define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
63 #define TRACE_API(fmt,...)
66 #ifndef AU_STATE_SUPPORT
67 static bool seen_get_state_message
= false;
68 static bool seen_set_state_message
= false;
69 static bool seen_loading_message
= false;
70 static bool seen_saving_message
= false;
73 AUPluginInfo::CachedInfoMap
AUPluginInfo::cached_info
;
75 static string preset_search_path
= "/Library/Audio/Presets:/Network/Library/Audio/Presets";
76 static string preset_suffix
= ".aupreset";
77 static bool preset_search_path_initialized
= false;
78 static bool debug_io_config
= true;
81 _render_callback(void *userData
,
82 AudioUnitRenderActionFlags
*ioActionFlags
,
83 const AudioTimeStamp
*inTimeStamp
,
85 UInt32 inNumberFrames
,
86 AudioBufferList
* ioData
)
89 return ((AUPlugin
*)userData
)->render_callback (ioActionFlags
, inTimeStamp
, inBusNumber
, inNumberFrames
, ioData
);
95 _get_beat_and_tempo_callback (void* userData
,
96 Float64
* outCurrentBeat
,
97 Float64
* outCurrentTempo
)
100 return ((AUPlugin
*)userData
)->get_beat_and_tempo_callback (outCurrentBeat
, outCurrentTempo
);
107 _get_musical_time_location_callback (void * userData
,
108 UInt32
* outDeltaSampleOffsetToNextBeat
,
109 Float32
* outTimeSig_Numerator
,
110 UInt32
* outTimeSig_Denominator
,
111 Float64
* outCurrentMeasureDownBeat
)
114 return ((AUPlugin
*)userData
)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat
,
115 outTimeSig_Numerator
,
116 outTimeSig_Denominator
,
117 outCurrentMeasureDownBeat
);
123 _get_transport_state_callback (void* userData
,
124 Boolean
* outIsPlaying
,
125 Boolean
* outTransportStateChanged
,
126 Float64
* outCurrentSampleInTimeLine
,
127 Boolean
* outIsCycling
,
128 Float64
* outCycleStartBeat
,
129 Float64
* outCycleEndBeat
)
132 return ((AUPlugin
*)userData
)->get_transport_state_callback (outIsPlaying
, outTransportStateChanged
,
133 outCurrentSampleInTimeLine
, outIsCycling
,
134 outCycleStartBeat
, outCycleEndBeat
);
141 save_property_list (CFPropertyListRef propertyList
, Glib::ustring path
)
147 // Convert the property list into XML data.
149 xmlData
= CFPropertyListCreateXMLData( kCFAllocatorDefault
, propertyList
);
152 error
<< _("Could not create XML version of property list") << endmsg
;
156 // Write the XML data to the file.
158 fd
= open (path
.c_str(), O_WRONLY
|O_CREAT
|O_EXCL
, 0664);
160 if (errno
== EEXIST
) {
161 /* tell any UI's that this file already exists and ask them what to do */
162 bool overwrite
= Plugin::PresetFileExists(); // EMIT SIGNAL
164 fd
= open (path
.c_str(), O_WRONLY
, 0664);
170 error
<< string_compose (_("Cannot open preset file %1 (%2)"), path
, strerror (errno
)) << endmsg
;
175 size_t cnt
= CFDataGetLength (xmlData
);
177 if (write (fd
, CFDataGetBytePtr (xmlData
), cnt
) != (ssize_t
) cnt
) {
188 static CFPropertyListRef
189 load_property_list (Glib::ustring path
)
192 CFPropertyListRef propertyList
;
194 CFStringRef errorString
;
196 // Read the XML file.
198 if ((fd
= open (path
.c_str(), O_RDONLY
)) < 0) {
203 off_t len
= lseek (fd
, 0, SEEK_END
);
204 char* buf
= new char[len
];
205 lseek (fd
, 0, SEEK_SET
);
207 if (read (fd
, buf
, len
) != len
) {
215 xmlData
= CFDataCreateWithBytesNoCopy (kCFAllocatorDefault
, (UInt8
*) buf
, len
, kCFAllocatorNull
);
217 // Reconstitute the dictionary using the XML data.
219 propertyList
= CFPropertyListCreateFromXMLData( kCFAllocatorDefault
,
221 kCFPropertyListImmutable
,
230 //-----------------------------------------------------------------------------
232 set_preset_name_in_plist (CFPropertyListRef plist
, string preset_name
)
237 CFStringRef pn
= CFStringCreateWithCString (kCFAllocatorDefault
, preset_name
.c_str(), kCFStringEncodingUTF8
);
239 if (CFGetTypeID (plist
) == CFDictionaryGetTypeID()) {
240 CFDictionarySetValue ((CFMutableDictionaryRef
)plist
, CFSTR(kAUPresetNameKey
), pn
);
246 //-----------------------------------------------------------------------------
248 get_preset_name_in_plist (CFPropertyListRef plist
)
256 if (CFGetTypeID (plist
) == CFDictionaryGetTypeID()) {
257 const void *p
= CFDictionaryGetValue ((CFMutableDictionaryRef
)plist
, CFSTR(kAUPresetNameKey
));
259 CFStringRef str
= (CFStringRef
) p
;
260 int len
= CFStringGetLength(str
);
262 char local_buffer
[len
];
263 if (CFStringGetCString (str
, local_buffer
, len
, kCFStringEncodingUTF8
)) {
271 //--------------------------------------------------------------------------
272 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
273 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
274 Boolean
ComponentDescriptionsMatch_General(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
, Boolean inIgnoreType
);
275 Boolean
ComponentDescriptionsMatch_General(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
, Boolean inIgnoreType
)
277 if ( (inComponentDescription1
== NULL
) || (inComponentDescription2
== NULL
) )
280 if ( (inComponentDescription1
->componentSubType
== inComponentDescription2
->componentSubType
)
281 && (inComponentDescription1
->componentManufacturer
== inComponentDescription2
->componentManufacturer
) )
283 // only sub-type and manufacturer IDs need to be equal
286 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
287 else if (inComponentDescription1
->componentType
== inComponentDescription2
->componentType
)
294 //--------------------------------------------------------------------------
295 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
296 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
297 Boolean
ComponentAndDescriptionMatch_General(Component inComponent
, const ComponentDescription
* inComponentDescription
, Boolean inIgnoreType
);
298 Boolean
ComponentAndDescriptionMatch_General(Component inComponent
, const ComponentDescription
* inComponentDescription
, Boolean inIgnoreType
)
301 ComponentDescription desc
;
303 if ( (inComponent
== NULL
) || (inComponentDescription
== NULL
) )
306 // get the ComponentDescription of the input Component
307 status
= GetComponentInfo(inComponent
, &desc
, NULL
, NULL
, NULL
);
311 // check if the Component's ComponentDescription matches the input ComponentDescription
312 return ComponentDescriptionsMatch_General(&desc
, inComponentDescription
, inIgnoreType
);
315 //--------------------------------------------------------------------------
316 // determine if 2 ComponentDescriptions are basically equal
317 // (by that, I mean that the important identifying values are compared,
318 // but not the ComponentDescription flags)
319 Boolean
ComponentDescriptionsMatch(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
)
321 return ComponentDescriptionsMatch_General(inComponentDescription1
, inComponentDescription2
, FALSE
);
324 //--------------------------------------------------------------------------
325 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
326 Boolean
ComponentDescriptionsMatch_Loose(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
)
328 return ComponentDescriptionsMatch_General(inComponentDescription1
, inComponentDescription2
, TRUE
);
331 //--------------------------------------------------------------------------
332 // determine if a ComponentDescription basically matches that of a particular Component
333 Boolean
ComponentAndDescriptionMatch(Component inComponent
, const ComponentDescription
* inComponentDescription
)
335 return ComponentAndDescriptionMatch_General(inComponent
, inComponentDescription
, FALSE
);
338 //--------------------------------------------------------------------------
339 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
340 Boolean
ComponentAndDescriptionMatch_Loosely(Component inComponent
, const ComponentDescription
* inComponentDescription
)
342 return ComponentAndDescriptionMatch_General(inComponent
, inComponentDescription
, TRUE
);
346 AUPlugin::AUPlugin (AudioEngine
& engine
, Session
& session
, boost::shared_ptr
<CAComponent
> _comp
)
347 : Plugin (engine
, session
)
349 , unit (new CAAudioUnit
)
350 , initialized (false)
351 , _current_block_size (0)
352 , _requires_fixed_size_buffers (false)
356 , current_buffers (0)
357 , frames_processed (0)
358 , last_transport_rolling (false)
359 , last_transport_speed (0.0)
361 if (!preset_search_path_initialized
) {
362 Glib::ustring p
= Glib::get_home_dir();
363 p
+= "/Library/Audio/Presets:";
364 p
+= preset_search_path
;
365 preset_search_path
= p
;
366 preset_search_path_initialized
= true;
372 AUPlugin::AUPlugin (const AUPlugin
& other
)
374 , comp (other
.get_comp())
375 , unit (new CAAudioUnit
)
376 , initialized (false)
377 , _current_block_size (0)
379 , _requires_fixed_size_buffers (false)
383 , current_buffers (0)
384 , frames_processed (0)
390 AUPlugin::~AUPlugin ()
393 TRACE_API ("about to call uninitialize in plugin destructor\n");
394 unit
->Uninitialize ();
403 AUPlugin::discover_factory_presets ()
406 UInt32 dataSize
= sizeof (presets
);
409 TRACE_API ("get property FactoryPresets in global scope\n");
410 if ((err
= unit
->GetProperty (kAudioUnitProperty_FactoryPresets
, kAudioUnitScope_Global
, 0, (void*) &presets
, &dataSize
)) != 0) {
411 cerr
<< "cannot get factory preset info: " << err
<< endl
;
419 CFIndex cnt
= CFArrayGetCount (presets
);
421 for (CFIndex i
= 0; i
< cnt
; ++i
) {
422 AUPreset
* preset
= (AUPreset
*) CFArrayGetValueAtIndex (presets
, i
);
424 string name
= CFStringRefToStdString (preset
->presetName
);
425 factory_preset_map
[name
] = preset
->presetNumber
;
437 TRACE_API ("opening AudioUnit\n");
438 err
= CAAudioUnit::Open (*(comp
.get()), *unit
);
440 error
<< _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg
;
441 throw failed_constructor();
445 error
<< _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg
;
446 throw failed_constructor ();
449 AURenderCallbackStruct renderCallbackInfo
;
451 renderCallbackInfo
.inputProc
= _render_callback
;
452 renderCallbackInfo
.inputProcRefCon
= this;
454 TRACE_API ("set render callback in input scope\n");
455 if ((err
= unit
->SetProperty (kAudioUnitProperty_SetRenderCallback
, kAudioUnitScope_Input
,
456 0, (void*) &renderCallbackInfo
, sizeof(renderCallbackInfo
))) != 0) {
457 cerr
<< "cannot install render callback (err = " << err
<< ')' << endl
;
458 throw failed_constructor();
461 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
463 HostCallbackInfo info
;
464 memset (&info
, 0, sizeof (HostCallbackInfo
));
465 info
.hostUserData
= this;
466 info
.beatAndTempoProc
= _get_beat_and_tempo_callback
;
467 info
.musicalTimeLocationProc
= _get_musical_time_location_callback
;
468 info
.transportStateProc
= _get_transport_state_callback
;
470 //ignore result of this - don't care if the property isn't supported
471 TRACE_API ("set host callbacks in global scope\n");
472 unit
->SetProperty (kAudioUnitProperty_HostCallbacks
,
473 kAudioUnitScope_Global
,
476 sizeof (HostCallbackInfo
));
478 TRACE_API ("count global elements\n");
479 unit
->GetElementCount (kAudioUnitScope_Global
, global_elements
);
480 TRACE_API ("count input elements\n");
481 unit
->GetElementCount (kAudioUnitScope_Input
, input_elements
);
482 TRACE_API ("count output elements\n");
483 unit
->GetElementCount (kAudioUnitScope_Output
, output_elements
);
485 /* these keep track of *configured* channel set up,
486 not potential set ups.
490 output_channels
= -1;
492 if (set_block_size (_session
.get_block_size())) {
493 error
<< _("AUPlugin: cannot set processing block size") << endmsg
;
494 throw failed_constructor();
497 discover_parameters ();
498 discover_factory_presets ();
500 Plugin::setup_controls ();
504 AUPlugin::discover_parameters ()
506 /* discover writable parameters */
508 AudioUnitScope scopes
[] = {
509 kAudioUnitScope_Global
,
510 kAudioUnitScope_Output
,
511 kAudioUnitScope_Input
514 descriptors
.clear ();
516 for (uint32_t i
= 0; i
< sizeof (scopes
) / sizeof (scopes
[0]); ++i
) {
518 AUParamInfo
param_info (unit
->AU(), false, false, scopes
[i
]);
520 for (uint32_t i
= 0; i
< param_info
.NumParams(); ++i
) {
522 AUParameterDescriptor d
;
524 d
.id
= param_info
.ParamID (i
);
526 const CAAUParameter
* param
= param_info
.GetParamInfo (d
.id
);
527 const AudioUnitParameterInfo
& info (param
->ParamInfo());
529 const int len
= CFStringGetLength (param
->GetName());;
530 char local_buffer
[len
*2];
531 Boolean good
= CFStringGetCString(param
->GetName(),local_buffer
,len
*2,kCFStringEncodingMacRoman
);
535 d
.label
= local_buffer
;
538 d
.scope
= param_info
.GetScope ();
539 d
.element
= param_info
.GetElement ();
541 /* info.units to consider */
543 kAudioUnitParameterUnit_Generic = 0
544 kAudioUnitParameterUnit_Indexed = 1
545 kAudioUnitParameterUnit_Boolean = 2
546 kAudioUnitParameterUnit_Percent = 3
547 kAudioUnitParameterUnit_Seconds = 4
548 kAudioUnitParameterUnit_SampleFrames = 5
549 kAudioUnitParameterUnit_Phase = 6
550 kAudioUnitParameterUnit_Rate = 7
551 kAudioUnitParameterUnit_Hertz = 8
552 kAudioUnitParameterUnit_Cents = 9
553 kAudioUnitParameterUnit_RelativeSemiTones = 10
554 kAudioUnitParameterUnit_MIDINoteNumber = 11
555 kAudioUnitParameterUnit_MIDIController = 12
556 kAudioUnitParameterUnit_Decibels = 13
557 kAudioUnitParameterUnit_LinearGain = 14
558 kAudioUnitParameterUnit_Degrees = 15
559 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
560 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
561 kAudioUnitParameterUnit_Pan = 18
562 kAudioUnitParameterUnit_Meters = 19
563 kAudioUnitParameterUnit_AbsoluteCents = 20
564 kAudioUnitParameterUnit_Octaves = 21
565 kAudioUnitParameterUnit_BPM = 22
566 kAudioUnitParameterUnit_Beats = 23
567 kAudioUnitParameterUnit_Milliseconds = 24
568 kAudioUnitParameterUnit_Ratio = 25
571 /* info.flags to consider */
575 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
576 kAudioUnitParameterFlag_HasClump = (1L << 20)
577 kAudioUnitParameterFlag_HasName = (1L << 21)
578 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
579 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
580 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
581 kAudioUnitParameterFlag_CanRamp = (1L << 25)
582 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
583 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
584 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
585 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
586 kAudioUnitParameterFlag_IsReadable = (1L << 30)
587 kAudioUnitParameterFlag_IsWritable = (1L << 31)
590 d
.lower
= info
.minValue
;
591 d
.upper
= info
.maxValue
;
592 d
.default_value
= info
.defaultValue
;
594 d
.integer_step
= (info
.unit
& kAudioUnitParameterUnit_Indexed
);
595 d
.toggled
= (info
.unit
& kAudioUnitParameterUnit_Boolean
) ||
596 (d
.integer_step
&& ((d
.upper
- d
.lower
) == 1.0));
597 d
.sr_dependent
= (info
.unit
& kAudioUnitParameterUnit_SampleFrames
);
598 d
.automatable
= !d
.toggled
&&
599 !(info
.flags
& kAudioUnitParameterFlag_NonRealTime
) &&
600 (info
.flags
& kAudioUnitParameterFlag_IsWritable
);
602 d
.logarithmic
= (info
.flags
& kAudioUnitParameterFlag_DisplayLogarithmic
);
608 d
.min_unbound
= 0; // lower is bound
609 d
.max_unbound
= 0; // upper is bound
611 descriptors
.push_back (d
);
618 four_ints_to_four_byte_literal (unsigned char n
[4])
620 /* this is actually implementation dependent. sigh. this is what gcc
621 and quite a few others do.
623 return ((n
[0] << 24) + (n
[1] << 16) + (n
[2] << 8) + n
[3]);
627 AUPlugin::maybe_fix_broken_au_id (const std::string
& id
)
629 if (isdigit (id
[0])) {
633 /* ID format is xxxx-xxxx-xxxx
634 where x maybe \xNN or a printable character.
636 Split at the '-' and and process each part into an integer.
637 Then put it back together.
641 unsigned char nascent
[4];
642 const char* cstr
= id
.c_str();
643 const char* estr
= cstr
+ id
.size();
654 while (*cstr
&& next_int
< 4) {
658 if (estr
- cstr
< 3) {
660 /* too close to the end for \xNN parsing: treat as literal characters */
662 cerr
<< "Parse " << cstr
<< " as a literal \\" << endl
;
669 if (cstr
[1] == 'x' && isxdigit (cstr
[2]) && isxdigit (cstr
[3])) {
673 memcpy (short_buf
, &cstr
[2], 2);
674 nascent
[in
] = strtol (short_buf
, NULL
, 16);
680 /* treat as literal characters */
681 cerr
<< "Parse " << cstr
<< " as a literal \\" << endl
;
695 if (in
&& (in
% 4 == 0)) {
696 /* nascent is ready */
697 n
[next_int
] = four_ints_to_four_byte_literal (nascent
);
701 /* swallow space-hyphen-space */
715 s
<< n
[0] << '-' << n
[1] << '-' << n
[2];
724 AUPlugin::unique_id () const
726 return AUPluginInfo::stringify_descriptor (comp
->Desc());
730 AUPlugin::label () const
732 return _info
->name
.c_str();
736 AUPlugin::parameter_count () const
738 return descriptors
.size();
742 AUPlugin::default_value (uint32_t port
)
744 if (port
< descriptors
.size()) {
745 return descriptors
[port
].default_value
;
752 AUPlugin::latency () const
754 return unit
->Latency() * _session
.frame_rate();
758 AUPlugin::set_parameter (uint32_t which
, float val
)
760 if (which
< descriptors
.size()) {
761 const AUParameterDescriptor
& d (descriptors
[which
]);
762 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d
.id
, d
.scope
, d
.element
, val
);
763 unit
->SetParameter (d
.id
, d
.scope
, d
.element
, val
);
765 /* tell the world what we did */
767 AudioUnitEvent theEvent
;
769 theEvent
.mEventType
= kAudioUnitEvent_ParameterValueChange
;
770 theEvent
.mArgument
.mParameter
.mAudioUnit
= unit
->AU();
771 theEvent
.mArgument
.mParameter
.mParameterID
= d
.id
;
772 theEvent
.mArgument
.mParameter
.mScope
= d
.scope
;
773 theEvent
.mArgument
.mParameter
.mElement
= d
.element
;
775 TRACE_API ("notify about parameter change\n");
776 AUEventListenerNotify (NULL
, NULL
, &theEvent
);
781 AUPlugin::get_parameter (uint32_t which
) const
784 if (which
< descriptors
.size()) {
785 const AUParameterDescriptor
& d (descriptors
[which
]);
786 TRACE_API ("get value of parameter %d in scope %d element %d\n", d
.id
, d
.scope
, d
.element
);
787 unit
->GetParameter(d
.id
, d
.scope
, d
.element
, val
);
793 AUPlugin::get_parameter_descriptor (uint32_t which
, ParameterDescriptor
& pd
) const
795 if (which
< descriptors
.size()) {
796 pd
= descriptors
[which
];
803 AUPlugin::nth_parameter (uint32_t which
, bool& ok
) const
805 if (which
< descriptors
.size()) {
814 AUPlugin::activate ()
818 TRACE_API ("call Initialize in activate()\n");
819 if ((err
= unit
->Initialize()) != noErr
) {
820 error
<< string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err
) << endmsg
;
822 frames_processed
= 0;
829 AUPlugin::deactivate ()
831 TRACE_API ("call Uninitialize in deactivate()\n");
832 unit
->Uninitialize ();
839 TRACE_API ("call Reset in flush()\n");
840 unit
->GlobalReset ();
844 AUPlugin::requires_fixed_size_buffers() const
846 return _requires_fixed_size_buffers
;
851 AUPlugin::set_block_size (nframes_t nframes
)
853 bool was_initialized
= initialized
;
854 UInt32 numFrames
= nframes
;
861 TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames
);
862 if ((err
= unit
->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice
, kAudioUnitScope_Global
,
863 0, &numFrames
, sizeof (numFrames
))) != noErr
) {
864 cerr
<< "cannot set max frames (err = " << err
<< ')' << endl
;
868 if (was_initialized
) {
872 _current_block_size
= nframes
;
878 AUPlugin::configure_io (int32_t in
, int32_t out
)
880 AudioStreamBasicDescription streamFormat
;
881 bool was_initialized
= initialized
;
884 //if we are already running with the requested i/o config, bail out here
885 if ( (in
==input_channels
) && (out
==output_channels
) ) {
892 streamFormat
.mSampleRate
= _session
.frame_rate();
893 streamFormat
.mFormatID
= kAudioFormatLinearPCM
;
894 streamFormat
.mFormatFlags
= kAudioFormatFlagIsFloat
|kAudioFormatFlagIsPacked
|kAudioFormatFlagIsNonInterleaved
;
896 #ifdef __LITTLE_ENDIAN__
899 streamFormat
.mFormatFlags
|= kAudioFormatFlagIsBigEndian
;
902 streamFormat
.mBitsPerChannel
= 32;
903 streamFormat
.mFramesPerPacket
= 1;
905 /* apple says that for non-interleaved data, these
906 values always refer to a single channel.
908 streamFormat
.mBytesPerPacket
= 4;
909 streamFormat
.mBytesPerFrame
= 4;
911 streamFormat
.mChannelsPerFrame
= in
;
913 if (set_input_format (streamFormat
) != 0) {
917 streamFormat
.mChannelsPerFrame
= out
;
919 if (set_output_format (streamFormat
) != 0) {
923 int ret
= Plugin::configure_io (in
, out
);
926 if (was_initialized
) {
935 AUPlugin::can_do (int32_t in
, int32_t& out
)
937 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
938 // attempt to multiply-instantiate plugins to meet io configurations.
940 int32_t plugcnt
= -1;
941 AUPluginInfoPtr pinfo
= boost::dynamic_pointer_cast
<AUPluginInfo
>(get_info());
943 vector
<pair
<int,int> >& io_configs
= pinfo
->cache
.io_configs
;
945 if (debug_io_config
) {
946 cerr
<< name() << " has " << io_configs
.size() << " IO Configurations\n";
949 //Ardour expects the plugin to tell it the output configuration
950 //but AU plugins can have multiple I/O configurations
951 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
952 //so first lets see if there's a configuration that keeps out==in
954 for (vector
<pair
<int,int> >::iterator i
= io_configs
.begin(); i
!= io_configs
.end(); ++i
) {
955 int32_t possible_in
= i
->first
;
956 int32_t possible_out
= i
->second
;
958 if (possible_in
== in
&& possible_out
== out
) {
959 cerr
<< "\tCHOSEN: in " << in
<< " out " << out
<< endl
;
964 /* now allow potentially "imprecise" matches */
966 for (vector
<pair
<int,int> >::iterator i
= io_configs
.begin(); i
!= io_configs
.end(); ++i
) {
968 int32_t possible_in
= i
->first
;
969 int32_t possible_out
= i
->second
;
971 if (debug_io_config
) {
972 cerr
<< "\tin " << possible_in
<< " out " << possible_out
<< endl
;
975 if (possible_out
== 0) {
976 warning
<< string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg
;
980 if (possible_in
== 0) {
982 /* instrument plugin, always legal but throws away inputs ...
985 if (possible_out
== -1) {
986 /* out much match in (UNLIKELY!!) */
989 } else if (possible_out
== -2) {
990 /* any configuration possible, pick matching */
993 } else if (possible_out
< -2) {
994 /* explicit variable number of outputs, pick maximum */
998 /* exact number of outputs */
1004 if (possible_in
== -1) {
1006 /* wildcard for input */
1008 if (possible_out
== -1) {
1009 /* out much match in */
1012 } else if (possible_out
== -2) {
1013 /* any configuration possible, pick matching */
1016 } else if (possible_out
< -2) {
1017 /* explicit variable number of outputs, pick maximum */
1018 out
= -possible_out
;
1021 /* exact number of outputs */
1027 if (possible_in
== -2) {
1029 if (possible_out
== -1) {
1030 /* any configuration possible, pick matching */
1033 } else if (possible_out
== -2) {
1034 error
<< string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1037 } else if (possible_out
< -2) {
1038 /* explicit variable number of outputs, pick maximum */
1039 out
= -possible_out
;
1042 /* exact number of outputs */
1048 if (possible_in
< -2) {
1050 /* explicit variable number of inputs */
1052 if (in
> -possible_in
) {
1053 /* request is too large */
1057 if (possible_out
== -1) {
1058 /* out must match in */
1061 } else if (possible_out
== -2) {
1062 error
<< string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1065 } else if (possible_out
< -2) {
1066 /* explicit variable number of outputs, pick maximum */
1067 out
= -possible_out
;
1070 /* exact number of outputs */
1076 if (possible_in
== in
) {
1078 /* exact number of inputs ... must match obviously */
1080 if (possible_out
== -1) {
1081 /* out must match in */
1084 } else if (possible_out
== -2) {
1085 /* any output configuration, pick matching */
1088 } else if (possible_out
< -2) {
1089 /* explicit variable number of outputs, pick maximum */
1090 out
= -possible_out
;
1093 /* exact number of outputs */
1105 if (debug_io_config
) {
1107 cerr
<< "\tCHOSEN: in " << in
<< " out " << out
<< " plugcnt will be " << plugcnt
<< endl
;
1109 cerr
<< "\tFAIL: no configs match requested in " << in
<< endl
;
1117 AUPlugin::set_input_format (AudioStreamBasicDescription
& fmt
)
1119 return set_stream_format (kAudioUnitScope_Input
, input_elements
, fmt
);
1123 AUPlugin::set_output_format (AudioStreamBasicDescription
& fmt
)
1125 if (set_stream_format (kAudioUnitScope_Output
, output_elements
, fmt
) != 0) {
1134 buffers
= (AudioBufferList
*) malloc (offsetof(AudioBufferList
, mBuffers
) +
1135 fmt
.mChannelsPerFrame
* sizeof(AudioBuffer
));
1137 Glib::Mutex::Lock
em (_session
.engine().process_lock());
1138 IO::MoreOutputs (fmt
.mChannelsPerFrame
);
1144 AUPlugin::set_stream_format (int scope
, uint32_t cnt
, AudioStreamBasicDescription
& fmt
)
1148 for (uint32_t i
= 0; i
< cnt
; ++i
) {
1149 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1150 (scope
== kAudioUnitScope_Input
? "input" : "output"),
1152 if ((result
= unit
->SetFormat (scope
, i
, fmt
)) != 0) {
1153 error
<< string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1154 (scope
== kAudioUnitScope_Input
? "input" : "output"), i
, result
) << endmsg
;
1159 if (scope
== kAudioUnitScope_Input
) {
1160 input_channels
= fmt
.mChannelsPerFrame
;
1162 output_channels
= fmt
.mChannelsPerFrame
;
1169 AUPlugin::input_streams() const
1171 if (input_channels
< 0) {
1172 warning
<< string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg
;
1175 return input_channels
;
1180 AUPlugin::output_streams() const
1182 if (output_channels
< 0) {
1183 warning
<< string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg
;
1186 return output_channels
;
1190 AUPlugin::render_callback(AudioUnitRenderActionFlags
*ioActionFlags
,
1191 const AudioTimeStamp
*inTimeStamp
,
1193 UInt32 inNumberFrames
,
1194 AudioBufferList
* ioData
)
1196 /* not much to do - the data is already in the buffers given to us in connect_and_run() */
1198 if (current_maxbuf
== 0) {
1199 error
<< _("AUPlugin: render callback called illegally!") << endmsg
;
1200 return kAudioUnitErr_CannotDoInCurrentContext
;
1202 uint32_t limit
= min ((uint32_t) ioData
->mNumberBuffers
, current_maxbuf
);
1203 for (uint32_t i
= 0; i
< limit
; ++i
) {
1204 ioData
->mBuffers
[i
].mNumberChannels
= 1;
1205 ioData
->mBuffers
[i
].mDataByteSize
= sizeof (Sample
) * inNumberFrames
;
1206 ioData
->mBuffers
[i
].mData
= (*current_buffers
)[i
] + cb_offset
+ current_offset
;
1207 // cerr << "chn " << i << " rendering from " << ioData->mBuffers[i].mData << endl;
1210 cb_offset
+= inNumberFrames
;
1216 AUPlugin::connect_and_run (vector
<Sample
*>& bufs
, uint32_t maxbuf
, int32_t& in
, int32_t& out
, nframes_t nframes
, nframes_t offset
)
1218 AudioUnitRenderActionFlags flags
= 0;
1222 if (requires_fixed_size_buffers() && (nframes
!= _last_nframes
)) {
1223 unit
->GlobalReset();
1224 _last_nframes
= nframes
;
1227 current_buffers
= &bufs
;
1228 current_maxbuf
= maxbuf
;
1229 current_offset
= offset
;
1232 buffers
->mNumberBuffers
= min ((uint32_t) output_channels
, maxbuf
);
1234 for (uint32_t i
= 0; i
< buffers
->mNumberBuffers
; ++i
) {
1235 buffers
->mBuffers
[i
].mNumberChannels
= 1;
1236 buffers
->mBuffers
[i
].mDataByteSize
= nframes
* sizeof (Sample
);
1237 buffers
->mBuffers
[i
].mData
= 0;
1240 ts
.mSampleTime
= frames_processed
;
1241 ts
.mFlags
= kAudioTimeStampSampleTimeValid
;
1243 if ((err
= unit
->Render (&flags
, &ts
, 0, nframes
, buffers
)) == noErr
) {
1246 frames_processed
+= nframes
;
1248 uint32_t limit
= min ((uint32_t) buffers
->mNumberBuffers
, maxbuf
);
1251 for (i
= 0; i
< limit
; ++i
) {
1252 if (bufs
[i
] + offset
!= buffers
->mBuffers
[i
].mData
) {
1253 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1254 memcpy (bufs
[i
]+offset
, buffers
->mBuffers
[i
].mData
, nframes
* sizeof (Sample
));
1258 /* now silence any buffers that were passed in but the that the plugin
1259 did not fill/touch/use.
1262 for (;i
< maxbuf
; ++i
) {
1263 memset (bufs
[i
]+offset
, 0, nframes
* sizeof (Sample
));
1269 // cerr << name() << " render error " << err << endl;
1275 AUPlugin::get_beat_and_tempo_callback (Float64
* outCurrentBeat
,
1276 Float64
* outCurrentTempo
)
1278 TempoMap
& tmap (_session
.tempo_map());
1280 TRACE_API ("AU calls ardour beat&tempo callback\n");
1282 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1283 (and interpretation) of a beat position will be incorrect. So refuse to
1287 if (tmap
.n_tempos() > 1 || tmap
.n_meters() > 1) {
1288 return kAudioUnitErr_CannotDoInCurrentContext
;
1292 TempoMap::Metric metric
= tmap
.metric_at (_session
.transport_frame() + current_offset
);
1293 tmap
.bbt_time_with_metric (_session
.transport_frame() + current_offset
, bbt
, metric
);
1295 if (outCurrentBeat
) {
1297 beat
= metric
.meter().beats_per_bar() * bbt
.bars
;
1299 beat
+= bbt
.ticks
/ Meter::ticks_per_beat
;
1300 *outCurrentBeat
= beat
;
1303 if (outCurrentTempo
) {
1304 *outCurrentTempo
= floor (metric
.tempo().beats_per_minute());
1312 AUPlugin::get_musical_time_location_callback (UInt32
* outDeltaSampleOffsetToNextBeat
,
1313 Float32
* outTimeSig_Numerator
,
1314 UInt32
* outTimeSig_Denominator
,
1315 Float64
* outCurrentMeasureDownBeat
)
1317 TempoMap
& tmap (_session
.tempo_map());
1319 TRACE_API ("AU calls ardour music time location callback\n");
1321 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1322 (and interpretation) of a beat position will be incorrect. So refuse to
1326 if (tmap
.n_tempos() > 1 || tmap
.n_meters() > 1) {
1327 return kAudioUnitErr_CannotDoInCurrentContext
;
1331 TempoMap::Metric metric
= tmap
.metric_at (_session
.transport_frame() + current_offset
);
1332 tmap
.bbt_time_with_metric (_session
.transport_frame() + current_offset
, bbt
, metric
);
1334 if (outDeltaSampleOffsetToNextBeat
) {
1335 if (bbt
.ticks
== 0) {
1337 *outDeltaSampleOffsetToNextBeat
= 0;
1339 *outDeltaSampleOffsetToNextBeat
= (UInt32
) floor (((Meter::ticks_per_beat
- bbt
.ticks
)/Meter::ticks_per_beat
) * // fraction of a beat to next beat
1340 metric
.tempo().frames_per_beat(_session
.frame_rate(), metric
.meter())); // frames per beat
1344 if (outTimeSig_Numerator
) {
1345 *outTimeSig_Numerator
= (UInt32
) lrintf (metric
.meter().beats_per_bar());
1347 if (outTimeSig_Denominator
) {
1348 *outTimeSig_Denominator
= (UInt32
) lrintf (metric
.meter().note_divisor());
1351 if (outCurrentMeasureDownBeat
) {
1353 /* beat for the start of the bar.
1355 2|1|0 -> 1 + beats_per_bar
1356 3|1|0 -> 1 + (2 * beats_per_bar)
1360 *outCurrentMeasureDownBeat
= 1 + metric
.meter().beats_per_bar() * (bbt
.bars
- 1);
1367 AUPlugin::get_transport_state_callback (Boolean
* outIsPlaying
,
1368 Boolean
* outTransportStateChanged
,
1369 Float64
* outCurrentSampleInTimeLine
,
1370 Boolean
* outIsCycling
,
1371 Float64
* outCycleStartBeat
,
1372 Float64
* outCycleEndBeat
)
1377 TRACE_API ("AU calls ardour transport state callback\n");
1379 rolling
= _session
.transport_rolling();
1380 speed
= _session
.transport_speed ();
1383 *outIsPlaying
= _session
.transport_rolling();
1386 if (outTransportStateChanged
) {
1387 if (rolling
!= last_transport_rolling
) {
1388 *outTransportStateChanged
= true;
1389 } else if (speed
!= last_transport_speed
) {
1390 *outTransportStateChanged
= true;
1392 *outTransportStateChanged
= false;
1396 if (outCurrentSampleInTimeLine
) {
1397 /* this assumes that the AU can only call this host callback from render context,
1398 where current_offset is valid.
1400 *outCurrentSampleInTimeLine
= _session
.transport_frame() + current_offset
;
1404 Location
* loc
= _session
.locations()->auto_loop_location();
1406 *outIsCycling
= (loc
&& _session
.transport_rolling() && _session
.get_play_loop());
1408 if (*outIsCycling
) {
1410 if (outCycleStartBeat
|| outCycleEndBeat
) {
1412 TempoMap
& tmap (_session
.tempo_map());
1414 /* more than 1 meter means that a simplistic computation (and interpretation) of
1415 a beat position will be incorrect. so refuse to offer the value.
1418 if (tmap
.n_meters() > 1) {
1419 return kAudioUnitErr_CannotDoInCurrentContext
;
1424 if (outCycleStartBeat
) {
1425 TempoMap::Metric metric
= tmap
.metric_at (loc
->start() + current_offset
);
1426 _session
.tempo_map().bbt_time_with_metric (loc
->start(), bbt
, metric
);
1429 beat
= metric
.meter().beats_per_bar() * bbt
.bars
;
1431 beat
+= bbt
.ticks
/ Meter::ticks_per_beat
;
1433 *outCycleStartBeat
= beat
;
1436 if (outCycleEndBeat
) {
1437 TempoMap::Metric metric
= tmap
.metric_at (loc
->end() + current_offset
);
1438 _session
.tempo_map().bbt_time_with_metric (loc
->end(), bbt
, metric
);
1441 beat
= metric
.meter().beats_per_bar() * bbt
.bars
;
1443 beat
+= bbt
.ticks
/ Meter::ticks_per_beat
;
1445 *outCycleEndBeat
= beat
;
1451 last_transport_rolling
= rolling
;
1452 last_transport_speed
= speed
;
1458 AUPlugin::automatable() const
1460 set
<uint32_t> automates
;
1462 for (uint32_t i
= 0; i
< descriptors
.size(); ++i
) {
1463 if (descriptors
[i
].automatable
) {
1464 automates
.insert (i
);
1472 AUPlugin::describe_parameter (uint32_t param
)
1474 return descriptors
[param
].label
;
1478 AUPlugin::print_parameter (uint32_t param
, char* buf
, uint32_t len
) const
1480 // NameValue stuff here
1484 AUPlugin::parameter_is_audio (uint32_t) const
1490 AUPlugin::parameter_is_control (uint32_t) const
1496 AUPlugin::parameter_is_input (uint32_t) const
1502 AUPlugin::parameter_is_output (uint32_t) const
1508 AUPlugin::get_state()
1510 LocaleGuard
lg (X_("POSIX"));
1511 XMLNode
*root
= new XMLNode (state_node_name());
1513 #ifdef AU_STATE_SUPPORT
1515 CFPropertyListRef propertyList
;
1517 TRACE_API ("get preset state\n");
1518 if (unit
->GetAUPreset (propertyList
) != noErr
) {
1522 // Convert the property list into XML data.
1524 xmlData
= CFPropertyListCreateXMLData( kCFAllocatorDefault
, propertyList
);
1527 error
<< _("Could not create XML version of property list") << endmsg
;
1531 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1532 our state node. GACK!
1537 if (t
.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData
), CFDataGetLength (xmlData
)))) {
1539 root
->add_child_copy (*t
.root());
1543 CFRelease (xmlData
);
1544 CFRelease (propertyList
);
1546 if (!seen_get_state_message
) {
1547 info
<< _("Saving AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1549 seen_get_state_message
= true;
1557 AUPlugin::set_state(const XMLNode
& node
)
1559 #ifdef AU_STATE_SUPPORT
1561 CFPropertyListRef propertyList
;
1562 LocaleGuard
lg (X_("POSIX"));
1564 if (node
.name() != state_node_name()) {
1565 error
<< _("Bad node sent to AUPlugin::set_state") << endmsg
;
1569 if (node
.children().empty()) {
1573 XMLNode
* top
= node
.children().front();
1574 XMLNode
* copy
= new XMLNode (*top
);
1579 const string
& xml
= t
.write_buffer ();
1580 CFDataRef xmlData
= CFDataCreateWithBytesNoCopy (kCFAllocatorDefault
, (UInt8
*) xml
.data(), xml
.length(), kCFAllocatorNull
);
1581 CFStringRef errorString
;
1583 propertyList
= CFPropertyListCreateFromXMLData( kCFAllocatorDefault
,
1585 kCFPropertyListImmutable
,
1588 CFRelease (xmlData
);
1591 TRACE_API ("set preset\n");
1592 if (unit
->SetAUPreset (propertyList
) == noErr
) {
1595 /* tell the world */
1597 AudioUnitParameter changedUnit
;
1598 changedUnit
.mAudioUnit
= unit
->AU();
1599 changedUnit
.mParameterID
= kAUParameterListener_AnyParameter
;
1600 AUParameterListenerNotify (NULL
, NULL
, &changedUnit
);
1602 CFRelease (propertyList
);
1607 if (!seen_set_state_message
) {
1608 info
<< _("Restoring AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1616 AUPlugin::load_preset (const string preset_label
)
1618 #ifdef AU_STATE_SUPPORT
1620 CFPropertyListRef propertyList
;
1622 UserPresetMap::iterator ux
;
1623 FactoryPresetMap::iterator fx
;
1625 /* look first in "user" presets */
1627 if ((ux
= user_preset_map
.find (preset_label
)) != user_preset_map
.end()) {
1629 if ((propertyList
= load_property_list (ux
->second
)) != 0) {
1630 TRACE_API ("set preset from user presets\n");
1631 if (unit
->SetAUPreset (propertyList
) == noErr
) {
1634 /* tell the world */
1636 AudioUnitParameter changedUnit
;
1637 changedUnit
.mAudioUnit
= unit
->AU();
1638 changedUnit
.mParameterID
= kAUParameterListener_AnyParameter
;
1639 AUParameterListenerNotify (NULL
, NULL
, &changedUnit
);
1641 CFRelease(propertyList
);
1644 } else if ((fx
= factory_preset_map
.find (preset_label
)) != factory_preset_map
.end()) {
1648 preset
.presetNumber
= fx
->second
;
1649 preset
.presetName
= CFStringCreateWithCString (kCFAllocatorDefault
, fx
->first
.c_str(), kCFStringEncodingUTF8
);
1651 TRACE_API ("set preset from factory presets\n");
1653 if (unit
->SetPresentPreset (preset
) == 0) {
1656 /* tell the world */
1658 AudioUnitParameter changedUnit
;
1659 changedUnit
.mAudioUnit
= unit
->AU();
1660 changedUnit
.mParameterID
= kAUParameterListener_AnyParameter
;
1661 AUParameterListenerNotify (NULL
, NULL
, &changedUnit
);
1667 if (!seen_loading_message
) {
1668 info
<< _("Loading AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1670 seen_loading_message
= true;
1677 AUPlugin::save_preset (string preset_name
)
1679 #ifdef AU_STATE_SUPPORT
1680 CFPropertyListRef propertyList
;
1681 vector
<Glib::ustring
> v
;
1682 Glib::ustring user_preset_path
;
1685 std::string m
= maker();
1686 std::string n
= name();
1688 strip_whitespace_edges (m
);
1689 strip_whitespace_edges (n
);
1691 v
.push_back (Glib::get_home_dir());
1692 v
.push_back ("Library");
1693 v
.push_back ("Audio");
1694 v
.push_back ("Presets");
1698 user_preset_path
= Glib::build_filename (v
);
1700 if (g_mkdir_with_parents (user_preset_path
.c_str(), 0775) < 0) {
1701 error
<< string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path
) << endmsg
;
1705 TRACE_API ("get current preset\n");
1706 if (unit
->GetAUPreset (propertyList
) != noErr
) {
1710 // add the actual preset name */
1712 v
.push_back (preset_name
+ preset_suffix
);
1716 user_preset_path
= Glib::build_filename (v
);
1718 set_preset_name_in_plist (propertyList
, preset_name
);
1720 if (save_property_list (propertyList
, user_preset_path
)) {
1721 error
<< string_compose (_("Saving plugin state to %1 failed"), user_preset_path
) << endmsg
;
1725 CFRelease(propertyList
);
1729 if (!seen_saving_message
) {
1730 info
<< _("Saving AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1732 seen_saving_message
= true;
1738 //-----------------------------------------------------------------------------
1739 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1741 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary
, CFStringRef inDictionaryKey
, Boolean
* outSuccess
)
1743 CFNumberRef cfNumber
;
1744 SInt32 numberValue
= 0;
1745 Boolean dummySuccess
;
1747 if (outSuccess
== NULL
)
1748 outSuccess
= &dummySuccess
;
1749 if ( (inAUStateDictionary
== NULL
) || (inDictionaryKey
== NULL
) )
1751 *outSuccess
= FALSE
;
1755 cfNumber
= (CFNumberRef
) CFDictionaryGetValue(inAUStateDictionary
, inDictionaryKey
);
1756 if (cfNumber
== NULL
)
1758 *outSuccess
= FALSE
;
1761 *outSuccess
= CFNumberGetValue(cfNumber
, kCFNumberSInt32Type
, &numberValue
);
1769 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData
, ComponentDescription
* outComponentDescription
)
1771 CFDictionaryRef auStateDictionary
;
1772 ComponentDescription tempDesc
= {0};
1773 SInt32 versionValue
;
1776 if ( (inAUStateData
== NULL
) || (outComponentDescription
== NULL
) )
1779 // the property list for AU state data must be of the dictionary type
1780 if (CFGetTypeID(inAUStateData
) != CFDictionaryGetTypeID()) {
1781 return kAudioUnitErr_InvalidPropertyValue
;
1784 auStateDictionary
= (CFDictionaryRef
)inAUStateData
;
1786 // first check to make sure that the version of the AU state data is one that we know understand
1787 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1788 versionValue
= GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetVersionKey
), &gotValue
);
1791 return kAudioUnitErr_InvalidPropertyValue
;
1793 #define kCurrentSavedStateVersion 0
1794 if (versionValue
!= kCurrentSavedStateVersion
) {
1795 return kAudioUnitErr_InvalidPropertyValue
;
1798 // grab the ComponentDescription values from the AU state data
1799 tempDesc
.componentType
= (OSType
) GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetTypeKey
), NULL
);
1800 tempDesc
.componentSubType
= (OSType
) GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetSubtypeKey
), NULL
);
1801 tempDesc
.componentManufacturer
= (OSType
) GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetManufacturerKey
), NULL
);
1802 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1803 if ( (tempDesc
.componentType
== 0) || (tempDesc
.componentSubType
== 0) || (tempDesc
.componentManufacturer
== 0) )
1804 return kAudioUnitErr_InvalidPropertyValue
;
1806 *outComponentDescription
= tempDesc
;
1811 static bool au_preset_filter (const string
& str
, void* arg
)
1813 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1817 ret
= (str
[0] != '.' && str
.length() > 9 && str
.find (preset_suffix
) == (str
.length() - preset_suffix
.length()));
1821 /* check the preset file path name against this plugin
1822 ID. The idea is that all preset files for this plugin
1823 include "<manufacturer>/<plugin-name>" in their path.
1826 Plugin
* p
= (Plugin
*) arg
;
1827 string match
= p
->maker();
1831 ret
= str
.find (match
) != string::npos
;
1834 string m
= p
->maker ();
1835 string n
= p
->name ();
1836 strip_whitespace_edges (m
);
1837 strip_whitespace_edges (n
);
1842 ret
= str
.find (match
) != string::npos
;
1850 check_and_get_preset_name (Component component
, const string
& pathstr
, string
& preset_name
)
1853 CFPropertyListRef plist
;
1854 ComponentDescription presetDesc
;
1857 plist
= load_property_list (pathstr
);
1863 // get the ComponentDescription from the AU preset file
1865 status
= GetAUComponentDescriptionFromStateData(plist
, &presetDesc
);
1867 if (status
== noErr
) {
1868 if (ComponentAndDescriptionMatch_Loosely(component
, &presetDesc
)) {
1870 /* try to get the preset name from the property list */
1872 if (CFGetTypeID(plist
) == CFDictionaryGetTypeID()) {
1874 const void* psk
= CFDictionaryGetValue ((CFMutableDictionaryRef
)plist
, CFSTR(kAUPresetNameKey
));
1878 const char* p
= CFStringGetCStringPtr ((CFStringRef
) psk
, kCFStringEncodingUTF8
);
1881 char buf
[PATH_MAX
+1];
1883 if (CFStringGetCString ((CFStringRef
)psk
, buf
, sizeof (buf
), kCFStringEncodingUTF8
)) {
1898 AUPlugin::current_preset() const
1902 #ifdef AU_STATE_SUPPORT
1903 CFPropertyListRef propertyList
;
1905 TRACE_API ("get current preset for current_preset()\n");
1906 if (unit
->GetAUPreset (propertyList
) == noErr
) {
1907 preset_name
= get_preset_name_in_plist (propertyList
);
1908 CFRelease(propertyList
);
1915 AUPlugin::get_presets ()
1917 vector
<string
> presets
;
1919 #ifdef AU_STATE_SUPPORT
1920 vector
<string
*>* preset_files
;
1921 PathScanner scanner
;
1923 user_preset_map
.clear ();
1925 preset_files
= scanner (preset_search_path
, au_preset_filter
, this, true, true, -1, true);
1927 if (!preset_files
) {
1931 for (vector
<string
*>::iterator x
= preset_files
->begin(); x
!= preset_files
->end(); ++x
) {
1933 string path
= *(*x
);
1936 /* make an initial guess at the preset name using the path */
1938 preset_name
= Glib::path_get_basename (path
);
1939 preset_name
= preset_name
.substr (0, preset_name
.find_last_of ('.'));
1941 /* check that this preset file really matches this plugin
1942 and potentially get the "real" preset name from
1946 if (check_and_get_preset_name (get_comp()->Comp(), path
, preset_name
)) {
1947 user_preset_map
[preset_name
] = path
;
1953 delete preset_files
;
1955 /* now fill the vector<string> with the names we have */
1957 for (UserPresetMap::iterator i
= user_preset_map
.begin(); i
!= user_preset_map
.end(); ++i
) {
1958 presets
.push_back (i
->first
);
1961 /* add factory presets */
1963 for (FactoryPresetMap::iterator i
= factory_preset_map
.begin(); i
!= factory_preset_map
.end(); ++i
) {
1964 presets
.push_back (i
->first
);
1973 AUPlugin::has_editor () const
1975 // even if the plugin doesn't have its own editor, the AU API can be used
1976 // to create one that looks native.
1980 AUPluginInfo::AUPluginInfo (boost::shared_ptr
<CAComponentDescription
> d
)
1983 type
= ARDOUR::AudioUnit
;
1986 AUPluginInfo::~AUPluginInfo ()
1988 type
= ARDOUR::AudioUnit
;
1992 AUPluginInfo::load (Session
& session
)
1997 TRACE_API ("load AU as a component\n");
1998 boost::shared_ptr
<CAComponent
> comp (new CAComponent(*descriptor
));
2000 if (!comp
->IsValid()) {
2001 error
<< ("AudioUnit: not a valid Component") << endmsg
;
2003 plugin
.reset (new AUPlugin (session
.engine(), session
, comp
));
2006 AUPluginInfo
*aup
= new AUPluginInfo (*this);
2007 plugin
->set_info (PluginInfoPtr (aup
));
2008 boost::dynamic_pointer_cast
<AUPlugin
> (plugin
)->set_fixed_size_buffers (aup
->creator
== "Universal Audio");
2012 catch (failed_constructor
&err
) {
2013 return PluginPtr ();
2018 AUPluginInfo::au_cache_path ()
2020 return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
2024 AUPluginInfo::discover ()
2028 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS
)) {
2029 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2032 PluginInfoList plugs
;
2034 discover_fx (plugs
);
2035 discover_music (plugs
);
2036 discover_generators (plugs
);
2042 AUPluginInfo::discover_music (PluginInfoList
& plugs
)
2044 CAComponentDescription desc
;
2045 desc
.componentFlags
= 0;
2046 desc
.componentFlagsMask
= 0;
2047 desc
.componentSubType
= 0;
2048 desc
.componentManufacturer
= 0;
2049 desc
.componentType
= kAudioUnitType_MusicEffect
;
2051 discover_by_description (plugs
, desc
);
2055 AUPluginInfo::discover_fx (PluginInfoList
& plugs
)
2057 CAComponentDescription desc
;
2058 desc
.componentFlags
= 0;
2059 desc
.componentFlagsMask
= 0;
2060 desc
.componentSubType
= 0;
2061 desc
.componentManufacturer
= 0;
2062 desc
.componentType
= kAudioUnitType_Effect
;
2064 discover_by_description (plugs
, desc
);
2068 AUPluginInfo::discover_generators (PluginInfoList
& plugs
)
2070 CAComponentDescription desc
;
2071 desc
.componentFlags
= 0;
2072 desc
.componentFlagsMask
= 0;
2073 desc
.componentSubType
= 0;
2074 desc
.componentManufacturer
= 0;
2075 desc
.componentType
= kAudioUnitType_Generator
;
2077 discover_by_description (plugs
, desc
);
2081 AUPluginInfo::discover_by_description (PluginInfoList
& plugs
, CAComponentDescription
& desc
)
2085 comp
= FindNextComponent (NULL
, &desc
);
2087 while (comp
!= NULL
) {
2088 CAComponentDescription temp
;
2089 GetComponentInfo (comp
, &temp
, NULL
, NULL
, NULL
);
2091 AUPluginInfoPtr
info (new AUPluginInfo
2092 (boost::shared_ptr
<CAComponentDescription
> (new CAComponentDescription(temp
))));
2094 /* although apple designed the subtype field to be a "category" indicator,
2095 its really turned into a plugin ID field for a given manufacturer. Hence
2096 there are no categories for AudioUnits. However, to keep the plugins
2097 showing up under "categories", we'll use the "type" as a high level
2100 NOTE: no panners, format converters or i/o AU's for our purposes
2103 switch (info
->descriptor
->Type()) {
2104 case kAudioUnitType_Panner
:
2105 case kAudioUnitType_OfflineEffect
:
2106 case kAudioUnitType_FormatConverter
:
2109 case kAudioUnitType_Output
:
2110 info
->category
= _("AudioUnit Outputs");
2112 case kAudioUnitType_MusicDevice
:
2113 info
->category
= _("AudioUnit Instruments");
2115 case kAudioUnitType_MusicEffect
:
2116 info
->category
= _("AudioUnit MusicEffects");
2118 case kAudioUnitType_Effect
:
2119 info
->category
= _("AudioUnit Effects");
2121 case kAudioUnitType_Mixer
:
2122 info
->category
= _("AudioUnit Mixers");
2124 case kAudioUnitType_Generator
:
2125 info
->category
= _("AudioUnit Generators");
2128 info
->category
= _("AudioUnit (Unknown)");
2132 AUPluginInfo::get_names (temp
, info
->name
, info
->creator
);
2134 info
->type
= ARDOUR::AudioUnit
;
2135 info
->unique_id
= stringify_descriptor (*info
->descriptor
);
2137 /* XXX not sure of the best way to handle plugin versioning yet
2140 CAComponent
cacomp (*info
->descriptor
);
2142 if (cacomp
.GetResourceVersion (info
->version
) != noErr
) {
2146 if (cached_io_configuration (info
->unique_id
, info
->version
, cacomp
, info
->cache
, info
->name
)) {
2148 /* here we have to map apple's wildcard system to a simple pair
2149 of values. in ::can_do() we use the whole system, but here
2150 we need a single pair of values. XXX probably means we should
2151 remove any use of these values.
2154 info
->n_inputs
= info
->cache
.io_configs
.front().first
;
2155 info
->n_outputs
= info
->cache
.io_configs
.front().second
;
2157 cerr
<< "detected AU: " << info
->name
.c_str() << " (" << info
->cache
.io_configs
.size() << " i/o configurations) - " << info
->unique_id
<< endl
;
2159 plugs
.push_back (info
);
2162 error
<< string_compose (_("Cannot get I/O configuration info for AU %1"), info
->name
) << endmsg
;
2165 comp
= FindNextComponent (comp
, &desc
);
2170 AUPluginInfo::cached_io_configuration (const std::string
& unique_id
,
2173 AUPluginCachedInfo
& cinfo
,
2174 const std::string
& name
)
2179 /* concatenate unique ID with version to provide a key for cached info lookup.
2180 this ensures we don't get stale information, or should if plugin developers
2181 follow Apple "guidelines".
2184 snprintf (buf
, sizeof (buf
), "%u", (uint32_t) version
);
2189 CachedInfoMap::iterator cim
= cached_info
.find (id
);
2191 if (cim
!= cached_info
.end()) {
2192 cinfo
= cim
->second
;
2197 AUChannelInfo
* channel_info
;
2201 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name
));
2205 if (CAAudioUnit::Open (comp
, unit
) != noErr
) {
2211 warning
<< string_compose (_("Could not load AU plugin %1 - ignored"), name
) << endmsg
;
2212 cerr
<< string_compose (_("Could not load AU plugin %1 - ignored"), name
) << endl
;
2217 TRACE_API ("get AU channel info\n");
2218 if ((ret
= unit
.GetChannelInfo (&channel_info
, cnt
)) < 0) {
2223 /* no explicit info available */
2225 cinfo
.io_configs
.push_back (pair
<int,int> (-1, -1));
2229 /* store each configuration */
2231 for (uint32_t n
= 0; n
< cnt
; ++n
) {
2232 cinfo
.io_configs
.push_back (pair
<int,int> (channel_info
[n
].inChannels
,
2233 channel_info
[n
].outChannels
));
2236 free (channel_info
);
2239 add_cached_info (id
, cinfo
);
2240 save_cached_info ();
2246 AUPluginInfo::add_cached_info (const std::string
& id
, AUPluginCachedInfo
& cinfo
)
2248 cached_info
[id
] = cinfo
;
2251 #define AU_CACHE_VERSION "2.0"
2254 AUPluginInfo::save_cached_info ()
2258 node
= new XMLNode (X_("AudioUnitPluginCache"));
2259 node
->add_property( "version", AU_CACHE_VERSION
);
2261 for (map
<string
,AUPluginCachedInfo
>::iterator i
= cached_info
.begin(); i
!= cached_info
.end(); ++i
) {
2262 XMLNode
* parent
= new XMLNode (X_("plugin"));
2263 parent
->add_property ("id", i
->first
);
2264 node
->add_child_nocopy (*parent
);
2266 for (vector
<pair
<int, int> >::iterator j
= i
->second
.io_configs
.begin(); j
!= i
->second
.io_configs
.end(); ++j
) {
2268 XMLNode
* child
= new XMLNode (X_("io"));
2271 snprintf (buf
, sizeof (buf
), "%d", j
->first
);
2272 child
->add_property (X_("in"), buf
);
2273 snprintf (buf
, sizeof (buf
), "%d", j
->second
);
2274 child
->add_property (X_("out"), buf
);
2275 parent
->add_child_nocopy (*child
);
2280 Glib::ustring path
= au_cache_path ();
2283 tree
.set_root (node
);
2285 if (!tree
.write (path
)) {
2286 error
<< string_compose (_("could not save AU cache to %1"), path
) << endmsg
;
2287 unlink (path
.c_str());
2292 AUPluginInfo::load_cached_info ()
2294 Glib::ustring path
= au_cache_path ();
2297 if (!Glib::file_test (path
, Glib::FILE_TEST_EXISTS
)) {
2301 if ( !tree
.read (path
) ) {
2302 error
<< "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg
;
2306 const XMLNode
* root (tree
.root());
2308 if (root
->name() != X_("AudioUnitPluginCache")) {
2312 //initial version has incorrectly stored i/o info, and/or garbage chars.
2313 const XMLProperty
* version
= root
->property(X_("version"));
2314 if (! ((version
!= NULL
) && (version
->value() == X_(AU_CACHE_VERSION
)))) {
2315 error
<< "au_cache is not correct version. AU plugins will be re-scanned" << endmsg
;
2319 cached_info
.clear ();
2321 const XMLNodeList children
= root
->children();
2323 for (XMLNodeConstIterator iter
= children
.begin(); iter
!= children
.end(); ++iter
) {
2325 const XMLNode
* child
= *iter
;
2327 if (child
->name() == X_("plugin")) {
2329 const XMLNode
* gchild
;
2330 const XMLNodeList gchildren
= child
->children();
2331 const XMLProperty
* prop
= child
->property (X_("id"));
2337 string id
= prop
->value();
2341 string::size_type slash
= id
.find_last_of ('/');
2343 if (slash
== string::npos
) {
2347 version
= id
.substr (slash
);
2348 id
= id
.substr (0, slash
);
2349 fixed
= AUPlugin::maybe_fix_broken_au_id (id
);
2351 if (fixed
.empty()) {
2352 error
<< string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id
) << endmsg
;
2359 AUPluginCachedInfo cinfo
;
2361 for (XMLNodeConstIterator giter
= gchildren
.begin(); giter
!= gchildren
.end(); giter
++) {
2365 if (gchild
->name() == X_("io")) {
2369 const XMLProperty
* iprop
;
2370 const XMLProperty
* oprop
;
2372 if (((iprop
= gchild
->property (X_("in"))) != 0) &&
2373 ((oprop
= gchild
->property (X_("out"))) != 0)) {
2374 in
= atoi (iprop
->value());
2375 out
= atoi (oprop
->value());
2377 cinfo
.io_configs
.push_back (pair
<int,int> (in
, out
));
2382 if (cinfo
.io_configs
.size()) {
2383 add_cached_info (id
, cinfo
);
2392 AUPluginInfo::get_names (CAComponentDescription
& comp_desc
, std::string
& name
, Glib::ustring
& maker
)
2394 CFStringRef itemName
= NULL
;
2396 // Marc Poirier-style item name
2397 CAComponent
auComponent (comp_desc
);
2398 if (auComponent
.IsValid()) {
2399 CAComponentDescription dummydesc
;
2400 Handle nameHandle
= NewHandle(sizeof(void*));
2401 if (nameHandle
!= NULL
) {
2402 OSErr err
= GetComponentInfo(auComponent
.Comp(), &dummydesc
, nameHandle
, NULL
, NULL
);
2404 ConstStr255Param nameString
= (ConstStr255Param
) (*nameHandle
);
2405 if (nameString
!= NULL
) {
2406 itemName
= CFStringCreateWithPascalString(kCFAllocatorDefault
, nameString
, CFStringGetSystemEncoding());
2409 DisposeHandle(nameHandle
);
2413 // if Marc-style fails, do the original way
2414 if (itemName
== NULL
) {
2415 CFStringRef compTypeString
= UTCreateStringForOSType(comp_desc
.componentType
);
2416 CFStringRef compSubTypeString
= UTCreateStringForOSType(comp_desc
.componentSubType
);
2417 CFStringRef compManufacturerString
= UTCreateStringForOSType(comp_desc
.componentManufacturer
);
2419 itemName
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("%@ - %@ - %@"),
2420 compTypeString
, compManufacturerString
, compSubTypeString
);
2422 if (compTypeString
!= NULL
)
2423 CFRelease(compTypeString
);
2424 if (compSubTypeString
!= NULL
)
2425 CFRelease(compSubTypeString
);
2426 if (compManufacturerString
!= NULL
)
2427 CFRelease(compManufacturerString
);
2430 string str
= CFStringRefToStdString(itemName
);
2431 string::size_type colon
= str
.find (':');
2434 name
= str
.substr (colon
+1);
2435 maker
= str
.substr (0, colon
);
2436 strip_whitespace_edges (maker
);
2437 strip_whitespace_edges (name
);
2441 strip_whitespace_edges (name
);
2446 AUPluginInfo::stringify_descriptor (const CAComponentDescription
& desc
)
2450 /* note: OSType is a compiler-implemenation-defined value,
2451 historically a 32 bit integer created with a multi-character
2452 constant such as 'abcd'. It is, fundamentally, an abomination.
2457 s
<< desc
.SubType();