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