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