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