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