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