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