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