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