Tweak colouring in the processor list.
[ardour.git] / libs / ardour / audio_unit.cc
index b0ced9bdfbe2b57eeac0f4db3df6adb12d60c6cc..54342c7f916d83b9d919059cbe7d2c1e7f8698cd 100644 (file)
@@ -1,5 +1,6 @@
 /*
-    Copyright (C) 2006 Paul Davis
+    Copyright (C) 2006-2009 Paul Davis 
+    Some portions Copyright (C) Sophia Poirier.
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
 #include <sstream>
 #include <errno.h>
 #include <string.h>
+#include <math.h>
+#include <ctype.h>
 
 #include "pbd/transmitter.h"
 #include "pbd/xml++.h"
+#include "pbd/convert.h"
 #include "pbd/whitespace.h"
 #include "pbd/pathscanner.h"
+#include "pbd/locale_guard.h"
 
 #include <glibmm/thread.h>
 #include <glibmm/fileutils.h>
 
 #include "ardour/ardour.h"
 #include "ardour/audioengine.h"
+#include "ardour/audio_buffer.h"
+#include "ardour/midi_buffer.h"
+#include "ardour/filesystem_paths.h"
 #include "ardour/io.h"
 #include "ardour/audio_unit.h"
 #include "ardour/session.h"
+#include "ardour/tempo.h"
 #include "ardour/utils.h"
 
-#include <appleutility/CAAudioUnit.h>
-#include <appleutility/CAAUParameter.h>
+#include "appleutility/CAAudioUnit.h"
+#include "appleutility/CAAUParameter.h"
 
 #include <CoreFoundation/CoreFoundation.h>
 #include <CoreServices/CoreServices.h>
+#include <AudioUnit/AudioUnit.h>
+#include <AudioToolbox/AudioUnitUtilities.h>
 
 #include "i18n.h"
 
@@ -49,6 +60,13 @@ using namespace std;
 using namespace PBD;
 using namespace ARDOUR;
 
+//#define TRACE_AU_API
+#ifdef TRACE_AU_API
+#define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
+#else
+#define TRACE_API(fmt,...)
+#endif
+
 #ifndef AU_STATE_SUPPORT
 static bool seen_get_state_message = false;
 static bool seen_set_state_message = false;
@@ -61,8 +79,9 @@ AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
 static string preset_suffix = ".aupreset";
 static bool preset_search_path_initialized = false;
+static bool debug_io_config = true;
 
-static OSStatus
+static OSStatus 
 _render_callback(void *userData,
                 AudioUnitRenderActionFlags *ioActionFlags,
                 const AudioTimeStamp    *inTimeStamp,
@@ -70,10 +89,59 @@ _render_callback(void *userData,
                 UInt32       inNumberFrames,
                 AudioBufferList*       ioData)
 {
-       return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
+       if (userData) {
+               return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
+       }
+       return paramErr;
+}
+
+static OSStatus 
+_get_beat_and_tempo_callback (void*                userData,
+                             Float64*             outCurrentBeat, 
+                             Float64*             outCurrentTempo)
+{
+       if (userData) {
+               return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
+       }
+    
+       return paramErr;
 }
 
-static int
+static OSStatus 
+_get_musical_time_location_callback (void *     userData,
+                                    UInt32 *   outDeltaSampleOffsetToNextBeat,
+                                    Float32 *  outTimeSig_Numerator,
+                                    UInt32 *   outTimeSig_Denominator,
+                                    Float64 *  outCurrentMeasureDownBeat)
+{
+       if (userData) {
+               return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
+                                                                                 outTimeSig_Numerator,
+                                                                                 outTimeSig_Denominator,
+                                                                                 outCurrentMeasureDownBeat);
+       }
+       return paramErr;
+}
+
+static OSStatus 
+_get_transport_state_callback (void*     userData,
+                              Boolean*  outIsPlaying,
+                              Boolean*  outTransportStateChanged,
+                              Float64*  outCurrentSampleInTimeLine,
+                              Boolean*  outIsCycling,
+                              Float64*  outCycleStartBeat,
+                              Float64*  outCycleEndBeat)
+{
+       if (userData) {
+               return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
+                                                                           outCurrentSampleInTimeLine, outIsCycling,
+                                                                           outCycleStartBeat, outCycleEndBeat);
+       }
+       return paramErr;
+}
+
+
+static int 
 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
 
 {
@@ -81,7 +149,7 @@ save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
        int fd;
 
        // Convert the property list into XML data.
-
+       
        xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
 
        if (!xmlData) {
@@ -94,23 +162,17 @@ save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
        fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
        while (fd < 0) {
                if (errno == EEXIST) {
-                       /* tell any UI's that this file already exists and ask them what to do */
-                       bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
-                       if (overwrite) {
-                               fd = open (path.c_str(), O_WRONLY, 0664);
-                               continue;
-                       } else {
-                               return 0;
-                       }
+                       error << string_compose (_("Preset file %1 exists; not overwriting"), path);
+               } else {
+                       error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
                }
-               error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
                CFRelease (xmlData);
                return -1;
        }
 
        size_t cnt = CFDataGetLength (xmlData);
 
-       if (write (fd, CFDataGetBytePtr (xmlData), cnt) != cnt) {
+       if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
                CFRelease (xmlData);
                close (fd);
                return -1;
@@ -119,23 +181,23 @@ save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
        close (fd);
        return 0;
 }
 
-
-static CFPropertyListRef
-load_property_list (Glib::ustring path)
+static CFPropertyListRef 
+load_property_list (Glib::ustring path) 
 {
        int fd;
-       CFPropertyListRef propertyList;
+       CFPropertyListRef propertyList = 0;
        CFDataRef         xmlData;
        CFStringRef       errorString;
 
        // Read the XML file.
-
+       
        if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
                return propertyList;
 
        }
-
+       
        off_t len = lseek (fd, 0, SEEK_END);
        char* buf = new char[len];
        lseek (fd, 0, SEEK_SET);
@@ -145,13 +207,13 @@ load_property_list (Glib::ustring path)
                close (fd);
                return propertyList;
        }
-
+       
        close (fd);
 
        xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
-
+       
        // Reconstitute the dictionary using the XML data.
-
+       
        propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
                                                        xmlData,
                                                        kCFPropertyListImmutable,
@@ -164,7 +226,7 @@ load_property_list (Glib::ustring path)
 }
 
 //-----------------------------------------------------------------------------
-static void
+static void 
 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
 {
        if (!plist) {
@@ -175,7 +237,7 @@ set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
        if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
                CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
        }
-
+       
        CFRelease (pn);
 }
 
@@ -199,7 +261,7 @@ get_preset_name_in_plist (CFPropertyListRef plist)
                        if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
                                ret = local_buffer;
                        }
-               }
+               } 
        }
        return ret;
 }
@@ -213,7 +275,7 @@ Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inCompon
        if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
                return FALSE;
 
-       if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
+       if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType) 
                        && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
        {
                // only sub-type and manufacturer IDs need to be equal
@@ -250,7 +312,7 @@ Boolean ComponentAndDescriptionMatch_General(Component inComponent, const Compon
 
 //--------------------------------------------------------------------------
 // determine if 2 ComponentDescriptions are basically equal
-// (by that, I mean that the important identifying values are compared,
+// (by that, I mean that the important identifying values are compared, 
 // but not the ComponentDescription flags)
 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
 {
@@ -280,16 +342,20 @@ Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const Compon
 
 
 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
-       : Plugin (engine, session),
-         comp (_comp),
-         unit (new CAAudioUnit),
-         initialized (false),
-         buffers (0),
-         current_maxbuf (0),
-         current_offset (0),
-         current_buffers (0),
-       frames_processed (0)
-{
+       : Plugin (engine, session)
+       , comp (_comp)
+       , unit (new CAAudioUnit)
+       , initialized (false)
+       , _current_block_size (0)
+       , _requires_fixed_size_buffers (false)
+       , buffers (0)
+       , current_maxbuf (0)
+       , current_offset (0)
+       , current_buffers (0)
+       , frames_processed (0)
+       , last_transport_rolling (false)
+       , last_transport_speed (0.0)
+{                      
        if (!preset_search_path_initialized) {
                Glib::ustring p = Glib::get_home_dir();
                p += "/Library/Audio/Presets:";
@@ -306,12 +372,15 @@ AUPlugin::AUPlugin (const AUPlugin& other)
        , comp (other.get_comp())
        , unit (new CAAudioUnit)
        , initialized (false)
+       , _current_block_size (0)
+       , _last_nframes (0)
+       , _requires_fixed_size_buffers (false)
        , buffers (0)
        , current_maxbuf (0)
        , current_offset (0)
        , current_buffers (0)
        , frames_processed (0)
-
+         
 {
        init ();
 }
@@ -319,6 +388,7 @@ AUPlugin::AUPlugin (const AUPlugin& other)
 AUPlugin::~AUPlugin ()
 {
        if (unit) {
+               TRACE_API ("about to call uninitialize in plugin destructor\n");
                unit->Uninitialize ();
        }
 
@@ -327,6 +397,34 @@ AUPlugin::~AUPlugin ()
        }
 }
 
+void
+AUPlugin::discover_factory_presets ()
+{
+       CFArrayRef presets;
+       UInt32 dataSize = sizeof (presets);
+       OSStatus err;
+       
+       TRACE_API ("get property FactoryPresets in global scope\n");
+       if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
+               cerr << "cannot get factory preset info: " << err << endl;
+               return;
+       }
+
+       if (!presets) {
+               return;
+       }
+
+       CFIndex cnt = CFArrayGetCount (presets);
+
+       for (CFIndex i = 0; i < cnt; ++i) {
+               AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
+
+               string name = CFStringRefToStdString (preset->presetName);
+               factory_preset_map[name] = preset->presetNumber;
+       }
+       
+       CFRelease (presets);
+}
 
 void
 AUPlugin::init ()
@@ -334,6 +432,7 @@ AUPlugin::init ()
        OSErr err;
 
        try {
+               TRACE_API ("opening AudioUnit\n");
                err = CAAudioUnit::Open (*(comp.get()), *unit);
        } catch (...) {
                error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
@@ -344,22 +443,45 @@ AUPlugin::init ()
                error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
                throw failed_constructor ();
        }
-
-       AURenderCallbackStruct renderCallbackInfo;
-
-       renderCallbackInfo.inputProc = _render_callback;
-       renderCallbackInfo.inputProcRefCon = this;
-
-       if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
-                                        0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
-               cerr << "cannot install render callback (err = " << err << ')' << endl;
-               throw failed_constructor();
-       }
-
+       
+       TRACE_API ("count global elements\n");
        unit->GetElementCount (kAudioUnitScope_Global, global_elements);
+       TRACE_API ("count input elements\n");
        unit->GetElementCount (kAudioUnitScope_Input, input_elements);
+       TRACE_API ("count output elements\n");
        unit->GetElementCount (kAudioUnitScope_Output, output_elements);
 
+        if (input_elements > 0) {
+                AURenderCallbackStruct renderCallbackInfo;
+                
+                renderCallbackInfo.inputProc = _render_callback;
+                renderCallbackInfo.inputProcRefCon = this;
+                
+                TRACE_API ("set render callback in input scope\n");
+                if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 
+                                              0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
+                        cerr << "cannot install render callback (err = " << err << ')' << endl;
+                        throw failed_constructor();
+                }
+        }
+
+       /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
+
+       HostCallbackInfo info;
+       memset (&info, 0, sizeof (HostCallbackInfo));
+       info.hostUserData = this;
+       info.beatAndTempoProc = _get_beat_and_tempo_callback;
+       info.musicalTimeLocationProc = _get_musical_time_location_callback;
+       info.transportStateProc = _get_transport_state_callback;
+       
+        //ignore result of this - don't care if the property isn't supported
+       TRACE_API ("set host callbacks in global scope\n");
+       unit->SetProperty (kAudioUnitProperty_HostCallbacks, 
+                          kAudioUnitScope_Global, 
+                          0, //elementID 
+                          &info,
+                          sizeof (HostCallbackInfo));
+
        /* these keep track of *configured* channel set up,
           not potential set ups.
        */
@@ -367,22 +489,27 @@ AUPlugin::init ()
        input_channels = -1;
        output_channels = -1;
 
-       if (_set_block_size (_session.get_block_size())) {
+       if (set_block_size (_session.get_block_size())) {
                error << _("AUPlugin: cannot set processing block size") << endmsg;
                throw failed_constructor();
        }
 
+       AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
+       _has_midi_input = pinfo->needs_midi_input ();
+       _has_midi_output = false;
+
        discover_parameters ();
+       discover_factory_presets ();
 
-       Plugin::setup_controls ();
+       // Plugin::setup_controls ();
 }
 
 void
 AUPlugin::discover_parameters ()
 {
        /* discover writable parameters */
-
-       AudioUnitScope scopes[] = {
+       
+       AudioUnitScope scopes[] = { 
                kAudioUnitScope_Global,
                kAudioUnitScope_Output,
                kAudioUnitScope_Input
@@ -393,7 +520,7 @@ AUPlugin::discover_parameters ()
        for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
 
                AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
-
+               
                for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
 
                        AUParameterDescriptor d;
@@ -468,14 +595,14 @@ AUPlugin::discover_parameters ()
                        d.upper = info.maxValue;
                        d.default_value = info.defaultValue;
 
-                       d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
-                       d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean) ||
+                       d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
+                       d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
                                (d.integer_step && ((d.upper - d.lower) == 1.0));
-                       d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
-                       d.automatable = !d.toggled &&
+                       d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
+                       d.automatable = !d.toggled && 
                                !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
                                (info.flags & kAudioUnitParameterFlag_IsWritable);
-
+                       
                        d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
                        d.unit = info.unit;
 
@@ -491,6 +618,112 @@ AUPlugin::discover_parameters ()
 }
 
 
+static unsigned int
+four_ints_to_four_byte_literal (unsigned char n[4])
+{
+       /* this is actually implementation dependent. sigh. this is what gcc
+          and quite a few others do.
+        */
+       return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
+}
+
+std::string
+AUPlugin::maybe_fix_broken_au_id (const std::string& id)
+{
+       if (isdigit (id[0])) {
+               return id;
+       }
+
+       /* ID format is xxxx-xxxx-xxxx
+          where x maybe \xNN or a printable character.
+          
+          Split at the '-' and and process each part into an integer. 
+          Then put it back together.
+       */
+
+
+       unsigned char nascent[4];
+       const char* cstr = id.c_str();
+       const char* estr = cstr + id.size();
+       uint32_t n[3];
+       int in;
+       int next_int;
+       char short_buf[3];
+       stringstream s;
+
+       in = 0;
+       next_int = 0;
+       short_buf[2] = '\0';
+
+       while (*cstr && next_int < 4) {
+
+               if (*cstr == '\\') {
+
+                       if (estr - cstr < 3) {
+
+                               /* too close to the end for \xNN parsing: treat as literal characters */
+
+                               cerr << "Parse " << cstr << " as a literal \\" << endl;
+                               nascent[in] = *cstr;
+                               ++cstr;
+                               ++in;
+
+                       } else {
+                               
+                               if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
+                                       
+                                       /* parse \xNN */
+                                       
+                                       memcpy (short_buf, &cstr[2], 2);
+                                       nascent[in] = strtol (short_buf, NULL, 16);
+                                       cstr += 4;
+                                       ++in;
+                                       
+                               } else {
+
+                                       /* treat as literal characters */
+                                       cerr << "Parse " << cstr << " as a literal \\" << endl;
+                                       nascent[in] = *cstr;
+                                       ++cstr;
+                                       ++in;
+                               }
+                       }
+
+               } else {
+
+                       nascent[in] = *cstr;
+                       ++cstr;
+                       ++in;
+               }
+
+               if (in && (in % 4 == 0)) {
+                       /* nascent is ready */
+                       n[next_int] = four_ints_to_four_byte_literal (nascent);
+                       in = 0;
+                       next_int++;
+
+                       /* swallow space-hyphen-space */
+
+                       if (next_int < 3) {
+                               ++cstr;
+                               ++cstr;
+                               ++cstr;
+                       }
+               }
+       }
+
+       if (next_int != 3) {
+               goto err;
+       }
+
+       s << n[0] << '-' << n[1] << '-' << n[2];
+       
+       return s.str();
+
+  err:
+       return string();
+}
+
 string
 AUPlugin::unique_id () const
 {
@@ -519,8 +752,8 @@ AUPlugin::default_value (uint32_t port)
        return 0;
 }
 
-nframes_t
-AUPlugin::latency () const
+framecnt_t
+AUPlugin::signal_latency () const
 {
        return unit->Latency() * _session.frame_rate();
 }
@@ -528,10 +761,28 @@ AUPlugin::latency () const
 void
 AUPlugin::set_parameter (uint32_t which, float val)
 {
-       if (which < descriptors.size()) {
-               const AUParameterDescriptor& d (descriptors[which]);
-               unit->SetParameter (d.id, d.scope, d.element, val);
+       if (which >= descriptors.size()) {
+               return;
        }
+       
+       const AUParameterDescriptor& d (descriptors[which]);
+       TRACE_API ("set parameter %d in scope %d element %d to %f\n", d.id, d.scope, d.element, val);
+       unit->SetParameter (d.id, d.scope, d.element, val);
+       
+       /* tell the world what we did */
+       
+       AudioUnitEvent theEvent;
+       
+       theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
+       theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
+       theEvent.mArgument.mParameter.mParameterID = d.id;
+       theEvent.mArgument.mParameter.mScope = d.scope;
+       theEvent.mArgument.mParameter.mElement = d.element;
+       
+       TRACE_API ("notify about parameter change\n");
+       AUEventListenerNotify (NULL, NULL, &theEvent);
+       
+       Plugin::set_parameter (which, val);
 }
 
 float
@@ -540,6 +791,7 @@ AUPlugin::get_parameter (uint32_t which) const
        float val = 0.0;
        if (which < descriptors.size()) {
                const AUParameterDescriptor& d (descriptors[which]);
+               TRACE_API ("get value of parameter %d in scope %d element %d\n", d.id, d.scope, d.element);
                unit->GetParameter(d.id, d.scope, d.element, val);
        }
        return val;
@@ -551,7 +803,7 @@ AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) con
        if (which < descriptors.size()) {
                pd = descriptors[which];
                return 0;
-       }
+       } 
        return -1;
 }
 
@@ -571,6 +823,7 @@ AUPlugin::activate ()
 {
        if (!initialized) {
                OSErr err;
+               TRACE_API ("call Initialize in activate()\n");
                if ((err = unit->Initialize()) != noErr) {
                        error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
                } else {
@@ -583,28 +836,38 @@ AUPlugin::activate ()
 void
 AUPlugin::deactivate ()
 {
-       unit->GlobalReset ();
+       TRACE_API ("call Uninitialize in deactivate()\n");
+       unit->Uninitialize ();
+       initialized = false;
 }
 
 void
-AUPlugin::set_block_size (nframes_t nframes)
+AUPlugin::flush ()
 {
-       _set_block_size (nframes);
+       TRACE_API ("call Reset in flush()\n");
+       unit->GlobalReset ();
 }
 
+bool
+AUPlugin::requires_fixed_size_buffers() const
+{
+       return _requires_fixed_size_buffers;
+}
+
+
 int
-AUPlugin::_set_block_size (nframes_t nframes)
+AUPlugin::set_block_size (pframes_t nframes)
 {
        bool was_initialized = initialized;
        UInt32 numFrames = nframes;
        OSErr err;
 
        if (initialized) {
-               unit->Uninitialize ();
-               initialized = false;
+               deactivate ();
        }
 
-       if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
+       TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
+       if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
                                      0, &numFrames, sizeof (numFrames))) != noErr) {
                cerr << "cannot set max frames (err = " << err << ')' << endl;
                return -1;
@@ -614,13 +877,27 @@ AUPlugin::_set_block_size (nframes_t nframes)
                activate ();
        }
 
+       _current_block_size = nframes;
+
        return 0;
 }
 
-int32_t
-AUPlugin::configure_io (int32_t in, int32_t out)
+bool
+AUPlugin::configure_io (ChanCount in, ChanCount out)
 {
        AudioStreamBasicDescription streamFormat;
+       bool was_initialized = initialized;
+       int32_t audio_in = in.n_audio();
+       int32_t audio_out = out.n_audio();
+
+       if (initialized) {
+               //if we are already running with the requested i/o config, bail out here
+               if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
+                       return 0;
+               } else {
+                       deactivate ();
+               }
+       }
 
        streamFormat.mSampleRate = _session.frame_rate();
        streamFormat.mFormatID = kAudioFormatLinearPCM;
@@ -641,39 +918,78 @@ AUPlugin::configure_io (int32_t in, int32_t out)
        streamFormat.mBytesPerPacket = 4;
        streamFormat.mBytesPerFrame = 4;
 
-       streamFormat.mChannelsPerFrame = in;
+       streamFormat.mChannelsPerFrame = audio_in;
 
        if (set_input_format (streamFormat) != 0) {
                return -1;
        }
 
-       streamFormat.mChannelsPerFrame = out;
+       streamFormat.mChannelsPerFrame = audio_out;
 
        if (set_output_format (streamFormat) != 0) {
                return -1;
        }
 
-       return Plugin::configure_io (in, out);
+       if (was_initialized) {
+               activate ();
+       }
+
+       return 0;
 }
 
-int32_t
-AUPlugin::can_do (int32_t in, int32_t& out)
+bool
+AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
 {
        // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
        // attempt to multiply-instantiate plugins to meet io configurations.
 
+       int32_t audio_in = in.n_audio();
+       int32_t audio_out;
        int32_t plugcnt = -1;
        AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
 
-       out = -1;
+       /* lets check MIDI first */
+
+       if (in.n_midi() > 0) {
+               if (!_has_midi_input) {
+                       return false;
+               }
+       }
 
        vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
 
+       if (debug_io_config) {
+               cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
+       }
+
+       //Ardour expects the plugin to tell it the output configuration
+       //but AU plugins can have multiple I/O configurations
+       //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
+       //so first lets see if there's a configuration that keeps out==in
+
+       audio_out = audio_in;
+
+       for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
+               int32_t possible_in = i->first;
+               int32_t possible_out = i->second;
+
+               if (possible_in == audio_in && possible_out== audio_out) {
+                       cerr << "\tCHOSEN: in " << in << " out " << out << endl;
+                       return 1;
+               }
+       }
+
+       /* now allow potentially "imprecise" matches */
+       audio_out = -1;
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
                int32_t possible_in = i->first;
                int32_t possible_out = i->second;
 
+               if (debug_io_config) {
+                       cerr << "\tin " << possible_in << " out " << possible_out << endl;
+               }
+
                if (possible_out == 0) {
                        warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
                        continue;
@@ -686,51 +1002,51 @@ AUPlugin::can_do (int32_t in, int32_t& out)
 
                        if (possible_out == -1) {
                                /* out much match in (UNLIKELY!!) */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out == -2) {
                                /* any configuration possible, pick matching */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out < -2) {
                                /* explicit variable number of outputs, pick maximum */
-                               out = -possible_out;
+                               audio_out = -possible_out;
                                plugcnt = 1;
                        } else {
                                /* exact number of outputs */
-                               out = possible_out;
+                               audio_out = possible_out;
                                plugcnt = 1;
                        }
                }
-
+               
                if (possible_in == -1) {
 
                        /* wildcard for input */
 
                        if (possible_out == -1) {
                                /* out much match in */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out == -2) {
                                /* any configuration possible, pick matching */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out < -2) {
                                /* explicit variable number of outputs, pick maximum */
-                               out = -possible_out;
+                               audio_out = -possible_out;
                                plugcnt = 1;
                        } else {
                                /* exact number of outputs */
-                               out = possible_out;
+                               audio_out = possible_out;
                                plugcnt = 1;
                        }
-               }
-
+               }       
+                       
                if (possible_in == -2) {
 
                        if (possible_out == -1) {
                                /* any configuration possible, pick matching */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out == -2) {
                                error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
@@ -738,11 +1054,11 @@ AUPlugin::can_do (int32_t in, int32_t& out)
                                plugcnt = -1;
                        } else if (possible_out < -2) {
                                /* explicit variable number of outputs, pick maximum */
-                               out = -possible_out;
+                               audio_out = -possible_out;
                                plugcnt = 1;
                        } else {
                                /* exact number of outputs */
-                               out = possible_out;
+                               audio_out = possible_out;
                                plugcnt = 1;
                        }
                }
@@ -751,14 +1067,14 @@ AUPlugin::can_do (int32_t in, int32_t& out)
 
                        /* explicit variable number of inputs */
 
-                       if (in > -possible_in) {
+                       if (audio_in > -possible_in) {
                                /* request is too large */
                                plugcnt = -1;
                        }
 
                        if (possible_out == -1) {
                                /* out must match in */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out == -2) {
                                error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
@@ -766,34 +1082,34 @@ AUPlugin::can_do (int32_t in, int32_t& out)
                                plugcnt = -1;
                        } else if (possible_out < -2) {
                                /* explicit variable number of outputs, pick maximum */
-                               out = -possible_out;
+                               audio_out = -possible_out;
                                plugcnt = 1;
                        } else {
                                /* exact number of outputs */
-                               out = possible_out;
+                               audio_out = possible_out;
                                plugcnt = 1;
                        }
                }
 
-               if (possible_in == in) {
+               if (possible_in == audio_in) {
 
                        /* exact number of inputs ... must match obviously */
-
+                       
                        if (possible_out == -1) {
                                /* out must match in */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = 1;
                        } else if (possible_out == -2) {
                                /* any output configuration, pick matching */
-                               out = in;
+                               audio_out = audio_in;
                                plugcnt = -1;
                        } else if (possible_out < -2) {
                                /* explicit variable number of outputs, pick maximum */
-                               out = -possible_out;
+                               audio_out = -possible_out;
                                plugcnt = 1;
                        } else {
                                /* exact number of outputs */
-                               out = possible_out;
+                               audio_out = possible_out;
                                plugcnt = 1;
                        }
                }
@@ -801,9 +1117,20 @@ AUPlugin::can_do (int32_t in, int32_t& out)
                if (plugcnt == 1) {
                        break;
                }
+
        }
 
-       /* no fit */
+       if (debug_io_config) {
+               if (plugcnt > 0) {
+                       cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
+               } else {
+                       cerr << "\tFAIL: no configs match requested in " << in << endl;
+               }
+       }
+
+       out.set (DataType::MIDI, 0);
+       out.set (DataType::AUDIO, audio_out);
+
        return plugcnt;
 }
 
@@ -824,12 +1151,12 @@ AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
                free (buffers);
                buffers = 0;
        }
-
-       buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
-                                             fmt.mChannelsPerFrame * sizeof(AudioBuffer));
+       
+       buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
+                                             fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
 
        Glib::Mutex::Lock em (_session.engine().process_lock());
-       IO::MoreOutputs (fmt.mChannelsPerFrame);
+       IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
 
        return 0;
 }
@@ -840,6 +1167,9 @@ AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescriptio
        OSErr result;
 
        for (uint32_t i = 0; i < cnt; ++i) {
+               TRACE_API ("set stream format for %s, scope = %d element %d\n",
+                          (scope == kAudioUnitScope_Input ? "input" : "output"),
+                          scope, cnt);
                if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
                        error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
                                                 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
@@ -856,45 +1186,62 @@ AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescriptio
        return 0;
 }
 
-uint32_t
-AUPlugin::input_streams() const
+OSStatus 
+AUPlugin::render_callback(AudioUnitRenderActionFlags*,
+                         const AudioTimeStamp*,
+                         UInt32,
+                         UInt32       inNumberFrames,
+                         AudioBufferList*       ioData)
 {
-       if (input_channels < 0) {
-               warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
-               return 1;
-       }
-       return input_channels;
-}
+       if (_has_midi_input) {
+               assert (current_buffers->count().n_midi() > 0);
 
+               /* deliver the first (and assumed only) MIDI buffer's data
+                  to the plugin
+               */
 
-uint32_t
-AUPlugin::output_streams() const
-{
-       if (output_channels < 0) {
-               warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
-               return 1;
+               MidiBuffer& mb (current_buffers->get_midi(0));
+
+               for (MidiBuffer::iterator i = mb.begin(); i != mb.end(); ++i) {
+                       Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *i;
+                       switch (ev.type()) {
+                       case MIDI_CMD_NOTE_ON:
+                       case MIDI_CMD_NOTE_OFF:
+                       case MIDI_CMD_CONTROL:
+                       case MIDI_CMD_BENDER:
+                       case MIDI_CMD_PGM_CHANGE:
+                       case MIDI_CMD_CHANNEL_PRESSURE:
+                       { 
+                               const uint8_t* b = ev.buffer();
+                               unit->MIDIEvent (b[0], b[1], b[2], ev.time());
+                               break;
+                       }
+                       
+                       default:
+                               /* plugins do not get other stuff by default */
+                               break;
+                       };
+               }
        }
-       return output_channels;
-}
 
-OSStatus
-AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
-                         const AudioTimeStamp    *inTimeStamp,
-                         UInt32       inBusNumber,
-                         UInt32       inNumberFrames,
-                         AudioBufferList*       ioData)
-{
-       /* not much to do - the data is already in the buffers given to us in connect_and_run() */
+       /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
 
        if (current_maxbuf == 0) {
                error << _("AUPlugin: render callback called illegally!") << endmsg;
                return kAudioUnitErr_CannotDoInCurrentContext;
        }
+       uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
 
-       for (uint32_t i = 0; i < current_maxbuf; ++i) {
+       for (uint32_t i = 0; i < limit; ++i) {
                ioData->mBuffers[i].mNumberChannels = 1;
                ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
-               ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
+
+               /* we don't use the channel mapping because audiounits are
+                  never replicated. one plugin instance uses all channels/buffers
+                  passed to PluginInsert::connect_and_run()
+               */
+
+               ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
        }
 
        cb_offset += inNumberFrames;
@@ -903,19 +1250,28 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
 }
 
 int
-AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
+AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
 {
+       Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
+       
        AudioUnitRenderActionFlags flags = 0;
        AudioTimeStamp ts;
+       OSErr err;
+       uint32_t maxbuf = bufs.count().n_audio();
+
+       if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
+               unit->GlobalReset();
+               _last_nframes = nframes;
+       }
 
        current_buffers = &bufs;
        current_maxbuf = maxbuf;
        current_offset = offset;
        cb_offset = 0;
 
-       buffers->mNumberBuffers = maxbuf;
+       buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
 
-       for (uint32_t i = 0; i < maxbuf; ++i) {
+       for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
                buffers->mBuffers[i].mNumberChannels = 1;
                buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
                buffers->mBuffers[i].mData = 0;
@@ -924,30 +1280,229 @@ AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in,
        ts.mSampleTime = frames_processed;
        ts.mFlags = kAudioTimeStampSampleTimeValid;
 
-       if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
+       if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
 
                current_maxbuf = 0;
                frames_processed += nframes;
-
-               for (uint32_t i = 0; i < maxbuf; ++i) {
-                       if (bufs[i] + offset != buffers->mBuffers[i].mData) {
-                               memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
+               
+               uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
+               uint32_t i;
+
+               for (i = 0; i < limit; ++i) {
+                       Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
+                       if (expected_buffer_address != buffers->mBuffers[i].mData) {
+                               // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
+                               memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
                        }
                }
+
+               /* now silence any buffers that were passed in but the that the plugin
+                  did not fill/touch/use.
+               */
+
+               for (;i < maxbuf; ++i) {
+                       Sample* buffer_address= bufs.get_audio (i).data (offset);
+                       memset (buffer_address, 0, nframes * sizeof (Sample));
+               }
+
                return 0;
-       }
+       } 
 
+       cerr << name() << " render status " << err << endl;
        return -1;
 }
 
-set<uint32_t>
+OSStatus 
+AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat, 
+                                      Float64* outCurrentTempo)
+{
+       TempoMap& tmap (_session.tempo_map());
+
+       TRACE_API ("AU calls ardour beat&tempo callback\n");
+
+       /* more than 1 meter or more than 1 tempo means that a simplistic computation 
+          (and interpretation) of a beat position will be incorrect. So refuse to 
+          offer the value.
+       */
+
+       if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
+               return kAudioUnitErr_CannotDoInCurrentContext;
+       }
+
+       Timecode::BBT_Time bbt;
+       TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
+       tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
+
+       if (outCurrentBeat) {
+               float beat;
+               beat = metric.meter().beats_per_bar() * bbt.bars;
+               beat += bbt.beats;
+               beat += bbt.ticks / BBT_Time::ticks_per_beat;
+               *outCurrentBeat = beat;
+       }
+
+       if (outCurrentTempo) {
+               *outCurrentTempo = floor (metric.tempo().beats_per_minute());
+       }
+
+       return noErr;
+
+}
+
+OSStatus 
+AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
+                                             Float32*  outTimeSig_Numerator,
+                                             UInt32*   outTimeSig_Denominator,
+                                             Float64*  outCurrentMeasureDownBeat)
+{
+       TempoMap& tmap (_session.tempo_map());
+
+       TRACE_API ("AU calls ardour music time location callback\n");
+
+       /* more than 1 meter or more than 1 tempo means that a simplistic computation 
+          (and interpretation) of a beat position will be incorrect. So refuse to 
+          offer the value.
+       */
+
+       if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
+               return kAudioUnitErr_CannotDoInCurrentContext;
+       }
+
+       Timecode::BBT_Time bbt;
+       TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
+       tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
+
+       if (outDeltaSampleOffsetToNextBeat) {
+               if (bbt.ticks == 0) {
+                       /* on the beat */
+                       *outDeltaSampleOffsetToNextBeat = 0;
+               } else {
+                       *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((BBT_Time::ticks_per_beat - bbt.ticks)/BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
+                                                                         metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
+               }
+       }
+       
+       if (outTimeSig_Numerator) {
+               *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
+       }
+       if (outTimeSig_Denominator) {
+               *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
+       }
+
+       if (outCurrentMeasureDownBeat) {
+
+               /* beat for the start of the bar. 
+                  1|1|0 -> 1
+                  2|1|0 -> 1 + beats_per_bar
+                  3|1|0 -> 1 + (2 * beats_per_bar)
+                  etc. 
+               */
+
+               *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
+       }
+
+       return noErr;
+}
+
+OSStatus 
+AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
+                                       Boolean*  outTransportStateChanged,
+                                       Float64*  outCurrentSampleInTimeLine,
+                                       Boolean*  outIsCycling,
+                                       Float64*  outCycleStartBeat,
+                                       Float64*  outCycleEndBeat)
+{
+       bool rolling;
+       float speed;
+
+       TRACE_API ("AU calls ardour transport state callback\n");
+
+       rolling = _session.transport_rolling();
+       speed = _session.transport_speed ();
+
+       if (outIsPlaying) {
+               *outIsPlaying = _session.transport_rolling();
+       }
+
+       if (outTransportStateChanged) {
+               if (rolling != last_transport_rolling) {
+                       *outTransportStateChanged = true;
+               } else if (speed != last_transport_speed) {
+                       *outTransportStateChanged = true;
+               } else {
+                       *outTransportStateChanged = false;
+               }
+       }
+
+       if (outCurrentSampleInTimeLine) {
+               /* this assumes that the AU can only call this host callback from render context,
+                  where current_offset is valid.
+               */
+               *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
+       }
+
+       if (outIsCycling) {
+               Location* loc = _session.locations()->auto_loop_location();
+
+               *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
+
+               if (*outIsCycling) {
+
+                       if (outCycleStartBeat || outCycleEndBeat) {
+
+                               TempoMap& tmap (_session.tempo_map());
+
+                               /* more than 1 meter means that a simplistic computation (and interpretation) of 
+                                  a beat position will be incorrect. so refuse to offer the value.
+                               */
+
+                               if (tmap.n_meters() > 1) {
+                                       return kAudioUnitErr_CannotDoInCurrentContext;
+                               }
+                               
+                               Timecode::BBT_Time bbt;
+
+                               if (outCycleStartBeat) {
+                                       TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
+                                       _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
+
+                                       float beat;
+                                       beat = metric.meter().beats_per_bar() * bbt.bars;
+                                       beat += bbt.beats;
+                                       beat += bbt.ticks / BBT_Time::ticks_per_beat;
+                                       
+                                       *outCycleStartBeat = beat;
+                               }
+
+                               if (outCycleEndBeat) {
+                                       TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
+                                       _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
+                                       
+                                       float beat;
+                                       beat = metric.meter().beats_per_bar() * bbt.bars;
+                                       beat += bbt.beats;
+                                       beat += bbt.ticks / BBT_Time::ticks_per_beat;
+                                       
+                                       *outCycleEndBeat = beat;
+                               }
+                       }
+               }
+       }
+
+       last_transport_rolling = rolling;
+       last_transport_speed = speed;
+
+       return noErr;
+}
+
+set<Evoral::Parameter>
 AUPlugin::automatable() const
 {
-       set<uint32_t> automates;
+       set<Evoral::Parameter> automates;
 
        for (uint32_t i = 0; i < descriptors.size(); ++i) {
                if (descriptors[i].automatable) {
-                       automates.insert (i);
+                       automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
                }
        }
 
@@ -955,13 +1510,17 @@ AUPlugin::automatable() const
 }
 
 string
-AUPlugin::describe_parameter (uint32_t param)
+AUPlugin::describe_parameter (Evoral::Parameter param)
 {
-       return descriptors[param].label;
+       if (param.type() == PluginAutomation && param.id() < parameter_count()) {
+               return descriptors[param.id()].label;
+       } else {
+               return "??";
+       }
 }
 
 void
-AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
+AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
 {
        // NameValue stuff here
 }
@@ -990,22 +1549,22 @@ AUPlugin::parameter_is_output (uint32_t) const
        return false;
 }
 
-XMLNode&
-AUPlugin::get_state()
+void
+AUPlugin::add_state (XMLNode* root)
 {
        LocaleGuard lg (X_("POSIX"));
-       XMLNode *root = new XMLNode (state_node_name());
 
 #ifdef AU_STATE_SUPPORT
        CFDataRef xmlData;
        CFPropertyListRef propertyList;
 
+       TRACE_API ("get preset state\n");
        if (unit->GetAUPreset (propertyList) != noErr) {
-               return *root;
+               return;
        }
 
        // Convert the property list into XML data.
-
+       
        xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
 
        if (!xmlData) {
@@ -1029,17 +1588,16 @@ AUPlugin::get_state()
        CFRelease (propertyList);
 #else
        if (!seen_get_state_message) {
-               info << _("Saving AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
+               info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
+                                       PROGRAM_NAME)
                     << endmsg;
                seen_get_state_message = true;
        }
 #endif
-
-       return *root;
 }
 
 int
-AUPlugin::set_state(const XMLNode& node)
+AUPlugin::set_state(const XMLNode& node, int version)
 {
 #ifdef AU_STATE_SUPPORT
        int ret = -1;
@@ -1050,7 +1608,7 @@ AUPlugin::set_state(const XMLNode& node)
                error << _("Bad node sent to AUPlugin::set_state") << endmsg;
                return -1;
        }
-
+       
        if (node.children().empty()) {
                return -1;
        }
@@ -1071,48 +1629,91 @@ AUPlugin::set_state(const XMLNode& node)
                                                        &errorString);
 
        CFRelease (xmlData);
-
+       
        if (propertyList) {
+               TRACE_API ("set preset\n");
                if (unit->SetAUPreset (propertyList) == noErr) {
                        ret = 0;
-               }
+                       
+                       /* tell the world */
+
+                       AudioUnitParameter changedUnit;
+                       changedUnit.mAudioUnit = unit->AU();
+                       changedUnit.mParameterID = kAUParameterListener_AnyParameter;
+                       AUParameterListenerNotify (NULL, NULL, &changedUnit);
+               } 
                CFRelease (propertyList);
        }
-
+       
+       Plugin::set_state (node, version);
        return ret;
 #else
        if (!seen_set_state_message) {
-               info << _("Restoring AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
+               info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
+                                       PROGRAM_NAME)
                     << endmsg;
        }
-       return 0;
+       return Plugin::set_state (node, version);
 #endif
 }
 
 bool
-AUPlugin::load_preset (const string preset_label)
+AUPlugin::load_preset (PluginRecord r)
 {
+       Plugin::load_preset (r);
+       
 #ifdef AU_STATE_SUPPORT
        bool ret = false;
        CFPropertyListRef propertyList;
        Glib::ustring path;
-       PresetMap::iterator x = preset_map.find (preset_label);
+       UserPresetMap::iterator ux;
+       FactoryPresetMap::iterator fx;
+
+       /* look first in "user" presets */
+
+       if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
+       
+               if ((propertyList = load_property_list (ux->second)) != 0) {
+                       TRACE_API ("set preset from user presets\n");
+                       if (unit->SetAUPreset (propertyList) == noErr) {
+                               ret = true;
+
+                               /* tell the world */
+                               
+                               AudioUnitParameter changedUnit;
+                               changedUnit.mAudioUnit = unit->AU();
+                               changedUnit.mParameterID = kAUParameterListener_AnyParameter;
+                               AUParameterListenerNotify (NULL, NULL, &changedUnit);
+                       }
+                       CFRelease(propertyList);
+               }
 
-       if (x == preset_map.end()) {
-               return false;
-       }
+       } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
+               
+               AUPreset preset;
+               
+               preset.presetNumber = fx->second;
+               preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
+               
+               TRACE_API ("set preset from factory presets\n");
 
-       if ((propertyList = load_property_list (x->second)) != 0) {
-               if (unit->SetAUPreset (propertyList) == noErr) {
+               if (unit->SetPresentPreset (preset) == 0) {
                        ret = true;
+
+                       /* tell the world */
+
+                       AudioUnitParameter changedUnit;
+                       changedUnit.mAudioUnit = unit->AU();
+                       changedUnit.mParameterID = kAUParameterListener_AnyParameter;
+                       AUParameterListenerNotify (NULL, NULL, &changedUnit);
                }
-               CFRelease(propertyList);
        }
-
+               
        return ret;
 #else
        if (!seen_loading_message) {
-               info << _("Loading AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
+               info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
+                                       PROGRAM_NAME)
                     << endmsg;
                seen_loading_message = true;
        }
@@ -1131,7 +1732,7 @@ AUPlugin::save_preset (string preset_name)
 
        std::string m = maker();
        std::string n = name();
-
+       
        strip_whitespace_edges (m);
        strip_whitespace_edges (n);
 
@@ -1141,7 +1742,7 @@ AUPlugin::save_preset (string preset_name)
        v.push_back ("Presets");
        v.push_back (m);
        v.push_back (n);
-
+       
        user_preset_path = Glib::build_filename (v);
 
        if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
@@ -1149,6 +1750,7 @@ AUPlugin::save_preset (string preset_name)
                return false;
        }
 
+       TRACE_API ("get current preset\n");
        if (unit->GetAUPreset (propertyList) != noErr) {
                return false;
        }
@@ -1156,11 +1758,11 @@ AUPlugin::save_preset (string preset_name)
        // add the actual preset name */
 
        v.push_back (preset_name + preset_suffix);
-
+               
        // rebuild
 
        user_preset_path = Glib::build_filename (v);
-
+       
        set_preset_name_in_plist (propertyList, preset_name);
 
        if (save_property_list (propertyList, user_preset_path)) {
@@ -1173,7 +1775,8 @@ AUPlugin::save_preset (string preset_name)
        return ret;
 #else
        if (!seen_saving_message) {
-               info << _("Saving AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
+               info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
+                                       PROGRAM_NAME)
                     << endmsg;
                seen_saving_message = true;
        }
@@ -1183,7 +1786,7 @@ AUPlugin::save_preset (string preset_name)
 
 //-----------------------------------------------------------------------------
 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
-static SInt32
+static SInt32 
 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
 {
        CFNumberRef cfNumber;
@@ -1211,17 +1814,17 @@ GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDict
                return 0;
 }
 
-static OSStatus
+static OSStatus 
 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
 {
         CFDictionaryRef auStateDictionary;
-        ComponentDescription tempDesc = {0};
+        ComponentDescription tempDesc = {0,0,0,0,0};
         SInt32 versionValue;
         Boolean gotValue;
 
         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
                 return paramErr;
-
+       
         // the property list for AU state data must be of the dictionary type
         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
                 return kAudioUnitErr_InvalidPropertyValue;
@@ -1259,7 +1862,7 @@ static bool au_preset_filter (const string& str, void* arg)
        /* Not a dotfile, has a prefix before a period, suffix is aupreset */
 
        bool ret;
-
+       
        ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
 
        if (ret && arg) {
@@ -1284,32 +1887,32 @@ static bool au_preset_filter (const string& str, void* arg)
                        match = m;
                        match += '/';
                        match += n;
-
+                       
                        ret = str.find (match) != string::npos;
                }
        }
-
+       
        return ret;
 }
 
-bool
+bool 
 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
 {
         OSStatus status;
         CFPropertyListRef plist;
        ComponentDescription presetDesc;
        bool ret = false;
-
+               
        plist = load_property_list (pathstr);
 
        if (!plist) {
                return ret;
        }
-
+       
        // get the ComponentDescription from the AU preset file
-
+       
        status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
-
+       
        if (status == noErr) {
                if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
 
@@ -1332,7 +1935,7 @@ check_and_get_preset_name (Component component, const string& pathstr, string& p
                                        }
                                }
                        }
-               }
+               } 
        }
 
        CFRelease (plist);
@@ -1344,10 +1947,11 @@ std::string
 AUPlugin::current_preset() const
 {
        string preset_name;
-
+       
 #ifdef AU_STATE_SUPPORT
        CFPropertyListRef propertyList;
 
+       TRACE_API ("get current preset for current_preset()\n");
        if (unit->GetAUPreset (propertyList) == noErr) {
                preset_name = get_preset_name_in_plist (propertyList);
                CFRelease(propertyList);
@@ -1356,17 +1960,19 @@ AUPlugin::current_preset() const
        return preset_name;
 }
 
-vector<string>
-AUPlugin::get_presets ()
+void
+AUPlugin::find_presets ()
 {
+#ifdef AU_STATE_SUPPORT
        vector<string*>* preset_files;
-       vector<string> presets;
        PathScanner scanner;
 
-       preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
+       user_preset_map.clear ();
 
+       preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
+       
        if (!preset_files) {
-               return presets;
+               return;
        }
 
        for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
@@ -1385,16 +1991,29 @@ AUPlugin::get_presets ()
                */
 
                if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
-                       presets.push_back (preset_name);
-                       preset_map[preset_name] = path;
-               }
+                       user_preset_map[preset_name] = path;
+               } 
 
                delete *x;
        }
 
        delete preset_files;
 
-       return presets;
+        /* now fill the vector<string> with the names we have */
+
+       for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
+               _presets.insert (i->second, Plugin::PresetRecord (i->second, i->first));
+       }
+
+        /* add factory presets */
+
+       for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
+               /* XXX: dubious */
+               string const uri = string_compose ("%1", _presets.size ());
+               _presets.push_back (uri, Plugin::PresetRecord (uri, i->first));
+       }
+
+#endif
 }
 
 bool
@@ -1408,11 +2027,12 @@ AUPlugin::has_editor () const
 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
        : descriptor (d)
 {
-
+       type = ARDOUR::AudioUnit;
 }
 
 AUPluginInfo::~AUPluginInfo ()
 {
+       type = ARDOUR::AudioUnit;
 }
 
 PluginPtr
@@ -1421,15 +2041,18 @@ AUPluginInfo::load (Session& session)
        try {
                PluginPtr plugin;
 
+               TRACE_API ("load AU as a component\n");
                boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
-
+               
                if (!comp->IsValid()) {
                        error << ("AudioUnit: not a valid Component") << endmsg;
                } else {
                        plugin.reset (new AUPlugin (session.engine(), session, comp));
                }
-
-               plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
+               
+               AUPluginInfo *aup = new AUPluginInfo (*this);
+               plugin->set_info (PluginInfoPtr (aup));
+               boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
                return plugin;
        }
 
@@ -1441,10 +2064,10 @@ AUPluginInfo::load (Session& session)
 Glib::ustring
 AUPluginInfo::au_cache_path ()
 {
-       return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
+       return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
 }
 
-PluginInfoList
+PluginInfoList*
 AUPluginInfo::discover ()
 {
        XMLTree tree;
@@ -1453,11 +2076,12 @@ AUPluginInfo::discover ()
                ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
        }
 
-       PluginInfoList plugs;
-
-       discover_fx (plugs);
-       discover_music (plugs);
-       discover_generators (plugs);
+       PluginInfoList* plugs = new PluginInfoList;
+       
+       discover_fx (*plugs);
+       discover_music (*plugs);
+       discover_generators (*plugs);
+       discover_instruments (*plugs);
 
        return plugs;
 }
@@ -1501,6 +2125,19 @@ AUPluginInfo::discover_generators (PluginInfoList& plugs)
        discover_by_description (plugs, desc);
 }
 
+void
+AUPluginInfo::discover_instruments (PluginInfoList& plugs)
+{
+       CAComponentDescription desc;
+       desc.componentFlags = 0;
+       desc.componentFlagsMask = 0;
+       desc.componentSubType = 0;
+       desc.componentManufacturer = 0;
+       desc.componentType = kAudioUnitType_MusicDevice;
+
+       discover_by_description (plugs, desc);
+}
+
 void
 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
 {
@@ -1512,10 +2149,16 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                CAComponentDescription temp;
                GetComponentInfo (comp, &temp, NULL, NULL, NULL);
 
-               AUPluginInfoPtr info (new AUPluginInfo
+               AUPluginInfoPtr info (new AUPluginInfo 
                                      (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
 
-               /* no panners, format converters or i/o AU's for our purposes
+               /* although apple designed the subtype field to be a "category" indicator,
+                  its really turned into a plugin ID field for a given manufacturer. Hence
+                  there are no categories for AudioUnits. However, to keep the plugins
+                  showing up under "categories", we'll use the "type" as a high level
+                  selector.
+                  
+                  NOTE: no panners, format converters or i/o AU's for our purposes
                 */
 
                switch (info->descriptor->Type()) {
@@ -1523,121 +2166,32 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                case kAudioUnitType_OfflineEffect:
                case kAudioUnitType_FormatConverter:
                        continue;
+
                case kAudioUnitType_Output:
+                       info->category = _("AudioUnit Outputs");
+                       break;
                case kAudioUnitType_MusicDevice:
+                       info->category = _("AudioUnit Instruments");
+                       break;
                case kAudioUnitType_MusicEffect:
+                       info->category = _("AudioUnit MusicEffects");
+                       break;
                case kAudioUnitType_Effect:
+                       info->category = _("AudioUnit Effects");
+                       break;
                case kAudioUnitType_Mixer:
+                       info->category = _("AudioUnit Mixers");
+                       break;
                case kAudioUnitType_Generator:
+                       info->category = _("AudioUnit Generators");
                        break;
                default:
+                       info->category = _("AudioUnit (Unknown)");
                        break;
                }
 
-               switch (info->descriptor->SubType()) {
-               case kAudioUnitSubType_DefaultOutput:
-               case kAudioUnitSubType_SystemOutput:
-               case kAudioUnitSubType_GenericOutput:
-               case kAudioUnitSubType_AUConverter:
-                       /* we don't want output units here */
-                       continue;
-                       break;
-
-               case kAudioUnitSubType_DLSSynth:
-                       info->category = "DLS Synth";
-                       break;
-
-               case kAudioUnitSubType_Varispeed:
-                       info->category = "Varispeed";
-                       break;
-
-               case kAudioUnitSubType_Delay:
-                       info->category = "Delay";
-                       break;
-
-               case kAudioUnitSubType_LowPassFilter:
-                       info->category = "Low-pass Filter";
-                       break;
-
-               case kAudioUnitSubType_HighPassFilter:
-                       info->category = "High-pass Filter";
-                       break;
-
-               case kAudioUnitSubType_BandPassFilter:
-                       info->category = "Band-pass Filter";
-                       break;
-
-               case kAudioUnitSubType_HighShelfFilter:
-                       info->category = "High-shelf Filter";
-                       break;
-
-               case kAudioUnitSubType_LowShelfFilter:
-                       info->category = "Low-shelf Filter";
-                       break;
-
-               case kAudioUnitSubType_ParametricEQ:
-                       info->category = "Parametric EQ";
-                       break;
-
-               case kAudioUnitSubType_GraphicEQ:
-                       info->category = "Graphic EQ";
-                       break;
-
-               case kAudioUnitSubType_PeakLimiter:
-                       info->category = "Peak Limiter";
-                       break;
-
-               case kAudioUnitSubType_DynamicsProcessor:
-                       info->category = "Dynamics Processor";
-                       break;
-
-               case kAudioUnitSubType_MultiBandCompressor:
-                       info->category = "Multiband Compressor";
-                       break;
-
-               case kAudioUnitSubType_MatrixReverb:
-                       info->category = "Matrix Reverb";
-                       break;
-
-               case kAudioUnitSubType_SampleDelay:
-                       info->category = "Sample Delay";
-                       break;
-
-               case kAudioUnitSubType_Pitch:
-                       info->category = "Pitch";
-                       break;
-
-               case kAudioUnitSubType_NetSend:
-                       info->category = "Net Sender";
-                       break;
-
-               case kAudioUnitSubType_3DMixer:
-                       info->category = "3DMixer";
-                       break;
-
-               case kAudioUnitSubType_MatrixMixer:
-                       info->category = "MatrixMixer";
-                       break;
-
-               case kAudioUnitSubType_ScheduledSoundPlayer:
-                       info->category = "Scheduled Sound Player";
-                       break;
-
-
-               case kAudioUnitSubType_AudioFilePlayer:
-                       info->category = "Audio File Player";
-                       break;
-
-               case kAudioUnitSubType_NetReceive:
-                       info->category = "Net Receiver";
-                       break;
-
-               default:
-                       info->category = "";
-               }
-
                AUPluginInfo::get_names (temp, info->name, info->creator);
-
+               
                info->type = ARDOUR::AudioUnit;
                info->unique_id = stringify_descriptor (*info->descriptor);
 
@@ -1649,7 +2203,7 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                if (cacomp.GetResourceVersion (info->version) != noErr) {
                        info->version = 0;
                }
-
+               
                if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
 
                        /* here we have to map apple's wildcard system to a simple pair
@@ -1658,28 +2212,26 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                           remove any use of these values.
                        */
 
-                       info->n_inputs = info->cache.io_configs.front().first;
-                       info->n_outputs = info->cache.io_configs.front().second;
+                       info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
+                       info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
 
-                       if (info->cache.io_configs.size() > 1) {
-                               cerr << "ODD: variable IO config for " << info->unique_id << endl;
-                       }
+                       cerr << "detected AU: " << info->name.c_str() << "  (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
 
                        plugs.push_back (info);
 
                } else {
                        error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
                }
-
+               
                comp = FindNextComponent (comp, &desc);
        }
 }
 
 bool
-AUPluginInfo::cached_io_configuration (const std::string& unique_id,
+AUPluginInfo::cached_io_configuration (const std::string& unique_id, 
                                       UInt32 version,
-                                      CAComponent& comp,
-                                      AUPluginCachedInfo& cinfo,
+                                      CAComponent& comp, 
+                                      AUPluginCachedInfo& cinfo, 
                                       const std::string& name)
 {
        std::string id;
@@ -1690,7 +2242,7 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
           follow Apple "guidelines".
         */
 
-       snprintf (buf, sizeof (buf), "%u", version);
+       snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
        id = unique_id;
        id += '/';
        id += buf;
@@ -1706,9 +2258,9 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
        AUChannelInfo* channel_info;
        UInt32 cnt;
        int ret;
-
+       
        ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
-
+       
        try {
 
                if (CAAudioUnit::Open (comp, unit) != noErr) {
@@ -1722,7 +2274,8 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
                return false;
 
        }
-
+               
+       TRACE_API ("get AU channel info\n");
        if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
                return false;
        }
@@ -1733,9 +2286,9 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
                cinfo.io_configs.push_back (pair<int,int> (-1, -1));
 
        } else {
-
+               
                /* store each configuration */
-
+               
                for (uint32_t n = 0; n < cnt; ++n) {
                        cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
                                                                   channel_info[n].outChannels));
@@ -1756,13 +2309,16 @@ AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
        cached_info[id] = cinfo;
 }
 
+#define AU_CACHE_VERSION "2.0"
+
 void
 AUPluginInfo::save_cached_info ()
 {
        XMLNode* node;
 
        node = new XMLNode (X_("AudioUnitPluginCache"));
-
+       node->add_property( "version", AU_CACHE_VERSION );
+       
        for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
                XMLNode* parent = new XMLNode (X_("plugin"));
                parent->add_property ("id", i->first);
@@ -1798,26 +2354,37 @@ AUPluginInfo::load_cached_info ()
 {
        Glib::ustring path = au_cache_path ();
        XMLTree tree;
-
+       
        if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
                return 0;
        }
 
-       tree.read (path);
+       if ( !tree.read (path) ) {
+               error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
+               return -1;
+       }
+       
        const XMLNode* root (tree.root());
 
        if (root->name() != X_("AudioUnitPluginCache")) {
                return -1;
        }
-
+       
+       //initial version has incorrectly stored i/o info, and/or garbage chars.
+       const XMLProperty* version = root->property(X_("version"));
+       if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
+               error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
+               return -1;
+       }
+       
        cached_info.clear ();
 
        const XMLNodeList children = root->children();
 
        for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
-
+               
                const XMLNode* child = *iter;
-
+               
                if (child->name() == X_("plugin")) {
 
                        const XMLNode* gchild;
@@ -1827,8 +2394,29 @@ AUPluginInfo::load_cached_info ()
                        if (!prop) {
                                continue;
                        }
+                       
+                       string id = prop->value();
+                       string fixed;
+                       string version;
+
+                       string::size_type slash = id.find_last_of ('/');
+
+                       if (slash == string::npos) {
+                               continue;
+                       }
+
+                       version = id.substr (slash);
+                       id = id.substr (0, slash);
+                       fixed = AUPlugin::maybe_fix_broken_au_id (id);
+
+                       if (fixed.empty()) {
+                               error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
+                               continue;
+                       } 
+
+                       id = fixed;
+                       id += version;
 
-                       std::string id = prop->value();
                        AUPluginCachedInfo cinfo;
 
                        for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
@@ -1845,8 +2433,8 @@ AUPluginInfo::load_cached_info ()
                                        if (((iprop = gchild->property (X_("in"))) != 0) &&
                                            ((oprop = gchild->property (X_("out"))) != 0)) {
                                                in = atoi (iprop->value());
-                                               out = atoi (iprop->value());
-
+                                               out = atoi (oprop->value());
+                                               
                                                cinfo.io_configs.push_back (pair<int,int> (in, out));
                                        }
                                }
@@ -1862,7 +2450,7 @@ AUPluginInfo::load_cached_info ()
 }
 
 void
-AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
+AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
 {
        CFStringRef itemName = NULL;
 
@@ -1882,16 +2470,16 @@ AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, G
                        DisposeHandle(nameHandle);
                }
        }
-
+    
        // if Marc-style fails, do the original way
        if (itemName == NULL) {
                CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
                CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
                CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
-
-               itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
+    
+               itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"), 
                        compTypeString, compManufacturerString, compSubTypeString);
-
+    
                if (compTypeString != NULL)
                        CFRelease(compTypeString);
                if (compSubTypeString != NULL)
@@ -1899,37 +2487,67 @@ AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, G
                if (compManufacturerString != NULL)
                        CFRelease(compManufacturerString);
        }
-
+       
        string str = CFStringRefToStdString(itemName);
        string::size_type colon = str.find (':');
 
        if (colon) {
                name = str.substr (colon+1);
                maker = str.substr (0, colon);
-               // strip_whitespace_edges (maker);
-               // strip_whitespace_edges (name);
+               strip_whitespace_edges (maker);
+               strip_whitespace_edges (name);
        } else {
                name = str;
                maker = "unknown";
+               strip_whitespace_edges (name);
        }
 }
 
-// from CAComponentDescription.cpp (in libs/appleutility in ardour source)
-extern char *StringForOSType (OSType t, char *writeLocation);
-
 std::string
 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
 {
-       char str[24];
        stringstream s;
 
-       s << StringForOSType (desc.Type(), str);
-       s << " - ";
-
-       s << StringForOSType (desc.SubType(), str);
-       s << " - ";
+       /* note: OSType is a compiler-implemenation-defined value,
+          historically a 32 bit integer created with a multi-character
+          constant such as 'abcd'. It is, fundamentally, an abomination.
+       */
 
-       s << StringForOSType (desc.Manu(), str);
+       s << desc.Type();
+       s << '-';
+       s << desc.SubType();
+       s << '-';
+       s << desc.Manu();
 
        return s.str();
 }
+
+bool
+AUPluginInfo::needs_midi_input ()
+{
+       return is_effect_with_midi_input () || is_instrument ();
+}
+
+bool
+AUPluginInfo::is_effect () const
+{
+       return is_effect_without_midi_input() || is_effect_with_midi_input();
+}
+
+bool
+AUPluginInfo::is_effect_without_midi_input () const
+{
+       return descriptor->IsAUFX();
+}
+
+bool
+AUPluginInfo::is_effect_with_midi_input () const
+{
+       return descriptor->IsAUFM();
+}
+
+bool
+AUPluginInfo::is_instrument () const
+{
+       return descriptor->IsMusicDevice();
+}