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