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