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