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