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