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