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