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