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