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