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