mark AU plugin as uninitialized after uninitializing it
[ardour.git] / libs / ardour / audio_unit.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3         
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.
8
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.
13
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.
17
18 */
19
20 #include <sstream>
21 #include <errno.h>
22 #include <string.h>
23
24 #include <pbd/transmitter.h>
25 #include <pbd/xml++.h>
26 #include <pbd/whitespace.h>
27 #include <pbd/pathscanner.h>
28
29 #include <glibmm/thread.h>
30 #include <glibmm/fileutils.h>
31 #include <glibmm/miscutils.h>
32
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>
39
40 #include <appleutility/CAAudioUnit.h>
41 #include <appleutility/CAAUParameter.h>
42
43 #include <CoreFoundation/CoreFoundation.h>
44 #include <CoreServices/CoreServices.h>
45 #include <AudioUnit/AudioUnit.h>
46
47 #include "i18n.h"
48
49 using namespace std;
50 using namespace PBD;
51 using namespace ARDOUR;
52
53 #ifndef AU_STATE_SUPPORT
54 static bool seen_get_state_message = false;
55 static bool seen_set_state_message = false;
56 static bool seen_loading_message = false;
57 static bool seen_saving_message = false;
58 #endif
59
60 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
61
62 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
63 static string preset_suffix = ".aupreset";
64 static bool preset_search_path_initialized = false;
65
66 static OSStatus 
67 _render_callback(void *userData,
68                  AudioUnitRenderActionFlags *ioActionFlags,
69                  const AudioTimeStamp    *inTimeStamp,
70                  UInt32       inBusNumber,
71                  UInt32       inNumberFrames,
72                  AudioBufferList*       ioData)
73 {
74         return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
75 }
76
77 static int 
78 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
79
80 {
81         CFDataRef xmlData;
82         int fd;
83
84         // Convert the property list into XML data.
85         
86         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
87
88         if (!xmlData) {
89                 error << _("Could not create XML version of property list") << endmsg;
90                 return -1;
91         }
92
93         // Write the XML data to the file.
94
95         fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
96         while (fd < 0) {
97                 if (errno == EEXIST) {
98                         /* tell any UI's that this file already exists and ask them what to do */
99                         bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
100                         if (overwrite) {
101                                 fd = open (path.c_str(), O_WRONLY, 0664);
102                                 continue;
103                         } else {
104                                 return 0;
105                         }
106                 }
107                 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
108                 CFRelease (xmlData);
109                 return -1;
110         }
111
112         size_t cnt = CFDataGetLength (xmlData);
113
114         if (write (fd, CFDataGetBytePtr (xmlData), cnt) != cnt) {
115                 CFRelease (xmlData);
116                 close (fd);
117                 return -1;
118         }
119
120         close (fd);
121         return 0;
122 }
123  
124
125 static CFPropertyListRef 
126 load_property_list (Glib::ustring path) 
127 {
128         int fd;
129         CFPropertyListRef propertyList;
130         CFDataRef         xmlData;
131         CFStringRef       errorString;
132
133         // Read the XML file.
134         
135         if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
136                 return propertyList;
137
138         }
139         
140         off_t len = lseek (fd, 0, SEEK_END);
141         char* buf = new char[len];
142         lseek (fd, 0, SEEK_SET);
143
144         if (read (fd, buf, len) != len) {
145                 delete [] buf;
146                 close (fd);
147                 return propertyList;
148         }
149         
150         close (fd);
151
152         xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
153         
154         // Reconstitute the dictionary using the XML data.
155         
156         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
157                                                         xmlData,
158                                                         kCFPropertyListImmutable,
159                                                         &errorString);
160
161         CFRelease (xmlData);
162         delete [] buf;
163
164         return propertyList;
165 }
166
167 //-----------------------------------------------------------------------------
168 static void 
169 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
170 {
171         if (!plist) {
172                 return;
173         }
174         CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
175
176         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
177                 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
178         }
179         
180         CFRelease (pn);
181 }
182
183 //-----------------------------------------------------------------------------
184 static std::string
185 get_preset_name_in_plist (CFPropertyListRef plist)
186 {
187         std::string ret;
188
189         if (!plist) {
190                 return ret;
191         }
192
193         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
194                 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
195                 if (p) {
196                         CFStringRef str = (CFStringRef) p;
197                         int len = CFStringGetLength(str);
198                         len =  (len * 2) + 1;
199                         char local_buffer[len];
200                         if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
201                                 ret = local_buffer;
202                         }
203                 } 
204         }
205         return ret;
206 }
207
208 //--------------------------------------------------------------------------
209 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
210 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
211 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
212 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
213 {
214         if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
215                 return FALSE;
216
217         if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType) 
218                         && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
219         {
220                 // only sub-type and manufacturer IDs need to be equal
221                 if (inIgnoreType)
222                         return TRUE;
223                 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
224                 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
225                         return TRUE;
226         }
227
228         return FALSE;
229 }
230
231 //--------------------------------------------------------------------------
232 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
233 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
234 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
235 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
236 {
237         OSErr status;
238         ComponentDescription desc;
239
240         if ( (inComponent == NULL) || (inComponentDescription == NULL) )
241                 return FALSE;
242
243         // get the ComponentDescription of the input Component
244         status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
245         if (status != noErr)
246                 return FALSE;
247
248         // check if the Component's ComponentDescription matches the input ComponentDescription
249         return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
250 }
251
252 //--------------------------------------------------------------------------
253 // determine if 2 ComponentDescriptions are basically equal
254 // (by that, I mean that the important identifying values are compared, 
255 // but not the ComponentDescription flags)
256 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
257 {
258         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
259 }
260
261 //--------------------------------------------------------------------------
262 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
263 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
264 {
265         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
266 }
267
268 //--------------------------------------------------------------------------
269 // determine if a ComponentDescription basically matches that of a particular Component
270 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
271 {
272         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
273 }
274
275 //--------------------------------------------------------------------------
276 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
277 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
278 {
279         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
280 }
281
282
283 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
284         : Plugin (engine, session),
285           comp (_comp),
286           unit (new CAAudioUnit),
287           initialized (false),
288           buffers (0),
289           current_maxbuf (0),
290           current_offset (0),
291           current_buffers (0),
292         frames_processed (0)
293 {                       
294         if (!preset_search_path_initialized) {
295                 Glib::ustring p = Glib::get_home_dir();
296                 p += "/Library/Audio/Presets:";
297                 p += preset_search_path;
298                 preset_search_path = p;
299                 preset_search_path_initialized = true;
300         }
301
302         init ();
303 }
304
305 AUPlugin::AUPlugin (const AUPlugin& other)
306         : Plugin (other)
307         , comp (other.get_comp())
308         , unit (new CAAudioUnit)
309         , initialized (false)
310         , buffers (0)
311         , current_maxbuf (0)
312         , current_offset (0)
313         , current_buffers (0)
314         , frames_processed (0)
315           
316 {
317         init ();
318 }
319
320 AUPlugin::~AUPlugin ()
321 {
322         if (unit) {
323                 unit->Uninitialize ();
324         }
325
326         if (buffers) {
327                 free (buffers);
328         }
329 }
330
331
332 void
333 AUPlugin::init ()
334 {
335         OSErr err;
336
337         try {
338                 err = CAAudioUnit::Open (*(comp.get()), *unit);
339         } catch (...) {
340                 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
341                 throw failed_constructor();
342         }
343
344         if (err != noErr) {
345                 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
346                 throw failed_constructor ();
347         }
348         
349         AURenderCallbackStruct renderCallbackInfo;
350
351         renderCallbackInfo.inputProc = _render_callback;
352         renderCallbackInfo.inputProcRefCon = this;
353
354         if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 
355                                          0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
356                 cerr << "cannot install render callback (err = " << err << ')' << endl;
357                 throw failed_constructor();
358         }
359
360         unit->GetElementCount (kAudioUnitScope_Global, global_elements);
361         unit->GetElementCount (kAudioUnitScope_Input, input_elements);
362         unit->GetElementCount (kAudioUnitScope_Output, output_elements);
363
364         /* these keep track of *configured* channel set up,
365            not potential set ups.
366         */
367
368         input_channels = -1;
369         output_channels = -1;
370
371         if (_set_block_size (_session.get_block_size())) {
372                 error << _("AUPlugin: cannot set processing block size") << endmsg;
373                 throw failed_constructor();
374         }
375
376         discover_parameters ();
377
378         Plugin::setup_controls ();
379 }
380
381 void
382 AUPlugin::discover_parameters ()
383 {
384         /* discover writable parameters */
385         
386         AudioUnitScope scopes[] = { 
387                 kAudioUnitScope_Global,
388                 kAudioUnitScope_Output,
389                 kAudioUnitScope_Input
390         };
391
392         descriptors.clear ();
393
394         for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
395
396                 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
397                 
398                 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
399
400                         AUParameterDescriptor d;
401
402                         d.id = param_info.ParamID (i);
403
404                         const CAAUParameter* param = param_info.GetParamInfo (d.id);
405                         const AudioUnitParameterInfo& info (param->ParamInfo());
406
407                         const int len = CFStringGetLength (param->GetName());;
408                         char local_buffer[len*2];
409                         Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
410                         if (!good) {
411                                 d.label = "???";
412                         } else {
413                                 d.label = local_buffer;
414                         }
415
416                         d.scope = param_info.GetScope ();
417                         d.element = param_info.GetElement ();
418
419                         /* info.units to consider */
420                         /*
421                           kAudioUnitParameterUnit_Generic             = 0
422                           kAudioUnitParameterUnit_Indexed             = 1
423                           kAudioUnitParameterUnit_Boolean             = 2
424                           kAudioUnitParameterUnit_Percent             = 3
425                           kAudioUnitParameterUnit_Seconds             = 4
426                           kAudioUnitParameterUnit_SampleFrames        = 5
427                           kAudioUnitParameterUnit_Phase               = 6
428                           kAudioUnitParameterUnit_Rate                = 7
429                           kAudioUnitParameterUnit_Hertz               = 8
430                           kAudioUnitParameterUnit_Cents               = 9
431                           kAudioUnitParameterUnit_RelativeSemiTones   = 10
432                           kAudioUnitParameterUnit_MIDINoteNumber      = 11
433                           kAudioUnitParameterUnit_MIDIController      = 12
434                           kAudioUnitParameterUnit_Decibels            = 13
435                           kAudioUnitParameterUnit_LinearGain          = 14
436                           kAudioUnitParameterUnit_Degrees             = 15
437                           kAudioUnitParameterUnit_EqualPowerCrossfade = 16
438                           kAudioUnitParameterUnit_MixerFaderCurve1    = 17
439                           kAudioUnitParameterUnit_Pan                 = 18
440                           kAudioUnitParameterUnit_Meters              = 19
441                           kAudioUnitParameterUnit_AbsoluteCents       = 20
442                           kAudioUnitParameterUnit_Octaves             = 21
443                           kAudioUnitParameterUnit_BPM                 = 22
444                           kAudioUnitParameterUnit_Beats               = 23
445                           kAudioUnitParameterUnit_Milliseconds        = 24
446                           kAudioUnitParameterUnit_Ratio               = 25
447                         */
448
449                         /* info.flags to consider */
450
451                         /*
452
453                           kAudioUnitParameterFlag_CFNameRelease       = (1L << 4)
454                           kAudioUnitParameterFlag_HasClump            = (1L << 20)
455                           kAudioUnitParameterFlag_HasName             = (1L << 21)
456                           kAudioUnitParameterFlag_DisplayLogarithmic  = (1L << 22)
457                           kAudioUnitParameterFlag_IsHighResolution    = (1L << 23)
458                           kAudioUnitParameterFlag_NonRealTime         = (1L << 24)
459                           kAudioUnitParameterFlag_CanRamp             = (1L << 25)
460                           kAudioUnitParameterFlag_ExpertMode          = (1L << 26)
461                           kAudioUnitParameterFlag_HasCFNameString     = (1L << 27)
462                           kAudioUnitParameterFlag_IsGlobalMeta        = (1L << 28)
463                           kAudioUnitParameterFlag_IsElementMeta       = (1L << 29)
464                           kAudioUnitParameterFlag_IsReadable          = (1L << 30)
465                           kAudioUnitParameterFlag_IsWritable          = (1L << 31)
466                         */
467
468                         d.lower = info.minValue;
469                         d.upper = info.maxValue;
470                         d.default_value = info.defaultValue;
471
472                         d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
473                         d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean) ||
474                                 (d.integer_step && ((d.upper - d.lower) == 1.0));
475                         d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
476                         d.automatable = !d.toggled && 
477                                 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
478                                 (info.flags & kAudioUnitParameterFlag_IsWritable);
479                         
480                         d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
481                         d.unit = info.unit;
482
483                         d.step = 1.0;
484                         d.smallstep = 0.1;
485                         d.largestep = 10.0;
486                         d.min_unbound = 0; // lower is bound
487                         d.max_unbound = 0; // upper is bound
488
489                         descriptors.push_back (d);
490                 }
491         }
492 }
493
494
495 string
496 AUPlugin::unique_id () const
497 {
498         return AUPluginInfo::stringify_descriptor (comp->Desc());
499 }
500
501 const char *
502 AUPlugin::label () const
503 {
504         return _info->name.c_str();
505 }
506
507 uint32_t
508 AUPlugin::parameter_count () const
509 {
510         return descriptors.size();
511 }
512
513 float
514 AUPlugin::default_value (uint32_t port)
515 {
516         if (port < descriptors.size()) {
517                 return descriptors[port].default_value;
518         }
519
520         return 0;
521 }
522
523 nframes_t
524 AUPlugin::latency () const
525 {
526         return unit->Latency() * _session.frame_rate();
527 }
528
529 void
530 AUPlugin::set_parameter (uint32_t which, float val)
531 {
532         if (which < descriptors.size()) {
533                 const AUParameterDescriptor& d (descriptors[which]);
534                 unit->SetParameter (d.id, d.scope, d.element, val);
535         }
536 }
537
538 float
539 AUPlugin::get_parameter (uint32_t which) const
540 {
541         float val = 0.0;
542         if (which < descriptors.size()) {
543                 const AUParameterDescriptor& d (descriptors[which]);
544                 unit->GetParameter(d.id, d.scope, d.element, val);
545         }
546         return val;
547 }
548
549 int
550 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
551 {
552         if (which < descriptors.size()) {
553                 pd = descriptors[which];
554                 return 0;
555         } 
556         return -1;
557 }
558
559 uint32_t
560 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
561 {
562         if (which < descriptors.size()) {
563                 ok = true;
564                 return which;
565         }
566         ok = false;
567         return 0;
568 }
569
570 void
571 AUPlugin::activate ()
572 {
573         if (!initialized) {
574                 OSErr err;
575                 if ((err = unit->Initialize()) != noErr) {
576                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
577                 } else {
578                         frames_processed = 0;
579                         initialized = true;
580                 }
581         }
582 }
583
584 void
585 AUPlugin::deactivate ()
586 {
587         unit->GlobalReset ();
588 }
589
590 void
591 AUPlugin::set_block_size (nframes_t nframes)
592 {
593         _set_block_size (nframes);
594 }
595
596 int
597 AUPlugin::_set_block_size (nframes_t nframes)
598 {
599         bool was_initialized = initialized;
600         UInt32 numFrames = nframes;
601         OSErr err;
602
603         if (initialized) {
604                 unit->Uninitialize ();
605                 initialized = false;
606         }
607
608         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
609                                       0, &numFrames, sizeof (numFrames))) != noErr) {
610                 cerr << "cannot set max frames (err = " << err << ')' << endl;
611                 return -1;
612         }
613
614         if (was_initialized) {
615                 activate ();
616         }
617
618         return 0;
619 }
620
621 int32_t
622 AUPlugin::configure_io (int32_t in, int32_t out)
623 {
624         AudioStreamBasicDescription streamFormat;
625
626         streamFormat.mSampleRate = _session.frame_rate();
627         streamFormat.mFormatID = kAudioFormatLinearPCM;
628         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
629
630 #ifdef __LITTLE_ENDIAN__
631         /* relax */
632 #else
633         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
634 #endif
635
636         streamFormat.mBitsPerChannel = 32;
637         streamFormat.mFramesPerPacket = 1;
638
639         /* apple says that for non-interleaved data, these
640            values always refer to a single channel.
641         */
642         streamFormat.mBytesPerPacket = 4;
643         streamFormat.mBytesPerFrame = 4;
644
645         streamFormat.mChannelsPerFrame = in;
646
647         if (set_input_format (streamFormat) != 0) {
648                 return -1;
649         }
650
651         streamFormat.mChannelsPerFrame = out;
652
653         if (set_output_format (streamFormat) != 0) {
654                 return -1;
655         }
656
657         return Plugin::configure_io (in, out);
658 }
659
660 int32_t
661 AUPlugin::can_do (int32_t in, int32_t& out)
662 {
663         // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
664         // attempt to multiply-instantiate plugins to meet io configurations.
665
666         int32_t plugcnt = -1;
667         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
668
669         out = -1;
670
671         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
672
673         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
674
675                 int32_t possible_in = i->first;
676                 int32_t possible_out = i->second;
677
678                 if (possible_out == 0) {
679                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
680                         continue;
681                 }
682
683                 if (possible_in == 0) {
684
685                         /* instrument plugin, always legal but throws away inputs ...
686                         */
687
688                         if (possible_out == -1) {
689                                 /* out much match in (UNLIKELY!!) */
690                                 out = in;
691                                 plugcnt = 1;
692                         } else if (possible_out == -2) {
693                                 /* any configuration possible, pick matching */
694                                 out = in;
695                                 plugcnt = 1;
696                         } else if (possible_out < -2) {
697                                 /* explicit variable number of outputs, pick maximum */
698                                 out = -possible_out;
699                                 plugcnt = 1;
700                         } else {
701                                 /* exact number of outputs */
702                                 out = possible_out;
703                                 plugcnt = 1;
704                         }
705                 }
706                 
707                 if (possible_in == -1) {
708
709                         /* wildcard for input */
710
711                         if (possible_out == -1) {
712                                 /* out much match in */
713                                 out = in;
714                                 plugcnt = 1;
715                         } else if (possible_out == -2) {
716                                 /* any configuration possible, pick matching */
717                                 out = in;
718                                 plugcnt = 1;
719                         } else if (possible_out < -2) {
720                                 /* explicit variable number of outputs, pick maximum */
721                                 out = -possible_out;
722                                 plugcnt = 1;
723                         } else {
724                                 /* exact number of outputs */
725                                 out = possible_out;
726                                 plugcnt = 1;
727                         }
728                 }       
729                         
730                 if (possible_in == -2) {
731
732                         if (possible_out == -1) {
733                                 /* any configuration possible, pick matching */
734                                 out = in;
735                                 plugcnt = 1;
736                         } else if (possible_out == -2) {
737                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
738                                       << endmsg;
739                                 plugcnt = -1;
740                         } else if (possible_out < -2) {
741                                 /* explicit variable number of outputs, pick maximum */
742                                 out = -possible_out;
743                                 plugcnt = 1;
744                         } else {
745                                 /* exact number of outputs */
746                                 out = possible_out;
747                                 plugcnt = 1;
748                         }
749                 }
750
751                 if (possible_in < -2) {
752
753                         /* explicit variable number of inputs */
754
755                         if (in > -possible_in) {
756                                 /* request is too large */
757                                 plugcnt = -1;
758                         }
759
760                         if (possible_out == -1) {
761                                 /* out must match in */
762                                 out = in;
763                                 plugcnt = 1;
764                         } else if (possible_out == -2) {
765                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
766                                       << endmsg;
767                                 plugcnt = -1;
768                         } else if (possible_out < -2) {
769                                 /* explicit variable number of outputs, pick maximum */
770                                 out = -possible_out;
771                                 plugcnt = 1;
772                         } else {
773                                 /* exact number of outputs */
774                                 out = possible_out;
775                                 plugcnt = 1;
776                         }
777                 }
778
779                 if (possible_in == in) {
780
781                         /* exact number of inputs ... must match obviously */
782                         
783                         if (possible_out == -1) {
784                                 /* out must match in */
785                                 out = in;
786                                 plugcnt = 1;
787                         } else if (possible_out == -2) {
788                                 /* any output configuration, pick matching */
789                                 out = in;
790                                 plugcnt = -1;
791                         } else if (possible_out < -2) {
792                                 /* explicit variable number of outputs, pick maximum */
793                                 out = -possible_out;
794                                 plugcnt = 1;
795                         } else {
796                                 /* exact number of outputs */
797                                 out = possible_out;
798                                 plugcnt = 1;
799                         }
800                 }
801
802         }
803
804         /* no fit */
805         return plugcnt;
806 }
807
808 int
809 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
810 {
811         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
812 }
813
814 int
815 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
816 {
817         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
818                 return -1;
819         }
820
821         if (buffers) {
822                 free (buffers);
823                 buffers = 0;
824         }
825         
826         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
827                                               fmt.mChannelsPerFrame * sizeof(AudioBuffer));
828
829         Glib::Mutex::Lock em (_session.engine().process_lock());
830         IO::MoreOutputs (fmt.mChannelsPerFrame);
831
832         return 0;
833 }
834
835 int
836 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
837 {
838         OSErr result;
839
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;
845                 }
846         }
847
848         if (scope == kAudioUnitScope_Input) {
849                 input_channels = fmt.mChannelsPerFrame;
850         } else {
851                 output_channels = fmt.mChannelsPerFrame;
852         }
853
854         return 0;
855 }
856
857 uint32_t
858 AUPlugin::input_streams() const
859 {
860         if (input_channels < 0) {
861                 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
862                 return 1;
863         }
864         return input_channels;
865 }
866
867
868 uint32_t
869 AUPlugin::output_streams() const
870 {
871         if (output_channels < 0) {
872                 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
873                 return 1;
874         }
875         return output_channels;
876 }
877
878 OSStatus 
879 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
880                           const AudioTimeStamp    *inTimeStamp,
881                           UInt32       inBusNumber,
882                           UInt32       inNumberFrames,
883                           AudioBufferList*       ioData)
884 {
885         /* not much to do - the data is already in the buffers given to us in connect_and_run() */
886
887         if (current_maxbuf == 0) {
888                 error << _("AUPlugin: render callback called illegally!") << endmsg;
889                 return kAudioUnitErr_CannotDoInCurrentContext;
890         }
891
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;
896         }
897
898         cb_offset += inNumberFrames;
899
900         return noErr;
901 }
902
903 int
904 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
905 {
906         AudioUnitRenderActionFlags flags = 0;
907         AudioTimeStamp ts;
908
909         current_buffers = &bufs;
910         current_maxbuf = maxbuf;
911         current_offset = offset;
912         cb_offset = 0;
913
914         buffers->mNumberBuffers = maxbuf;
915
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;
920         }
921
922         ts.mSampleTime = frames_processed;
923         ts.mFlags = kAudioTimeStampSampleTimeValid;
924
925         if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
926
927                 current_maxbuf = 0;
928                 frames_processed += nframes;
929                 
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));
933                         }
934                 }
935                 return 0;
936         }
937
938         return -1;
939 }
940
941 set<uint32_t>
942 AUPlugin::automatable() const
943 {
944         set<uint32_t> automates;
945
946         for (uint32_t i = 0; i < descriptors.size(); ++i) {
947                 if (descriptors[i].automatable) {
948                         automates.insert (i);
949                 }
950         }
951
952         return automates;
953 }
954
955 string
956 AUPlugin::describe_parameter (uint32_t param)
957 {
958         return descriptors[param].label;
959 }
960
961 void
962 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
963 {
964         // NameValue stuff here
965 }
966
967 bool
968 AUPlugin::parameter_is_audio (uint32_t) const
969 {
970         return false;
971 }
972
973 bool
974 AUPlugin::parameter_is_control (uint32_t) const
975 {
976         return true;
977 }
978
979 bool
980 AUPlugin::parameter_is_input (uint32_t) const
981 {
982         return false;
983 }
984
985 bool
986 AUPlugin::parameter_is_output (uint32_t) const
987 {
988         return false;
989 }
990
991 XMLNode&
992 AUPlugin::get_state()
993 {
994         LocaleGuard lg (X_("POSIX"));
995         XMLNode *root = new XMLNode (state_node_name());
996
997 #ifdef AU_STATE_SUPPORT
998         CFDataRef xmlData;
999         CFPropertyListRef propertyList;
1000
1001         if (unit->GetAUPreset (propertyList) != noErr) {
1002                 return *root;
1003         }
1004
1005         // Convert the property list into XML data.
1006         
1007         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1008
1009         if (!xmlData) {
1010                 error << _("Could not create XML version of property list") << endmsg;
1011                 return *root;
1012         }
1013
1014         /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1015            our state node. GACK!
1016         */
1017
1018         XMLTree t;
1019
1020         if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1021                 if (t.root()) {
1022                         root->add_child_copy (*t.root());
1023                 }
1024         }
1025
1026         CFRelease (xmlData);
1027         CFRelease (propertyList);
1028 #else
1029         if (!seen_get_state_message) {
1030                 info << _("Saving AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1031                      << endmsg;
1032                 seen_get_state_message = true;
1033         }
1034 #endif
1035         
1036         return *root;
1037 }
1038
1039 int
1040 AUPlugin::set_state(const XMLNode& node)
1041 {
1042 #ifdef AU_STATE_SUPPORT
1043         int ret = -1;
1044         CFPropertyListRef propertyList;
1045         LocaleGuard lg (X_("POSIX"));
1046
1047         if (node.name() != state_node_name()) {
1048                 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1049                 return -1;
1050         }
1051         
1052         if (node.children().empty()) {
1053                 return -1;
1054         }
1055
1056         XMLNode* top = node.children().front();
1057         XMLNode* copy = new XMLNode (*top);
1058
1059         XMLTree t;
1060         t.set_root (copy);
1061
1062         const string& xml = t.write_buffer ();
1063         CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1064         CFStringRef errorString;
1065
1066         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1067                                                         xmlData,
1068                                                         kCFPropertyListImmutable,
1069                                                         &errorString);
1070
1071         CFRelease (xmlData);
1072         
1073         if (propertyList) {
1074                 if (unit->SetAUPreset (propertyList) == noErr) {
1075                         ret = 0;
1076                 } 
1077                 CFRelease (propertyList);
1078         }
1079         
1080         return ret;
1081 #else
1082         if (!seen_set_state_message) {
1083                 info << _("Restoring AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1084                      << endmsg;
1085         }
1086         return 0;
1087 #endif
1088 }
1089
1090 bool
1091 AUPlugin::load_preset (const string preset_label)
1092 {
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);
1098
1099         if (x == preset_map.end()) {
1100                 return false;
1101         }
1102         
1103         if ((propertyList = load_property_list (x->second)) != 0) {
1104                 if (unit->SetAUPreset (propertyList) == noErr) {
1105                         ret = true;
1106                 }
1107                 CFRelease(propertyList);
1108         }
1109         
1110         return ret;
1111 #else
1112         if (!seen_loading_message) {
1113                 info << _("Loading AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1114                      << endmsg;
1115                 seen_loading_message = true;
1116         }
1117         return true;
1118 #endif
1119 }
1120
1121 bool
1122 AUPlugin::save_preset (string preset_name)
1123 {
1124 #ifdef AU_STATE_SUPPORT
1125         CFPropertyListRef propertyList;
1126         vector<Glib::ustring> v;
1127         Glib::ustring user_preset_path;
1128         bool ret = true;
1129
1130         std::string m = maker();
1131         std::string n = name();
1132         
1133         strip_whitespace_edges (m);
1134         strip_whitespace_edges (n);
1135
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);
1142         
1143         user_preset_path = Glib::build_filename (v);
1144
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;
1148         }
1149
1150         if (unit->GetAUPreset (propertyList) != noErr) {
1151                 return false;
1152         }
1153
1154         // add the actual preset name */
1155
1156         v.push_back (preset_name + preset_suffix);
1157                 
1158         // rebuild
1159
1160         user_preset_path = Glib::build_filename (v);
1161         
1162         set_preset_name_in_plist (propertyList, preset_name);
1163
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;
1167         }
1168
1169         CFRelease(propertyList);
1170
1171         return ret;
1172 #else
1173         if (!seen_saving_message) {
1174                 info << _("Saving AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1175                      << endmsg;
1176                 seen_saving_message = true;
1177         }
1178         return false;
1179 #endif
1180 }
1181
1182 //-----------------------------------------------------------------------------
1183 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1184 static SInt32 
1185 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1186 {
1187         CFNumberRef cfNumber;
1188         SInt32 numberValue = 0;
1189         Boolean dummySuccess;
1190
1191         if (outSuccess == NULL)
1192                 outSuccess = &dummySuccess;
1193         if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1194         {
1195                 *outSuccess = FALSE;
1196                 return 0;
1197         }
1198
1199         cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1200         if (cfNumber == NULL)
1201         {
1202                 *outSuccess = FALSE;
1203                 return 0;
1204         }
1205         *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1206         if (*outSuccess)
1207                 return numberValue;
1208         else
1209                 return 0;
1210 }
1211
1212 static OSStatus 
1213 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1214 {
1215         CFDictionaryRef auStateDictionary;
1216         ComponentDescription tempDesc = {0};
1217         SInt32 versionValue;
1218         Boolean gotValue;
1219
1220         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1221                 return paramErr;
1222         
1223         // the property list for AU state data must be of the dictionary type
1224         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1225                 return kAudioUnitErr_InvalidPropertyValue;
1226         }
1227
1228         auStateDictionary = (CFDictionaryRef)inAUStateData;
1229
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);
1233
1234         if (!gotValue) {
1235                 return kAudioUnitErr_InvalidPropertyValue;
1236         }
1237 #define kCurrentSavedStateVersion 0
1238         if (versionValue != kCurrentSavedStateVersion) {
1239                 return kAudioUnitErr_InvalidPropertyValue;
1240         }
1241
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;
1249
1250         *outComponentDescription = tempDesc;
1251         return noErr;
1252 }
1253
1254
1255 static bool au_preset_filter (const string& str, void* arg)
1256 {
1257         /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1258
1259         bool ret;
1260         
1261         ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1262
1263         if (ret && arg) {
1264
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.
1268                 */
1269
1270                 Plugin* p = (Plugin *) arg;
1271                 string match = p->maker();
1272                 match += '/';
1273                 match += p->name();
1274
1275                 ret = str.find (match) != string::npos;
1276
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;
1285                         
1286                         ret = str.find (match) != string::npos;
1287                 }
1288         }
1289         
1290         return ret;
1291 }
1292
1293 bool 
1294 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1295 {
1296         OSStatus status;
1297         CFPropertyListRef plist;
1298         ComponentDescription presetDesc;
1299         bool ret = false;
1300                 
1301         plist = load_property_list (pathstr);
1302
1303         if (!plist) {
1304                 return ret;
1305         }
1306         
1307         // get the ComponentDescription from the AU preset file
1308         
1309         status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1310         
1311         if (status == noErr) {
1312                 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1313
1314                         /* try to get the preset name from the property list */
1315
1316                         if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1317
1318                                 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1319
1320                                 if (psk) {
1321
1322                                         const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1323
1324                                         if (!p) {
1325                                                 char buf[PATH_MAX+1];
1326
1327                                                 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1328                                                         preset_name = buf;
1329                                                 }
1330                                         }
1331                                 }
1332                         }
1333                 } 
1334         }
1335
1336         CFRelease (plist);
1337
1338         return true;
1339 }
1340
1341 std::string
1342 AUPlugin::current_preset() const
1343 {
1344         string preset_name;
1345         
1346 #ifdef AU_STATE_SUPPORT
1347         CFPropertyListRef propertyList;
1348
1349         if (unit->GetAUPreset (propertyList) == noErr) {
1350                 preset_name = get_preset_name_in_plist (propertyList);
1351                 CFRelease(propertyList);
1352         }
1353 #endif
1354         return preset_name;
1355 }
1356
1357 vector<string>
1358 AUPlugin::get_presets ()
1359 {
1360         vector<string*>* preset_files;
1361         vector<string> presets;
1362         PathScanner scanner;
1363
1364         preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1365         
1366         if (!preset_files) {
1367                 return presets;
1368         }
1369
1370         for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1371
1372                 string path = *(*x);
1373                 string preset_name;
1374
1375                 /* make an initial guess at the preset name using the path */
1376
1377                 preset_name = Glib::path_get_basename (path);
1378                 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1379
1380                 /* check that this preset file really matches this plugin
1381                    and potentially get the "real" preset name from
1382                    within the file.
1383                 */
1384
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;
1388                 } 
1389
1390                 delete *x;
1391         }
1392
1393         delete preset_files;
1394         
1395         return presets;
1396 }
1397
1398 bool
1399 AUPlugin::has_editor () const
1400 {
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;
1404 }
1405
1406 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
1407         : descriptor (d)
1408 {
1409
1410 }
1411
1412 AUPluginInfo::~AUPluginInfo ()
1413 {
1414 }
1415
1416 PluginPtr
1417 AUPluginInfo::load (Session& session)
1418 {
1419         try {
1420                 PluginPtr plugin;
1421
1422                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
1423                 
1424                 if (!comp->IsValid()) {
1425                         error << ("AudioUnit: not a valid Component") << endmsg;
1426                 } else {
1427                         plugin.reset (new AUPlugin (session.engine(), session, comp));
1428                 }
1429                 
1430                 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
1431                 return plugin;
1432         }
1433
1434         catch (failed_constructor &err) {
1435                 return PluginPtr ();
1436         }
1437 }
1438
1439 Glib::ustring
1440 AUPluginInfo::au_cache_path ()
1441 {
1442         return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
1443 }
1444
1445 PluginInfoList
1446 AUPluginInfo::discover ()
1447 {
1448         XMLTree tree;
1449
1450         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
1451                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
1452         }
1453
1454         PluginInfoList plugs;
1455         
1456         discover_fx (plugs);
1457         discover_music (plugs);
1458         discover_generators (plugs);
1459
1460         return plugs;
1461 }
1462
1463 void
1464 AUPluginInfo::discover_music (PluginInfoList& plugs)
1465 {
1466         CAComponentDescription desc;
1467         desc.componentFlags = 0;
1468         desc.componentFlagsMask = 0;
1469         desc.componentSubType = 0;
1470         desc.componentManufacturer = 0;
1471         desc.componentType = kAudioUnitType_MusicEffect;
1472
1473         discover_by_description (plugs, desc);
1474 }
1475
1476 void
1477 AUPluginInfo::discover_fx (PluginInfoList& plugs)
1478 {
1479         CAComponentDescription desc;
1480         desc.componentFlags = 0;
1481         desc.componentFlagsMask = 0;
1482         desc.componentSubType = 0;
1483         desc.componentManufacturer = 0;
1484         desc.componentType = kAudioUnitType_Effect;
1485
1486         discover_by_description (plugs, desc);
1487 }
1488
1489 void
1490 AUPluginInfo::discover_generators (PluginInfoList& plugs)
1491 {
1492         CAComponentDescription desc;
1493         desc.componentFlags = 0;
1494         desc.componentFlagsMask = 0;
1495         desc.componentSubType = 0;
1496         desc.componentManufacturer = 0;
1497         desc.componentType = kAudioUnitType_Generator;
1498
1499         discover_by_description (plugs, desc);
1500 }
1501
1502 void
1503 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
1504 {
1505         Component comp = 0;
1506
1507         comp = FindNextComponent (NULL, &desc);
1508
1509         while (comp != NULL) {
1510                 CAComponentDescription temp;
1511                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
1512
1513                 AUPluginInfoPtr info (new AUPluginInfo 
1514                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
1515
1516                 /* no panners, format converters or i/o AU's for our purposes
1517                  */
1518
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;
1533                 }
1534
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;
1543
1544                 case kAudioUnitSubType_DLSSynth:
1545                         info->category = "DLS Synth";
1546                         break;
1547
1548                 case kAudioUnitSubType_Varispeed:
1549                         info->category = "Varispeed";
1550                         break;
1551
1552                 case kAudioUnitSubType_Delay:
1553                         info->category = "Delay";
1554                         break;
1555
1556                 case kAudioUnitSubType_LowPassFilter:
1557                         info->category = "Low-pass Filter";
1558                         break;
1559
1560                 case kAudioUnitSubType_HighPassFilter:
1561                         info->category = "High-pass Filter";
1562                         break;
1563
1564                 case kAudioUnitSubType_BandPassFilter:
1565                         info->category = "Band-pass Filter";
1566                         break;
1567
1568                 case kAudioUnitSubType_HighShelfFilter:
1569                         info->category = "High-shelf Filter";
1570                         break;
1571
1572                 case kAudioUnitSubType_LowShelfFilter:
1573                         info->category = "Low-shelf Filter";
1574                         break;
1575
1576                 case kAudioUnitSubType_ParametricEQ:
1577                         info->category = "Parametric EQ";
1578                         break;
1579
1580                 case kAudioUnitSubType_GraphicEQ:
1581                         info->category = "Graphic EQ";
1582                         break;
1583
1584                 case kAudioUnitSubType_PeakLimiter:
1585                         info->category = "Peak Limiter";
1586                         break;
1587
1588                 case kAudioUnitSubType_DynamicsProcessor:
1589                         info->category = "Dynamics Processor";
1590                         break;
1591
1592                 case kAudioUnitSubType_MultiBandCompressor:
1593                         info->category = "Multiband Compressor";
1594                         break;
1595
1596                 case kAudioUnitSubType_MatrixReverb:
1597                         info->category = "Matrix Reverb";
1598                         break;
1599
1600                 case kAudioUnitSubType_SampleDelay:
1601                         info->category = "Sample Delay";
1602                         break;
1603
1604                 case kAudioUnitSubType_Pitch:
1605                         info->category = "Pitch";
1606                         break;
1607
1608                 case kAudioUnitSubType_NetSend:
1609                         info->category = "Net Sender";
1610                         break;
1611
1612                 case kAudioUnitSubType_3DMixer:
1613                         info->category = "3DMixer";
1614                         break;
1615
1616                 case kAudioUnitSubType_MatrixMixer:
1617                         info->category = "MatrixMixer";
1618                         break;
1619
1620                 case kAudioUnitSubType_ScheduledSoundPlayer:
1621                         info->category = "Scheduled Sound Player";
1622                         break;
1623
1624
1625                 case kAudioUnitSubType_AudioFilePlayer:
1626                         info->category = "Audio File Player";
1627                         break;
1628
1629                 case kAudioUnitSubType_NetReceive:
1630                         info->category = "Net Receiver";
1631                         break;
1632
1633                 default:
1634                         info->category = "";
1635                 }
1636
1637                 AUPluginInfo::get_names (temp, info->name, info->creator);
1638
1639                 info->type = ARDOUR::AudioUnit;
1640                 info->unique_id = stringify_descriptor (*info->descriptor);
1641
1642                 /* XXX not sure of the best way to handle plugin versioning yet
1643                  */
1644
1645                 CAComponent cacomp (*info->descriptor);
1646
1647                 if (cacomp.GetResourceVersion (info->version) != noErr) {
1648                         info->version = 0;
1649                 }
1650                 
1651                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
1652
1653                         /* here we have to map apple's wildcard system to a simple pair
1654                            of values.
1655                         */
1656
1657                         info->n_inputs = info->cache.io_configs.front().first;
1658                         info->n_outputs = info->cache.io_configs.front().second;
1659
1660                         if (info->cache.io_configs.size() > 1) {
1661                                 cerr << "ODD: variable IO config for " << info->unique_id << endl;
1662                         }
1663
1664                         plugs.push_back (info);
1665
1666                 } else {
1667                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
1668                 }
1669                 
1670                 comp = FindNextComponent (comp, &desc);
1671         }
1672 }
1673
1674 bool
1675 AUPluginInfo::cached_io_configuration (const std::string& unique_id, 
1676                                        UInt32 version,
1677                                        CAComponent& comp, 
1678                                        AUPluginCachedInfo& cinfo, 
1679                                        const std::string& name)
1680 {
1681         std::string id;
1682         char buf[32];
1683
1684         /* concatenate unique ID with version to provide a key for cached info lookup.
1685            this ensures we don't get stale information, or should if plugin developers
1686            follow Apple "guidelines".
1687          */
1688
1689         snprintf (buf, sizeof (buf), "%u", version);
1690         id = unique_id;
1691         id += '/';
1692         id += buf;
1693
1694         CachedInfoMap::iterator cim = cached_info.find (id);
1695
1696         if (cim != cached_info.end()) {
1697                 cinfo = cim->second;
1698                 return true;
1699         }
1700
1701         CAAudioUnit unit;
1702         AUChannelInfo* channel_info;
1703         UInt32 cnt;
1704         int ret;
1705         
1706         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
1707         
1708         try {
1709
1710                 if (CAAudioUnit::Open (comp, unit) != noErr) {
1711                         return false;
1712                 }
1713
1714         } catch (...) {
1715
1716                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
1717                 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
1718                 return false;
1719
1720         }
1721                 
1722         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
1723                 return false;
1724         }
1725
1726         if (ret > 0) {
1727                 /* no explicit info available */
1728
1729                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
1730
1731         } else {
1732                 
1733                 /* store each configuration */
1734                 
1735                 for (uint32_t n = 0; n < cnt; ++n) {
1736                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
1737                                                                    channel_info[n].outChannels));
1738                 }
1739
1740                 free (channel_info);
1741         }
1742
1743         add_cached_info (id, cinfo);
1744         save_cached_info ();
1745
1746         return true;
1747 }
1748
1749 void
1750 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
1751 {
1752         cached_info[id] = cinfo;
1753 }
1754
1755 void
1756 AUPluginInfo::save_cached_info ()
1757 {
1758         XMLNode* node;
1759
1760         node = new XMLNode (X_("AudioUnitPluginCache"));
1761         
1762         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
1763                 XMLNode* parent = new XMLNode (X_("plugin"));
1764                 parent->add_property ("id", i->first);
1765                 node->add_child_nocopy (*parent);
1766
1767                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
1768
1769                         XMLNode* child = new XMLNode (X_("io"));
1770                         char buf[32];
1771
1772                         snprintf (buf, sizeof (buf), "%d", j->first);
1773                         child->add_property (X_("in"), buf);
1774                         snprintf (buf, sizeof (buf), "%d", j->second);
1775                         child->add_property (X_("out"), buf);
1776                         parent->add_child_nocopy (*child);
1777                 }
1778
1779         }
1780
1781         Glib::ustring path = au_cache_path ();
1782         XMLTree tree;
1783
1784         tree.set_root (node);
1785
1786         if (!tree.write (path)) {
1787                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
1788                 unlink (path.c_str());
1789         }
1790 }
1791
1792 int
1793 AUPluginInfo::load_cached_info ()
1794 {
1795         Glib::ustring path = au_cache_path ();
1796         XMLTree tree;
1797         
1798         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1799                 return 0;
1800         }
1801
1802         tree.read (path);
1803         const XMLNode* root (tree.root());
1804
1805         if (root->name() != X_("AudioUnitPluginCache")) {
1806                 return -1;
1807         }
1808
1809         cached_info.clear ();
1810
1811         const XMLNodeList children = root->children();
1812
1813         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
1814                 
1815                 const XMLNode* child = *iter;
1816                 
1817                 if (child->name() == X_("plugin")) {
1818
1819                         const XMLNode* gchild;
1820                         const XMLNodeList gchildren = child->children();
1821                         const XMLProperty* prop = child->property (X_("id"));
1822
1823                         if (!prop) {
1824                                 continue;
1825                         }
1826
1827                         std::string id = prop->value();
1828                         
1829                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
1830
1831                                 gchild = *giter;
1832
1833                                 if (gchild->name() == X_("io")) {
1834
1835                                         int in;
1836                                         int out;
1837                                         const XMLProperty* iprop;
1838                                         const XMLProperty* oprop;
1839
1840                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
1841                                             ((oprop = gchild->property (X_("out"))) != 0)) {
1842                                                 in = atoi (iprop->value());
1843                                                 out = atoi (iprop->value());
1844                                                 
1845                                                 AUPluginCachedInfo cinfo;
1846                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
1847                                                 add_cached_info (id, cinfo);
1848                                         }
1849                                 }
1850                         }
1851                 }
1852         }
1853
1854         return 0;
1855 }
1856
1857 void
1858 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
1859 {
1860         CFStringRef itemName = NULL;
1861
1862         // Marc Poirier-style item name
1863         CAComponent auComponent (comp_desc);
1864         if (auComponent.IsValid()) {
1865                 CAComponentDescription dummydesc;
1866                 Handle nameHandle = NewHandle(sizeof(void*));
1867                 if (nameHandle != NULL) {
1868                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
1869                         if (err == noErr) {
1870                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
1871                                 if (nameString != NULL) {
1872                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
1873                                 }
1874                         }
1875                         DisposeHandle(nameHandle);
1876                 }
1877         }
1878     
1879         // if Marc-style fails, do the original way
1880         if (itemName == NULL) {
1881                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
1882                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
1883                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
1884     
1885                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"), 
1886                         compTypeString, compManufacturerString, compSubTypeString);
1887     
1888                 if (compTypeString != NULL)
1889                         CFRelease(compTypeString);
1890                 if (compSubTypeString != NULL)
1891                         CFRelease(compSubTypeString);
1892                 if (compManufacturerString != NULL)
1893                         CFRelease(compManufacturerString);
1894         }
1895         
1896         string str = CFStringRefToStdString(itemName);
1897         string::size_type colon = str.find (':');
1898
1899         if (colon) {
1900                 name = str.substr (colon+1);
1901                 maker = str.substr (0, colon);
1902                 // strip_whitespace_edges (maker);
1903                 // strip_whitespace_edges (name);
1904         } else {
1905                 name = str;
1906                 maker = "unknown";
1907         }
1908 }
1909
1910 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
1911 extern char *StringForOSType (OSType t, char *writeLocation);
1912
1913 std::string
1914 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
1915 {
1916         char str[24];
1917         stringstream s;
1918
1919         s << StringForOSType (desc.Type(), str);
1920         s << " - ";
1921                 
1922         s << StringForOSType (desc.SubType(), str);
1923         s << " - ";
1924                 
1925         s << StringForOSType (desc.Manu(), str);
1926
1927         return s.str();
1928 }