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.
26 #include <pbd/transmitter.h>
27 #include <pbd/xml++.h>
28 #include <pbd/whitespace.h>
29 #include <pbd/pathscanner.h>
31 #include <glibmm/thread.h>
32 #include <glibmm/fileutils.h>
33 #include <glibmm/miscutils.h>
35 #include <ardour/ardour.h>
36 #include <ardour/audioengine.h>
37 #include <ardour/io.h>
38 #include <ardour/audio_unit.h>
39 #include <ardour/session.h>
40 #include <ardour/tempo.h>
41 #include <ardour/utils.h>
43 #include <appleutility/CAAudioUnit.h>
44 #include <appleutility/CAAUParameter.h>
46 #include <CoreFoundation/CoreFoundation.h>
47 #include <CoreServices/CoreServices.h>
48 #include <AudioUnit/AudioUnit.h>
49 #include <AudioToolbox/AudioUnitUtilities.h>
55 using namespace ARDOUR;
57 #ifndef AU_STATE_SUPPORT
58 static bool seen_get_state_message = false;
59 static bool seen_set_state_message = false;
60 static bool seen_loading_message = false;
61 static bool seen_saving_message = false;
64 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
66 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
67 static string preset_suffix = ".aupreset";
68 static bool preset_search_path_initialized = false;
71 _render_callback(void *userData,
72 AudioUnitRenderActionFlags *ioActionFlags,
73 const AudioTimeStamp *inTimeStamp,
75 UInt32 inNumberFrames,
76 AudioBufferList* ioData)
79 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
85 _get_beat_and_tempo_callback (void* userData,
86 Float64* outCurrentBeat,
87 Float64* outCurrentTempo)
90 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
97 _get_musical_time_location_callback (void * userData,
98 UInt32 * outDeltaSampleOffsetToNextBeat,
99 Float32 * outTimeSig_Numerator,
100 UInt32 * outTimeSig_Denominator,
101 Float64 * outCurrentMeasureDownBeat)
104 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
105 outTimeSig_Numerator,
106 outTimeSig_Denominator,
107 outCurrentMeasureDownBeat);
113 _get_transport_state_callback (void* userData,
114 Boolean* outIsPlaying,
115 Boolean* outTransportStateChanged,
116 Float64* outCurrentSampleInTimeLine,
117 Boolean* outIsCycling,
118 Float64* outCycleStartBeat,
119 Float64* outCycleEndBeat)
122 return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
123 outCurrentSampleInTimeLine, outIsCycling,
124 outCycleStartBeat, outCycleEndBeat);
131 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
137 // Convert the property list into XML data.
139 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
142 error << _("Could not create XML version of property list") << endmsg;
146 // Write the XML data to the file.
148 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
150 if (errno == EEXIST) {
151 /* tell any UI's that this file already exists and ask them what to do */
152 bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
154 fd = open (path.c_str(), O_WRONLY, 0664);
160 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
165 size_t cnt = CFDataGetLength (xmlData);
167 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
178 static CFPropertyListRef
179 load_property_list (Glib::ustring path)
182 CFPropertyListRef propertyList;
184 CFStringRef errorString;
186 // Read the XML file.
188 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
193 off_t len = lseek (fd, 0, SEEK_END);
194 char* buf = new char[len];
195 lseek (fd, 0, SEEK_SET);
197 if (read (fd, buf, len) != len) {
205 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
207 // Reconstitute the dictionary using the XML data.
209 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
211 kCFPropertyListImmutable,
220 //-----------------------------------------------------------------------------
222 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
227 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
229 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
230 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
236 //-----------------------------------------------------------------------------
238 get_preset_name_in_plist (CFPropertyListRef plist)
246 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
247 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
249 CFStringRef str = (CFStringRef) p;
250 int len = CFStringGetLength(str);
252 char local_buffer[len];
253 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
261 //--------------------------------------------------------------------------
262 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
263 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
264 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
265 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
267 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
270 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
271 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
273 // only sub-type and manufacturer IDs need to be equal
276 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
277 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
284 //--------------------------------------------------------------------------
285 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
286 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
287 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
288 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
291 ComponentDescription desc;
293 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
296 // get the ComponentDescription of the input Component
297 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
301 // check if the Component's ComponentDescription matches the input ComponentDescription
302 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
305 //--------------------------------------------------------------------------
306 // determine if 2 ComponentDescriptions are basically equal
307 // (by that, I mean that the important identifying values are compared,
308 // but not the ComponentDescription flags)
309 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
311 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
314 //--------------------------------------------------------------------------
315 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
316 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
318 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
321 //--------------------------------------------------------------------------
322 // determine if a ComponentDescription basically matches that of a particular Component
323 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
325 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
328 //--------------------------------------------------------------------------
329 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
330 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
332 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
336 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
337 : Plugin (engine, session),
339 unit (new CAAudioUnit),
347 if (!preset_search_path_initialized) {
348 Glib::ustring p = Glib::get_home_dir();
349 p += "/Library/Audio/Presets:";
350 p += preset_search_path;
351 preset_search_path = p;
352 preset_search_path_initialized = true;
358 AUPlugin::AUPlugin (const AUPlugin& other)
360 , comp (other.get_comp())
361 , unit (new CAAudioUnit)
362 , initialized (false)
366 , current_buffers (0)
367 , frames_processed (0)
373 AUPlugin::~AUPlugin ()
376 unit->Uninitialize ();
385 AUPlugin::discover_factory_presets ()
389 OSStatus err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets,
390 kAudioUnitScope_Global, 0,
392 if (err || !dataSize) {
397 dataSize = sizeof (presets);
399 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
400 cerr << "cannot get factory preset info: " << err << endl;
404 CFIndex cnt = CFArrayGetCount (presets);
406 for (CFIndex i = 0; i < cnt; ++i) {
407 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
409 string name = CFStringRefToStdString (preset->presetName);
410 factory_preset_map[name] = preset->presetNumber;
420 err = CAAudioUnit::Open (*(comp.get()), *unit);
422 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
423 throw failed_constructor();
427 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
428 throw failed_constructor ();
431 AURenderCallbackStruct renderCallbackInfo;
433 renderCallbackInfo.inputProc = _render_callback;
434 renderCallbackInfo.inputProcRefCon = this;
436 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
437 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
438 cerr << "cannot install render callback (err = " << err << ')' << endl;
439 throw failed_constructor();
442 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
444 HostCallbackInfo info;
445 memset (&info, 0, sizeof (HostCallbackInfo));
446 info.hostUserData = this;
447 info.beatAndTempoProc = _get_beat_and_tempo_callback;
448 info.musicalTimeLocationProc = _get_musical_time_location_callback;
449 info.transportStateProc = _get_transport_state_callback;
451 //ignore result of this - don't care if the property isn't supported
452 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
453 kAudioUnitScope_Global,
456 sizeof (HostCallbackInfo));
458 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
459 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
460 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
462 /* these keep track of *configured* channel set up,
463 not potential set ups.
467 output_channels = -1;
469 if (_set_block_size (_session.get_block_size())) {
470 error << _("AUPlugin: cannot set processing block size") << endmsg;
471 throw failed_constructor();
474 discover_parameters ();
475 discover_factory_presets ();
477 Plugin::setup_controls ();
481 AUPlugin::discover_parameters ()
483 /* discover writable parameters */
485 AudioUnitScope scopes[] = {
486 kAudioUnitScope_Global,
487 kAudioUnitScope_Output,
488 kAudioUnitScope_Input
491 descriptors.clear ();
493 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
495 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
497 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
499 AUParameterDescriptor d;
501 d.id = param_info.ParamID (i);
503 const CAAUParameter* param = param_info.GetParamInfo (d.id);
504 const AudioUnitParameterInfo& info (param->ParamInfo());
506 const int len = CFStringGetLength (param->GetName());;
507 char local_buffer[len*2];
508 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
512 d.label = local_buffer;
515 d.scope = param_info.GetScope ();
516 d.element = param_info.GetElement ();
518 /* info.units to consider */
520 kAudioUnitParameterUnit_Generic = 0
521 kAudioUnitParameterUnit_Indexed = 1
522 kAudioUnitParameterUnit_Boolean = 2
523 kAudioUnitParameterUnit_Percent = 3
524 kAudioUnitParameterUnit_Seconds = 4
525 kAudioUnitParameterUnit_SampleFrames = 5
526 kAudioUnitParameterUnit_Phase = 6
527 kAudioUnitParameterUnit_Rate = 7
528 kAudioUnitParameterUnit_Hertz = 8
529 kAudioUnitParameterUnit_Cents = 9
530 kAudioUnitParameterUnit_RelativeSemiTones = 10
531 kAudioUnitParameterUnit_MIDINoteNumber = 11
532 kAudioUnitParameterUnit_MIDIController = 12
533 kAudioUnitParameterUnit_Decibels = 13
534 kAudioUnitParameterUnit_LinearGain = 14
535 kAudioUnitParameterUnit_Degrees = 15
536 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
537 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
538 kAudioUnitParameterUnit_Pan = 18
539 kAudioUnitParameterUnit_Meters = 19
540 kAudioUnitParameterUnit_AbsoluteCents = 20
541 kAudioUnitParameterUnit_Octaves = 21
542 kAudioUnitParameterUnit_BPM = 22
543 kAudioUnitParameterUnit_Beats = 23
544 kAudioUnitParameterUnit_Milliseconds = 24
545 kAudioUnitParameterUnit_Ratio = 25
548 /* info.flags to consider */
552 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
553 kAudioUnitParameterFlag_HasClump = (1L << 20)
554 kAudioUnitParameterFlag_HasName = (1L << 21)
555 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
556 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
557 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
558 kAudioUnitParameterFlag_CanRamp = (1L << 25)
559 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
560 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
561 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
562 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
563 kAudioUnitParameterFlag_IsReadable = (1L << 30)
564 kAudioUnitParameterFlag_IsWritable = (1L << 31)
567 d.lower = info.minValue;
568 d.upper = info.maxValue;
569 d.default_value = info.defaultValue;
571 d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
572 d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean) ||
573 (d.integer_step && ((d.upper - d.lower) == 1.0));
574 d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
575 d.automatable = !d.toggled &&
576 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
577 (info.flags & kAudioUnitParameterFlag_IsWritable);
579 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
585 d.min_unbound = 0; // lower is bound
586 d.max_unbound = 0; // upper is bound
588 descriptors.push_back (d);
595 AUPlugin::unique_id () const
597 return AUPluginInfo::stringify_descriptor (comp->Desc());
601 AUPlugin::label () const
603 return _info->name.c_str();
607 AUPlugin::parameter_count () const
609 return descriptors.size();
613 AUPlugin::default_value (uint32_t port)
615 if (port < descriptors.size()) {
616 return descriptors[port].default_value;
623 AUPlugin::latency () const
625 return unit->Latency() * _session.frame_rate();
629 AUPlugin::set_parameter (uint32_t which, float val)
631 if (which < descriptors.size()) {
632 const AUParameterDescriptor& d (descriptors[which]);
633 unit->SetParameter (d.id, d.scope, d.element, val);
635 /* tell the world what we did */
637 AudioUnitEvent theEvent;
639 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
640 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
641 theEvent.mArgument.mParameter.mParameterID = d.id;
642 theEvent.mArgument.mParameter.mScope = d.scope;
643 theEvent.mArgument.mParameter.mElement = d.element;
645 AUEventListenerNotify (NULL, NULL, &theEvent);
650 AUPlugin::get_parameter (uint32_t which) const
653 if (which < descriptors.size()) {
654 const AUParameterDescriptor& d (descriptors[which]);
655 unit->GetParameter(d.id, d.scope, d.element, val);
661 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
663 if (which < descriptors.size()) {
664 pd = descriptors[which];
671 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
673 if (which < descriptors.size()) {
682 AUPlugin::activate ()
686 if ((err = unit->Initialize()) != noErr) {
687 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
689 frames_processed = 0;
696 AUPlugin::deactivate ()
698 unit->GlobalReset ();
702 AUPlugin::set_block_size (nframes_t nframes)
704 _set_block_size (nframes);
708 AUPlugin::_set_block_size (nframes_t nframes)
710 bool was_initialized = initialized;
711 UInt32 numFrames = nframes;
715 unit->Uninitialize ();
719 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
720 0, &numFrames, sizeof (numFrames))) != noErr) {
721 cerr << "cannot set max frames (err = " << err << ')' << endl;
725 if (was_initialized) {
733 AUPlugin::configure_io (int32_t in, int32_t out)
735 AudioStreamBasicDescription streamFormat;
737 streamFormat.mSampleRate = _session.frame_rate();
738 streamFormat.mFormatID = kAudioFormatLinearPCM;
739 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
741 #ifdef __LITTLE_ENDIAN__
744 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
747 streamFormat.mBitsPerChannel = 32;
748 streamFormat.mFramesPerPacket = 1;
750 /* apple says that for non-interleaved data, these
751 values always refer to a single channel.
753 streamFormat.mBytesPerPacket = 4;
754 streamFormat.mBytesPerFrame = 4;
756 streamFormat.mChannelsPerFrame = in;
758 if (set_input_format (streamFormat) != 0) {
762 streamFormat.mChannelsPerFrame = out;
764 if (set_output_format (streamFormat) != 0) {
768 return Plugin::configure_io (in, out);
772 AUPlugin::can_do (int32_t in, int32_t& out)
774 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
775 // attempt to multiply-instantiate plugins to meet io configurations.
777 int32_t plugcnt = -1;
778 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
782 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
784 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
786 int32_t possible_in = i->first;
787 int32_t possible_out = i->second;
789 if (possible_out == 0) {
790 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
794 if (possible_in == 0) {
796 /* instrument plugin, always legal but throws away inputs ...
799 if (possible_out == -1) {
800 /* out much match in (UNLIKELY!!) */
803 } else if (possible_out == -2) {
804 /* any configuration possible, pick matching */
807 } else if (possible_out < -2) {
808 /* explicit variable number of outputs, pick maximum */
812 /* exact number of outputs */
818 if (possible_in == -1) {
820 /* wildcard for input */
822 if (possible_out == -1) {
823 /* out much match in */
826 } else if (possible_out == -2) {
827 /* any configuration possible, pick matching */
830 } else if (possible_out < -2) {
831 /* explicit variable number of outputs, pick maximum */
835 /* exact number of outputs */
841 if (possible_in == -2) {
843 if (possible_out == -1) {
844 /* any configuration possible, pick matching */
847 } else if (possible_out == -2) {
848 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
851 } else if (possible_out < -2) {
852 /* explicit variable number of outputs, pick maximum */
856 /* exact number of outputs */
862 if (possible_in < -2) {
864 /* explicit variable number of inputs */
866 if (in > -possible_in) {
867 /* request is too large */
871 if (possible_out == -1) {
872 /* out must match in */
875 } else if (possible_out == -2) {
876 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
879 } else if (possible_out < -2) {
880 /* explicit variable number of outputs, pick maximum */
884 /* exact number of outputs */
890 if (possible_in == in) {
892 /* exact number of inputs ... must match obviously */
894 if (possible_out == -1) {
895 /* out must match in */
898 } else if (possible_out == -2) {
899 /* any output configuration, pick matching */
902 } else if (possible_out < -2) {
903 /* explicit variable number of outputs, pick maximum */
907 /* exact number of outputs */
923 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
925 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
929 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
931 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
940 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
941 fmt.mChannelsPerFrame * sizeof(AudioBuffer));
943 Glib::Mutex::Lock em (_session.engine().process_lock());
944 IO::MoreOutputs (fmt.mChannelsPerFrame);
950 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
954 for (uint32_t i = 0; i < cnt; ++i) {
955 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
956 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
957 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
962 if (scope == kAudioUnitScope_Input) {
963 input_channels = fmt.mChannelsPerFrame;
965 output_channels = fmt.mChannelsPerFrame;
972 AUPlugin::input_streams() const
974 if (input_channels < 0) {
975 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
978 return input_channels;
983 AUPlugin::output_streams() const
985 if (output_channels < 0) {
986 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
989 return output_channels;
993 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
994 const AudioTimeStamp *inTimeStamp,
996 UInt32 inNumberFrames,
997 AudioBufferList* ioData)
999 /* not much to do - the data is already in the buffers given to us in connect_and_run() */
1001 if (current_maxbuf == 0) {
1002 error << _("AUPlugin: render callback called illegally!") << endmsg;
1003 return kAudioUnitErr_CannotDoInCurrentContext;
1006 for (uint32_t i = 0; i < current_maxbuf; ++i) {
1007 ioData->mBuffers[i].mNumberChannels = 1;
1008 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1009 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
1012 cb_offset += inNumberFrames;
1018 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
1020 AudioUnitRenderActionFlags flags = 0;
1023 current_buffers = &bufs;
1024 current_maxbuf = maxbuf;
1025 current_offset = offset;
1028 buffers->mNumberBuffers = maxbuf;
1030 for (uint32_t i = 0; i < maxbuf; ++i) {
1031 buffers->mBuffers[i].mNumberChannels = 1;
1032 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1033 buffers->mBuffers[i].mData = 0;
1036 ts.mSampleTime = frames_processed;
1037 ts.mFlags = kAudioTimeStampSampleTimeValid;
1039 if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
1042 frames_processed += nframes;
1044 for (uint32_t i = 0; i < maxbuf; ++i) {
1045 if (bufs[i] + offset != buffers->mBuffers[i].mData) {
1046 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1056 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1057 Float64* outCurrentTempo)
1059 TempoMap& tmap (_session.tempo_map());
1061 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1062 (and interpretation) of a beat position will be incorrect. So refuse to
1066 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1067 return kAudioUnitErr_CannotDoInCurrentContext;
1071 TempoMap::Metric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1072 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1074 if (outCurrentBeat) {
1076 beat = metric.meter().beats_per_bar() * bbt.bars;
1078 beat += bbt.ticks / Meter::ticks_per_beat;
1079 *outCurrentBeat = beat;
1082 if (outCurrentTempo) {
1083 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1091 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1092 Float32* outTimeSig_Numerator,
1093 UInt32* outTimeSig_Denominator,
1094 Float64* outCurrentMeasureDownBeat)
1096 TempoMap& tmap (_session.tempo_map());
1098 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1099 (and interpretation) of a beat position will be incorrect. So refuse to
1103 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1104 return kAudioUnitErr_CannotDoInCurrentContext;
1108 TempoMap::Metric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1109 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1111 if (*outDeltaSampleOffsetToNextBeat) {
1112 if (bbt.ticks == 0) {
1114 *outDeltaSampleOffsetToNextBeat = 0;
1116 *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((Meter::ticks_per_beat - bbt.ticks)/Meter::ticks_per_beat) * // fraction of a beat to next beat
1117 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1121 if (*outTimeSig_Numerator) {
1122 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1124 if (*outTimeSig_Denominator) {
1125 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1128 if (*outCurrentMeasureDownBeat) {
1130 /* beat for the start of the bar.
1132 2|1|0 -> 1 + beats_per_bar
1133 3|1|0 -> 1 + (2 * beats_per_bar)
1137 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1144 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1145 Boolean* outTransportStateChanged,
1146 Float64* outCurrentSampleInTimeLine,
1147 Boolean* outIsCycling,
1148 Float64* outCycleStartBeat,
1149 Float64* outCycleEndBeat)
1152 *outIsPlaying = _session.transport_rolling();
1155 if (outTransportStateChanged) {
1156 *outTransportStateChanged = false;
1159 if (outCurrentSampleInTimeLine) {
1160 *outCurrentSampleInTimeLine = _session.transport_frame();
1164 Location* loc = _session.locations()->auto_loop_location();
1166 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1168 if (*outIsCycling) {
1170 if (outCycleStartBeat || outCycleEndBeat) {
1172 TempoMap& tmap (_session.tempo_map());
1174 /* more than 1 meter means that a simplistic computation (and interpretation) of
1175 a beat position will be incorrect. so refuse to offer the value.
1178 if (tmap.n_meters() > 1) {
1179 return kAudioUnitErr_CannotDoInCurrentContext;
1184 if (outCycleStartBeat) {
1185 TempoMap::Metric metric = tmap.metric_at (loc->start() + current_offset);
1186 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1189 beat = metric.meter().beats_per_bar() * bbt.bars;
1191 beat += bbt.ticks / Meter::ticks_per_beat;
1193 *outCycleStartBeat = beat;
1196 if (outCycleEndBeat) {
1197 TempoMap::Metric metric = tmap.metric_at (loc->end() + current_offset);
1198 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1201 beat = metric.meter().beats_per_bar() * bbt.bars;
1203 beat += bbt.ticks / Meter::ticks_per_beat;
1205 *outCycleEndBeat = beat;
1215 AUPlugin::automatable() const
1217 set<uint32_t> automates;
1219 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1220 if (descriptors[i].automatable) {
1221 automates.insert (i);
1229 AUPlugin::describe_parameter (uint32_t param)
1231 return descriptors[param].label;
1235 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
1237 // NameValue stuff here
1241 AUPlugin::parameter_is_audio (uint32_t) const
1247 AUPlugin::parameter_is_control (uint32_t) const
1253 AUPlugin::parameter_is_input (uint32_t) const
1259 AUPlugin::parameter_is_output (uint32_t) const
1265 AUPlugin::get_state()
1267 LocaleGuard lg (X_("POSIX"));
1268 XMLNode *root = new XMLNode (state_node_name());
1270 #ifdef AU_STATE_SUPPORT
1272 CFPropertyListRef propertyList;
1274 if (unit->GetAUPreset (propertyList) != noErr) {
1278 // Convert the property list into XML data.
1280 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1283 error << _("Could not create XML version of property list") << endmsg;
1287 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1288 our state node. GACK!
1293 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1295 root->add_child_copy (*t.root());
1299 CFRelease (xmlData);
1300 CFRelease (propertyList);
1302 if (!seen_get_state_message) {
1303 info << _("Saving AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1305 seen_get_state_message = true;
1313 AUPlugin::set_state(const XMLNode& node)
1315 #ifdef AU_STATE_SUPPORT
1317 CFPropertyListRef propertyList;
1318 LocaleGuard lg (X_("POSIX"));
1320 if (node.name() != state_node_name()) {
1321 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1325 if (node.children().empty()) {
1329 XMLNode* top = node.children().front();
1330 XMLNode* copy = new XMLNode (*top);
1335 const string& xml = t.write_buffer ();
1336 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1337 CFStringRef errorString;
1339 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1341 kCFPropertyListImmutable,
1344 CFRelease (xmlData);
1347 if (unit->SetAUPreset (propertyList) == noErr) {
1350 /* tell the world */
1352 AudioUnitParameter changedUnit;
1353 changedUnit.mAudioUnit = unit->AU();
1354 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1355 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1357 CFRelease (propertyList);
1362 if (!seen_set_state_message) {
1363 info << _("Restoring AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1371 AUPlugin::load_preset (const string preset_label)
1373 #ifdef AU_STATE_SUPPORT
1375 CFPropertyListRef propertyList;
1377 UserPresetMap::iterator ux;
1378 FactoryPresetMap::iterator fx;
1380 /* look first in "user" presets */
1382 if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
1384 if ((propertyList = load_property_list (ux->second)) != 0) {
1385 if (unit->SetAUPreset (propertyList) == noErr) {
1388 CFRelease(propertyList);
1391 } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
1395 preset.presetNumber = fx->second;
1396 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1398 cerr << "Setting factory preset " << fx->second << endl;
1400 if (unit->SetPresentPreset (preset) == 0) {
1403 /* tell the world */
1405 AudioUnitParameter changedUnit;
1406 changedUnit.mAudioUnit = unit->AU();
1407 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1408 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1414 if (!seen_loading_message) {
1415 info << _("Loading AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1417 seen_loading_message = true;
1424 AUPlugin::save_preset (string preset_name)
1426 #ifdef AU_STATE_SUPPORT
1427 CFPropertyListRef propertyList;
1428 vector<Glib::ustring> v;
1429 Glib::ustring user_preset_path;
1432 std::string m = maker();
1433 std::string n = name();
1435 strip_whitespace_edges (m);
1436 strip_whitespace_edges (n);
1438 v.push_back (Glib::get_home_dir());
1439 v.push_back ("Library");
1440 v.push_back ("Audio");
1441 v.push_back ("Presets");
1445 user_preset_path = Glib::build_filename (v);
1447 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1448 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1452 if (unit->GetAUPreset (propertyList) != noErr) {
1456 // add the actual preset name */
1458 v.push_back (preset_name + preset_suffix);
1462 user_preset_path = Glib::build_filename (v);
1464 set_preset_name_in_plist (propertyList, preset_name);
1466 if (save_property_list (propertyList, user_preset_path)) {
1467 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1471 CFRelease(propertyList);
1475 if (!seen_saving_message) {
1476 info << _("Saving AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1478 seen_saving_message = true;
1484 //-----------------------------------------------------------------------------
1485 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1487 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1489 CFNumberRef cfNumber;
1490 SInt32 numberValue = 0;
1491 Boolean dummySuccess;
1493 if (outSuccess == NULL)
1494 outSuccess = &dummySuccess;
1495 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1497 *outSuccess = FALSE;
1501 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1502 if (cfNumber == NULL)
1504 *outSuccess = FALSE;
1507 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1515 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1517 CFDictionaryRef auStateDictionary;
1518 ComponentDescription tempDesc = {0};
1519 SInt32 versionValue;
1522 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1525 // the property list for AU state data must be of the dictionary type
1526 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1527 return kAudioUnitErr_InvalidPropertyValue;
1530 auStateDictionary = (CFDictionaryRef)inAUStateData;
1532 // first check to make sure that the version of the AU state data is one that we know understand
1533 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1534 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1537 return kAudioUnitErr_InvalidPropertyValue;
1539 #define kCurrentSavedStateVersion 0
1540 if (versionValue != kCurrentSavedStateVersion) {
1541 return kAudioUnitErr_InvalidPropertyValue;
1544 // grab the ComponentDescription values from the AU state data
1545 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1546 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1547 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1548 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1549 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1550 return kAudioUnitErr_InvalidPropertyValue;
1552 *outComponentDescription = tempDesc;
1557 static bool au_preset_filter (const string& str, void* arg)
1559 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1563 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1567 /* check the preset file path name against this plugin
1568 ID. The idea is that all preset files for this plugin
1569 include "<manufacturer>/<plugin-name>" in their path.
1572 Plugin* p = (Plugin *) arg;
1573 string match = p->maker();
1577 ret = str.find (match) != string::npos;
1580 string m = p->maker ();
1581 string n = p->name ();
1582 strip_whitespace_edges (m);
1583 strip_whitespace_edges (n);
1588 ret = str.find (match) != string::npos;
1596 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1599 CFPropertyListRef plist;
1600 ComponentDescription presetDesc;
1603 plist = load_property_list (pathstr);
1609 // get the ComponentDescription from the AU preset file
1611 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1613 if (status == noErr) {
1614 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1616 /* try to get the preset name from the property list */
1618 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1620 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1624 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1627 char buf[PATH_MAX+1];
1629 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1644 AUPlugin::current_preset() const
1648 #ifdef AU_STATE_SUPPORT
1649 CFPropertyListRef propertyList;
1651 if (unit->GetAUPreset (propertyList) == noErr) {
1652 preset_name = get_preset_name_in_plist (propertyList);
1653 CFRelease(propertyList);
1660 AUPlugin::get_presets ()
1662 vector<string> presets;
1664 #ifdef AU_STATE_SUPPORT
1665 vector<string*>* preset_files;
1666 PathScanner scanner;
1668 user_preset_map.clear ();
1670 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1672 if (!preset_files) {
1676 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1678 string path = *(*x);
1681 /* make an initial guess at the preset name using the path */
1683 preset_name = Glib::path_get_basename (path);
1684 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1686 /* check that this preset file really matches this plugin
1687 and potentially get the "real" preset name from
1691 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
1692 user_preset_map[preset_name] = path;
1698 delete preset_files;
1700 /* now fill the vector<string> with the names we have */
1702 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
1703 presets.push_back (i->first);
1706 /* add factory presets */
1708 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
1709 presets.push_back (i->first);
1718 AUPlugin::has_editor () const
1720 // even if the plugin doesn't have its own editor, the AU API can be used
1721 // to create one that looks native.
1725 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
1728 type = ARDOUR::AudioUnit;
1731 AUPluginInfo::~AUPluginInfo ()
1733 type = ARDOUR::AudioUnit;
1737 AUPluginInfo::load (Session& session)
1742 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
1744 if (!comp->IsValid()) {
1745 error << ("AudioUnit: not a valid Component") << endmsg;
1747 plugin.reset (new AUPlugin (session.engine(), session, comp));
1750 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
1754 catch (failed_constructor &err) {
1755 return PluginPtr ();
1760 AUPluginInfo::au_cache_path ()
1762 return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
1766 AUPluginInfo::discover ()
1770 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
1771 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
1774 PluginInfoList plugs;
1776 discover_fx (plugs);
1777 discover_music (plugs);
1778 discover_generators (plugs);
1784 AUPluginInfo::discover_music (PluginInfoList& plugs)
1786 CAComponentDescription desc;
1787 desc.componentFlags = 0;
1788 desc.componentFlagsMask = 0;
1789 desc.componentSubType = 0;
1790 desc.componentManufacturer = 0;
1791 desc.componentType = kAudioUnitType_MusicEffect;
1793 discover_by_description (plugs, desc);
1797 AUPluginInfo::discover_fx (PluginInfoList& plugs)
1799 CAComponentDescription desc;
1800 desc.componentFlags = 0;
1801 desc.componentFlagsMask = 0;
1802 desc.componentSubType = 0;
1803 desc.componentManufacturer = 0;
1804 desc.componentType = kAudioUnitType_Effect;
1806 discover_by_description (plugs, desc);
1810 AUPluginInfo::discover_generators (PluginInfoList& plugs)
1812 CAComponentDescription desc;
1813 desc.componentFlags = 0;
1814 desc.componentFlagsMask = 0;
1815 desc.componentSubType = 0;
1816 desc.componentManufacturer = 0;
1817 desc.componentType = kAudioUnitType_Generator;
1819 discover_by_description (plugs, desc);
1823 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
1827 comp = FindNextComponent (NULL, &desc);
1829 while (comp != NULL) {
1830 CAComponentDescription temp;
1831 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
1833 AUPluginInfoPtr info (new AUPluginInfo
1834 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
1836 /* no panners, format converters or i/o AU's for our purposes
1839 switch (info->descriptor->Type()) {
1840 case kAudioUnitType_Panner:
1841 case kAudioUnitType_OfflineEffect:
1842 case kAudioUnitType_FormatConverter:
1844 case kAudioUnitType_Output:
1845 case kAudioUnitType_MusicDevice:
1846 case kAudioUnitType_MusicEffect:
1847 case kAudioUnitType_Effect:
1848 case kAudioUnitType_Mixer:
1849 case kAudioUnitType_Generator:
1855 switch (info->descriptor->SubType()) {
1856 case kAudioUnitSubType_DefaultOutput:
1857 case kAudioUnitSubType_SystemOutput:
1858 case kAudioUnitSubType_GenericOutput:
1859 case kAudioUnitSubType_AUConverter:
1860 /* we don't want output units here */
1864 case kAudioUnitSubType_DLSSynth:
1865 info->category = "DLS Synth";
1868 case kAudioUnitSubType_Varispeed:
1869 info->category = "Varispeed";
1872 case kAudioUnitSubType_Delay:
1873 info->category = "Delay";
1876 case kAudioUnitSubType_LowPassFilter:
1877 info->category = "Low-pass Filter";
1880 case kAudioUnitSubType_HighPassFilter:
1881 info->category = "High-pass Filter";
1884 case kAudioUnitSubType_BandPassFilter:
1885 info->category = "Band-pass Filter";
1888 case kAudioUnitSubType_HighShelfFilter:
1889 info->category = "High-shelf Filter";
1892 case kAudioUnitSubType_LowShelfFilter:
1893 info->category = "Low-shelf Filter";
1896 case kAudioUnitSubType_ParametricEQ:
1897 info->category = "Parametric EQ";
1900 case kAudioUnitSubType_GraphicEQ:
1901 info->category = "Graphic EQ";
1904 case kAudioUnitSubType_PeakLimiter:
1905 info->category = "Peak Limiter";
1908 case kAudioUnitSubType_DynamicsProcessor:
1909 info->category = "Dynamics Processor";
1912 case kAudioUnitSubType_MultiBandCompressor:
1913 info->category = "Multiband Compressor";
1916 case kAudioUnitSubType_MatrixReverb:
1917 info->category = "Matrix Reverb";
1920 case kAudioUnitSubType_SampleDelay:
1921 info->category = "Sample Delay";
1924 case kAudioUnitSubType_Pitch:
1925 info->category = "Pitch";
1928 case kAudioUnitSubType_NetSend:
1929 info->category = "Net Sender";
1932 case kAudioUnitSubType_3DMixer:
1933 info->category = "3DMixer";
1936 case kAudioUnitSubType_MatrixMixer:
1937 info->category = "MatrixMixer";
1940 case kAudioUnitSubType_ScheduledSoundPlayer:
1941 info->category = "Scheduled Sound Player";
1945 case kAudioUnitSubType_AudioFilePlayer:
1946 info->category = "Audio File Player";
1949 case kAudioUnitSubType_NetReceive:
1950 info->category = "Net Receiver";
1954 info->category = "";
1957 AUPluginInfo::get_names (temp, info->name, info->creator);
1959 info->type = ARDOUR::AudioUnit;
1960 info->unique_id = stringify_descriptor (*info->descriptor);
1962 /* XXX not sure of the best way to handle plugin versioning yet
1965 CAComponent cacomp (*info->descriptor);
1967 if (cacomp.GetResourceVersion (info->version) != noErr) {
1971 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
1973 /* here we have to map apple's wildcard system to a simple pair
1974 of values. in ::can_do() we use the whole system, but here
1975 we need a single pair of values. XXX probably means we should
1976 remove any use of these values.
1979 info->n_inputs = info->cache.io_configs.front().first;
1980 info->n_outputs = info->cache.io_configs.front().second;
1982 if (info->cache.io_configs.size() > 1) {
1983 cerr << "ODD: variable IO config for " << info->unique_id << endl;
1986 plugs.push_back (info);
1989 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
1992 comp = FindNextComponent (comp, &desc);
1997 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2000 AUPluginCachedInfo& cinfo,
2001 const std::string& name)
2006 /* concatenate unique ID with version to provide a key for cached info lookup.
2007 this ensures we don't get stale information, or should if plugin developers
2008 follow Apple "guidelines".
2011 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2016 CachedInfoMap::iterator cim = cached_info.find (id);
2018 if (cim != cached_info.end()) {
2019 cinfo = cim->second;
2024 AUChannelInfo* channel_info;
2028 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2032 if (CAAudioUnit::Open (comp, unit) != noErr) {
2038 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2039 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
2044 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2049 /* no explicit info available */
2051 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2055 /* store each configuration */
2057 for (uint32_t n = 0; n < cnt; ++n) {
2058 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2059 channel_info[n].outChannels));
2062 free (channel_info);
2065 add_cached_info (id, cinfo);
2066 save_cached_info ();
2072 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2074 cached_info[id] = cinfo;
2078 AUPluginInfo::save_cached_info ()
2082 node = new XMLNode (X_("AudioUnitPluginCache"));
2084 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2085 XMLNode* parent = new XMLNode (X_("plugin"));
2086 parent->add_property ("id", i->first);
2087 node->add_child_nocopy (*parent);
2089 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2091 XMLNode* child = new XMLNode (X_("io"));
2094 snprintf (buf, sizeof (buf), "%d", j->first);
2095 child->add_property (X_("in"), buf);
2096 snprintf (buf, sizeof (buf), "%d", j->second);
2097 child->add_property (X_("out"), buf);
2098 parent->add_child_nocopy (*child);
2103 Glib::ustring path = au_cache_path ();
2106 tree.set_root (node);
2108 if (!tree.write (path)) {
2109 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2110 unlink (path.c_str());
2115 AUPluginInfo::load_cached_info ()
2117 Glib::ustring path = au_cache_path ();
2120 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2125 const XMLNode* root (tree.root());
2127 if (root->name() != X_("AudioUnitPluginCache")) {
2131 cached_info.clear ();
2133 const XMLNodeList children = root->children();
2135 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2137 const XMLNode* child = *iter;
2139 if (child->name() == X_("plugin")) {
2141 const XMLNode* gchild;
2142 const XMLNodeList gchildren = child->children();
2143 const XMLProperty* prop = child->property (X_("id"));
2149 std::string id = prop->value();
2150 AUPluginCachedInfo cinfo;
2152 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2156 if (gchild->name() == X_("io")) {
2160 const XMLProperty* iprop;
2161 const XMLProperty* oprop;
2163 if (((iprop = gchild->property (X_("in"))) != 0) &&
2164 ((oprop = gchild->property (X_("out"))) != 0)) {
2165 in = atoi (iprop->value());
2166 out = atoi (iprop->value());
2168 cinfo.io_configs.push_back (pair<int,int> (in, out));
2173 if (cinfo.io_configs.size()) {
2174 add_cached_info (id, cinfo);
2183 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
2185 CFStringRef itemName = NULL;
2187 // Marc Poirier-style item name
2188 CAComponent auComponent (comp_desc);
2189 if (auComponent.IsValid()) {
2190 CAComponentDescription dummydesc;
2191 Handle nameHandle = NewHandle(sizeof(void*));
2192 if (nameHandle != NULL) {
2193 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2195 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2196 if (nameString != NULL) {
2197 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2200 DisposeHandle(nameHandle);
2204 // if Marc-style fails, do the original way
2205 if (itemName == NULL) {
2206 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2207 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2208 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2210 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2211 compTypeString, compManufacturerString, compSubTypeString);
2213 if (compTypeString != NULL)
2214 CFRelease(compTypeString);
2215 if (compSubTypeString != NULL)
2216 CFRelease(compSubTypeString);
2217 if (compManufacturerString != NULL)
2218 CFRelease(compManufacturerString);
2221 string str = CFStringRefToStdString(itemName);
2222 string::size_type colon = str.find (':');
2225 name = str.substr (colon+1);
2226 maker = str.substr (0, colon);
2227 // strip_whitespace_edges (maker);
2228 // strip_whitespace_edges (name);
2235 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
2236 extern char *StringForOSType (OSType t, char *writeLocation);
2239 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2244 s << StringForOSType (desc.Type(), str);
2247 s << StringForOSType (desc.SubType(), str);
2250 s << StringForOSType (desc.Manu(), str);