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