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