AU blacklist
[ardour.git] / libs / ardour / audio_unit.cc
1 /*
2     Copyright (C) 2006-2009 Paul Davis
3     Some portions Copyright (C) Sophia Poirier.
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <sstream>
22 #include <fstream>
23 #include <errno.h>
24 #include <string.h>
25 #include <math.h>
26 #include <ctype.h>
27
28 #include "pbd/transmitter.h"
29 #include "pbd/xml++.h"
30 #include "pbd/convert.h"
31 #include "pbd/whitespace.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/locale_guard.h"
34
35 #include <glibmm/threads.h>
36 #include <glibmm/fileutils.h>
37 #include <glibmm/miscutils.h>
38 #include <glib/gstdio.h>
39
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
52
53 #include "appleutility/CAAudioUnit.h"
54 #include "appleutility/CAAUParameter.h"
55
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
60 #ifdef WITH_CARBON
61 #include <Carbon/Carbon.h>
62 #endif
63
64 #include "i18n.h"
65
66 using namespace std;
67 using namespace PBD;
68 using namespace ARDOUR;
69
70 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
71
72 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
73 static string preset_suffix = ".aupreset";
74 static bool preset_search_path_initialized = false;
75 FILE * AUPluginInfo::_crashlog_fd = NULL;
76
77
78 static void au_blacklist (std::string id)
79 {
80         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
81         FILE * blacklist_fd = NULL;
82         if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
83                 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
84                 return;
85         }
86         assert(id.find("\n") == string::npos);
87         fprintf(blacklist_fd, "%s\n", id.c_str());
88         ::fclose(blacklist_fd);
89 }
90
91 static void au_unblacklist (std::string id)
92 {
93         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
94         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
95                 PBD::warning << "Expected Blacklist file does not exist.\n";
96                 return;
97         }
98
99         std::string bl;
100         std::ifstream ifs(fn.c_str());
101         bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
102         ::g_unlink(fn.c_str());
103
104         assert(id.find("\n") == string::npos);
105
106         id += "\n"; // add separator
107         const size_t rpl = bl.find(id);
108         if (rpl != string::npos) {
109                 bl.replace(rpl, id.size(), "");
110         }
111         if (bl.empty()) {
112                 return;
113         }
114
115         FILE * blacklist_fd = NULL;
116         if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
117                 PBD::error << "Cannot open AU blacklist.\n";
118                 return;
119         }
120         fprintf(blacklist_fd, "%s", bl.c_str());
121         ::fclose(blacklist_fd);
122 }
123
124 static bool is_blacklisted (std::string id)
125 {
126         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
127         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
128                 return false;
129         }
130         std::string bl;
131         std::ifstream ifs(fn.c_str());
132         bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
133
134         assert(id.find("\n") == string::npos);
135
136         id += "\n"; // add separator
137         const size_t rpl = bl.find(id);
138         if (rpl != string::npos) {
139                 return true;
140         }
141         return false;
142 }
143
144
145
146 static OSStatus
147 _render_callback(void *userData,
148                  AudioUnitRenderActionFlags *ioActionFlags,
149                  const AudioTimeStamp    *inTimeStamp,
150                  UInt32       inBusNumber,
151                  UInt32       inNumberFrames,
152                  AudioBufferList*       ioData)
153 {
154         if (userData) {
155                 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
156         }
157         return paramErr;
158 }
159
160 static OSStatus
161 _get_beat_and_tempo_callback (void*    userData,
162                               Float64* outCurrentBeat,
163                               Float64* outCurrentTempo)
164 {
165         if (userData) {
166                 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
167         }
168
169         return paramErr;
170 }
171
172 static OSStatus
173 _get_musical_time_location_callback (void *     userData,
174                                      UInt32 *   outDeltaSampleOffsetToNextBeat,
175                                      Float32 *  outTimeSig_Numerator,
176                                      UInt32 *   outTimeSig_Denominator,
177                                      Float64 *  outCurrentMeasureDownBeat)
178 {
179         if (userData) {
180                 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
181                                                                                   outTimeSig_Numerator,
182                                                                                   outTimeSig_Denominator,
183                                                                                   outCurrentMeasureDownBeat);
184         }
185         return paramErr;
186 }
187
188 static OSStatus
189 _get_transport_state_callback (void*     userData,
190                                Boolean*  outIsPlaying,
191                                Boolean*  outTransportStateChanged,
192                                Float64*  outCurrentSampleInTimeLine,
193                                Boolean*  outIsCycling,
194                                Float64*  outCycleStartBeat,
195                                Float64*  outCycleEndBeat)
196 {
197         if (userData) {
198                 return ((AUPlugin*)userData)->get_transport_state_callback (
199                         outIsPlaying, outTransportStateChanged,
200                         outCurrentSampleInTimeLine, outIsCycling,
201                         outCycleStartBeat, outCycleEndBeat);
202         }
203         return paramErr;
204 }
205
206
207 static int
208 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
209
210 {
211         CFDataRef xmlData;
212         int fd;
213
214         // Convert the property list into XML data.
215
216         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
217
218         if (!xmlData) {
219                 error << _("Could not create XML version of property list") << endmsg;
220                 return -1;
221         }
222
223         // Write the XML data to the file.
224
225         fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
226         while (fd < 0) {
227                 if (errno == EEXIST) {
228                         error << string_compose (_("Preset file %1 exists; not overwriting"),
229                                                  path) << endmsg;
230                 } else {
231                         error << string_compose (_("Cannot open preset file %1 (%2)"),
232                                                  path, strerror (errno)) << endmsg;
233                 }
234                 CFRelease (xmlData);
235                 return -1;
236         }
237
238         size_t cnt = CFDataGetLength (xmlData);
239
240         if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
241                 CFRelease (xmlData);
242                 close (fd);
243                 return -1;
244         }
245
246         close (fd);
247         return 0;
248 }
249
250
251 static CFPropertyListRef
252 load_property_list (Glib::ustring path)
253 {
254         int fd;
255         CFPropertyListRef propertyList = 0;
256         CFDataRef         xmlData;
257         CFStringRef       errorString;
258
259         // Read the XML file.
260
261         if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
262                 return propertyList;
263
264         }
265
266         off_t len = lseek (fd, 0, SEEK_END);
267         char* buf = new char[len];
268         lseek (fd, 0, SEEK_SET);
269
270         if (read (fd, buf, len) != len) {
271                 delete [] buf;
272                 close (fd);
273                 return propertyList;
274         }
275
276         close (fd);
277
278         xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
279
280         // Reconstitute the dictionary using the XML data.
281
282         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
283                                                         xmlData,
284                                                         kCFPropertyListImmutable,
285                                                         &errorString);
286
287         CFRelease (xmlData);
288         delete [] buf;
289
290         return propertyList;
291 }
292
293 //-----------------------------------------------------------------------------
294 static void
295 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
296 {
297         if (!plist) {
298                 return;
299         }
300         CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
301
302         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
303                 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
304         }
305
306         CFRelease (pn);
307 }
308
309 //-----------------------------------------------------------------------------
310 static std::string
311 get_preset_name_in_plist (CFPropertyListRef plist)
312 {
313         std::string ret;
314
315         if (!plist) {
316                 return ret;
317         }
318
319         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
320                 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
321                 if (p) {
322                         CFStringRef str = (CFStringRef) p;
323                         int len = CFStringGetLength(str);
324                         len =  (len * 2) + 1;
325                         char local_buffer[len];
326                         if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
327                                 ret = local_buffer;
328                         }
329                 }
330         }
331         return ret;
332 }
333
334 //--------------------------------------------------------------------------
335 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
336 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
337 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
338 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
339 {
340         if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
341                 return FALSE;
342
343         if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
344                         && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
345         {
346                 // only sub-type and manufacturer IDs need to be equal
347                 if (inIgnoreType)
348                         return TRUE;
349                 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
350                 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
351                         return TRUE;
352         }
353
354         return FALSE;
355 }
356
357 //--------------------------------------------------------------------------
358 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
359 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
360 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
361 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
362 {
363         OSErr status;
364         ComponentDescription desc;
365
366         if ( (inComponent == NULL) || (inComponentDescription == NULL) )
367                 return FALSE;
368
369         // get the ComponentDescription of the input Component
370         status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
371         if (status != noErr)
372                 return FALSE;
373
374         // check if the Component's ComponentDescription matches the input ComponentDescription
375         return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
376 }
377
378 //--------------------------------------------------------------------------
379 // determine if 2 ComponentDescriptions are basically equal
380 // (by that, I mean that the important identifying values are compared,
381 // but not the ComponentDescription flags)
382 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
383 {
384         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
385 }
386
387 //--------------------------------------------------------------------------
388 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
389 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
390 {
391         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
392 }
393
394 //--------------------------------------------------------------------------
395 // determine if a ComponentDescription basically matches that of a particular Component
396 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
397 {
398         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
399 }
400
401 //--------------------------------------------------------------------------
402 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
403 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
404 {
405         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
406 }
407
408
409 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
410         : Plugin (engine, session)
411         , comp (_comp)
412         , unit (new CAAudioUnit)
413         , initialized (false)
414         , _current_block_size (0)
415         , _requires_fixed_size_buffers (false)
416         , buffers (0)
417         , input_maxbuf (0)
418         , input_offset (0)
419         , input_buffers (0)
420         , frames_processed (0)
421         , _parameter_listener (0)
422         , _parameter_listener_arg (0)
423         , last_transport_rolling (false)
424         , last_transport_speed (0.0)
425 {
426         if (!preset_search_path_initialized) {
427                 Glib::ustring p = Glib::get_home_dir();
428                 p += "/Library/Audio/Presets:";
429                 p += preset_search_path;
430                 preset_search_path = p;
431                 preset_search_path_initialized = true;
432         }
433
434         init ();
435 }
436
437
438 AUPlugin::AUPlugin (const AUPlugin& other)
439         : Plugin (other)
440         , comp (other.get_comp())
441         , unit (new CAAudioUnit)
442         , initialized (false)
443         , _current_block_size (0)
444         , _last_nframes (0)
445         , _requires_fixed_size_buffers (false)
446         , buffers (0)
447         , input_maxbuf (0)
448         , input_offset (0)
449         , input_buffers (0)
450         , frames_processed (0)
451         , _parameter_listener (0)
452         , _parameter_listener_arg (0)
453
454 {
455         init ();
456 }
457
458 AUPlugin::~AUPlugin ()
459 {
460         if (_parameter_listener) {
461                 AUListenerDispose (_parameter_listener);
462                 _parameter_listener = 0;
463         }
464         
465         if (unit) {
466                 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
467                 unit->Uninitialize ();
468         }
469
470         if (buffers) {
471                 free (buffers);
472         }
473 }
474
475 void
476 AUPlugin::discover_factory_presets ()
477 {
478         CFArrayRef presets;
479         UInt32 dataSize;
480         Boolean isWritable;
481         OSStatus err;
482
483         if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
484                 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
485                 return;
486         }
487
488         assert (dataSize == sizeof (presets));
489
490         if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
491                 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
492                 return;
493         }
494
495         if (!presets) {
496                 return;
497         }
498
499         CFIndex cnt = CFArrayGetCount (presets);
500
501         for (CFIndex i = 0; i < cnt; ++i) {
502                 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
503
504                 string name = CFStringRefToStdString (preset->presetName);
505                 factory_preset_map[name] = preset->presetNumber;
506         }
507
508         CFRelease (presets);
509 }
510
511 void
512 AUPlugin::init ()
513 {
514         OSErr err;
515         CFStringRef itemName;
516
517         /* these keep track of *configured* channel set up,
518            not potential set ups.
519         */
520
521         input_channels = -1;
522         output_channels = -1;
523         {
524                 CAComponentDescription temp;
525                 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
526                 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
527                 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
528                 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
529                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
530                                 compTypeString, compManufacturerString, compSubTypeString);
531                 if (compTypeString != NULL) CFRelease(compTypeString);
532                 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
533                 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
534         }
535
536         au_blacklist(CFStringRefToStdString(itemName));
537
538         try {
539                 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
540                 err = CAAudioUnit::Open (*(comp.get()), *unit);
541         } catch (...) {
542                 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
543                 throw failed_constructor();
544         }
545
546         if (err != noErr) {
547                 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
548                 throw failed_constructor ();
549         }
550
551         DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
552         unit->GetElementCount (kAudioUnitScope_Global, global_elements);
553         DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
554         unit->GetElementCount (kAudioUnitScope_Input, input_elements);
555         DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
556         unit->GetElementCount (kAudioUnitScope_Output, output_elements);
557
558         if (input_elements > 0) {
559                 /* setup render callback: the plugin calls this to get input data 
560                  */
561                 
562                 AURenderCallbackStruct renderCallbackInfo;
563                 
564                 renderCallbackInfo.inputProc = _render_callback;
565                 renderCallbackInfo.inputProcRefCon = this;
566                 
567                 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
568                 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
569                                               0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
570                         error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
571                         throw failed_constructor();
572                 }
573         }
574
575         /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
576
577         HostCallbackInfo info;
578         memset (&info, 0, sizeof (HostCallbackInfo));
579         info.hostUserData = this;
580         info.beatAndTempoProc = _get_beat_and_tempo_callback;
581         info.musicalTimeLocationProc = _get_musical_time_location_callback;
582         info.transportStateProc = _get_transport_state_callback;
583
584         //ignore result of this - don't care if the property isn't supported
585         DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
586         unit->SetProperty (kAudioUnitProperty_HostCallbacks,
587                            kAudioUnitScope_Global,
588                            0, //elementID
589                            &info,
590                            sizeof (HostCallbackInfo));
591
592         if (set_block_size (_session.get_block_size())) {
593                 error << _("AUPlugin: cannot set processing block size") << endmsg;
594                 throw failed_constructor();
595         }
596
597         create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
598         discover_parameters ();
599         discover_factory_presets ();
600
601         // Plugin::setup_controls ();
602
603         au_blacklist(CFStringRefToStdString(itemName));
604         if (itemName != NULL) CFRelease(itemName);
605 }
606
607 void
608 AUPlugin::discover_parameters ()
609 {
610         /* discover writable parameters */
611
612         AudioUnitScope scopes[] = {
613                 kAudioUnitScope_Global,
614                 kAudioUnitScope_Output,
615                 kAudioUnitScope_Input
616         };
617
618         descriptors.clear ();
619
620         for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
621
622                 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
623
624                 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
625
626                         AUParameterDescriptor d;
627
628                         d.id = param_info.ParamID (i);
629
630                         const CAAUParameter* param = param_info.GetParamInfo (d.id);
631                         const AudioUnitParameterInfo& info (param->ParamInfo());
632
633                         const int len = CFStringGetLength (param->GetName());;
634                         char local_buffer[len*2];
635                         Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
636                         if (!good) {
637                                 d.label = "???";
638                         } else {
639                                 d.label = local_buffer;
640                         }
641
642                         d.scope = param_info.GetScope ();
643                         d.element = param_info.GetElement ();
644
645                         /* info.units to consider */
646                         /*
647                           kAudioUnitParameterUnit_Generic             = 0
648                           kAudioUnitParameterUnit_Indexed             = 1
649                           kAudioUnitParameterUnit_Boolean             = 2
650                           kAudioUnitParameterUnit_Percent             = 3
651                           kAudioUnitParameterUnit_Seconds             = 4
652                           kAudioUnitParameterUnit_SampleFrames        = 5
653                           kAudioUnitParameterUnit_Phase               = 6
654                           kAudioUnitParameterUnit_Rate                = 7
655                           kAudioUnitParameterUnit_Hertz               = 8
656                           kAudioUnitParameterUnit_Cents               = 9
657                           kAudioUnitParameterUnit_RelativeSemiTones   = 10
658                           kAudioUnitParameterUnit_MIDINoteNumber      = 11
659                           kAudioUnitParameterUnit_MIDIController      = 12
660                           kAudioUnitParameterUnit_Decibels            = 13
661                           kAudioUnitParameterUnit_LinearGain          = 14
662                           kAudioUnitParameterUnit_Degrees             = 15
663                           kAudioUnitParameterUnit_EqualPowerCrossfade = 16
664                           kAudioUnitParameterUnit_MixerFaderCurve1    = 17
665                           kAudioUnitParameterUnit_Pan                 = 18
666                           kAudioUnitParameterUnit_Meters              = 19
667                           kAudioUnitParameterUnit_AbsoluteCents       = 20
668                           kAudioUnitParameterUnit_Octaves             = 21
669                           kAudioUnitParameterUnit_BPM                 = 22
670                           kAudioUnitParameterUnit_Beats               = 23
671                           kAudioUnitParameterUnit_Milliseconds        = 24
672                           kAudioUnitParameterUnit_Ratio               = 25
673                         */
674
675                         /* info.flags to consider */
676
677                         /*
678
679                           kAudioUnitParameterFlag_CFNameRelease       = (1L << 4)
680                           kAudioUnitParameterFlag_HasClump            = (1L << 20)
681                           kAudioUnitParameterFlag_HasName             = (1L << 21)
682                           kAudioUnitParameterFlag_DisplayLogarithmic  = (1L << 22)
683                           kAudioUnitParameterFlag_IsHighResolution    = (1L << 23)
684                           kAudioUnitParameterFlag_NonRealTime         = (1L << 24)
685                           kAudioUnitParameterFlag_CanRamp             = (1L << 25)
686                           kAudioUnitParameterFlag_ExpertMode          = (1L << 26)
687                           kAudioUnitParameterFlag_HasCFNameString     = (1L << 27)
688                           kAudioUnitParameterFlag_IsGlobalMeta        = (1L << 28)
689                           kAudioUnitParameterFlag_IsElementMeta       = (1L << 29)
690                           kAudioUnitParameterFlag_IsReadable          = (1L << 30)
691                           kAudioUnitParameterFlag_IsWritable          = (1L << 31)
692                         */
693
694                         d.lower = info.minValue;
695                         d.upper = info.maxValue;
696                         d.normal = info.defaultValue;
697
698                         d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
699                         d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
700                                 (d.integer_step && ((d.upper - d.lower) == 1.0));
701                         d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
702                         d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
703                                 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
704                                 (info.flags & kAudioUnitParameterFlag_IsWritable);
705
706                         d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
707                         d.au_unit = info.unit;
708                         switch (info.unit) {
709                         case kAudioUnitParameterUnit_Decibels:
710                                 d.unit = ParameterDescriptor::DB;
711                                 break;
712                         case kAudioUnitParameterUnit_MIDINoteNumber:
713                                 d.unit = ParameterDescriptor::MIDI_NOTE;
714                                 break;
715                         case kAudioUnitParameterUnit_Hertz:
716                                 d.unit = ParameterDescriptor::HZ;
717                                 break;
718                         }
719
720                         d.min_unbound = 0; // lower is bound
721                         d.max_unbound = 0; // upper is bound
722                         d.update_steps();
723
724                         descriptors.push_back (d);
725
726                         uint32_t last_param = descriptors.size() - 1;
727                         parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
728                         listen_to_parameter (last_param);
729                 }
730         }
731 }
732
733
734 static unsigned int
735 four_ints_to_four_byte_literal (unsigned char n[4])
736 {
737         /* this is actually implementation dependent. sigh. this is what gcc
738            and quite a few others do.
739          */
740         return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
741 }
742
743 std::string
744 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
745 {
746         if (isdigit (id[0])) {
747                 return id;
748         }
749
750         /* ID format is xxxx-xxxx-xxxx
751            where x maybe \xNN or a printable character.
752
753            Split at the '-' and and process each part into an integer.
754            Then put it back together.
755         */
756
757
758         unsigned char nascent[4];
759         const char* cstr = id.c_str();
760         const char* estr = cstr + id.size();
761         uint32_t n[3];
762         int in;
763         int next_int;
764         char short_buf[3];
765         stringstream s;
766
767         in = 0;
768         next_int = 0;
769         short_buf[2] = '\0';
770
771         while (*cstr && next_int < 4) {
772
773                 if (*cstr == '\\') {
774
775                         if (estr - cstr < 3) {
776
777                                 /* too close to the end for \xNN parsing: treat as literal characters */
778
779                                 nascent[in] = *cstr;
780                                 ++cstr;
781                                 ++in;
782
783                         } else {
784
785                                 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
786
787                                         /* parse \xNN */
788
789                                         memcpy (short_buf, &cstr[2], 2);
790                                         nascent[in] = strtol (short_buf, NULL, 16);
791                                         cstr += 4;
792                                         ++in;
793
794                                 } else {
795
796                                         /* treat as literal characters */
797                                         nascent[in] = *cstr;
798                                         ++cstr;
799                                         ++in;
800                                 }
801                         }
802
803                 } else {
804
805                         nascent[in] = *cstr;
806                         ++cstr;
807                         ++in;
808                 }
809
810                 if (in && (in % 4 == 0)) {
811                         /* nascent is ready */
812                         n[next_int] = four_ints_to_four_byte_literal (nascent);
813                         in = 0;
814                         next_int++;
815
816                         /* swallow space-hyphen-space */
817
818                         if (next_int < 3) {
819                                 ++cstr;
820                                 ++cstr;
821                                 ++cstr;
822                         }
823                 }
824         }
825
826         if (next_int != 3) {
827                 goto err;
828         }
829
830         s << n[0] << '-' << n[1] << '-' << n[2];
831
832         return s.str();
833
834   err:
835         return string();
836 }
837
838 string
839 AUPlugin::unique_id () const
840 {
841         return AUPluginInfo::stringify_descriptor (comp->Desc());
842 }
843
844 const char *
845 AUPlugin::label () const
846 {
847         return _info->name.c_str();
848 }
849
850 uint32_t
851 AUPlugin::parameter_count () const
852 {
853         return descriptors.size();
854 }
855
856 float
857 AUPlugin::default_value (uint32_t port)
858 {
859         if (port < descriptors.size()) {
860                 return descriptors[port].normal;
861         }
862
863         return 0;
864 }
865
866 framecnt_t
867 AUPlugin::signal_latency () const
868 {
869         return unit->Latency() * _session.frame_rate();
870 }
871
872 void
873 AUPlugin::set_parameter (uint32_t which, float val)
874 {
875         if (which >= descriptors.size()) {
876                 return;
877         }
878
879         if (get_parameter(which) == val) {
880                 return;
881         }
882
883         const AUParameterDescriptor& d (descriptors[which]);
884         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
885         unit->SetParameter (d.id, d.scope, d.element, val);
886
887         /* tell the world what we did */
888
889         AudioUnitEvent theEvent;
890
891         theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
892         theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
893         theEvent.mArgument.mParameter.mParameterID = d.id;
894         theEvent.mArgument.mParameter.mScope = d.scope;
895         theEvent.mArgument.mParameter.mElement = d.element;
896
897         DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
898         AUEventListenerNotify (NULL, NULL, &theEvent);
899
900         Plugin::set_parameter (which, val);
901 }
902
903 float
904 AUPlugin::get_parameter (uint32_t which) const
905 {
906         float val = 0.0;
907         if (which < descriptors.size()) {
908                 const AUParameterDescriptor& d (descriptors[which]);
909                 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
910                 unit->GetParameter(d.id, d.scope, d.element, val);
911         }
912         return val;
913 }
914
915 int
916 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
917 {
918         if (which < descriptors.size()) {
919                 pd = descriptors[which];
920                 return 0;
921         }
922         return -1;
923 }
924
925 uint32_t
926 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
927 {
928         if (which < descriptors.size()) {
929                 ok = true;
930                 return which;
931         }
932         ok = false;
933         return 0;
934 }
935
936 void
937 AUPlugin::activate ()
938 {
939         if (!initialized) {
940                 OSErr err;
941                 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
942                 if ((err = unit->Initialize()) != noErr) {
943                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
944                 } else {
945                         frames_processed = 0;
946                         initialized = true;
947                 }
948         }
949 }
950
951 void
952 AUPlugin::deactivate ()
953 {
954         DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
955         unit->Uninitialize ();
956         initialized = false;
957 }
958
959 void
960 AUPlugin::flush ()
961 {
962         DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
963         unit->GlobalReset ();
964 }
965
966 bool
967 AUPlugin::requires_fixed_size_buffers() const
968 {
969         return _requires_fixed_size_buffers;
970 }
971
972
973 int
974 AUPlugin::set_block_size (pframes_t nframes)
975 {
976         bool was_initialized = initialized;
977         UInt32 numFrames = nframes;
978         OSErr err;
979
980         if (initialized) {
981                 deactivate ();
982         }
983
984         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
985         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
986                                       0, &numFrames, sizeof (numFrames))) != noErr) {
987                 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
988                 return -1;
989         }
990
991         if (was_initialized) {
992                 activate ();
993         }
994
995         _current_block_size = nframes;
996
997         return 0;
998 }
999
1000 bool
1001 AUPlugin::configure_io (ChanCount in, ChanCount out)
1002 {
1003         AudioStreamBasicDescription streamFormat;
1004         bool was_initialized = initialized;
1005         int32_t audio_in = in.n_audio();
1006         int32_t audio_out = out.n_audio();
1007
1008         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1009
1010         if (initialized) {
1011                 //if we are already running with the requested i/o config, bail out here
1012                 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1013                         return 0;
1014                 } else {
1015                         deactivate ();
1016                 }
1017         }
1018
1019         streamFormat.mSampleRate = _session.frame_rate();
1020         streamFormat.mFormatID = kAudioFormatLinearPCM;
1021         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1022
1023 #ifdef __LITTLE_ENDIAN__
1024         /* relax */
1025 #else
1026         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1027 #endif
1028
1029         streamFormat.mBitsPerChannel = 32;
1030         streamFormat.mFramesPerPacket = 1;
1031
1032         /* apple says that for non-interleaved data, these
1033            values always refer to a single channel.
1034         */
1035         streamFormat.mBytesPerPacket = 4;
1036         streamFormat.mBytesPerFrame = 4;
1037
1038         streamFormat.mChannelsPerFrame = audio_in;
1039
1040         if (set_input_format (streamFormat) != 0) {
1041                 return -1;
1042         }
1043
1044         streamFormat.mChannelsPerFrame = audio_out;
1045
1046         if (set_output_format (streamFormat) != 0) {
1047                 return -1;
1048         }
1049
1050         /* reset plugin info to show currently configured state */
1051         
1052         _info->n_inputs = in;
1053         _info->n_outputs = out;
1054
1055         if (was_initialized) {
1056                 activate ();
1057         }
1058
1059         return 0;
1060 }
1061
1062 ChanCount
1063 AUPlugin::input_streams() const
1064 {
1065         ChanCount c;
1066
1067
1068         if (input_channels < 0) {
1069                 // force PluginIoReConfigure -- see also commit msg e38eb06
1070                 c.set (DataType::AUDIO, 0);
1071                 c.set (DataType::MIDI, 0);
1072         } else {
1073                 c.set (DataType::AUDIO, input_channels);
1074                 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1075         }
1076
1077         return c;
1078 }
1079
1080
1081 ChanCount
1082 AUPlugin::output_streams() const
1083 {
1084         ChanCount c;
1085
1086         if (output_channels < 0) {
1087                 // force PluginIoReConfigure - see also commit msg e38eb06
1088                 c.set (DataType::AUDIO, 0);
1089                 c.set (DataType::MIDI, 0);
1090         } else {
1091                 c.set (DataType::AUDIO, output_channels);
1092                 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1093         }
1094
1095         return c;
1096 }
1097
1098 bool
1099 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1100 {
1101         // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1102
1103         int32_t audio_in = in.n_audio();
1104         int32_t audio_out;
1105         bool found = false;
1106         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1107
1108         /* lets check MIDI first */
1109
1110         if (in.n_midi() > 0) {
1111                 if (!_has_midi_input) {
1112                         return false;
1113                 }
1114         }
1115
1116         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1117
1118         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n", 
1119                                                         name(), io_configs.size(), in, out));
1120
1121         //Ardour expects the plugin to tell it the output
1122         //configuration but AU plugins can have multiple I/O
1123         //configurations in most cases. so first lets see
1124         //if there's a configuration that keeps out==in
1125
1126         if (in.n_midi() > 0 && audio_in == 0) {
1127                 audio_out = 2; // prefer stereo version if available.
1128         } else {
1129                 audio_out = audio_in;
1130         }
1131
1132         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1133
1134                 int32_t possible_in = i->first;
1135                 int32_t possible_out = i->second;
1136
1137                 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1138                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n", 
1139                                                                         possible_in, possible_out,
1140                                                                         in, out));
1141
1142                         out.set (DataType::MIDI, 0);
1143                         out.set (DataType::AUDIO, audio_out);
1144
1145                         return 1;
1146                 }
1147         }
1148
1149         /* now allow potentially "imprecise" matches */
1150
1151         audio_out = -1;
1152
1153         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1154
1155                 int32_t possible_in = i->first;
1156                 int32_t possible_out = i->second;
1157
1158                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1159
1160                 if (possible_out == 0) {
1161                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1162                         /* XXX surely this is just a send? (e.g. AUNetSend) */
1163                         continue;
1164                 }
1165
1166                 if (possible_in == 0) {
1167
1168                         /* instrument plugin, always legal but throws away inputs ...
1169                         */
1170
1171                         if (possible_out == -1) {
1172                                 /* any configuration possible, provide stereo output */
1173                                 audio_out = 2;
1174                                 found = true;
1175                         } else if (possible_out == -2) {
1176                                 /* plugins shouldn't really use (0,-2) but might. 
1177                                    any configuration possible, provide stereo output 
1178                                 */
1179                                 audio_out = 2;
1180                                 found = true;
1181                         } else if (possible_out < -2) {
1182                                 /* explicitly variable number of outputs. 
1183
1184                                    Since Ardour can handle any configuration,
1185                                    we have to somehow pick a number. 
1186
1187                                    We'll use the number of inputs
1188                                    to the master bus, or 2 if there
1189                                    is no master bus.
1190                                 */
1191                                 boost::shared_ptr<Route> master = _session.master_out();
1192                                 if (master) {
1193                                         audio_out = master->input()->n_ports().n_audio();
1194                                 } else {
1195                                         audio_out = 2;
1196                                 }
1197                                 found = true;
1198                         } else {
1199                                 /* exact number of outputs */
1200                                 audio_out = possible_out;
1201                                 found = true;
1202                         }
1203                 }
1204
1205                 if (possible_in == -1) {
1206
1207                         /* wildcard for input */
1208
1209                         if (possible_out == -1) {
1210                                 /* out much match in */
1211                                 audio_out = audio_in;
1212                                 found = true;
1213                         } else if (possible_out == -2) {
1214                                 /* any configuration possible, pick matching */
1215                                 audio_out = audio_in;
1216                                 found = true;
1217                         } else if (possible_out < -2) {
1218                                 /* explicitly variable number of outputs, pick maximum */
1219                                 audio_out = -possible_out;
1220                                 found = true;
1221                         } else {
1222                                 /* exact number of outputs */
1223                                 audio_out = possible_out;
1224                                 found = true;
1225                         }
1226                 }
1227
1228                 if (possible_in == -2) {
1229
1230                         if (possible_out == -1) {
1231                                 /* any configuration possible, pick matching */
1232                                 audio_out = audio_in;
1233                                 found = true;
1234                         } else if (possible_out == -2) {
1235                                 /* plugins shouldn't really use (-2,-2) but might. 
1236                                    interpret as (-1,-1).
1237                                 */
1238                                 audio_out = audio_in;
1239                                 found = true;
1240                         } else if (possible_out < -2) {
1241                                 /* explicitly variable number of outputs, pick maximum */
1242                                 audio_out = -possible_out;
1243                                 found = true;
1244                         } else {
1245                                 /* exact number of outputs */
1246                                 audio_out = possible_out;
1247                                 found = true;
1248                         }
1249                 }
1250
1251                 if (possible_in < -2) {
1252
1253                         /* explicit variable number of inputs */
1254
1255                         if (audio_in > -possible_in) {
1256                                 /* request is too large */
1257                         }
1258
1259
1260                         if (possible_out == -1) {
1261                                 /* any output configuration possible, provide stereo out */
1262                                 audio_out = 2;
1263                                 found = true;
1264                         } else if (possible_out == -2) {
1265                                 /* plugins shouldn't really use (<-2,-2) but might. 
1266                                    interpret as (<-2,-1): any configuration possible, provide stereo output 
1267                                 */
1268                                 audio_out = 2;
1269                                 found = true;
1270                         } else if (possible_out < -2) {
1271                                 /* explicitly variable number of outputs. 
1272
1273                                    Since Ardour can handle any configuration,
1274                                    we have to somehow pick a number. 
1275
1276                                    We'll use the number of inputs
1277                                    to the master bus, or 2 if there
1278                                    is no master bus.
1279                                 */
1280                                 boost::shared_ptr<Route> master = _session.master_out();
1281                                 if (master) {
1282                                         audio_out = master->input()->n_ports().n_audio();
1283                                 } else {
1284                                         audio_out = 2;
1285                                 }
1286                                 found = true;
1287                         } else {
1288                                 /* exact number of outputs */
1289                                 audio_out = possible_out;
1290                                 found = true;
1291                         }
1292                 }
1293
1294                 if (possible_in && (possible_in == audio_in)) {
1295
1296                         /* exact number of inputs ... must match obviously */
1297
1298                         if (possible_out == -1) {
1299                                 /* any output configuration possible, provide stereo output */
1300                                 audio_out = 2;
1301                                 found = true;
1302                         } else if (possible_out == -2) {
1303                                 /* plugins shouldn't really use (>0,-2) but might. 
1304                                    interpret as (>0,-1): 
1305                                    any output configuration possible, provide stereo output
1306                                 */
1307                                 audio_out = 2;
1308                                 found = true;
1309                         } else if (possible_out < -2) {
1310                                 /* explicitly variable number of outputs, pick maximum */
1311                                 audio_out = -possible_out;
1312                                 found = true;
1313                         } else {
1314                                 /* exact number of outputs */
1315                                 audio_out = possible_out;
1316                                 found = true;
1317                         }
1318                 }
1319
1320                 if (found) {
1321                         break;
1322                 }
1323
1324         }
1325
1326         if (found) {
1327                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1328         } else {
1329                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1330                 return false;
1331         }
1332
1333         out.set (DataType::MIDI, 0);
1334         out.set (DataType::AUDIO, audio_out);
1335
1336         return true;
1337 }
1338
1339 int
1340 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1341 {
1342         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1343 }
1344
1345 int
1346 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1347 {
1348         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1349                 return -1;
1350         }
1351
1352         if (buffers) {
1353                 free (buffers);
1354                 buffers = 0;
1355         }
1356
1357         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1358                                               fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1359
1360         return 0;
1361 }
1362
1363 int
1364 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1365 {
1366         OSErr result;
1367
1368         for (uint32_t i = 0; i < cnt; ++i) {
1369                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1370                                                                 (scope == kAudioUnitScope_Input ? "input" : "output"),
1371                                                                 scope, cnt));
1372                 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1373                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1374                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1375                         return -1;
1376                 }
1377         }
1378
1379         if (scope == kAudioUnitScope_Input) {
1380                 input_channels = fmt.mChannelsPerFrame;
1381         } else {
1382                 output_channels = fmt.mChannelsPerFrame;
1383         }
1384
1385         return 0;
1386 }
1387
1388 OSStatus
1389 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1390                           const AudioTimeStamp*,
1391                           UInt32,
1392                           UInt32       inNumberFrames,
1393                           AudioBufferList*       ioData)
1394 {
1395         /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1396
1397         // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1398         // name(), inNumberFrames, ioData->mNumberBuffers));
1399
1400         if (input_maxbuf == 0) {
1401                 error << _("AUPlugin: render callback called illegally!") << endmsg;
1402                 return kAudioUnitErr_CannotDoInCurrentContext;
1403         }
1404         uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1405
1406         for (uint32_t i = 0; i < limit; ++i) {
1407                 ioData->mBuffers[i].mNumberChannels = 1;
1408                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1409
1410                 /* we don't use the channel mapping because audiounits are
1411                    never replicated. one plugin instance uses all channels/buffers
1412                    passed to PluginInsert::connect_and_run()
1413                 */
1414
1415                 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1416         }
1417
1418         cb_offset += inNumberFrames;
1419
1420         return noErr;
1421 }
1422
1423 int
1424 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1425 {
1426         Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1427
1428         AudioUnitRenderActionFlags flags = 0;
1429         AudioTimeStamp ts;
1430         OSErr err;
1431
1432         if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1433                 unit->GlobalReset();
1434                 _last_nframes = nframes;
1435         }
1436
1437         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1438                                                         name(), input_channels, output_channels, _has_midi_input,
1439                                                         bufs.count(), bufs.available()));
1440
1441         /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1442            has the capacity to handle our outputs.
1443         */
1444
1445         assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1446
1447         input_buffers = &bufs;
1448         input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1449         input_offset = offset;
1450         cb_offset = 0;
1451
1452         buffers->mNumberBuffers = output_channels;
1453
1454         for (int32_t i = 0; i < output_channels; ++i) {
1455                 buffers->mBuffers[i].mNumberChannels = 1;
1456                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1457                 /* setting this to 0 indicates to the AU that it can provide buffers here
1458                    if necessary. if it can process in-place, it will use the buffers provided
1459                    as input by ::render_callback() above. 
1460                    
1461                    a non-null values tells the plugin to render into the buffer pointed
1462                    at by the value.
1463                 */
1464                 buffers->mBuffers[i].mData = 0;
1465         }
1466
1467         if (_has_midi_input) {
1468
1469                 uint32_t nmidi = bufs.count().n_midi();
1470
1471                 for (uint32_t i = 0; i < nmidi; ++i) {
1472                         
1473                         /* one MIDI port/buffer only */
1474                         
1475                         MidiBuffer& m = bufs.get_midi (i);
1476                         
1477                         for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1478                                 Evoral::MIDIEvent<framepos_t> ev (*i);
1479                                 
1480                                 if (ev.is_channel_event()) {
1481                                         const uint8_t* b = ev.buffer();
1482                                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1483                                         unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1484                                 }
1485
1486                                 /* XXX need to handle sysex and other message types */
1487                         }
1488                 }
1489         }
1490
1491         /* does this really mean anything ? 
1492          */
1493
1494         ts.mSampleTime = frames_processed;
1495         ts.mFlags = kAudioTimeStampSampleTimeValid;
1496
1497         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1498                                                         name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1499
1500         if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1501
1502                 input_maxbuf = 0;
1503                 frames_processed += nframes;
1504
1505                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1506                                                                 name(), buffers->mNumberBuffers, output_channels));
1507
1508                 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1509                 int32_t i;
1510
1511                 for (i = 0; i < limit; ++i) {
1512                         Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1513                         if (expected_buffer_address != buffers->mBuffers[i].mData) {
1514                                 /* plugin provided its own buffer for output so copy it back to where we want it
1515                                  */
1516                                 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1517                         }
1518                 }
1519
1520                 /* now silence any buffers that were passed in but the that the plugin
1521                    did not fill/touch/use.
1522                 */
1523
1524                 for (;i < output_channels; ++i) {
1525                         memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1526                 }
1527
1528                 return 0;
1529         }
1530
1531         error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1532         return -1;
1533 }
1534
1535 OSStatus
1536 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1537                                        Float64* outCurrentTempo)
1538 {
1539         TempoMap& tmap (_session.tempo_map());
1540
1541         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1542
1543         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1544            (and interpretation) of a beat position will be incorrect. So refuse to
1545            offer the value.
1546         */
1547
1548         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1549                 return kAudioUnitErr_CannotDoInCurrentContext;
1550         }
1551
1552         Timecode::BBT_Time bbt;
1553         TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1554         tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1555
1556         if (outCurrentBeat) {
1557                 float beat;
1558                 beat = metric.meter().divisions_per_bar() * bbt.bars;
1559                 beat += bbt.beats;
1560                 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1561                 *outCurrentBeat = beat;
1562         }
1563
1564         if (outCurrentTempo) {
1565                 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1566         }
1567
1568         return noErr;
1569
1570 }
1571
1572 OSStatus
1573 AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
1574                                               Float32*  outTimeSig_Numerator,
1575                                               UInt32*   outTimeSig_Denominator,
1576                                               Float64*  outCurrentMeasureDownBeat)
1577 {
1578         TempoMap& tmap (_session.tempo_map());
1579
1580         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1581
1582         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1583            (and interpretation) of a beat position will be incorrect. So refuse to
1584            offer the value.
1585         */
1586
1587         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1588                 return kAudioUnitErr_CannotDoInCurrentContext;
1589         }
1590
1591         Timecode::BBT_Time bbt;
1592         TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1593         tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1594
1595         if (outDeltaSampleOffsetToNextBeat) {
1596                 if (bbt.ticks == 0) {
1597                         /* on the beat */
1598                         *outDeltaSampleOffsetToNextBeat = 0;
1599                 } else {
1600                         *outDeltaSampleOffsetToNextBeat = (UInt32) 
1601                                 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1602                                        metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1603                 }
1604         }
1605
1606         if (outTimeSig_Numerator) {
1607                 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1608         }
1609         if (outTimeSig_Denominator) {
1610                 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1611         }
1612
1613         if (outCurrentMeasureDownBeat) {
1614
1615                 /* beat for the start of the bar.
1616                    1|1|0 -> 1
1617                    2|1|0 -> 1 + divisions_per_bar
1618                    3|1|0 -> 1 + (2 * divisions_per_bar)
1619                    etc.
1620                 */
1621
1622                 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1623         }
1624
1625         return noErr;
1626 }
1627
1628 OSStatus
1629 AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
1630                                         Boolean*  outTransportStateChanged,
1631                                         Float64*  outCurrentSampleInTimeLine,
1632                                         Boolean*  outIsCycling,
1633                                         Float64*  outCycleStartBeat,
1634                                         Float64*  outCycleEndBeat)
1635 {
1636         bool rolling;
1637         float speed;
1638
1639         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1640
1641         rolling = _session.transport_rolling();
1642         speed = _session.transport_speed ();
1643
1644         if (outIsPlaying) {
1645                 *outIsPlaying = _session.transport_rolling();
1646         }
1647
1648         if (outTransportStateChanged) {
1649                 if (rolling != last_transport_rolling) {
1650                         *outTransportStateChanged = true;
1651                 } else if (speed != last_transport_speed) {
1652                         *outTransportStateChanged = true;
1653                 } else {
1654                         *outTransportStateChanged = false;
1655                 }
1656         }
1657
1658         if (outCurrentSampleInTimeLine) {
1659                 /* this assumes that the AU can only call this host callback from render context,
1660                    where input_offset is valid.
1661                 */
1662                 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1663         }
1664
1665         if (outIsCycling) {
1666                 Location* loc = _session.locations()->auto_loop_location();
1667
1668                 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1669
1670                 if (*outIsCycling) {
1671
1672                         if (outCycleStartBeat || outCycleEndBeat) {
1673
1674                                 TempoMap& tmap (_session.tempo_map());
1675
1676                                 /* more than 1 meter means that a simplistic computation (and interpretation) of
1677                                    a beat position will be incorrect. so refuse to offer the value.
1678                                 */
1679
1680                                 if (tmap.n_meters() > 1) {
1681                                         return kAudioUnitErr_CannotDoInCurrentContext;
1682                                 }
1683
1684                                 Timecode::BBT_Time bbt;
1685
1686                                 if (outCycleStartBeat) {
1687                                         TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1688                                         _session.tempo_map().bbt_time (loc->start(), bbt);
1689
1690                                         float beat;
1691                                         beat = metric.meter().divisions_per_bar() * bbt.bars;
1692                                         beat += bbt.beats;
1693                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1694
1695                                         *outCycleStartBeat = beat;
1696                                 }
1697
1698                                 if (outCycleEndBeat) {
1699                                         TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1700                                         _session.tempo_map().bbt_time (loc->end(), bbt);
1701
1702                                         float beat;
1703                                         beat = metric.meter().divisions_per_bar() * bbt.bars;
1704                                         beat += bbt.beats;
1705                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1706
1707                                         *outCycleEndBeat = beat;
1708                                 }
1709                         }
1710                 }
1711         }
1712
1713         last_transport_rolling = rolling;
1714         last_transport_speed = speed;
1715
1716         return noErr;
1717 }
1718
1719 set<Evoral::Parameter>
1720 AUPlugin::automatable() const
1721 {
1722         set<Evoral::Parameter> automates;
1723
1724         for (uint32_t i = 0; i < descriptors.size(); ++i) {
1725                 if (descriptors[i].automatable) {
1726                         automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1727                 }
1728         }
1729
1730         return automates;
1731 }
1732
1733 string
1734 AUPlugin::describe_parameter (Evoral::Parameter param)
1735 {
1736         if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1737                 return descriptors[param.id()].label;
1738         } else {
1739                 return "??";
1740         }
1741 }
1742
1743 void
1744 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1745 {
1746         // NameValue stuff here
1747 }
1748
1749 bool
1750 AUPlugin::parameter_is_audio (uint32_t) const
1751 {
1752         return false;
1753 }
1754
1755 bool
1756 AUPlugin::parameter_is_control (uint32_t param) const
1757 {
1758         assert(param < descriptors.size());
1759         if (descriptors[param].automatable) {
1760                 /* corrently ardour expects all controls to be automatable
1761                  * IOW ardour GUI elements mandate an Evoral::Parameter
1762                  * for all input+control ports.
1763                  */
1764                 return true;
1765         }
1766         return false;
1767 }
1768
1769 bool
1770 AUPlugin::parameter_is_input (uint32_t param) const
1771 {
1772         /* AU params that are both readable and writeable,
1773          * are listed in kAudioUnitScope_Global
1774          */
1775         return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1776 }
1777
1778 bool
1779 AUPlugin::parameter_is_output (uint32_t param) const
1780 {
1781         assert(param < descriptors.size());
1782         // TODO check if ardour properly handles ports
1783         // that report is_input + is_output == true
1784         // -> add || descriptors[param].scope == kAudioUnitScope_Global
1785         return (descriptors[param].scope == kAudioUnitScope_Output);
1786 }
1787
1788 void
1789 AUPlugin::add_state (XMLNode* root) const
1790 {
1791         LocaleGuard lg (X_("C"));
1792         CFDataRef xmlData;
1793         CFPropertyListRef propertyList;
1794
1795         DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1796         if (unit->GetAUPreset (propertyList) != noErr) {
1797                 return;
1798         }
1799
1800         // Convert the property list into XML data.
1801
1802         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1803
1804         if (!xmlData) {
1805                 error << _("Could not create XML version of property list") << endmsg;
1806                 return;
1807         }
1808
1809         /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1810            our state node. GACK!
1811         */
1812
1813         XMLTree t;
1814
1815         if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1816                 if (t.root()) {
1817                         root->add_child_copy (*t.root());
1818                 }
1819         }
1820
1821         CFRelease (xmlData);
1822         CFRelease (propertyList);
1823 }
1824
1825 int
1826 AUPlugin::set_state(const XMLNode& node, int version)
1827 {
1828         int ret = -1;
1829         CFPropertyListRef propertyList;
1830         LocaleGuard lg (X_("C"));
1831
1832         if (node.name() != state_node_name()) {
1833                 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1834                 return -1;
1835         }
1836
1837 #ifndef NO_PLUGIN_STATE
1838         if (node.children().empty()) {
1839                 return -1;
1840         }
1841
1842         XMLNode* top = node.children().front();
1843         XMLNode* copy = new XMLNode (*top);
1844
1845         XMLTree t;
1846         t.set_root (copy);
1847
1848         const string& xml = t.write_buffer ();
1849         CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1850         CFStringRef errorString;
1851
1852         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1853                                                         xmlData,
1854                                                         kCFPropertyListImmutable,
1855                                                         &errorString);
1856
1857         CFRelease (xmlData);
1858
1859         if (propertyList) {
1860                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1861                 if (unit->SetAUPreset (propertyList) == noErr) {
1862                         ret = 0;
1863
1864                         /* tell the world */
1865
1866                         AudioUnitParameter changedUnit;
1867                         changedUnit.mAudioUnit = unit->AU();
1868                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1869                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1870                 }
1871                 CFRelease (propertyList);
1872         }
1873 #endif
1874
1875         Plugin::set_state (node, version);
1876         return ret;
1877 }
1878
1879 bool
1880 AUPlugin::load_preset (PresetRecord r)
1881 {
1882         Plugin::load_preset (r);
1883
1884         bool ret = false;
1885         CFPropertyListRef propertyList;
1886         Glib::ustring path;
1887         UserPresetMap::iterator ux;
1888         FactoryPresetMap::iterator fx;
1889
1890         /* look first in "user" presets */
1891
1892         if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1893
1894                 if ((propertyList = load_property_list (ux->second)) != 0) {
1895                         DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1896                         if (unit->SetAUPreset (propertyList) == noErr) {
1897                                 ret = true;
1898
1899                                 /* tell the world */
1900
1901                                 AudioUnitParameter changedUnit;
1902                                 changedUnit.mAudioUnit = unit->AU();
1903                                 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1904                                 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1905                         }
1906                         CFRelease(propertyList);
1907                 }
1908
1909         } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1910
1911                 AUPreset preset;
1912
1913                 preset.presetNumber = fx->second;
1914                 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1915
1916                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1917
1918                 if (unit->SetPresentPreset (preset) == 0) {
1919                         ret = true;
1920
1921                         /* tell the world */
1922
1923                         AudioUnitParameter changedUnit;
1924                         changedUnit.mAudioUnit = unit->AU();
1925                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1926                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1927                 }
1928         }
1929
1930         return ret;
1931 }
1932
1933 void
1934 AUPlugin::do_remove_preset (std::string) 
1935 {
1936 }
1937
1938 string
1939 AUPlugin::do_save_preset (string preset_name)
1940 {
1941         CFPropertyListRef propertyList;
1942         vector<Glib::ustring> v;
1943         Glib::ustring user_preset_path;
1944
1945         std::string m = maker();
1946         std::string n = name();
1947
1948         strip_whitespace_edges (m);
1949         strip_whitespace_edges (n);
1950
1951         v.push_back (Glib::get_home_dir());
1952         v.push_back ("Library");
1953         v.push_back ("Audio");
1954         v.push_back ("Presets");
1955         v.push_back (m);
1956         v.push_back (n);
1957
1958         user_preset_path = Glib::build_filename (v);
1959
1960         if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1961                 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1962                 return string();
1963         }
1964
1965         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1966         if (unit->GetAUPreset (propertyList) != noErr) {
1967                 return string();
1968         }
1969
1970         // add the actual preset name */
1971
1972         v.push_back (preset_name + preset_suffix);
1973
1974         // rebuild
1975
1976         user_preset_path = Glib::build_filename (v);
1977
1978         set_preset_name_in_plist (propertyList, preset_name);
1979
1980         if (save_property_list (propertyList, user_preset_path)) {
1981                 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1982                 return string();
1983         }
1984
1985         CFRelease(propertyList);
1986
1987         user_preset_map[preset_name] = user_preset_path;;
1988
1989         return string ("file:///") + user_preset_path;
1990 }
1991
1992 //-----------------------------------------------------------------------------
1993 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1994 static SInt32
1995 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1996 {
1997         CFNumberRef cfNumber;
1998         SInt32 numberValue = 0;
1999         Boolean dummySuccess;
2000
2001         if (outSuccess == NULL)
2002                 outSuccess = &dummySuccess;
2003         if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2004         {
2005                 *outSuccess = FALSE;
2006                 return 0;
2007         }
2008
2009         cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2010         if (cfNumber == NULL)
2011         {
2012                 *outSuccess = FALSE;
2013                 return 0;
2014         }
2015         *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2016         if (*outSuccess)
2017                 return numberValue;
2018         else
2019                 return 0;
2020 }
2021
2022 static OSStatus
2023 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
2024 {
2025         CFDictionaryRef auStateDictionary;
2026         ComponentDescription tempDesc = {0,0,0,0,0};
2027         SInt32 versionValue;
2028         Boolean gotValue;
2029
2030         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2031                 return paramErr;
2032
2033         // the property list for AU state data must be of the dictionary type
2034         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2035                 return kAudioUnitErr_InvalidPropertyValue;
2036         }
2037
2038         auStateDictionary = (CFDictionaryRef)inAUStateData;
2039
2040         // first check to make sure that the version of the AU state data is one that we know understand
2041         // XXX should I really do this?  later versions would probably still hold these ID keys, right?
2042         versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2043
2044         if (!gotValue) {
2045                 return kAudioUnitErr_InvalidPropertyValue;
2046         }
2047 #define kCurrentSavedStateVersion 0
2048         if (versionValue != kCurrentSavedStateVersion) {
2049                 return kAudioUnitErr_InvalidPropertyValue;
2050         }
2051
2052         // grab the ComponentDescription values from the AU state data
2053         tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2054         tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2055         tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2056         // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2057         if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2058                 return kAudioUnitErr_InvalidPropertyValue;
2059
2060         *outComponentDescription = tempDesc;
2061         return noErr;
2062 }
2063
2064
2065 static bool au_preset_filter (const string& str, void* arg)
2066 {
2067         /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2068
2069         bool ret;
2070
2071         ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2072
2073         if (ret && arg) {
2074
2075                 /* check the preset file path name against this plugin
2076                    ID. The idea is that all preset files for this plugin
2077                    include "<manufacturer>/<plugin-name>" in their path.
2078                 */
2079
2080                 Plugin* p = (Plugin *) arg;
2081                 string match = p->maker();
2082                 match += '/';
2083                 match += p->name();
2084
2085                 ret = str.find (match) != string::npos;
2086
2087                 if (ret == false) {
2088                         string m = p->maker ();
2089                         string n = p->name ();
2090                         strip_whitespace_edges (m);
2091                         strip_whitespace_edges (n);
2092                         match = m;
2093                         match += '/';
2094                         match += n;
2095
2096                         ret = str.find (match) != string::npos;
2097                 }
2098         }
2099
2100         return ret;
2101 }
2102
2103 bool
2104 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2105 {
2106         OSStatus status;
2107         CFPropertyListRef plist;
2108         ComponentDescription presetDesc;
2109         bool ret = false;
2110
2111         plist = load_property_list (pathstr);
2112
2113         if (!plist) {
2114                 return ret;
2115         }
2116
2117         // get the ComponentDescription from the AU preset file
2118
2119         status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2120
2121         if (status == noErr) {
2122                 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2123
2124                         /* try to get the preset name from the property list */
2125
2126                         if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2127
2128                                 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2129
2130                                 if (psk) {
2131
2132                                         const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2133
2134                                         if (!p) {
2135                                                 char buf[PATH_MAX+1];
2136
2137                                                 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2138                                                         preset_name = buf;
2139                                                 }
2140                                         }
2141                                 }
2142                         }
2143                 }
2144         }
2145
2146         CFRelease (plist);
2147
2148         return true;
2149 }
2150
2151 std::string
2152 AUPlugin::current_preset() const
2153 {
2154         string preset_name;
2155
2156         CFPropertyListRef propertyList;
2157
2158         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2159         if (unit->GetAUPreset (propertyList) == noErr) {
2160                 preset_name = get_preset_name_in_plist (propertyList);
2161                 CFRelease(propertyList);
2162         }
2163
2164         return preset_name;
2165 }
2166
2167 void
2168 AUPlugin::find_presets ()
2169 {
2170         vector<string> preset_files;
2171
2172         user_preset_map.clear ();
2173
2174         find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2175
2176         if (preset_files.empty()) {
2177                 return;
2178         }
2179
2180         for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2181
2182                 string path = *x;
2183                 string preset_name;
2184
2185                 /* make an initial guess at the preset name using the path */
2186
2187                 preset_name = Glib::path_get_basename (path);
2188                 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2189
2190                 /* check that this preset file really matches this plugin
2191                    and potentially get the "real" preset name from
2192                    within the file.
2193                 */
2194
2195                 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2196                         user_preset_map[preset_name] = path;
2197                 }
2198
2199         }
2200
2201         /* now fill the vector<string> with the names we have */
2202
2203         for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2204                 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2205         }
2206
2207         /* add factory presets */
2208
2209         for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2210                 /* XXX: dubious */
2211                 string const uri = string_compose ("%1", _presets.size ());
2212                 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2213         }
2214 }
2215
2216 bool
2217 AUPlugin::has_editor () const
2218 {
2219         // even if the plugin doesn't have its own editor, the AU API can be used
2220         // to create one that looks native.
2221         return true;
2222 }
2223
2224 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2225         : descriptor (d)
2226 {
2227         type = ARDOUR::AudioUnit;
2228 }
2229
2230 AUPluginInfo::~AUPluginInfo ()
2231 {
2232         type = ARDOUR::AudioUnit;
2233 }
2234
2235 PluginPtr
2236 AUPluginInfo::load (Session& session)
2237 {
2238         try {
2239                 PluginPtr plugin;
2240
2241                 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2242                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2243
2244                 if (!comp->IsValid()) {
2245                         error << ("AudioUnit: not a valid Component") << endmsg;
2246                 } else {
2247                         plugin.reset (new AUPlugin (session.engine(), session, comp));
2248                 }
2249
2250                 AUPluginInfo *aup = new AUPluginInfo (*this);
2251                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2252                 plugin->set_info (PluginInfoPtr (aup));
2253                 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2254                 return plugin;
2255         }
2256
2257         catch (failed_constructor &err) {
2258                 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2259                 return PluginPtr ();
2260         }
2261 }
2262
2263 Glib::ustring
2264 AUPluginInfo::au_cache_path ()
2265 {
2266         return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2267 }
2268
2269 PluginInfoList*
2270 AUPluginInfo::discover ()
2271 {
2272         XMLTree tree;
2273
2274         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2275                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2276         }
2277         // create crash log file
2278         au_start_crashlog ();
2279
2280         PluginInfoList* plugs = new PluginInfoList;
2281
2282         discover_fx (*plugs);
2283         discover_music (*plugs);
2284         discover_generators (*plugs);
2285         discover_instruments (*plugs);
2286
2287         // all fine if we get here
2288         au_remove_crashlog ();
2289
2290         DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2291
2292         return plugs;
2293 }
2294
2295 void
2296 AUPluginInfo::discover_music (PluginInfoList& plugs)
2297 {
2298         CAComponentDescription desc;
2299         desc.componentFlags = 0;
2300         desc.componentFlagsMask = 0;
2301         desc.componentSubType = 0;
2302         desc.componentManufacturer = 0;
2303         desc.componentType = kAudioUnitType_MusicEffect;
2304
2305         discover_by_description (plugs, desc);
2306 }
2307
2308 void
2309 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2310 {
2311         CAComponentDescription desc;
2312         desc.componentFlags = 0;
2313         desc.componentFlagsMask = 0;
2314         desc.componentSubType = 0;
2315         desc.componentManufacturer = 0;
2316         desc.componentType = kAudioUnitType_Effect;
2317
2318         discover_by_description (plugs, desc);
2319 }
2320
2321 void
2322 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2323 {
2324         CAComponentDescription desc;
2325         desc.componentFlags = 0;
2326         desc.componentFlagsMask = 0;
2327         desc.componentSubType = 0;
2328         desc.componentManufacturer = 0;
2329         desc.componentType = kAudioUnitType_Generator;
2330
2331         discover_by_description (plugs, desc);
2332 }
2333
2334 void
2335 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2336 {
2337         CAComponentDescription desc;
2338         desc.componentFlags = 0;
2339         desc.componentFlagsMask = 0;
2340         desc.componentSubType = 0;
2341         desc.componentManufacturer = 0;
2342         desc.componentType = kAudioUnitType_MusicDevice;
2343
2344         discover_by_description (plugs, desc);
2345 }
2346
2347
2348 bool
2349 AUPluginInfo::au_get_crashlog (std::string &msg)
2350 {
2351         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2352         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2353                 return false;
2354         }
2355         std::ifstream ifs(fn.c_str());
2356         msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2357         au_remove_crashlog ();
2358         return true;
2359 }
2360
2361 void
2362 AUPluginInfo::au_start_crashlog ()
2363 {
2364         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2365         assert(!_crashlog_fd);
2366         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2367         if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2368                 PBD::error << "Cannot create AU error-log\n";
2369         }
2370 }
2371
2372 void
2373 AUPluginInfo::au_remove_crashlog ()
2374 {
2375         if (_crashlog_fd) {
2376                 ::fclose(_crashlog_fd);
2377                 _crashlog_fd = NULL;
2378         }
2379         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2380         ::g_unlink(fn.c_str());
2381         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2382 }
2383
2384
2385 void
2386 AUPluginInfo::au_crashlog (std::string msg)
2387 {
2388         assert(_crashlog_fd);
2389         fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2390         ::fflush(_crashlog_fd);
2391 }
2392
2393 void
2394 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2395 {
2396         Component comp = 0;
2397         au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2398
2399         comp = FindNextComponent (NULL, &desc);
2400
2401         while (comp != NULL) {
2402                 CAComponentDescription temp;
2403                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2404                 CFStringRef itemName = NULL;
2405
2406                 {
2407                         if (itemName != NULL) CFRelease(itemName);
2408                         CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2409                         CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2410                         CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2411                         itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2412                                         compTypeString, compManufacturerString, compSubTypeString);
2413                         au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2414                         if (compTypeString != NULL)
2415                                 CFRelease(compTypeString);
2416                         if (compSubTypeString != NULL)
2417                                 CFRelease(compSubTypeString);
2418                         if (compManufacturerString != NULL)
2419                                 CFRelease(compManufacturerString);
2420                 }
2421
2422                 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2423                         info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2424                         comp = FindNextComponent (comp, &desc);
2425                         continue;
2426                 }
2427
2428                 AUPluginInfoPtr info (new AUPluginInfo
2429                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2430
2431                 /* although apple designed the subtype field to be a "category" indicator,
2432                    its really turned into a plugin ID field for a given manufacturer. Hence
2433                    there are no categories for AudioUnits. However, to keep the plugins
2434                    showing up under "categories", we'll use the "type" as a high level
2435                    selector.
2436
2437                    NOTE: no panners, format converters or i/o AU's for our purposes
2438                  */
2439
2440                 switch (info->descriptor->Type()) {
2441                 case kAudioUnitType_Panner:
2442                 case kAudioUnitType_OfflineEffect:
2443                 case kAudioUnitType_FormatConverter:
2444                         comp = FindNextComponent (comp, &desc);
2445                         continue;
2446
2447                 case kAudioUnitType_Output:
2448                         info->category = _("AudioUnit Outputs");
2449                         break;
2450                 case kAudioUnitType_MusicDevice:
2451                         info->category = _("AudioUnit Instruments");
2452                         break;
2453                 case kAudioUnitType_MusicEffect:
2454                         info->category = _("AudioUnit MusicEffects");
2455                         break;
2456                 case kAudioUnitType_Effect:
2457                         info->category = _("AudioUnit Effects");
2458                         break;
2459                 case kAudioUnitType_Mixer:
2460                         info->category = _("AudioUnit Mixers");
2461                         break;
2462                 case kAudioUnitType_Generator:
2463                         info->category = _("AudioUnit Generators");
2464                         break;
2465                 default:
2466                         info->category = _("AudioUnit (Unknown)");
2467                         break;
2468                 }
2469
2470                 au_blacklist(CFStringRefToStdString(itemName));
2471                 AUPluginInfo::get_names (temp, info->name, info->creator);
2472                 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2473                 au_crashlog(string_compose("Plugin: %1", info->name));
2474
2475                 info->type = ARDOUR::AudioUnit;
2476                 info->unique_id = stringify_descriptor (*info->descriptor);
2477
2478                 /* XXX not sure of the best way to handle plugin versioning yet
2479                  */
2480
2481                 CAComponent cacomp (*info->descriptor);
2482
2483                 if (cacomp.GetResourceVersion (info->version) != noErr) {
2484                         info->version = 0;
2485                 }
2486
2487                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2488
2489                         /* here we have to map apple's wildcard system to a simple pair
2490                            of values. in ::can_do() we use the whole system, but here
2491                            we need a single pair of values. XXX probably means we should
2492                            remove any use of these values.
2493
2494                            for now, if the plugin provides a wildcard, treat it as 1. we really
2495                            don't care much, because whether we can handle an i/o configuration
2496                            depends upon ::can_support_io_configuration(), not these counts.
2497
2498                            they exist because other parts of ardour try to present i/o configuration
2499                            info to the user, which should perhaps be revisited.
2500                         */
2501
2502                         int32_t possible_in = info->cache.io_configs.front().first;
2503                         int32_t possible_out = info->cache.io_configs.front().second;
2504                         
2505                         if (possible_in > 0) {
2506                                 info->n_inputs.set (DataType::AUDIO, possible_in);
2507                         } else {
2508                                 info->n_inputs.set (DataType::AUDIO, 1);
2509                         }
2510
2511                         if (possible_out > 0) {
2512                                 info->n_outputs.set (DataType::AUDIO, possible_out);
2513                         } else {
2514                                 info->n_outputs.set (DataType::AUDIO, 1);
2515                         }
2516
2517                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2518                                                                         info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2519
2520                         plugs.push_back (info);
2521
2522                 } else {
2523                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2524                 }
2525
2526                 au_unblacklist(CFStringRefToStdString(itemName));
2527                 au_crashlog("Success.");
2528                 comp = FindNextComponent (comp, &desc);
2529                 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2530         }
2531         au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2532 }
2533
2534 bool
2535 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2536                                        UInt32 version,
2537                                        CAComponent& comp,
2538                                        AUPluginCachedInfo& cinfo,
2539                                        const std::string& name)
2540 {
2541         std::string id;
2542         char buf[32];
2543
2544         /* concatenate unique ID with version to provide a key for cached info lookup.
2545            this ensures we don't get stale information, or should if plugin developers
2546            follow Apple "guidelines".
2547          */
2548
2549         snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2550         id = unique_id;
2551         id += '/';
2552         id += buf;
2553
2554         CachedInfoMap::iterator cim = cached_info.find (id);
2555
2556         if (cim != cached_info.end()) {
2557                 cinfo = cim->second;
2558                 return true;
2559         }
2560
2561         CAAudioUnit unit;
2562         AUChannelInfo* channel_info;
2563         UInt32 cnt;
2564         int ret;
2565
2566         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2567
2568         try {
2569
2570                 if (CAAudioUnit::Open (comp, unit) != noErr) {
2571                         return false;
2572                 }
2573
2574         } catch (...) {
2575
2576                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2577                 return false;
2578
2579         }
2580
2581         DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2582         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2583                 return false;
2584         }
2585
2586         if (ret > 0) {
2587
2588                 /* no explicit info available, so default to 1in/1out */
2589
2590                 /* XXX this is wrong. we should be indicating wildcard values */
2591
2592                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2593
2594         } else {
2595
2596                 /* store each configuration */
2597
2598                 for (uint32_t n = 0; n < cnt; ++n) {
2599                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2600                                                                    channel_info[n].outChannels));
2601                 }
2602
2603                 free (channel_info);
2604         }
2605
2606         add_cached_info (id, cinfo);
2607         save_cached_info ();
2608
2609         return true;
2610 }
2611
2612 void
2613 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2614 {
2615         cached_info[id] = cinfo;
2616 }
2617
2618 #define AU_CACHE_VERSION "2.0"
2619
2620 void
2621 AUPluginInfo::save_cached_info ()
2622 {
2623         XMLNode* node;
2624
2625         node = new XMLNode (X_("AudioUnitPluginCache"));
2626         node->add_property( "version", AU_CACHE_VERSION );
2627
2628         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2629                 XMLNode* parent = new XMLNode (X_("plugin"));
2630                 parent->add_property ("id", i->first);
2631                 node->add_child_nocopy (*parent);
2632
2633                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2634
2635                         XMLNode* child = new XMLNode (X_("io"));
2636                         char buf[32];
2637
2638                         snprintf (buf, sizeof (buf), "%d", j->first);
2639                         child->add_property (X_("in"), buf);
2640                         snprintf (buf, sizeof (buf), "%d", j->second);
2641                         child->add_property (X_("out"), buf);
2642                         parent->add_child_nocopy (*child);
2643                 }
2644
2645         }
2646
2647         Glib::ustring path = au_cache_path ();
2648         XMLTree tree;
2649
2650         tree.set_root (node);
2651
2652         if (!tree.write (path)) {
2653                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2654                 g_unlink (path.c_str());
2655         }
2656 }
2657
2658 int
2659 AUPluginInfo::load_cached_info ()
2660 {
2661         Glib::ustring path = au_cache_path ();
2662         XMLTree tree;
2663
2664         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2665                 return 0;
2666         }
2667
2668         if ( !tree.read (path) ) {
2669                 error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
2670                 return -1;
2671         }
2672
2673         const XMLNode* root (tree.root());
2674
2675         if (root->name() != X_("AudioUnitPluginCache")) {
2676                 return -1;
2677         }
2678
2679         //initial version has incorrectly stored i/o info, and/or garbage chars.
2680         const XMLProperty* version = root->property(X_("version"));
2681         if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2682                 error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
2683                 return -1;
2684         }
2685
2686         cached_info.clear ();
2687
2688         const XMLNodeList children = root->children();
2689
2690         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2691
2692                 const XMLNode* child = *iter;
2693
2694                 if (child->name() == X_("plugin")) {
2695
2696                         const XMLNode* gchild;
2697                         const XMLNodeList gchildren = child->children();
2698                         const XMLProperty* prop = child->property (X_("id"));
2699
2700                         if (!prop) {
2701                                 continue;
2702                         }
2703
2704                         string id = prop->value();
2705                         string fixed;
2706                         string version;
2707
2708                         string::size_type slash = id.find_last_of ('/');
2709
2710                         if (slash == string::npos) {
2711                                 continue;
2712                         }
2713
2714                         version = id.substr (slash);
2715                         id = id.substr (0, slash);
2716                         fixed = AUPlugin::maybe_fix_broken_au_id (id);
2717
2718                         if (fixed.empty()) {
2719                                 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2720                                 continue;
2721                         }
2722
2723                         id = fixed;
2724                         id += version;
2725
2726                         AUPluginCachedInfo cinfo;
2727
2728                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2729
2730                                 gchild = *giter;
2731
2732                                 if (gchild->name() == X_("io")) {
2733
2734                                         int in;
2735                                         int out;
2736                                         const XMLProperty* iprop;
2737                                         const XMLProperty* oprop;
2738
2739                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
2740                                             ((oprop = gchild->property (X_("out"))) != 0)) {
2741                                                 in = atoi (iprop->value());
2742                                                 out = atoi (oprop->value());
2743
2744                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
2745                                         }
2746                                 }
2747                         }
2748
2749                         if (cinfo.io_configs.size()) {
2750                                 add_cached_info (id, cinfo);
2751                         }
2752                 }
2753         }
2754
2755         return 0;
2756 }
2757
2758 void
2759 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2760 {
2761         CFStringRef itemName = NULL;
2762
2763         // Marc Poirier-style item name
2764         CAComponent auComponent (comp_desc);
2765         if (auComponent.IsValid()) {
2766                 CAComponentDescription dummydesc;
2767                 Handle nameHandle = NewHandle(sizeof(void*));
2768                 if (nameHandle != NULL) {
2769                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2770                         if (err == noErr) {
2771                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2772                                 if (nameString != NULL) {
2773                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2774                                 }
2775                         }
2776                         DisposeHandle(nameHandle);
2777                 }
2778         }
2779
2780         // if Marc-style fails, do the original way
2781         if (itemName == NULL) {
2782                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2783                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2784                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2785
2786                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2787                         compTypeString, compManufacturerString, compSubTypeString);
2788
2789                 if (compTypeString != NULL)
2790                         CFRelease(compTypeString);
2791                 if (compSubTypeString != NULL)
2792                         CFRelease(compSubTypeString);
2793                 if (compManufacturerString != NULL)
2794                         CFRelease(compManufacturerString);
2795         }
2796
2797         string str = CFStringRefToStdString(itemName);
2798         string::size_type colon = str.find (':');
2799
2800         if (colon) {
2801                 name = str.substr (colon+1);
2802                 maker = str.substr (0, colon);
2803                 strip_whitespace_edges (maker);
2804                 strip_whitespace_edges (name);
2805         } else {
2806                 name = str;
2807                 maker = "unknown";
2808                 strip_whitespace_edges (name);
2809         }
2810 }
2811
2812 std::string
2813 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2814 {
2815         stringstream s;
2816
2817         /* note: OSType is a compiler-implemenation-defined value,
2818            historically a 32 bit integer created with a multi-character
2819            constant such as 'abcd'. It is, fundamentally, an abomination.
2820         */
2821
2822         s << desc.Type();
2823         s << '-';
2824         s << desc.SubType();
2825         s << '-';
2826         s << desc.Manu();
2827
2828         return s.str();
2829 }
2830
2831 bool
2832 AUPluginInfo::needs_midi_input ()
2833 {
2834         return is_effect_with_midi_input () || is_instrument ();
2835 }
2836
2837 bool
2838 AUPluginInfo::is_effect () const
2839 {
2840         return is_effect_without_midi_input() || is_effect_with_midi_input();
2841 }
2842
2843 bool
2844 AUPluginInfo::is_effect_without_midi_input () const
2845 {
2846         return descriptor->IsAUFX();
2847 }
2848
2849 bool
2850 AUPluginInfo::is_effect_with_midi_input () const
2851 {
2852         return descriptor->IsAUFM();
2853 }
2854
2855 bool
2856 AUPluginInfo::is_instrument () const
2857 {
2858         return descriptor->IsMusicDevice();
2859 }
2860
2861 void
2862 AUPlugin::set_info (PluginInfoPtr info)
2863 {
2864         Plugin::set_info (info);
2865         
2866         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2867         _has_midi_input = pinfo->needs_midi_input ();
2868         _has_midi_output = false;
2869 }
2870
2871 int
2872 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2873 {
2874 #ifdef WITH_CARBON
2875         CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop()); 
2876 #else
2877         CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2878 #endif
2879         CFStringRef  loop_mode = kCFRunLoopDefaultMode;
2880
2881         if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2882                 return -1;
2883         }
2884
2885         _parameter_listener_arg = arg;
2886
2887         return 0;
2888 }
2889
2890 int
2891 AUPlugin::listen_to_parameter (uint32_t param_id)
2892 {
2893         AudioUnitEvent      event;
2894
2895         if (!_parameter_listener || param_id >= descriptors.size()) {
2896                 return -2;
2897         }
2898
2899         event.mEventType = kAudioUnitEvent_ParameterValueChange;
2900         event.mArgument.mParameter.mAudioUnit = unit->AU();
2901         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2902         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2903         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2904
2905         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2906                 return -1;
2907         } 
2908
2909         event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2910         event.mArgument.mParameter.mAudioUnit = unit->AU();
2911         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2912         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2913         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2914
2915         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2916                 return -1;
2917         } 
2918
2919         event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2920         event.mArgument.mParameter.mAudioUnit = unit->AU();
2921         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2922         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2923         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2924
2925         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2926                 return -1;
2927         } 
2928
2929         return 0;
2930 }
2931
2932 int
2933 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2934 {
2935         AudioUnitEvent      event;
2936
2937         if (!_parameter_listener || param_id >= descriptors.size()) {
2938                 return -2;
2939         }
2940
2941         event.mEventType = kAudioUnitEvent_ParameterValueChange;
2942         event.mArgument.mParameter.mAudioUnit = unit->AU();
2943         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2944         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2945         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2946
2947         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2948                 return -1;
2949         } 
2950
2951         event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2952         event.mArgument.mParameter.mAudioUnit = unit->AU();
2953         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2954         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2955         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2956
2957         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2958                 return -1;
2959         } 
2960
2961         event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2962         event.mArgument.mParameter.mAudioUnit = unit->AU();
2963         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2964         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2965         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2966
2967         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2968                 return -1;
2969         } 
2970
2971         return 0;
2972 }
2973
2974 void
2975 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2976 {
2977         ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2978 }
2979
2980 void
2981 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2982 {
2983         ParameterMap::iterator i;
2984
2985         if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2986                 return;
2987         }
2988         
2989         switch (event->mEventType) {
2990         case kAudioUnitEvent_BeginParameterChangeGesture:
2991                 StartTouch (i->second);
2992                 break;
2993         case kAudioUnitEvent_EndParameterChangeGesture:
2994                 EndTouch (i->second);
2995                 break;
2996         case kAudioUnitEvent_ParameterValueChange:
2997                 ParameterChanged (i->second, new_value);
2998                 break;
2999         default:
3000                 break;
3001         }
3002 }