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