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