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