more work on the suprisingly ongoing filename/path/origin issue
[ardour.git] / libs / ardour / audio_unit.cc
1 /*
2     Copyright (C) 2006-2009 Paul Davis
3     Some portions Copyright (C) Sophia Poirier.
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <sstream>
22 #include <errno.h>
23 #include <string.h>
24 #include <math.h>
25 #include <ctype.h>
26
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
33
34 #include <glibmm/threads.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
37
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/debug.h"
42 #include "ardour/midi_buffer.h"
43 #include "ardour/filesystem_paths.h"
44 #include "ardour/io.h"
45 #include "ardour/audio_unit.h"
46 #include "ardour/route.h"
47 #include "ardour/session.h"
48 #include "ardour/tempo.h"
49 #include "ardour/utils.h"
50
51 #include "appleutility/CAAudioUnit.h"
52 #include "appleutility/CAAUParameter.h"
53
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <CoreServices/CoreServices.h>
56 #include <AudioUnit/AudioUnit.h>
57 #include <AudioToolbox/AudioUnitUtilities.h>
58 #ifdef WITH_CARBON
59 #include <Carbon/Carbon.h>
60 #endif
61
62 #include "i18n.h"
63
64 using namespace std;
65 using namespace PBD;
66 using namespace ARDOUR;
67
68 #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         if (get_parameter(which) == val) {
788                 return;
789         }
790
791         const AUParameterDescriptor& d (descriptors[which]);
792         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
793         unit->SetParameter (d.id, d.scope, d.element, val);
794
795         /* tell the world what we did */
796
797         AudioUnitEvent theEvent;
798
799         theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
800         theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
801         theEvent.mArgument.mParameter.mParameterID = d.id;
802         theEvent.mArgument.mParameter.mScope = d.scope;
803         theEvent.mArgument.mParameter.mElement = d.element;
804
805         DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
806         AUEventListenerNotify (NULL, NULL, &theEvent);
807
808         Plugin::set_parameter (which, val);
809 }
810
811 float
812 AUPlugin::get_parameter (uint32_t which) const
813 {
814         float val = 0.0;
815         if (which < descriptors.size()) {
816                 const AUParameterDescriptor& d (descriptors[which]);
817                 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
818                 unit->GetParameter(d.id, d.scope, d.element, val);
819         }
820         return val;
821 }
822
823 int
824 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
825 {
826         if (which < descriptors.size()) {
827                 pd = descriptors[which];
828                 return 0;
829         }
830         return -1;
831 }
832
833 uint32_t
834 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
835 {
836         if (which < descriptors.size()) {
837                 ok = true;
838                 return which;
839         }
840         ok = false;
841         return 0;
842 }
843
844 void
845 AUPlugin::activate ()
846 {
847         if (!initialized) {
848                 OSErr err;
849                 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
850                 if ((err = unit->Initialize()) != noErr) {
851                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
852                 } else {
853                         frames_processed = 0;
854                         initialized = true;
855                 }
856         }
857 }
858
859 void
860 AUPlugin::deactivate ()
861 {
862         DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
863         unit->Uninitialize ();
864         initialized = false;
865 }
866
867 void
868 AUPlugin::flush ()
869 {
870         DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
871         unit->GlobalReset ();
872 }
873
874 bool
875 AUPlugin::requires_fixed_size_buffers() const
876 {
877         return _requires_fixed_size_buffers;
878 }
879
880
881 int
882 AUPlugin::set_block_size (pframes_t nframes)
883 {
884         bool was_initialized = initialized;
885         UInt32 numFrames = nframes;
886         OSErr err;
887
888         if (initialized) {
889                 deactivate ();
890         }
891
892         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
893         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
894                                       0, &numFrames, sizeof (numFrames))) != noErr) {
895                 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
896                 return -1;
897         }
898
899         if (was_initialized) {
900                 activate ();
901         }
902
903         _current_block_size = nframes;
904
905         return 0;
906 }
907
908 bool
909 AUPlugin::configure_io (ChanCount in, ChanCount out)
910 {
911         AudioStreamBasicDescription streamFormat;
912         bool was_initialized = initialized;
913         int32_t audio_in = in.n_audio();
914         int32_t audio_out = out.n_audio();
915
916         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
917
918         if (initialized) {
919                 //if we are already running with the requested i/o config, bail out here
920                 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
921                         return 0;
922                 } else {
923                         deactivate ();
924                 }
925         }
926
927         streamFormat.mSampleRate = _session.frame_rate();
928         streamFormat.mFormatID = kAudioFormatLinearPCM;
929         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
930
931 #ifdef __LITTLE_ENDIAN__
932         /* relax */
933 #else
934         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
935 #endif
936
937         streamFormat.mBitsPerChannel = 32;
938         streamFormat.mFramesPerPacket = 1;
939
940         /* apple says that for non-interleaved data, these
941            values always refer to a single channel.
942         */
943         streamFormat.mBytesPerPacket = 4;
944         streamFormat.mBytesPerFrame = 4;
945
946         streamFormat.mChannelsPerFrame = audio_in;
947
948         if (set_input_format (streamFormat) != 0) {
949                 return -1;
950         }
951
952         streamFormat.mChannelsPerFrame = audio_out;
953
954         if (set_output_format (streamFormat) != 0) {
955                 return -1;
956         }
957
958         /* reset plugin info to show currently configured state */
959         
960         _info->n_inputs = in;
961         _info->n_outputs = out;
962
963         if (was_initialized) {
964                 activate ();
965         }
966
967         return 0;
968 }
969
970 ChanCount
971 AUPlugin::input_streams() const
972 {
973         ChanCount c;
974
975         c.set (DataType::AUDIO, 1);
976         c.set (DataType::MIDI, 0);
977
978         if (input_channels < 0) {
979                 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
980         } else {
981                 c.set (DataType::AUDIO, input_channels);
982                 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
983         }
984
985         return c;
986 }
987
988
989 ChanCount
990 AUPlugin::output_streams() const
991 {
992         ChanCount c;
993
994         c.set (DataType::AUDIO, 1);
995         c.set (DataType::MIDI, 0);
996
997         if (output_channels < 0) {
998                 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
999         } else {
1000                 c.set (DataType::AUDIO, output_channels);
1001                 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1002         }
1003
1004         return c;
1005 }
1006
1007 bool
1008 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
1009 {
1010         // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1011
1012         int32_t audio_in = in.n_audio();
1013         int32_t audio_out;
1014         bool found = false;
1015         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1016
1017         /* lets check MIDI first */
1018
1019         if (in.n_midi() > 0) {
1020                 if (!_has_midi_input) {
1021                         return false;
1022                 }
1023         }
1024
1025         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1026
1027         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n", 
1028                                                         name(), io_configs.size(), in, out));
1029
1030         //Ardour expects the plugin to tell it the output
1031         //configuration but AU plugins can have multiple I/O
1032         //configurations in most cases. so first lets see
1033         //if there's a configuration that keeps out==in
1034
1035         audio_out = audio_in;
1036
1037         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1038
1039                 int32_t possible_in = i->first;
1040                 int32_t possible_out = i->second;
1041
1042                 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1043                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n", 
1044                                                                         possible_in, possible_out,
1045                                                                         in, out));
1046
1047                         out.set (DataType::MIDI, 0);
1048                         out.set (DataType::AUDIO, audio_out);
1049
1050                         return 1;
1051                 }
1052         }
1053
1054         /* now allow potentially "imprecise" matches */
1055
1056         audio_out = -1;
1057
1058         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1059
1060                 int32_t possible_in = i->first;
1061                 int32_t possible_out = i->second;
1062
1063                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1064
1065                 if (possible_out == 0) {
1066                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1067                         /* XXX surely this is just a send? (e.g. AUNetSend) */
1068                         continue;
1069                 }
1070
1071                 if (possible_in == 0) {
1072
1073                         /* instrument plugin, always legal but throws away inputs ...
1074                         */
1075
1076                         if (possible_out == -1) {
1077                                 /* any configuration possible, provide stereo output */
1078                                 audio_out = 2;
1079                                 found = true;
1080                         } else if (possible_out == -2) {
1081                                 /* plugins shouldn't really use (0,-2) but might. 
1082                                    any configuration possible, provide stereo output 
1083                                 */
1084                                 audio_out = 2;
1085                                 found = true;
1086                         } else if (possible_out < -2) {
1087                                 /* explicitly variable number of outputs. 
1088
1089                                    Since Ardour can handle any configuration,
1090                                    we have to somehow pick a number. 
1091
1092                                    We'll use the number of inputs
1093                                    to the master bus, or 2 if there
1094                                    is no master bus.
1095                                 */
1096                                 boost::shared_ptr<Route> master = _session.master_out();
1097                                 if (master) {
1098                                         audio_out = master->input()->n_ports().n_audio();
1099                                 } else {
1100                                         audio_out = 2;
1101                                 }
1102                                 found = true;
1103                         } else {
1104                                 /* exact number of outputs */
1105                                 audio_out = possible_out;
1106                                 found = true;
1107                         }
1108                 }
1109
1110                 if (possible_in == -1) {
1111
1112                         /* wildcard for input */
1113
1114                         if (possible_out == -1) {
1115                                 /* out much match in */
1116                                 audio_out = audio_in;
1117                                 found = true;
1118                         } else if (possible_out == -2) {
1119                                 /* any configuration possible, pick matching */
1120                                 audio_out = audio_in;
1121                                 found = true;
1122                         } else if (possible_out < -2) {
1123                                 /* explicitly variable number of outputs, pick maximum */
1124                                 audio_out = -possible_out;
1125                                 found = true;
1126                         } else {
1127                                 /* exact number of outputs */
1128                                 audio_out = possible_out;
1129                                 found = true;
1130                         }
1131                 }
1132
1133                 if (possible_in == -2) {
1134
1135                         if (possible_out == -1) {
1136                                 /* any configuration possible, pick matching */
1137                                 audio_out = audio_in;
1138                                 found = true;
1139                         } else if (possible_out == -2) {
1140                                 /* plugins shouldn't really use (-2,-2) but might. 
1141                                    interpret as (-1,-1).
1142                                 */
1143                                 audio_out = audio_in;
1144                                 found = true;
1145                         } else if (possible_out < -2) {
1146                                 /* explicitly variable number of outputs, pick maximum */
1147                                 audio_out = -possible_out;
1148                                 found = true;
1149                         } else {
1150                                 /* exact number of outputs */
1151                                 audio_out = possible_out;
1152                                 found = true;
1153                         }
1154                 }
1155
1156                 if (possible_in < -2) {
1157
1158                         /* explicit variable number of inputs */
1159
1160                         if (audio_in > -possible_in) {
1161                                 /* request is too large */
1162                         }
1163
1164
1165                         if (possible_out == -1) {
1166                                 /* any output configuration possible, provide stereo out */
1167                                 audio_out = 2;
1168                                 found = true;
1169                         } else if (possible_out == -2) {
1170                                 /* plugins shouldn't really use (<-2,-2) but might. 
1171                                    interpret as (<-2,-1): any configuration possible, provide stereo output 
1172                                 */
1173                                 audio_out = 2;
1174                                 found = true;
1175                         } else if (possible_out < -2) {
1176                                 /* explicitly variable number of outputs. 
1177
1178                                    Since Ardour can handle any configuration,
1179                                    we have to somehow pick a number. 
1180
1181                                    We'll use the number of inputs
1182                                    to the master bus, or 2 if there
1183                                    is no master bus.
1184                                 */
1185                                 boost::shared_ptr<Route> master = _session.master_out();
1186                                 if (master) {
1187                                         audio_out = master->input()->n_ports().n_audio();
1188                                 } else {
1189                                         audio_out = 2;
1190                                 }
1191                                 found = true;
1192                         } else {
1193                                 /* exact number of outputs */
1194                                 audio_out = possible_out;
1195                                 found = true;
1196                         }
1197                 }
1198
1199                 if (possible_in && (possible_in == audio_in)) {
1200
1201                         /* exact number of inputs ... must match obviously */
1202
1203                         if (possible_out == -1) {
1204                                 /* any output configuration possible, provide stereo output */
1205                                 audio_out = 2;
1206                                 found = true;
1207                         } else if (possible_out == -2) {
1208                                 /* plugins shouldn't really use (>0,-2) but might. 
1209                                    interpret as (>0,-1): 
1210                                    any output configuration possible, provide stereo output
1211                                 */
1212                                 audio_out = 2;
1213                                 found = true;
1214                         } else if (possible_out < -2) {
1215                                 /* explicitly variable number of outputs, pick maximum */
1216                                 audio_out = -possible_out;
1217                                 found = true;
1218                         } else {
1219                                 /* exact number of outputs */
1220                                 audio_out = possible_out;
1221                                 found = true;
1222                         }
1223                 }
1224
1225                 if (found) {
1226                         break;
1227                 }
1228
1229         }
1230
1231         if (found) {
1232                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1233         } else {
1234                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1235                 return false;
1236         }
1237
1238         out.set (DataType::MIDI, 0);
1239         out.set (DataType::AUDIO, audio_out);
1240
1241         return true;
1242 }
1243
1244 int
1245 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1246 {
1247         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1248 }
1249
1250 int
1251 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1252 {
1253         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1254                 return -1;
1255         }
1256
1257         if (buffers) {
1258                 free (buffers);
1259                 buffers = 0;
1260         }
1261
1262         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1263                                               fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1264
1265         return 0;
1266 }
1267
1268 int
1269 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1270 {
1271         OSErr result;
1272
1273         for (uint32_t i = 0; i < cnt; ++i) {
1274                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1275                                                                 (scope == kAudioUnitScope_Input ? "input" : "output"),
1276                                                                 scope, cnt));
1277                 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1278                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1279                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1280                         return -1;
1281                 }
1282         }
1283
1284         if (scope == kAudioUnitScope_Input) {
1285                 input_channels = fmt.mChannelsPerFrame;
1286         } else {
1287                 output_channels = fmt.mChannelsPerFrame;
1288         }
1289
1290         return 0;
1291 }
1292
1293 OSStatus
1294 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1295                           const AudioTimeStamp*,
1296                           UInt32,
1297                           UInt32       inNumberFrames,
1298                           AudioBufferList*       ioData)
1299 {
1300         /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1301
1302         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1303                                                         name(), inNumberFrames, ioData->mNumberBuffers));
1304
1305         if (input_maxbuf == 0) {
1306                 error << _("AUPlugin: render callback called illegally!") << endmsg;
1307                 return kAudioUnitErr_CannotDoInCurrentContext;
1308         }
1309         uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1310
1311         for (uint32_t i = 0; i < limit; ++i) {
1312                 ioData->mBuffers[i].mNumberChannels = 1;
1313                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1314
1315                 /* we don't use the channel mapping because audiounits are
1316                    never replicated. one plugin instance uses all channels/buffers
1317                    passed to PluginInsert::connect_and_run()
1318                 */
1319
1320                 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1321         }
1322
1323         cb_offset += inNumberFrames;
1324
1325         return noErr;
1326 }
1327
1328 int
1329 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1330 {
1331         Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1332
1333         AudioUnitRenderActionFlags flags = 0;
1334         AudioTimeStamp ts;
1335         OSErr err;
1336
1337         if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1338                 unit->GlobalReset();
1339                 _last_nframes = nframes;
1340         }
1341
1342         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1343                                                         name(), input_channels, output_channels, _has_midi_input,
1344                                                         bufs.count(), bufs.available()));
1345
1346         /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1347            has the capacity to handle our outputs.
1348         */
1349
1350         assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1351
1352         input_buffers = &bufs;
1353         input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1354         input_offset = offset;
1355         cb_offset = 0;
1356
1357         buffers->mNumberBuffers = output_channels;
1358
1359         for (int32_t i = 0; i < output_channels; ++i) {
1360                 buffers->mBuffers[i].mNumberChannels = 1;
1361                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1362                 /* setting this to 0 indicates to the AU that it can provide buffers here
1363                    if necessary. if it can process in-place, it will use the buffers provided
1364                    as input by ::render_callback() above. 
1365                    
1366                    a non-null values tells the plugin to render into the buffer pointed
1367                    at by the value.
1368                 */
1369                 buffers->mBuffers[i].mData = 0;
1370         }
1371
1372         if (_has_midi_input) {
1373
1374                 uint32_t nmidi = bufs.count().n_midi();
1375
1376                 for (uint32_t i = 0; i < nmidi; ++i) {
1377                         
1378                         /* one MIDI port/buffer only */
1379                         
1380                         MidiBuffer& m = bufs.get_midi (i);
1381                         
1382                         for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1383                                 Evoral::MIDIEvent<framepos_t> ev (*i);
1384                                 
1385                                 if (ev.is_channel_event()) {
1386                                         const uint8_t* b = ev.buffer();
1387                                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1388                                         unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1389                                 }
1390
1391                                 /* XXX need to handle sysex and other message types */
1392                         }
1393                 }
1394         }
1395
1396         /* does this really mean anything ? 
1397          */
1398
1399         ts.mSampleTime = frames_processed;
1400         ts.mFlags = kAudioTimeStampSampleTimeValid;
1401
1402         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1403                                                         name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1404
1405         if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1406
1407                 input_maxbuf = 0;
1408                 frames_processed += nframes;
1409
1410                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1411                                                                 name(), buffers->mNumberBuffers, output_channels));
1412
1413                 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1414                 int32_t i;
1415
1416                 for (i = 0; i < limit; ++i) {
1417                         Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1418                         if (expected_buffer_address != buffers->mBuffers[i].mData) {
1419                                 /* plugin provided its own buffer for output so copy it back to where we want it
1420                                  */
1421                                 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1422                         }
1423                 }
1424
1425                 /* now silence any buffers that were passed in but the that the plugin
1426                    did not fill/touch/use.
1427                 */
1428
1429                 for (;i < output_channels; ++i) {
1430                         memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1431                 }
1432
1433                 return 0;
1434         }
1435
1436         error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1437         return -1;
1438 }
1439
1440 OSStatus
1441 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1442                                        Float64* outCurrentTempo)
1443 {
1444         TempoMap& tmap (_session.tempo_map());
1445
1446         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1447
1448         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1449            (and interpretation) of a beat position will be incorrect. So refuse to
1450            offer the value.
1451         */
1452
1453         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1454                 return kAudioUnitErr_CannotDoInCurrentContext;
1455         }
1456
1457         Timecode::BBT_Time bbt;
1458         TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1459         tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1460
1461         if (outCurrentBeat) {
1462                 float beat;
1463                 beat = metric.meter().divisions_per_bar() * bbt.bars;
1464                 beat += bbt.beats;
1465                 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1466                 *outCurrentBeat = beat;
1467         }
1468
1469         if (outCurrentTempo) {
1470                 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1471         }
1472
1473         return noErr;
1474
1475 }
1476
1477 OSStatus
1478 AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
1479                                               Float32*  outTimeSig_Numerator,
1480                                               UInt32*   outTimeSig_Denominator,
1481                                               Float64*  outCurrentMeasureDownBeat)
1482 {
1483         TempoMap& tmap (_session.tempo_map());
1484
1485         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1486
1487         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1488            (and interpretation) of a beat position will be incorrect. So refuse to
1489            offer the value.
1490         */
1491
1492         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1493                 return kAudioUnitErr_CannotDoInCurrentContext;
1494         }
1495
1496         Timecode::BBT_Time bbt;
1497         TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1498         tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1499
1500         if (outDeltaSampleOffsetToNextBeat) {
1501                 if (bbt.ticks == 0) {
1502                         /* on the beat */
1503                         *outDeltaSampleOffsetToNextBeat = 0;
1504                 } else {
1505                         *outDeltaSampleOffsetToNextBeat = (UInt32) 
1506                                 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1507                                        metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1508                 }
1509         }
1510
1511         if (outTimeSig_Numerator) {
1512                 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1513         }
1514         if (outTimeSig_Denominator) {
1515                 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1516         }
1517
1518         if (outCurrentMeasureDownBeat) {
1519
1520                 /* beat for the start of the bar.
1521                    1|1|0 -> 1
1522                    2|1|0 -> 1 + divisions_per_bar
1523                    3|1|0 -> 1 + (2 * divisions_per_bar)
1524                    etc.
1525                 */
1526
1527                 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1528         }
1529
1530         return noErr;
1531 }
1532
1533 OSStatus
1534 AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
1535                                         Boolean*  outTransportStateChanged,
1536                                         Float64*  outCurrentSampleInTimeLine,
1537                                         Boolean*  outIsCycling,
1538                                         Float64*  outCycleStartBeat,
1539                                         Float64*  outCycleEndBeat)
1540 {
1541         bool rolling;
1542         float speed;
1543
1544         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1545
1546         rolling = _session.transport_rolling();
1547         speed = _session.transport_speed ();
1548
1549         if (outIsPlaying) {
1550                 *outIsPlaying = _session.transport_rolling();
1551         }
1552
1553         if (outTransportStateChanged) {
1554                 if (rolling != last_transport_rolling) {
1555                         *outTransportStateChanged = true;
1556                 } else if (speed != last_transport_speed) {
1557                         *outTransportStateChanged = true;
1558                 } else {
1559                         *outTransportStateChanged = false;
1560                 }
1561         }
1562
1563         if (outCurrentSampleInTimeLine) {
1564                 /* this assumes that the AU can only call this host callback from render context,
1565                    where input_offset is valid.
1566                 */
1567                 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1568         }
1569
1570         if (outIsCycling) {
1571                 Location* loc = _session.locations()->auto_loop_location();
1572
1573                 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1574
1575                 if (*outIsCycling) {
1576
1577                         if (outCycleStartBeat || outCycleEndBeat) {
1578
1579                                 TempoMap& tmap (_session.tempo_map());
1580
1581                                 /* more than 1 meter means that a simplistic computation (and interpretation) of
1582                                    a beat position will be incorrect. so refuse to offer the value.
1583                                 */
1584
1585                                 if (tmap.n_meters() > 1) {
1586                                         return kAudioUnitErr_CannotDoInCurrentContext;
1587                                 }
1588
1589                                 Timecode::BBT_Time bbt;
1590
1591                                 if (outCycleStartBeat) {
1592                                         TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1593                                         _session.tempo_map().bbt_time (loc->start(), bbt);
1594
1595                                         float beat;
1596                                         beat = metric.meter().divisions_per_bar() * bbt.bars;
1597                                         beat += bbt.beats;
1598                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1599
1600                                         *outCycleStartBeat = beat;
1601                                 }
1602
1603                                 if (outCycleEndBeat) {
1604                                         TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1605                                         _session.tempo_map().bbt_time (loc->end(), bbt);
1606
1607                                         float beat;
1608                                         beat = metric.meter().divisions_per_bar() * bbt.bars;
1609                                         beat += bbt.beats;
1610                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1611
1612                                         *outCycleEndBeat = beat;
1613                                 }
1614                         }
1615                 }
1616         }
1617
1618         last_transport_rolling = rolling;
1619         last_transport_speed = speed;
1620
1621         return noErr;
1622 }
1623
1624 set<Evoral::Parameter>
1625 AUPlugin::automatable() const
1626 {
1627         set<Evoral::Parameter> automates;
1628
1629         for (uint32_t i = 0; i < descriptors.size(); ++i) {
1630                 if (descriptors[i].automatable) {
1631                         automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1632                 }
1633         }
1634
1635         return automates;
1636 }
1637
1638 string
1639 AUPlugin::describe_parameter (Evoral::Parameter param)
1640 {
1641         if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1642                 return descriptors[param.id()].label;
1643         } else {
1644                 return "??";
1645         }
1646 }
1647
1648 void
1649 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1650 {
1651         // NameValue stuff here
1652 }
1653
1654 bool
1655 AUPlugin::parameter_is_audio (uint32_t) const
1656 {
1657         return false;
1658 }
1659
1660 bool
1661 AUPlugin::parameter_is_control (uint32_t) const
1662 {
1663         return true;
1664 }
1665
1666 bool
1667 AUPlugin::parameter_is_input (uint32_t) const
1668 {
1669         return false;
1670 }
1671
1672 bool
1673 AUPlugin::parameter_is_output (uint32_t) const
1674 {
1675         return false;
1676 }
1677
1678 void
1679 AUPlugin::add_state (XMLNode* root) const
1680 {
1681         LocaleGuard lg (X_("POSIX"));
1682
1683 #ifdef AU_STATE_SUPPORT
1684         CFDataRef xmlData;
1685         CFPropertyListRef propertyList;
1686
1687         DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1688         if (unit->GetAUPreset (propertyList) != noErr) {
1689                 return;
1690         }
1691
1692         // Convert the property list into XML data.
1693
1694         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1695
1696         if (!xmlData) {
1697                 error << _("Could not create XML version of property list") << endmsg;
1698                 return;
1699         }
1700
1701         /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1702            our state node. GACK!
1703         */
1704
1705         XMLTree t;
1706
1707         if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1708                 if (t.root()) {
1709                         root->add_child_copy (*t.root());
1710                 }
1711         }
1712
1713         CFRelease (xmlData);
1714         CFRelease (propertyList);
1715 #else
1716         if (!seen_get_state_message) {
1717                 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1718                                         PROGRAM_NAME)
1719                      << endmsg;
1720                 seen_get_state_message = true;
1721         }
1722 #endif
1723 }
1724
1725 int
1726 AUPlugin::set_state(const XMLNode& node, int version)
1727 {
1728 #ifdef AU_STATE_SUPPORT
1729         int ret = -1;
1730         CFPropertyListRef propertyList;
1731         LocaleGuard lg (X_("POSIX"));
1732
1733         if (node.name() != state_node_name()) {
1734                 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1735                 return -1;
1736         }
1737
1738         if (node.children().empty()) {
1739                 return -1;
1740         }
1741
1742         XMLNode* top = node.children().front();
1743         XMLNode* copy = new XMLNode (*top);
1744
1745         XMLTree t;
1746         t.set_root (copy);
1747
1748         const string& xml = t.write_buffer ();
1749         CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1750         CFStringRef errorString;
1751
1752         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1753                                                         xmlData,
1754                                                         kCFPropertyListImmutable,
1755                                                         &errorString);
1756
1757         CFRelease (xmlData);
1758
1759         if (propertyList) {
1760                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1761                 if (unit->SetAUPreset (propertyList) == noErr) {
1762                         ret = 0;
1763
1764                         /* tell the world */
1765
1766                         AudioUnitParameter changedUnit;
1767                         changedUnit.mAudioUnit = unit->AU();
1768                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1769                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1770                 }
1771                 CFRelease (propertyList);
1772         }
1773
1774         Plugin::set_state (node, version);
1775         return ret;
1776 #else
1777         if (!seen_set_state_message) {
1778                 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1779                                         PROGRAM_NAME)
1780                      << endmsg;
1781         }
1782         return Plugin::set_state (node, version);
1783 #endif
1784 }
1785
1786 bool
1787 AUPlugin::load_preset (PresetRecord r)
1788 {
1789         Plugin::load_preset (r);
1790
1791 #ifdef AU_STATE_SUPPORT
1792         bool ret = false;
1793         CFPropertyListRef propertyList;
1794         Glib::ustring path;
1795         UserPresetMap::iterator ux;
1796         FactoryPresetMap::iterator fx;
1797
1798         /* look first in "user" presets */
1799
1800         if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1801
1802                 if ((propertyList = load_property_list (ux->second)) != 0) {
1803                         DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1804                         if (unit->SetAUPreset (propertyList) == noErr) {
1805                                 ret = true;
1806
1807                                 /* tell the world */
1808
1809                                 AudioUnitParameter changedUnit;
1810                                 changedUnit.mAudioUnit = unit->AU();
1811                                 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1812                                 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1813                         }
1814                         CFRelease(propertyList);
1815                 }
1816
1817         } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1818
1819                 AUPreset preset;
1820
1821                 preset.presetNumber = fx->second;
1822                 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1823
1824                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1825
1826                 if (unit->SetPresentPreset (preset) == 0) {
1827                         ret = true;
1828
1829                         /* tell the world */
1830
1831                         AudioUnitParameter changedUnit;
1832                         changedUnit.mAudioUnit = unit->AU();
1833                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1834                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1835                 }
1836         }
1837
1838         return ret;
1839 #else
1840         if (!seen_loading_message) {
1841                 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1842                                         PROGRAM_NAME)
1843                      << endmsg;
1844                 seen_loading_message = true;
1845         }
1846         return true;
1847 #endif
1848 }
1849
1850 void
1851 AUPlugin::do_remove_preset (std::string) 
1852 {
1853 }
1854
1855 string
1856 AUPlugin::do_save_preset (string preset_name)
1857 {
1858 #ifdef AU_STATE_SUPPORT
1859         CFPropertyListRef propertyList;
1860         vector<Glib::ustring> v;
1861         Glib::ustring user_preset_path;
1862         bool ret = true;
1863
1864         std::string m = maker();
1865         std::string n = name();
1866
1867         strip_whitespace_edges (m);
1868         strip_whitespace_edges (n);
1869
1870         v.push_back (Glib::get_home_dir());
1871         v.push_back ("Library");
1872         v.push_back ("Audio");
1873         v.push_back ("Presets");
1874         v.push_back (m);
1875         v.push_back (n);
1876
1877         user_preset_path = Glib::build_filename (v);
1878
1879         if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1880                 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1881                 return false;
1882         }
1883
1884         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1885         if (unit->GetAUPreset (propertyList) != noErr) {
1886                 return false;
1887         }
1888
1889         // add the actual preset name */
1890
1891         v.push_back (preset_name + preset_suffix);
1892
1893         // rebuild
1894
1895         user_preset_path = Glib::build_filename (v);
1896
1897         set_preset_name_in_plist (propertyList, preset_name);
1898
1899         if (save_property_list (propertyList, user_preset_path)) {
1900                 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1901                 ret = false;
1902         }
1903
1904         CFRelease(propertyList);
1905
1906         return string ("file:///") + user_preset_path;
1907 #else
1908         if (!seen_saving_message) {
1909                 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1910                                         PROGRAM_NAME)
1911                      << endmsg;
1912                 seen_saving_message = true;
1913         }
1914         return string();
1915 #endif
1916 }
1917
1918 //-----------------------------------------------------------------------------
1919 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1920 static SInt32
1921 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1922 {
1923         CFNumberRef cfNumber;
1924         SInt32 numberValue = 0;
1925         Boolean dummySuccess;
1926
1927         if (outSuccess == NULL)
1928                 outSuccess = &dummySuccess;
1929         if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1930         {
1931                 *outSuccess = FALSE;
1932                 return 0;
1933         }
1934
1935         cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1936         if (cfNumber == NULL)
1937         {
1938                 *outSuccess = FALSE;
1939                 return 0;
1940         }
1941         *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1942         if (*outSuccess)
1943                 return numberValue;
1944         else
1945                 return 0;
1946 }
1947
1948 static OSStatus
1949 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1950 {
1951         CFDictionaryRef auStateDictionary;
1952         ComponentDescription tempDesc = {0,0,0,0,0};
1953         SInt32 versionValue;
1954         Boolean gotValue;
1955
1956         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1957                 return paramErr;
1958
1959         // the property list for AU state data must be of the dictionary type
1960         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1961                 return kAudioUnitErr_InvalidPropertyValue;
1962         }
1963
1964         auStateDictionary = (CFDictionaryRef)inAUStateData;
1965
1966         // first check to make sure that the version of the AU state data is one that we know understand
1967         // XXX should I really do this?  later versions would probably still hold these ID keys, right?
1968         versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1969
1970         if (!gotValue) {
1971                 return kAudioUnitErr_InvalidPropertyValue;
1972         }
1973 #define kCurrentSavedStateVersion 0
1974         if (versionValue != kCurrentSavedStateVersion) {
1975                 return kAudioUnitErr_InvalidPropertyValue;
1976         }
1977
1978         // grab the ComponentDescription values from the AU state data
1979         tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1980         tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1981         tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1982         // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1983         if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1984                 return kAudioUnitErr_InvalidPropertyValue;
1985
1986         *outComponentDescription = tempDesc;
1987         return noErr;
1988 }
1989
1990
1991 static bool au_preset_filter (const string& str, void* arg)
1992 {
1993         /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1994
1995         bool ret;
1996
1997         ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1998
1999         if (ret && arg) {
2000
2001                 /* check the preset file path name against this plugin
2002                    ID. The idea is that all preset files for this plugin
2003                    include "<manufacturer>/<plugin-name>" in their path.
2004                 */
2005
2006                 Plugin* p = (Plugin *) arg;
2007                 string match = p->maker();
2008                 match += '/';
2009                 match += p->name();
2010
2011                 ret = str.find (match) != string::npos;
2012
2013                 if (ret == false) {
2014                         string m = p->maker ();
2015                         string n = p->name ();
2016                         strip_whitespace_edges (m);
2017                         strip_whitespace_edges (n);
2018                         match = m;
2019                         match += '/';
2020                         match += n;
2021
2022                         ret = str.find (match) != string::npos;
2023                 }
2024         }
2025
2026         return ret;
2027 }
2028
2029 bool
2030 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2031 {
2032         OSStatus status;
2033         CFPropertyListRef plist;
2034         ComponentDescription presetDesc;
2035         bool ret = false;
2036
2037         plist = load_property_list (pathstr);
2038
2039         if (!plist) {
2040                 return ret;
2041         }
2042
2043         // get the ComponentDescription from the AU preset file
2044
2045         status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2046
2047         if (status == noErr) {
2048                 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2049
2050                         /* try to get the preset name from the property list */
2051
2052                         if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2053
2054                                 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2055
2056                                 if (psk) {
2057
2058                                         const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2059
2060                                         if (!p) {
2061                                                 char buf[PATH_MAX+1];
2062
2063                                                 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2064                                                         preset_name = buf;
2065                                                 }
2066                                         }
2067                                 }
2068                         }
2069                 }
2070         }
2071
2072         CFRelease (plist);
2073
2074         return true;
2075 }
2076
2077 std::string
2078 AUPlugin::current_preset() const
2079 {
2080         string preset_name;
2081
2082 #ifdef AU_STATE_SUPPORT
2083         CFPropertyListRef propertyList;
2084
2085         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2086         if (unit->GetAUPreset (propertyList) == noErr) {
2087                 preset_name = get_preset_name_in_plist (propertyList);
2088                 CFRelease(propertyList);
2089         }
2090 #endif
2091         return preset_name;
2092 }
2093
2094 void
2095 AUPlugin::find_presets ()
2096 {
2097 #ifdef AU_STATE_SUPPORT
2098         vector<string*>* preset_files;
2099         PathScanner scanner;
2100
2101         user_preset_map.clear ();
2102
2103         preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2104
2105         if (!preset_files) {
2106                 return;
2107         }
2108
2109         for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2110
2111                 string path = *(*x);
2112                 string preset_name;
2113
2114                 /* make an initial guess at the preset name using the path */
2115
2116                 preset_name = Glib::path_get_basename (path);
2117                 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2118
2119                 /* check that this preset file really matches this plugin
2120                    and potentially get the "real" preset name from
2121                    within the file.
2122                 */
2123
2124                 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2125                         user_preset_map[preset_name] = path;
2126                 }
2127
2128                 delete *x;
2129         }
2130
2131         delete preset_files;
2132
2133         /* now fill the vector<string> with the names we have */
2134
2135         for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2136                 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2137         }
2138
2139         /* add factory presets */
2140
2141         for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2142                 /* XXX: dubious */
2143                 string const uri = string_compose ("%1", _presets.size ());
2144                 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2145         }
2146
2147 #endif
2148 }
2149
2150 bool
2151 AUPlugin::has_editor () const
2152 {
2153         // even if the plugin doesn't have its own editor, the AU API can be used
2154         // to create one that looks native.
2155         return true;
2156 }
2157
2158 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2159         : descriptor (d)
2160 {
2161         type = ARDOUR::AudioUnit;
2162 }
2163
2164 AUPluginInfo::~AUPluginInfo ()
2165 {
2166         type = ARDOUR::AudioUnit;
2167 }
2168
2169 PluginPtr
2170 AUPluginInfo::load (Session& session)
2171 {
2172         try {
2173                 PluginPtr plugin;
2174
2175                 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2176                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2177
2178                 if (!comp->IsValid()) {
2179                         error << ("AudioUnit: not a valid Component") << endmsg;
2180                 } else {
2181                         plugin.reset (new AUPlugin (session.engine(), session, comp));
2182                 }
2183
2184                 AUPluginInfo *aup = new AUPluginInfo (*this);
2185                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2186                 plugin->set_info (PluginInfoPtr (aup));
2187                 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2188                 return plugin;
2189         }
2190
2191         catch (failed_constructor &err) {
2192                 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2193                 return PluginPtr ();
2194         }
2195 }
2196
2197 Glib::ustring
2198 AUPluginInfo::au_cache_path ()
2199 {
2200         return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2201 }
2202
2203 PluginInfoList*
2204 AUPluginInfo::discover ()
2205 {
2206         XMLTree tree;
2207
2208         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2209                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2210         }
2211
2212         PluginInfoList* plugs = new PluginInfoList;
2213
2214         discover_fx (*plugs);
2215         discover_music (*plugs);
2216         discover_generators (*plugs);
2217         discover_instruments (*plugs);
2218
2219         DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2220
2221         return plugs;
2222 }
2223
2224 void
2225 AUPluginInfo::discover_music (PluginInfoList& plugs)
2226 {
2227         CAComponentDescription desc;
2228         desc.componentFlags = 0;
2229         desc.componentFlagsMask = 0;
2230         desc.componentSubType = 0;
2231         desc.componentManufacturer = 0;
2232         desc.componentType = kAudioUnitType_MusicEffect;
2233
2234         discover_by_description (plugs, desc);
2235 }
2236
2237 void
2238 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2239 {
2240         CAComponentDescription desc;
2241         desc.componentFlags = 0;
2242         desc.componentFlagsMask = 0;
2243         desc.componentSubType = 0;
2244         desc.componentManufacturer = 0;
2245         desc.componentType = kAudioUnitType_Effect;
2246
2247         discover_by_description (plugs, desc);
2248 }
2249
2250 void
2251 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2252 {
2253         CAComponentDescription desc;
2254         desc.componentFlags = 0;
2255         desc.componentFlagsMask = 0;
2256         desc.componentSubType = 0;
2257         desc.componentManufacturer = 0;
2258         desc.componentType = kAudioUnitType_Generator;
2259
2260         discover_by_description (plugs, desc);
2261 }
2262
2263 void
2264 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2265 {
2266         CAComponentDescription desc;
2267         desc.componentFlags = 0;
2268         desc.componentFlagsMask = 0;
2269         desc.componentSubType = 0;
2270         desc.componentManufacturer = 0;
2271         desc.componentType = kAudioUnitType_MusicDevice;
2272
2273         discover_by_description (plugs, desc);
2274 }
2275
2276 void
2277 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2278 {
2279         Component comp = 0;
2280
2281         comp = FindNextComponent (NULL, &desc);
2282
2283         while (comp != NULL) {
2284                 CAComponentDescription temp;
2285                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2286
2287                 AUPluginInfoPtr info (new AUPluginInfo
2288                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2289
2290                 /* although apple designed the subtype field to be a "category" indicator,
2291                    its really turned into a plugin ID field for a given manufacturer. Hence
2292                    there are no categories for AudioUnits. However, to keep the plugins
2293                    showing up under "categories", we'll use the "type" as a high level
2294                    selector.
2295
2296                    NOTE: no panners, format converters or i/o AU's for our purposes
2297                  */
2298
2299                 switch (info->descriptor->Type()) {
2300                 case kAudioUnitType_Panner:
2301                 case kAudioUnitType_OfflineEffect:
2302                 case kAudioUnitType_FormatConverter:
2303                         continue;
2304
2305                 case kAudioUnitType_Output:
2306                         info->category = _("AudioUnit Outputs");
2307                         break;
2308                 case kAudioUnitType_MusicDevice:
2309                         info->category = _("AudioUnit Instruments");
2310                         break;
2311                 case kAudioUnitType_MusicEffect:
2312                         info->category = _("AudioUnit MusicEffects");
2313                         break;
2314                 case kAudioUnitType_Effect:
2315                         info->category = _("AudioUnit Effects");
2316                         break;
2317                 case kAudioUnitType_Mixer:
2318                         info->category = _("AudioUnit Mixers");
2319                         break;
2320                 case kAudioUnitType_Generator:
2321                         info->category = _("AudioUnit Generators");
2322                         break;
2323                 default:
2324                         info->category = _("AudioUnit (Unknown)");
2325                         break;
2326                 }
2327
2328                 AUPluginInfo::get_names (temp, info->name, info->creator);
2329
2330                 info->type = ARDOUR::AudioUnit;
2331                 info->unique_id = stringify_descriptor (*info->descriptor);
2332
2333                 /* XXX not sure of the best way to handle plugin versioning yet
2334                  */
2335
2336                 CAComponent cacomp (*info->descriptor);
2337
2338                 if (cacomp.GetResourceVersion (info->version) != noErr) {
2339                         info->version = 0;
2340                 }
2341
2342                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2343
2344                         /* here we have to map apple's wildcard system to a simple pair
2345                            of values. in ::can_do() we use the whole system, but here
2346                            we need a single pair of values. XXX probably means we should
2347                            remove any use of these values.
2348
2349                            for now, if the plugin provides a wildcard, treat it as 1. we really
2350                            don't care much, because whether we can handle an i/o configuration
2351                            depends upon ::can_support_io_configuration(), not these counts.
2352
2353                            they exist because other parts of ardour try to present i/o configuration
2354                            info to the user, which should perhaps be revisited.
2355                         */
2356
2357                         int32_t possible_in = info->cache.io_configs.front().first;
2358                         int32_t possible_out = info->cache.io_configs.front().second;
2359                         
2360                         if (possible_in > 0) {
2361                                 info->n_inputs.set (DataType::AUDIO, possible_in);
2362                         } else {
2363                                 info->n_inputs.set (DataType::AUDIO, 1);
2364                         }
2365
2366                         if (possible_out > 0) {
2367                                 info->n_outputs.set (DataType::AUDIO, possible_out);
2368                         } else {
2369                                 info->n_outputs.set (DataType::AUDIO, 1);
2370                         }
2371
2372                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2373                                                                         info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2374
2375                         plugs.push_back (info);
2376
2377                 } else {
2378                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2379                 }
2380
2381                 comp = FindNextComponent (comp, &desc);
2382         }
2383 }
2384
2385 bool
2386 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2387                                        UInt32 version,
2388                                        CAComponent& comp,
2389                                        AUPluginCachedInfo& cinfo,
2390                                        const std::string& name)
2391 {
2392         std::string id;
2393         char buf[32];
2394
2395         /* concatenate unique ID with version to provide a key for cached info lookup.
2396            this ensures we don't get stale information, or should if plugin developers
2397            follow Apple "guidelines".
2398          */
2399
2400         snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2401         id = unique_id;
2402         id += '/';
2403         id += buf;
2404
2405         CachedInfoMap::iterator cim = cached_info.find (id);
2406
2407         if (cim != cached_info.end()) {
2408                 cinfo = cim->second;
2409                 return true;
2410         }
2411
2412         CAAudioUnit unit;
2413         AUChannelInfo* channel_info;
2414         UInt32 cnt;
2415         int ret;
2416
2417         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2418
2419         try {
2420
2421                 if (CAAudioUnit::Open (comp, unit) != noErr) {
2422                         return false;
2423                 }
2424
2425         } catch (...) {
2426
2427                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2428                 return false;
2429
2430         }
2431
2432         DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2433         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2434                 return false;
2435         }
2436
2437         if (ret > 0) {
2438
2439                 /* no explicit info available, so default to 1in/1out */
2440
2441                 /* XXX this is wrong. we should be indicating wildcard values */
2442
2443                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2444
2445         } else {
2446
2447                 /* store each configuration */
2448
2449                 for (uint32_t n = 0; n < cnt; ++n) {
2450                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2451                                                                    channel_info[n].outChannels));
2452                 }
2453
2454                 free (channel_info);
2455         }
2456
2457         add_cached_info (id, cinfo);
2458         save_cached_info ();
2459
2460         return true;
2461 }
2462
2463 void
2464 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2465 {
2466         cached_info[id] = cinfo;
2467 }
2468
2469 #define AU_CACHE_VERSION "2.0"
2470
2471 void
2472 AUPluginInfo::save_cached_info ()
2473 {
2474         XMLNode* node;
2475
2476         node = new XMLNode (X_("AudioUnitPluginCache"));
2477         node->add_property( "version", AU_CACHE_VERSION );
2478
2479         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2480                 XMLNode* parent = new XMLNode (X_("plugin"));
2481                 parent->add_property ("id", i->first);
2482                 node->add_child_nocopy (*parent);
2483
2484                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2485
2486                         XMLNode* child = new XMLNode (X_("io"));
2487                         char buf[32];
2488
2489                         snprintf (buf, sizeof (buf), "%d", j->first);
2490                         child->add_property (X_("in"), buf);
2491                         snprintf (buf, sizeof (buf), "%d", j->second);
2492                         child->add_property (X_("out"), buf);
2493                         parent->add_child_nocopy (*child);
2494                 }
2495
2496         }
2497
2498         Glib::ustring path = au_cache_path ();
2499         XMLTree tree;
2500
2501         tree.set_root (node);
2502
2503         if (!tree.write (path)) {
2504                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2505                 unlink (path.c_str());
2506         }
2507 }
2508
2509 int
2510 AUPluginInfo::load_cached_info ()
2511 {
2512         Glib::ustring path = au_cache_path ();
2513         XMLTree tree;
2514
2515         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2516                 return 0;
2517         }
2518
2519         if ( !tree.read (path) ) {
2520                 error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
2521                 return -1;
2522         }
2523
2524         const XMLNode* root (tree.root());
2525
2526         if (root->name() != X_("AudioUnitPluginCache")) {
2527                 return -1;
2528         }
2529
2530         //initial version has incorrectly stored i/o info, and/or garbage chars.
2531         const XMLProperty* version = root->property(X_("version"));
2532         if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2533                 error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
2534                 return -1;
2535         }
2536
2537         cached_info.clear ();
2538
2539         const XMLNodeList children = root->children();
2540
2541         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2542
2543                 const XMLNode* child = *iter;
2544
2545                 if (child->name() == X_("plugin")) {
2546
2547                         const XMLNode* gchild;
2548                         const XMLNodeList gchildren = child->children();
2549                         const XMLProperty* prop = child->property (X_("id"));
2550
2551                         if (!prop) {
2552                                 continue;
2553                         }
2554
2555                         string id = prop->value();
2556                         string fixed;
2557                         string version;
2558
2559                         string::size_type slash = id.find_last_of ('/');
2560
2561                         if (slash == string::npos) {
2562                                 continue;
2563                         }
2564
2565                         version = id.substr (slash);
2566                         id = id.substr (0, slash);
2567                         fixed = AUPlugin::maybe_fix_broken_au_id (id);
2568
2569                         if (fixed.empty()) {
2570                                 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2571                                 continue;
2572                         }
2573
2574                         id = fixed;
2575                         id += version;
2576
2577                         AUPluginCachedInfo cinfo;
2578
2579                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2580
2581                                 gchild = *giter;
2582
2583                                 if (gchild->name() == X_("io")) {
2584
2585                                         int in;
2586                                         int out;
2587                                         const XMLProperty* iprop;
2588                                         const XMLProperty* oprop;
2589
2590                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
2591                                             ((oprop = gchild->property (X_("out"))) != 0)) {
2592                                                 in = atoi (iprop->value());
2593                                                 out = atoi (oprop->value());
2594
2595                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
2596                                         }
2597                                 }
2598                         }
2599
2600                         if (cinfo.io_configs.size()) {
2601                                 add_cached_info (id, cinfo);
2602                         }
2603                 }
2604         }
2605
2606         return 0;
2607 }
2608
2609 void
2610 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2611 {
2612         CFStringRef itemName = NULL;
2613
2614         // Marc Poirier-style item name
2615         CAComponent auComponent (comp_desc);
2616         if (auComponent.IsValid()) {
2617                 CAComponentDescription dummydesc;
2618                 Handle nameHandle = NewHandle(sizeof(void*));
2619                 if (nameHandle != NULL) {
2620                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2621                         if (err == noErr) {
2622                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2623                                 if (nameString != NULL) {
2624                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2625                                 }
2626                         }
2627                         DisposeHandle(nameHandle);
2628                 }
2629         }
2630
2631         // if Marc-style fails, do the original way
2632         if (itemName == NULL) {
2633                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2634                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2635                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2636
2637                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2638                         compTypeString, compManufacturerString, compSubTypeString);
2639
2640                 if (compTypeString != NULL)
2641                         CFRelease(compTypeString);
2642                 if (compSubTypeString != NULL)
2643                         CFRelease(compSubTypeString);
2644                 if (compManufacturerString != NULL)
2645                         CFRelease(compManufacturerString);
2646         }
2647
2648         string str = CFStringRefToStdString(itemName);
2649         string::size_type colon = str.find (':');
2650
2651         if (colon) {
2652                 name = str.substr (colon+1);
2653                 maker = str.substr (0, colon);
2654                 strip_whitespace_edges (maker);
2655                 strip_whitespace_edges (name);
2656         } else {
2657                 name = str;
2658                 maker = "unknown";
2659                 strip_whitespace_edges (name);
2660         }
2661 }
2662
2663 std::string
2664 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2665 {
2666         stringstream s;
2667
2668         /* note: OSType is a compiler-implemenation-defined value,
2669            historically a 32 bit integer created with a multi-character
2670            constant such as 'abcd'. It is, fundamentally, an abomination.
2671         */
2672
2673         s << desc.Type();
2674         s << '-';
2675         s << desc.SubType();
2676         s << '-';
2677         s << desc.Manu();
2678
2679         return s.str();
2680 }
2681
2682 bool
2683 AUPluginInfo::needs_midi_input ()
2684 {
2685         return is_effect_with_midi_input () || is_instrument ();
2686 }
2687
2688 bool
2689 AUPluginInfo::is_effect () const
2690 {
2691         return is_effect_without_midi_input() || is_effect_with_midi_input();
2692 }
2693
2694 bool
2695 AUPluginInfo::is_effect_without_midi_input () const
2696 {
2697         return descriptor->IsAUFX();
2698 }
2699
2700 bool
2701 AUPluginInfo::is_effect_with_midi_input () const
2702 {
2703         return descriptor->IsAUFM();
2704 }
2705
2706 bool
2707 AUPluginInfo::is_instrument () const
2708 {
2709         return descriptor->IsMusicDevice();
2710 }
2711
2712 void
2713 AUPlugin::set_info (PluginInfoPtr info)
2714 {
2715         Plugin::set_info (info);
2716         
2717         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2718         _has_midi_input = pinfo->needs_midi_input ();
2719         _has_midi_output = false;
2720 }
2721
2722 int
2723 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2724 {
2725 #ifdef WITH_CARBON
2726         CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop()); 
2727 #else
2728         CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2729 #endif
2730         CFStringRef  loop_mode = kCFRunLoopDefaultMode;
2731
2732         if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2733                 return -1;
2734         }
2735
2736         _parameter_listener_arg = arg;
2737
2738         return 0;
2739 }
2740
2741 int
2742 AUPlugin::listen_to_parameter (uint32_t param_id)
2743 {
2744         AudioUnitEvent      event;
2745
2746         if (!_parameter_listener || param_id >= descriptors.size()) {
2747                 return -2;
2748         }
2749
2750         event.mEventType = kAudioUnitEvent_ParameterValueChange;
2751         event.mArgument.mParameter.mAudioUnit = unit->AU();
2752         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2753         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2754         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2755
2756         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2757                 return -1;
2758         } 
2759
2760         event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2761         event.mArgument.mParameter.mAudioUnit = unit->AU();
2762         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2763         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2764         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2765
2766         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2767                 return -1;
2768         } 
2769
2770         event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2771         event.mArgument.mParameter.mAudioUnit = unit->AU();
2772         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2773         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2774         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2775
2776         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2777                 return -1;
2778         } 
2779
2780         return 0;
2781 }
2782
2783 int
2784 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2785 {
2786         AudioUnitEvent      event;
2787
2788         if (!_parameter_listener || param_id >= descriptors.size()) {
2789                 return -2;
2790         }
2791
2792         event.mEventType = kAudioUnitEvent_ParameterValueChange;
2793         event.mArgument.mParameter.mAudioUnit = unit->AU();
2794         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2795         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2796         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2797
2798         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2799                 return -1;
2800         } 
2801
2802         event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2803         event.mArgument.mParameter.mAudioUnit = unit->AU();
2804         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2805         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2806         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2807
2808         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2809                 return -1;
2810         } 
2811
2812         event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2813         event.mArgument.mParameter.mAudioUnit = unit->AU();
2814         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2815         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2816         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2817
2818         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2819                 return -1;
2820         } 
2821
2822         return 0;
2823 }
2824
2825 void
2826 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2827 {
2828         ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2829 }
2830
2831 void
2832 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2833 {
2834         ParameterMap::iterator i;
2835
2836         if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2837                 return;
2838         }
2839         
2840         switch (event->mEventType) {
2841         case kAudioUnitEvent_BeginParameterChangeGesture:
2842                 StartTouch (i->second);
2843                 break;
2844         case kAudioUnitEvent_EndParameterChangeGesture:
2845                 EndTouch (i->second);
2846                 break;
2847         case kAudioUnitEvent_ParameterValueChange:
2848                 ParameterChanged (i->second, new_value);
2849                 break;
2850         default:
2851                 break;
2852         }
2853 }