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