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