use -r argument with JACK if realtime is not requested in engine dialog (also applied...
[ArdourMidi.git] / libs / ardour / audio_unit.cc
blob4a63f66cf5cd1543677b2f1345b66ec4519c2b40
1 /*
2 Copyright (C) 2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include <sstream>
21 #include <errno.h>
22 #include <string.h>
24 #include "pbd/transmitter.h"
25 #include "pbd/xml++.h"
26 #include "pbd/whitespace.h"
27 #include "pbd/pathscanner.h"
29 #include <glibmm/thread.h>
30 #include <glibmm/fileutils.h>
31 #include <glibmm/miscutils.h>
33 #include "ardour/ardour.h"
34 #include "ardour/audioengine.h"
35 #include "ardour/io.h"
36 #include "ardour/audio_unit.h"
37 #include "ardour/session.h"
38 #include "ardour/utils.h"
40 #include <appleutility/CAAudioUnit.h>
41 #include <appleutility/CAAUParameter.h>
43 #include <CoreFoundation/CoreFoundation.h>
44 #include <CoreServices/CoreServices.h>
46 #include "i18n.h"
48 using namespace std;
49 using namespace PBD;
50 using namespace ARDOUR;
52 #ifndef AU_STATE_SUPPORT
53 static bool seen_get_state_message = false;
54 static bool seen_set_state_message = false;
55 static bool seen_loading_message = false;
56 static bool seen_saving_message = false;
57 #endif
59 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
61 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
62 static string preset_suffix = ".aupreset";
63 static bool preset_search_path_initialized = false;
65 static OSStatus
66 _render_callback(void *userData,
67 AudioUnitRenderActionFlags *ioActionFlags,
68 const AudioTimeStamp *inTimeStamp,
69 UInt32 inBusNumber,
70 UInt32 inNumberFrames,
71 AudioBufferList* ioData)
73 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
76 static int
77 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
80 CFDataRef xmlData;
81 int fd;
83 // Convert the property list into XML data.
85 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
87 if (!xmlData) {
88 error << _("Could not create XML version of property list") << endmsg;
89 return -1;
92 // Write the XML data to the file.
94 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
95 while (fd < 0) {
96 if (errno == EEXIST) {
97 /* tell any UI's that this file already exists and ask them what to do */
98 bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
99 if (overwrite) {
100 fd = open (path.c_str(), O_WRONLY, 0664);
101 continue;
102 } else {
103 return 0;
106 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
107 CFRelease (xmlData);
108 return -1;
111 size_t cnt = CFDataGetLength (xmlData);
113 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != cnt) {
114 CFRelease (xmlData);
115 close (fd);
116 return -1;
119 close (fd);
120 return 0;
124 static CFPropertyListRef
125 load_property_list (Glib::ustring path)
127 int fd;
128 CFPropertyListRef propertyList;
129 CFDataRef xmlData;
130 CFStringRef errorString;
132 // Read the XML file.
134 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
135 return propertyList;
139 off_t len = lseek (fd, 0, SEEK_END);
140 char* buf = new char[len];
141 lseek (fd, 0, SEEK_SET);
143 if (read (fd, buf, len) != len) {
144 delete [] buf;
145 close (fd);
146 return propertyList;
149 close (fd);
151 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
153 // Reconstitute the dictionary using the XML data.
155 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
156 xmlData,
157 kCFPropertyListImmutable,
158 &errorString);
160 CFRelease (xmlData);
161 delete [] buf;
163 return propertyList;
166 //-----------------------------------------------------------------------------
167 static void
168 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
170 if (!plist) {
171 return;
173 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
175 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
176 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
179 CFRelease (pn);
182 //-----------------------------------------------------------------------------
183 static std::string
184 get_preset_name_in_plist (CFPropertyListRef plist)
186 std::string ret;
188 if (!plist) {
189 return ret;
192 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
193 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
194 if (p) {
195 CFStringRef str = (CFStringRef) p;
196 int len = CFStringGetLength(str);
197 len = (len * 2) + 1;
198 char local_buffer[len];
199 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
200 ret = local_buffer;
204 return ret;
207 //--------------------------------------------------------------------------
208 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
209 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
210 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
211 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
213 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
214 return FALSE;
216 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
217 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
219 // only sub-type and manufacturer IDs need to be equal
220 if (inIgnoreType)
221 return TRUE;
222 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
223 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
224 return TRUE;
227 return FALSE;
230 //--------------------------------------------------------------------------
231 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
232 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
233 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
234 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
236 OSErr status;
237 ComponentDescription desc;
239 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
240 return FALSE;
242 // get the ComponentDescription of the input Component
243 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
244 if (status != noErr)
245 return FALSE;
247 // check if the Component's ComponentDescription matches the input ComponentDescription
248 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
251 //--------------------------------------------------------------------------
252 // determine if 2 ComponentDescriptions are basically equal
253 // (by that, I mean that the important identifying values are compared,
254 // but not the ComponentDescription flags)
255 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
257 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
260 //--------------------------------------------------------------------------
261 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
262 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
264 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
267 //--------------------------------------------------------------------------
268 // determine if a ComponentDescription basically matches that of a particular Component
269 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
271 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
274 //--------------------------------------------------------------------------
275 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
276 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
278 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
282 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
283 : Plugin (engine, session),
284 comp (_comp),
285 unit (new CAAudioUnit),
286 initialized (false),
287 buffers (0),
288 current_maxbuf (0),
289 current_offset (0),
290 current_buffers (0),
291 frames_processed (0)
293 if (!preset_search_path_initialized) {
294 Glib::ustring p = Glib::get_home_dir();
295 p += "/Library/Audio/Presets:";
296 p += preset_search_path;
297 preset_search_path = p;
298 preset_search_path_initialized = true;
301 init ();
304 AUPlugin::AUPlugin (const AUPlugin& other)
305 : Plugin (other)
306 , comp (other.get_comp())
307 , unit (new CAAudioUnit)
308 , initialized (false)
309 , buffers (0)
310 , current_maxbuf (0)
311 , current_offset (0)
312 , current_buffers (0)
313 , frames_processed (0)
316 init ();
319 AUPlugin::~AUPlugin ()
321 if (unit) {
322 unit->Uninitialize ();
325 free (buffers);
329 void
330 AUPlugin::init ()
332 OSErr err;
334 try {
335 err = CAAudioUnit::Open (*(comp.get()), *unit);
336 } catch (...) {
337 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
338 throw failed_constructor();
341 if (err != noErr) {
342 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
343 throw failed_constructor ();
346 AURenderCallbackStruct renderCallbackInfo;
348 renderCallbackInfo.inputProc = _render_callback;
349 renderCallbackInfo.inputProcRefCon = this;
351 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
352 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
353 cerr << "cannot install render callback (err = " << err << ')' << endl;
354 throw failed_constructor();
357 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
358 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
359 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
361 /* these keep track of *configured* channel set up,
362 not potential set ups.
365 input_channels = ChanCount::ZERO;
366 output_channels = ChanCount::ZERO;
368 if (_set_block_size (_session.get_block_size())) {
369 error << _("AUPlugin: cannot set processing block size") << endmsg;
370 throw failed_constructor();
373 discover_parameters ();
375 Plugin::setup_controls ();
378 void
379 AUPlugin::discover_parameters ()
381 /* discover writable parameters */
383 AudioUnitScope scopes[] = {
384 kAudioUnitScope_Global,
385 kAudioUnitScope_Output,
386 kAudioUnitScope_Input
389 descriptors.clear ();
391 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
393 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
395 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
397 AUParameterDescriptor d;
399 d.id = param_info.ParamID (i);
401 const CAAUParameter* param = param_info.GetParamInfo (d.id);
402 const AudioUnitParameterInfo& info (param->ParamInfo());
404 const int len = CFStringGetLength (param->GetName());;
405 char local_buffer[len*2];
406 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
407 if (!good) {
408 d.label = "???";
409 } else {
410 d.label = local_buffer;
413 d.scope = param_info.GetScope ();
414 d.element = param_info.GetElement ();
416 /* info.units to consider */
418 kAudioUnitParameterUnit_Generic = 0
419 kAudioUnitParameterUnit_Indexed = 1
420 kAudioUnitParameterUnit_Boolean = 2
421 kAudioUnitParameterUnit_Percent = 3
422 kAudioUnitParameterUnit_Seconds = 4
423 kAudioUnitParameterUnit_SampleFrames = 5
424 kAudioUnitParameterUnit_Phase = 6
425 kAudioUnitParameterUnit_Rate = 7
426 kAudioUnitParameterUnit_Hertz = 8
427 kAudioUnitParameterUnit_Cents = 9
428 kAudioUnitParameterUnit_RelativeSemiTones = 10
429 kAudioUnitParameterUnit_MIDINoteNumber = 11
430 kAudioUnitParameterUnit_MIDIController = 12
431 kAudioUnitParameterUnit_Decibels = 13
432 kAudioUnitParameterUnit_LinearGain = 14
433 kAudioUnitParameterUnit_Degrees = 15
434 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
435 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
436 kAudioUnitParameterUnit_Pan = 18
437 kAudioUnitParameterUnit_Meters = 19
438 kAudioUnitParameterUnit_AbsoluteCents = 20
439 kAudioUnitParameterUnit_Octaves = 21
440 kAudioUnitParameterUnit_BPM = 22
441 kAudioUnitParameterUnit_Beats = 23
442 kAudioUnitParameterUnit_Milliseconds = 24
443 kAudioUnitParameterUnit_Ratio = 25
446 /* info.flags to consider */
450 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
451 kAudioUnitParameterFlag_HasClump = (1L << 20)
452 kAudioUnitParameterFlag_HasName = (1L << 21)
453 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
454 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
455 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
456 kAudioUnitParameterFlag_CanRamp = (1L << 25)
457 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
458 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
459 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
460 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
461 kAudioUnitParameterFlag_IsReadable = (1L << 30)
462 kAudioUnitParameterFlag_IsWritable = (1L << 31)
465 d.lower = info.minValue;
466 d.upper = info.maxValue;
467 d.default_value = info.defaultValue;
469 d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
470 d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean) ||
471 (d.integer_step && ((d.upper - d.lower) == 1.0));
472 d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
473 d.automatable = !d.toggled &&
474 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
475 (info.flags & kAudioUnitParameterFlag_IsWritable);
477 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
478 d.unit = info.unit;
480 d.step = 1.0;
481 d.smallstep = 0.1;
482 d.largestep = 10.0;
483 d.min_unbound = 0; // lower is bound
484 d.max_unbound = 0; // upper is bound
486 descriptors.push_back (d);
492 string
493 AUPlugin::unique_id () const
495 return AUPluginInfo::stringify_descriptor (comp->Desc());
498 const char *
499 AUPlugin::label () const
501 return _info->name.c_str();
504 uint32_t
505 AUPlugin::parameter_count () const
507 return descriptors.size();
510 float
511 AUPlugin::default_value (uint32_t port)
513 if (port < descriptors.size()) {
514 return descriptors[port].default_value;
517 return 0;
520 nframes_t
521 AUPlugin::latency () const
523 return unit->Latency() * _session.frame_rate();
526 void
527 AUPlugin::set_parameter (uint32_t which, float val)
529 if (which < descriptors.size()) {
530 const AUParameterDescriptor& d (descriptors[which]);
531 unit->SetParameter (d.id, d.scope, d.element, val);
535 float
536 AUPlugin::get_parameter (uint32_t which) const
538 float val = 0.0;
539 if (which < descriptors.size()) {
540 const AUParameterDescriptor& d (descriptors[which]);
541 unit->GetParameter(d.id, d.scope, d.element, val);
543 return val;
547 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
549 if (which < descriptors.size()) {
550 pd = descriptors[which];
551 return 0;
553 return -1;
556 uint32_t
557 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
559 if (which < descriptors.size()) {
560 ok = true;
561 return which;
563 ok = false;
564 return 0;
567 void
568 AUPlugin::activate ()
570 if (!initialized) {
571 OSErr err;
572 if ((err = unit->Initialize()) != noErr) {
573 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
574 } else {
575 frames_processed = 0;
576 initialized = true;
581 void
582 AUPlugin::deactivate ()
584 unit->GlobalReset ();
587 void
588 AUPlugin::set_block_size (nframes_t nframes)
590 _set_block_size (nframes);
594 AUPlugin::_set_block_size (nframes_t nframes)
596 bool was_initialized = initialized;
597 UInt32 numFrames = nframes;
598 OSErr err;
600 if (initialized) {
601 unit->Uninitialize ();
602 initialized = false;
605 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
606 0, &numFrames, sizeof (numFrames))) != noErr) {
607 cerr << "cannot set max frames (err = " << err << ')' << endl;
608 return -1;
611 if (was_initialized) {
612 activate ();
615 return 0;
618 int32_t
619 AUPlugin::configure_io (int32_t in, int32_t out)
621 AudioStreamBasicDescription streamFormat;
623 streamFormat.mSampleRate = _session.frame_rate();
624 streamFormat.mFormatID = kAudioFormatLinearPCM;
625 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
627 #ifdef __LITTLE_ENDIAN__
628 /* relax */
629 #else
630 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
631 #endif
633 streamFormat.mBitsPerChannel = 32;
634 streamFormat.mFramesPerPacket = 1;
636 /* apple says that for non-interleaved data, these
637 values always refer to a single channel.
639 streamFormat.mBytesPerPacket = 4;
640 streamFormat.mBytesPerFrame = 4;
642 streamFormat.mChannelsPerFrame = in;
644 if (set_input_format (streamFormat) != 0) {
645 return -1;
648 streamFormat.mChannelsPerFrame = out;
650 if (set_output_format (streamFormat) != 0) {
651 return -1;
654 return Plugin::configure_io (in, out);
657 int32_t
658 AUPlugin::can_do (int32_t in, int32_t& out)
660 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
661 // attempt to multiply-instantiate plugins to meet io configurations.
663 int32_t plugcnt = -1;
664 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
666 out = -1;
668 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
670 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
672 int32_t possible_in = i->first;
673 int32_t possible_out = i->second;
675 if (possible_out == 0) {
676 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
677 continue;
680 if (possible_in == 0) {
682 /* instrument plugin, always legal but throws away inputs ...
685 if (possible_out == -1) {
686 /* out much match in (UNLIKELY!!) */
687 out = in;
688 plugcnt = 1;
689 } else if (possible_out == -2) {
690 /* any configuration possible, pick matching */
691 out = in;
692 plugcnt = 1;
693 } else if (possible_out < -2) {
694 /* explicit variable number of outputs, pick maximum */
695 out = -possible_out;
696 plugcnt = 1;
697 } else {
698 /* exact number of outputs */
699 out = possible_out;
700 plugcnt = 1;
704 if (possible_in == -1) {
706 /* wildcard for input */
708 if (possible_out == -1) {
709 /* out much match in */
710 out = in;
711 plugcnt = 1;
712 } else if (possible_out == -2) {
713 /* any configuration possible, pick matching */
714 out = in;
715 plugcnt = 1;
716 } else if (possible_out < -2) {
717 /* explicit variable number of outputs, pick maximum */
718 out = -possible_out;
719 plugcnt = 1;
720 } else {
721 /* exact number of outputs */
722 out = possible_out;
723 plugcnt = 1;
727 if (possible_in == -2) {
729 if (possible_out == -1) {
730 /* any configuration possible, pick matching */
731 out = in;
732 plugcnt = 1;
733 } else if (possible_out == -2) {
734 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
735 << endmsg;
736 plugcnt = -1;
737 } else if (possible_out < -2) {
738 /* explicit variable number of outputs, pick maximum */
739 out = -possible_out;
740 plugcnt = 1;
741 } else {
742 /* exact number of outputs */
743 out = possible_out;
744 plugcnt = 1;
748 if (possible_in < -2) {
750 /* explicit variable number of inputs */
752 if (in > -possible_in) {
753 /* request is too large */
754 plugcnt = -1;
757 if (possible_out == -1) {
758 /* out must match in */
759 out = in;
760 plugcnt = 1;
761 } else if (possible_out == -2) {
762 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
763 << endmsg;
764 plugcnt = -1;
765 } else if (possible_out < -2) {
766 /* explicit variable number of outputs, pick maximum */
767 out = -possible_out;
768 plugcnt = 1;
769 } else {
770 /* exact number of outputs */
771 out = possible_out;
772 plugcnt = 1;
776 if (possible_in == in) {
778 /* exact number of inputs ... must match obviously */
780 if (possible_out == -1) {
781 /* out must match in */
782 out = in;
783 plugcnt = 1;
784 } else if (possible_out == -2) {
785 /* any output configuration, pick matching */
786 out = in;
787 plugcnt = -1;
788 } else if (possible_out < -2) {
789 /* explicit variable number of outputs, pick maximum */
790 out = -possible_out;
791 plugcnt = 1;
792 } else {
793 /* exact number of outputs */
794 out = possible_out;
795 plugcnt = 1;
799 if (plugcnt == 1) {
800 break;
804 /* no fit */
805 return plugcnt;
809 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
811 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
815 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
817 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
818 return -1;
821 if (buffers) {
822 free (buffers);
823 buffers = 0;
826 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
827 fmt.mChannelsPerFrame * sizeof(AudioBuffer));
829 Glib::Mutex::Lock em (_session.engine().process_lock());
830 IO::MoreOutputs (fmt.mChannelsPerFrame);
832 return 0;
836 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
838 OSErr result;
840 for (uint32_t i = 0; i < cnt; ++i) {
841 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
842 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
843 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
844 return -1;
848 if (scope == kAudioUnitScope_Input) {
849 input_channels.setAudio( fmt.mChannelsPerFrame );
850 } else {
851 output_channels.setAudio( fmt.mChannelsPerFrame );
854 return 0;
857 ChanCount
858 AUPlugin::input_streams() const
860 if (input_channels < 0) {
861 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
862 return 1;
864 return input_channels;
868 ChanCount
869 AUPlugin::output_streams() const
871 if (output_channels < 0) {
872 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
873 return 1;
875 return output_channels;
878 OSStatus
879 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
880 const AudioTimeStamp *inTimeStamp,
881 UInt32 inBusNumber,
882 UInt32 inNumberFrames,
883 AudioBufferList* ioData)
885 /* not much to do - the data is already in the buffers given to us in connect_and_run() */
887 if (current_maxbuf == 0) {
888 error << _("AUPlugin: render callback called illegally!") << endmsg;
889 return kAudioUnitErr_CannotDoInCurrentContext;
892 for (uint32_t i = 0; i < current_maxbuf; ++i) {
893 ioData->mBuffers[i].mNumberChannels = 1;
894 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
895 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
898 cb_offset += inNumberFrames;
900 return noErr;
904 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
906 AudioUnitRenderActionFlags flags = 0;
907 AudioTimeStamp ts;
909 current_buffers = &bufs;
910 current_maxbuf = maxbuf;
911 current_offset = offset;
912 cb_offset = 0;
914 buffers->mNumberBuffers = maxbuf;
916 for (uint32_t i = 0; i < maxbuf; ++i) {
917 buffers->mBuffers[i].mNumberChannels = 1;
918 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
919 buffers->mBuffers[i].mData = 0;
922 ts.mSampleTime = frames_processed;
923 ts.mFlags = kAudioTimeStampSampleTimeValid;
925 if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
927 current_maxbuf = 0;
928 frames_processed += nframes;
930 for (uint32_t i = 0; i < maxbuf; ++i) {
931 if (bufs[i] + offset != buffers->mBuffers[i].mData) {
932 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
935 return 0;
938 return -1;
941 set<uint32_t>
942 AUPlugin::automatable() const
944 set<uint32_t> automates;
946 for (uint32_t i = 0; i < descriptors.size(); ++i) {
947 if (descriptors[i].automatable) {
948 automates.insert (i);
952 return automates;
955 string
956 AUPlugin::describe_parameter (uint32_t param)
958 return descriptors[param].label;
961 void
962 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
964 // NameValue stuff here
967 bool
968 AUPlugin::parameter_is_audio (uint32_t) const
970 return false;
973 bool
974 AUPlugin::parameter_is_control (uint32_t) const
976 return true;
979 bool
980 AUPlugin::parameter_is_input (uint32_t) const
982 return false;
985 bool
986 AUPlugin::parameter_is_output (uint32_t) const
988 return false;
991 XMLNode&
992 AUPlugin::get_state()
994 LocaleGuard lg (X_("POSIX"));
995 XMLNode *root = new XMLNode (state_node_name());
997 #ifdef AU_STATE_SUPPORT
998 CFDataRef xmlData;
999 CFPropertyListRef propertyList;
1001 if (unit->GetAUPreset (propertyList) != noErr) {
1002 return *root;
1005 // Convert the property list into XML data.
1007 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1009 if (!xmlData) {
1010 error << _("Could not create XML version of property list") << endmsg;
1011 return *root;
1014 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1015 our state node. GACK!
1018 XMLTree t;
1020 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1021 if (t.root()) {
1022 root->add_child_copy (*t.root());
1026 CFRelease (xmlData);
1027 CFRelease (propertyList);
1028 #else
1029 if (!seen_get_state_message) {
1030 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"), PROGRAM_NAME)
1031 << endmsg;
1032 seen_get_state_message = true;
1034 #endif
1036 return *root;
1040 AUPlugin::set_state(const XMLNode& node)
1042 #ifdef AU_STATE_SUPPORT
1043 int ret = -1;
1044 CFPropertyListRef propertyList;
1045 LocaleGuard lg (X_("POSIX"));
1047 if (node.name() != state_node_name()) {
1048 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1049 return -1;
1052 if (node.children().empty()) {
1053 return -1;
1056 XMLNode* top = node.children().front();
1057 XMLNode* copy = new XMLNode (*top);
1059 XMLTree t;
1060 t.set_root (copy);
1062 const string& xml = t.write_buffer ();
1063 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1064 CFStringRef errorString;
1066 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1067 xmlData,
1068 kCFPropertyListImmutable,
1069 &errorString);
1071 CFRelease (xmlData);
1073 if (propertyList) {
1074 if (unit->SetAUPreset (propertyList) == noErr) {
1075 ret = 0;
1077 CFRelease (propertyList);
1080 return ret;
1081 #else
1082 if (!seen_set_state_message) {
1083 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version", PROGRAM_NAME)
1084 << endmsg;
1086 return 0;
1087 #endif
1090 bool
1091 AUPlugin::load_preset (const string& preset_label)
1093 #ifdef AU_STATE_SUPPORT
1094 bool ret = false;
1095 CFPropertyListRef propertyList;
1096 Glib::ustring path;
1097 PresetMap::iterator x = preset_map.find (preset_label);
1099 if (x == preset_map.end()) {
1100 return false;
1103 if ((propertyList = load_property_list (x->second)) != 0) {
1104 if (unit->SetAUPreset (propertyList) == noErr) {
1105 ret = true;
1107 CFRelease(propertyList);
1110 return ret;
1111 #else
1112 if (!seen_loading_message) {
1113 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version", PROGRAM_NAME)
1114 << endmsg;
1115 seen_loading_message = true;
1117 return true;
1118 #endif
1121 bool
1122 AUPlugin::save_preset (string preset_name)
1124 #ifdef AU_STATE_SUPPORT
1125 CFPropertyListRef propertyList;
1126 vector<Glib::ustring> v;
1127 Glib::ustring user_preset_path;
1128 bool ret = true;
1130 std::string m = maker();
1131 std::string n = name();
1133 strip_whitespace_edges (m);
1134 strip_whitespace_edges (n);
1136 v.push_back (Glib::get_home_dir());
1137 v.push_back ("Library");
1138 v.push_back ("Audio");
1139 v.push_back ("Presets");
1140 v.push_back (m);
1141 v.push_back (n);
1143 user_preset_path = Glib::build_filename (v);
1145 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1146 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1147 return false;
1150 if (unit->GetAUPreset (propertyList) != noErr) {
1151 return false;
1154 // add the actual preset name */
1156 v.push_back (preset_name + preset_suffix);
1158 // rebuild
1160 user_preset_path = Glib::build_filename (v);
1162 set_preset_name_in_plist (propertyList, preset_name);
1164 if (save_property_list (propertyList, user_preset_path)) {
1165 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1166 ret = false;
1169 CFRelease(propertyList);
1171 return ret;
1172 #else
1173 if (!seen_saving_message) {
1174 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"), PROGRAM_NAME)
1175 << endmsg;
1176 seen_saving_message = true;
1178 return false;
1179 #endif
1182 //-----------------------------------------------------------------------------
1183 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1184 static SInt32
1185 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1187 CFNumberRef cfNumber;
1188 SInt32 numberValue = 0;
1189 Boolean dummySuccess;
1191 if (outSuccess == NULL)
1192 outSuccess = &dummySuccess;
1193 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1195 *outSuccess = FALSE;
1196 return 0;
1199 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1200 if (cfNumber == NULL)
1202 *outSuccess = FALSE;
1203 return 0;
1205 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1206 if (*outSuccess)
1207 return numberValue;
1208 else
1209 return 0;
1212 static OSStatus
1213 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1215 CFDictionaryRef auStateDictionary;
1216 ComponentDescription tempDesc = {0};
1217 SInt32 versionValue;
1218 Boolean gotValue;
1220 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1221 return paramErr;
1223 // the property list for AU state data must be of the dictionary type
1224 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1225 return kAudioUnitErr_InvalidPropertyValue;
1228 auStateDictionary = (CFDictionaryRef)inAUStateData;
1230 // first check to make sure that the version of the AU state data is one that we know understand
1231 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1232 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1234 if (!gotValue) {
1235 return kAudioUnitErr_InvalidPropertyValue;
1237 #define kCurrentSavedStateVersion 0
1238 if (versionValue != kCurrentSavedStateVersion) {
1239 return kAudioUnitErr_InvalidPropertyValue;
1242 // grab the ComponentDescription values from the AU state data
1243 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1244 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1245 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1246 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1247 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1248 return kAudioUnitErr_InvalidPropertyValue;
1250 *outComponentDescription = tempDesc;
1251 return noErr;
1255 static bool au_preset_filter (const string& str, void* arg)
1257 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1259 bool ret;
1261 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1263 if (ret && arg) {
1265 /* check the preset file path name against this plugin
1266 ID. The idea is that all preset files for this plugin
1267 include "<manufacturer>/<plugin-name>" in their path.
1270 Plugin* p = (Plugin *) arg;
1271 string match = p->maker();
1272 match += '/';
1273 match += p->name();
1275 ret = str.find (match) != string::npos;
1277 if (ret == false) {
1278 string m = p->maker ();
1279 string n = p->name ();
1280 strip_whitespace_edges (m);
1281 strip_whitespace_edges (n);
1282 match = m;
1283 match += '/';
1284 match += n;
1286 ret = str.find (match) != string::npos;
1290 return ret;
1293 bool
1294 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1296 OSStatus status;
1297 CFPropertyListRef plist;
1298 ComponentDescription presetDesc;
1299 bool ret = false;
1301 plist = load_property_list (pathstr);
1303 if (!plist) {
1304 return ret;
1307 // get the ComponentDescription from the AU preset file
1309 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1311 if (status == noErr) {
1312 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1314 /* try to get the preset name from the property list */
1316 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1318 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1320 if (psk) {
1322 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1324 if (!p) {
1325 char buf[PATH_MAX+1];
1327 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1328 preset_name = buf;
1336 CFRelease (plist);
1338 return true;
1341 std::string
1342 AUPlugin::current_preset() const
1344 string preset_name;
1346 #ifdef AU_STATE_SUPPORT
1347 CFPropertyListRef propertyList;
1349 if (unit->GetAUPreset (propertyList) == noErr) {
1350 preset_name = get_preset_name_in_plist (propertyList);
1351 CFRelease(propertyList);
1353 #endif
1354 return preset_name;
1357 vector<string>
1358 AUPlugin::get_presets ()
1360 vector<string*>* preset_files;
1361 vector<string> presets;
1362 PathScanner scanner;
1364 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1366 if (!preset_files) {
1367 return presets;
1370 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1372 string path = *(*x);
1373 string preset_name;
1375 /* make an initial guess at the preset name using the path */
1377 preset_name = Glib::path_get_basename (path);
1378 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1380 /* check that this preset file really matches this plugin
1381 and potentially get the "real" preset name from
1382 within the file.
1385 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
1386 presets.push_back (preset_name);
1387 preset_map[preset_name] = path;
1390 delete *x;
1393 delete preset_files;
1395 return presets;
1398 bool
1399 AUPlugin::has_editor () const
1401 // even if the plugin doesn't have its own editor, the AU API can be used
1402 // to create one that looks native.
1403 return true;
1406 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
1407 : descriptor (d)
1412 AUPluginInfo::~AUPluginInfo ()
1416 PluginPtr
1417 AUPluginInfo::load (Session& session)
1419 try {
1420 PluginPtr plugin;
1422 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
1424 if (!comp->IsValid()) {
1425 error << ("AudioUnit: not a valid Component") << endmsg;
1426 } else {
1427 plugin.reset (new AUPlugin (session.engine(), session, comp));
1430 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
1431 return plugin;
1434 catch (failed_constructor &err) {
1435 return PluginPtr ();
1439 Glib::ustring
1440 AUPluginInfo::au_cache_path ()
1442 return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
1445 PluginInfoList*
1446 AUPluginInfo::discover ()
1448 XMLTree tree;
1450 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
1451 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
1454 PluginInfoList* plugs = new PluginInfoList ();
1456 discover_fx (plugs);
1457 discover_music (plugs);
1458 discover_generators (plugs);
1460 return plugs;
1463 void
1464 AUPluginInfo::discover_music (PluginInfoList& plugs)
1466 CAComponentDescription desc;
1467 desc.componentFlags = 0;
1468 desc.componentFlagsMask = 0;
1469 desc.componentSubType = 0;
1470 desc.componentManufacturer = 0;
1471 desc.componentType = kAudioUnitType_MusicEffect;
1473 discover_by_description (plugs, desc);
1476 void
1477 AUPluginInfo::discover_fx (PluginInfoList& plugs)
1479 CAComponentDescription desc;
1480 desc.componentFlags = 0;
1481 desc.componentFlagsMask = 0;
1482 desc.componentSubType = 0;
1483 desc.componentManufacturer = 0;
1484 desc.componentType = kAudioUnitType_Effect;
1486 discover_by_description (plugs, desc);
1489 void
1490 AUPluginInfo::discover_generators (PluginInfoList& plugs)
1492 CAComponentDescription desc;
1493 desc.componentFlags = 0;
1494 desc.componentFlagsMask = 0;
1495 desc.componentSubType = 0;
1496 desc.componentManufacturer = 0;
1497 desc.componentType = kAudioUnitType_Generator;
1499 discover_by_description (plugs, desc);
1502 void
1503 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
1505 Component comp = 0;
1507 comp = FindNextComponent (NULL, &desc);
1509 while (comp != NULL) {
1510 CAComponentDescription temp;
1511 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
1513 AUPluginInfoPtr info (new AUPluginInfo
1514 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
1516 /* no panners, format converters or i/o AU's for our purposes
1519 switch (info->descriptor->Type()) {
1520 case kAudioUnitType_Panner:
1521 case kAudioUnitType_OfflineEffect:
1522 case kAudioUnitType_FormatConverter:
1523 continue;
1524 case kAudioUnitType_Output:
1525 case kAudioUnitType_MusicDevice:
1526 case kAudioUnitType_MusicEffect:
1527 case kAudioUnitType_Effect:
1528 case kAudioUnitType_Mixer:
1529 case kAudioUnitType_Generator:
1530 break;
1531 default:
1532 break;
1535 switch (info->descriptor->SubType()) {
1536 case kAudioUnitSubType_DefaultOutput:
1537 case kAudioUnitSubType_SystemOutput:
1538 case kAudioUnitSubType_GenericOutput:
1539 case kAudioUnitSubType_AUConverter:
1540 /* we don't want output units here */
1541 continue;
1542 break;
1544 case kAudioUnitSubType_DLSSynth:
1545 info->category = "DLS Synth";
1546 break;
1548 case kAudioUnitSubType_Varispeed:
1549 info->category = "Varispeed";
1550 break;
1552 case kAudioUnitSubType_Delay:
1553 info->category = "Delay";
1554 break;
1556 case kAudioUnitSubType_LowPassFilter:
1557 info->category = "Low-pass Filter";
1558 break;
1560 case kAudioUnitSubType_HighPassFilter:
1561 info->category = "High-pass Filter";
1562 break;
1564 case kAudioUnitSubType_BandPassFilter:
1565 info->category = "Band-pass Filter";
1566 break;
1568 case kAudioUnitSubType_HighShelfFilter:
1569 info->category = "High-shelf Filter";
1570 break;
1572 case kAudioUnitSubType_LowShelfFilter:
1573 info->category = "Low-shelf Filter";
1574 break;
1576 case kAudioUnitSubType_ParametricEQ:
1577 info->category = "Parametric EQ";
1578 break;
1580 case kAudioUnitSubType_GraphicEQ:
1581 info->category = "Graphic EQ";
1582 break;
1584 case kAudioUnitSubType_PeakLimiter:
1585 info->category = "Peak Limiter";
1586 break;
1588 case kAudioUnitSubType_DynamicsProcessor:
1589 info->category = "Dynamics Processor";
1590 break;
1592 case kAudioUnitSubType_MultiBandCompressor:
1593 info->category = "Multiband Compressor";
1594 break;
1596 case kAudioUnitSubType_MatrixReverb:
1597 info->category = "Matrix Reverb";
1598 break;
1600 case kAudioUnitSubType_SampleDelay:
1601 info->category = "Sample Delay";
1602 break;
1604 case kAudioUnitSubType_Pitch:
1605 info->category = "Pitch";
1606 break;
1608 case kAudioUnitSubType_NetSend:
1609 info->category = "Net Sender";
1610 break;
1612 case kAudioUnitSubType_3DMixer:
1613 info->category = "3DMixer";
1614 break;
1616 case kAudioUnitSubType_MatrixMixer:
1617 info->category = "MatrixMixer";
1618 break;
1620 case kAudioUnitSubType_ScheduledSoundPlayer:
1621 info->category = "Scheduled Sound Player";
1622 break;
1625 case kAudioUnitSubType_AudioFilePlayer:
1626 info->category = "Audio File Player";
1627 break;
1629 case kAudioUnitSubType_NetReceive:
1630 info->category = "Net Receiver";
1631 break;
1633 default:
1634 info->category = "";
1637 AUPluginInfo::get_names (temp, info->name, info->creator);
1639 info->type = ARDOUR::AudioUnit;
1640 info->unique_id = stringify_descriptor (*info->descriptor);
1642 /* XXX not sure of the best way to handle plugin versioning yet
1645 CAComponent cacomp (*info->descriptor);
1647 if (cacomp.GetResourceVersion (info->version) != noErr) {
1648 info->version = 0;
1651 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
1653 /* here we have to map apple's wildcard system to a simple pair
1654 of values. in ::can_do() we use the whole system, but here
1655 we need a single pair of values. XXX probably means we should
1656 remove any use of these values.
1659 info->n_inputs = info->cache.io_configs.front().first;
1660 info->n_outputs = info->cache.io_configs.front().second;
1662 if (info->cache.io_configs.size() > 1) {
1663 cerr << "ODD: variable IO config for " << info->unique_id << endl;
1666 plugs.push_back (info);
1668 } else {
1669 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
1672 comp = FindNextComponent (comp, &desc);
1676 bool
1677 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
1678 UInt32 version,
1679 CAComponent& comp,
1680 AUPluginCachedInfo& cinfo,
1681 const std::string& name)
1683 std::string id;
1684 char buf[32];
1686 /* concatenate unique ID with version to provide a key for cached info lookup.
1687 this ensures we don't get stale information, or should if plugin developers
1688 follow Apple "guidelines".
1691 snprintf (buf, sizeof (buf), "%u", version);
1692 id = unique_id;
1693 id += '/';
1694 id += buf;
1696 CachedInfoMap::iterator cim = cached_info.find (id);
1698 if (cim != cached_info.end()) {
1699 cinfo = cim->second;
1700 return true;
1703 CAAudioUnit unit;
1704 AUChannelInfo* channel_info;
1705 UInt32 cnt;
1706 int ret;
1708 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
1710 try {
1712 if (CAAudioUnit::Open (comp, unit) != noErr) {
1713 return false;
1716 } catch (...) {
1718 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
1719 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
1720 return false;
1724 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
1725 return false;
1728 if (ret > 0) {
1729 /* no explicit info available */
1731 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
1733 } else {
1735 /* store each configuration */
1737 for (uint32_t n = 0; n < cnt; ++n) {
1738 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
1739 channel_info[n].outChannels));
1742 free (channel_info);
1745 add_cached_info (id, cinfo);
1746 save_cached_info ();
1748 return true;
1751 void
1752 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
1754 cached_info[id] = cinfo;
1757 void
1758 AUPluginInfo::save_cached_info ()
1760 XMLNode* node;
1762 node = new XMLNode (X_("AudioUnitPluginCache"));
1764 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
1765 XMLNode* parent = new XMLNode (X_("plugin"));
1766 parent->add_property ("id", i->first);
1767 node->add_child_nocopy (*parent);
1769 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
1771 XMLNode* child = new XMLNode (X_("io"));
1772 char buf[32];
1774 snprintf (buf, sizeof (buf), "%d", j->first);
1775 child->add_property (X_("in"), buf);
1776 snprintf (buf, sizeof (buf), "%d", j->second);
1777 child->add_property (X_("out"), buf);
1778 parent->add_child_nocopy (*child);
1783 Glib::ustring path = au_cache_path ();
1784 XMLTree tree;
1786 tree.set_root (node);
1788 if (!tree.write (path)) {
1789 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
1790 unlink (path.c_str());
1795 AUPluginInfo::load_cached_info ()
1797 Glib::ustring path = au_cache_path ();
1798 XMLTree tree;
1800 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1801 return 0;
1804 tree.read (path);
1805 const XMLNode* root (tree.root());
1807 if (root->name() != X_("AudioUnitPluginCache")) {
1808 return -1;
1811 cached_info.clear ();
1813 const XMLNodeList children = root->children();
1815 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
1817 const XMLNode* child = *iter;
1819 if (child->name() == X_("plugin")) {
1821 const XMLNode* gchild;
1822 const XMLNodeList gchildren = child->children();
1823 const XMLProperty* prop = child->property (X_("id"));
1825 if (!prop) {
1826 continue;
1829 std::string id = prop->value();
1830 AUPluginCachedInfo cinfo;
1832 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
1834 gchild = *giter;
1836 if (gchild->name() == X_("io")) {
1838 const XMLProperty* iprop;
1839 const XMLProperty* oprop;
1841 if (((iprop = gchild->property (X_("in"))) != 0) &&
1842 ((oprop = gchild->property (X_("out"))) != 0)) {
1843 const int in = atoi (iprop->value());
1844 const int out = atoi (iprop->value());
1846 cinfo.io_configs.push_back (pair<int,int> (in, out));
1851 if (cinfo.io_configs.size()) {
1852 add_cached_info (id, cinfo);
1857 return 0;
1860 void
1861 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
1863 CFStringRef itemName = NULL;
1865 // Marc Poirier-style item name
1866 CAComponent auComponent (comp_desc);
1867 if (auComponent.IsValid()) {
1868 CAComponentDescription dummydesc;
1869 Handle nameHandle = NewHandle(sizeof(void*));
1870 if (nameHandle != NULL) {
1871 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
1872 if (err == noErr) {
1873 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
1874 if (nameString != NULL) {
1875 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
1878 DisposeHandle(nameHandle);
1882 // if Marc-style fails, do the original way
1883 if (itemName == NULL) {
1884 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
1885 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
1886 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
1888 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
1889 compTypeString, compManufacturerString, compSubTypeString);
1891 if (compTypeString != NULL)
1892 CFRelease(compTypeString);
1893 if (compSubTypeString != NULL)
1894 CFRelease(compSubTypeString);
1895 if (compManufacturerString != NULL)
1896 CFRelease(compManufacturerString);
1899 string str = CFStringRefToStdString(itemName);
1900 string::size_type colon = str.find (':');
1902 if (colon) {
1903 name = str.substr (colon+1);
1904 maker = str.substr (0, colon);
1905 // strip_whitespace_edges (maker);
1906 // strip_whitespace_edges (name);
1907 } else {
1908 name = str;
1909 maker = "unknown";
1913 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
1914 extern char *StringForOSType (OSType t, char *writeLocation);
1916 std::string
1917 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
1919 char str[24];
1920 stringstream s;
1922 s << StringForOSType (desc.Type(), str);
1923 s << " - ";
1925 s << StringForOSType (desc.SubType(), str);
1926 s << " - ";
1928 s << StringForOSType (desc.Manu(), str);
1930 return s.str();