deliver MIDI events to AU plugins that want them
[ardour.git] / libs / ardour / audio_unit.cc
index 6746845f67c3896d5f1bb6c9d31590c3d8e6e66f..7a94797e3362b4386c9821b7defcf6327fb75801 100644 (file)
@@ -1,5 +1,5 @@
 /*
-    Copyright (C) 2006-2009 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
@@ -38,6 +38,7 @@
 #include "ardour/ardour.h"
 #include "ardour/audioengine.h"
 #include "ardour/audio_buffer.h"
+#include "ardour/debug.h"
 #include "ardour/midi_buffer.h"
 #include "ardour/filesystem_paths.h"
 #include "ardour/io.h"
@@ -60,13 +61,6 @@ 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;
@@ -79,9 +73,8 @@ 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,
@@ -95,24 +88,24 @@ _render_callback(void *userData,
        return paramErr;
 }
 
-static OSStatus 
-_get_beat_and_tempo_callback (void*                userData,
-                             Float64*             outCurrentBeat, 
-                             Float64*             outCurrentTempo)
+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 OSStatus 
+static OSStatus
 _get_musical_time_location_callback (void *     userData,
-                                    UInt32 *   outDeltaSampleOffsetToNextBeat,
-                                    Float32 *  outTimeSig_Numerator,
-                                    UInt32 *   outTimeSig_Denominator,
-                                    Float64 *  outCurrentMeasureDownBeat)
+                                     UInt32 *   outDeltaSampleOffsetToNextBeat,
+                                     Float32 *  outTimeSig_Numerator,
+                                     UInt32 *   outTimeSig_Denominator,
+                                     Float64 *  outCurrentMeasureDownBeat)
 {
        if (userData) {
                return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
@@ -123,7 +116,7 @@ _get_musical_time_location_callback (void *     userData,
        return paramErr;
 }
 
-static OSStatus 
+static OSStatus
 _get_transport_state_callback (void*     userData,
                               Boolean*  outIsPlaying,
                               Boolean*  outTransportStateChanged,
@@ -133,15 +126,16 @@ _get_transport_state_callback (void*     userData,
                               Float64*  outCycleEndBeat)
 {
        if (userData) {
-               return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
-                                                                           outCurrentSampleInTimeLine, outIsCycling,
-                                                                           outCycleStartBeat, outCycleEndBeat);
+               return ((AUPlugin*)userData)->get_transport_state_callback (
+                       outIsPlaying, outTransportStateChanged,
+                       outCurrentSampleInTimeLine, outIsCycling,
+                       outCycleStartBeat, outCycleEndBeat);
        }
        return paramErr;
 }
 
 
-static int 
+static int
 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
 
 {
@@ -149,7 +143,7 @@ save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
        int fd;
 
        // Convert the property list into XML data.
-       
+
        xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
 
        if (!xmlData) {
@@ -162,16 +156,12 @@ 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) << endmsg;
+               } 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;
        }
@@ -187,10 +177,10 @@ 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 = 0;
@@ -198,12 +188,12 @@ load_property_list (Glib::ustring path)
        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);
@@ -213,13 +203,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,
@@ -232,7 +222,7 @@ load_property_list (Glib::ustring path)
 }
 
 //-----------------------------------------------------------------------------
-static void 
+static void
 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
 {
        if (!plist) {
@@ -243,7 +233,7 @@ set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
        if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
                CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
        }
-       
+
        CFRelease (pn);
 }
 
@@ -267,7 +257,7 @@ get_preset_name_in_plist (CFPropertyListRef plist)
                        if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
                                ret = local_buffer;
                        }
-               } 
+               }
        }
        return ret;
 }
@@ -281,7 +271,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
@@ -318,7 +308,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)
 {
@@ -361,7 +351,7 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
        , 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:";
@@ -373,6 +363,7 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
        init ();
 }
 
+
 AUPlugin::AUPlugin (const AUPlugin& other)
        : Plugin (other)
        , comp (other.get_comp())
@@ -386,7 +377,7 @@ AUPlugin::AUPlugin (const AUPlugin& other)
        , current_offset (0)
        , current_buffers (0)
        , frames_processed (0)
-         
+
 {
        init ();
 }
@@ -394,7 +385,7 @@ AUPlugin::AUPlugin (const AUPlugin& other)
 AUPlugin::~AUPlugin ()
 {
        if (unit) {
-               TRACE_API ("about to call uninitialize in plugin destructor\n");
+               DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
                unit->Uninitialize ();
        }
 
@@ -409,8 +400,8 @@ AUPlugin::discover_factory_presets ()
        CFArrayRef presets;
        UInt32 dataSize = sizeof (presets);
        OSStatus err;
-       
-       TRACE_API ("get property FactoryPresets in global scope\n");
+
+       DEBUG_TRACE (DEBUG::AudioUnits, "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;
@@ -428,7 +419,7 @@ AUPlugin::discover_factory_presets ()
                string name = CFStringRefToStdString (preset->presetName);
                factory_preset_map[name] = preset->presetNumber;
        }
-       
+
        CFRelease (presets);
 }
 
@@ -437,8 +428,15 @@ AUPlugin::init ()
 {
        OSErr err;
 
+       /* these keep track of *configured* channel set up,
+          not potential set ups.
+       */
+
+       input_channels = -1;
+       output_channels = -1;
+
        try {
-               TRACE_API ("opening AudioUnit\n");
+               DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
                err = CAAudioUnit::Open (*(comp.get()), *unit);
        } catch (...) {
                error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
@@ -449,27 +447,27 @@ AUPlugin::init ()
                error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
                throw failed_constructor ();
        }
-       
-       TRACE_API ("count global elements\n");
+
+       DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
        unit->GetElementCount (kAudioUnitScope_Global, global_elements);
-       TRACE_API ("count input elements\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
        unit->GetElementCount (kAudioUnitScope_Input, input_elements);
-       TRACE_API ("count output elements\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "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();
-                }
-        }
+       if (input_elements > 0) {
+               AURenderCallbackStruct renderCallbackInfo;
+
+               renderCallbackInfo.inputProc = _render_callback;
+               renderCallbackInfo.inputProcRefCon = this;
+
+               DEBUG_TRACE (DEBUG::AudioUnits, "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 */
 
@@ -479,31 +477,20 @@ AUPlugin::init ()
        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 
+
+       //ignore result of this - don't care if the property isn't supported
+       DEBUG_TRACE (DEBUG::AudioUnits, "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.
-       */
-
-       input_channels = -1;
-       output_channels = -1;
-
        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 ();
 
@@ -514,8 +501,8 @@ void
 AUPlugin::discover_parameters ()
 {
        /* discover writable parameters */
-       
-       AudioUnitScope scopes[] = { 
+
+       AudioUnitScope scopes[] = {
                kAudioUnitScope_Global,
                kAudioUnitScope_Output,
                kAudioUnitScope_Input
@@ -526,7 +513,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;
@@ -605,10 +592,10 @@ AUPlugin::discover_parameters ()
                        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.automatable = !d.toggled &&
                                !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
                                (info.flags & kAudioUnitParameterFlag_IsWritable);
-                       
+
                        d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
                        d.unit = info.unit;
 
@@ -642,8 +629,8 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& 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. 
+
+          Split at the '-' and and process each part into an integer.
           Then put it back together.
        */
 
@@ -675,16 +662,16 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& id)
                                ++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 */
@@ -723,7 +710,7 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& id)
        }
 
        s << n[0] << '-' << n[1] << '-' << n[2];
-       
+
        return s.str();
 
   err:
@@ -767,24 +754,28 @@ AUPlugin::signal_latency () const
 void
 AUPlugin::set_parameter (uint32_t which, float val)
 {
-       if (which < descriptors.size()) {
-               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);
+       if (which >= descriptors.size()) {
+               return;
+       }
 
-               /* tell the world what we did */
+       const AUParameterDescriptor& d (descriptors[which]);
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
+       unit->SetParameter (d.id, d.scope, d.element, val);
 
-               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;
+       /* tell the world what we did */
 
-               TRACE_API ("notify about parameter change\n");
-               AUEventListenerNotify (NULL, NULL, &theEvent);
-       }
+       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;
+
+       DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
+       AUEventListenerNotify (NULL, NULL, &theEvent);
+
+       Plugin::set_parameter (which, val);
 }
 
 float
@@ -793,7 +784,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);
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
                unit->GetParameter(d.id, d.scope, d.element, val);
        }
        return val;
@@ -805,7 +796,7 @@ AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) con
        if (which < descriptors.size()) {
                pd = descriptors[which];
                return 0;
-       } 
+       }
        return -1;
 }
 
@@ -825,7 +816,7 @@ AUPlugin::activate ()
 {
        if (!initialized) {
                OSErr err;
-               TRACE_API ("call Initialize in activate()\n");
+               DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
                if ((err = unit->Initialize()) != noErr) {
                        error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
                } else {
@@ -838,7 +829,7 @@ AUPlugin::activate ()
 void
 AUPlugin::deactivate ()
 {
-       TRACE_API ("call Uninitialize in deactivate()\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
        unit->Uninitialize ();
        initialized = false;
 }
@@ -846,7 +837,7 @@ AUPlugin::deactivate ()
 void
 AUPlugin::flush ()
 {
-       TRACE_API ("call Reset in flush()\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
        unit->GlobalReset ();
 }
 
@@ -868,8 +859,8 @@ AUPlugin::set_block_size (pframes_t nframes)
                deactivate ();
        }
 
-       TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
-       if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\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;
@@ -892,6 +883,8 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
        int32_t audio_in = in.n_audio();
        int32_t audio_out = out.n_audio();
 
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
+
        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) ) {
@@ -932,6 +925,11 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
                return -1;
        }
 
+       /* reset plugin info to show currently configured state */
+       
+       _info->n_inputs = in;
+       _info->n_outputs = out;
+
        if (was_initialized) {
                activate ();
        }
@@ -939,6 +937,43 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
        return 0;
 }
 
+ChanCount
+AUPlugin::input_streams() const
+{
+       ChanCount c;
+
+       c.set (DataType::AUDIO, 1);
+       c.set (DataType::MIDI, 0);
+
+       if (input_channels < 0) {
+               warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
+       } else {
+               c.set (DataType::AUDIO, input_channels);
+               c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
+       }
+
+       return c;
+}
+
+
+ChanCount
+AUPlugin::output_streams() const
+{
+       ChanCount c;
+
+       c.set (DataType::AUDIO, 1);
+       c.set (DataType::MIDI, 0);
+
+       if (output_channels < 0) {
+               warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
+       } else {
+               c.set (DataType::AUDIO, output_channels);
+               c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
+       }
+
+       return c;
+}
+
 bool
 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
 {
@@ -960,9 +995,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
 
        vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
 
-       if (debug_io_config) {
-               cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
-       }
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations\n", name(), io_configs.size()));
 
        //Ardour expects the plugin to tell it the output configuration
        //but AU plugins can have multiple I/O configurations
@@ -975,8 +1008,8 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                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;
+               if (possible_in == audio_in && possible_out == audio_out) {
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
                        return 1;
                }
        }
@@ -988,9 +1021,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                int32_t possible_in = i->first;
                int32_t possible_out = i->second;
 
-               if (debug_io_config) {
-                       cerr << "\tin " << possible_in << " out " << possible_out << endl;
-               }
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
 
                if (possible_out == 0) {
                        warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
@@ -1020,7 +1051,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                                plugcnt = 1;
                        }
                }
-               
+
                if (possible_in == -1) {
 
                        /* wildcard for input */
@@ -1042,8 +1073,8 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                                audio_out = possible_out;
                                plugcnt = 1;
                        }
-               }       
-                       
+               }
+
                if (possible_in == -2) {
 
                        if (possible_out == -1) {
@@ -1096,7 +1127,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                if (possible_in == audio_in) {
 
                        /* exact number of inputs ... must match obviously */
-                       
+
                        if (possible_out == -1) {
                                /* out must match in */
                                audio_out = audio_in;
@@ -1122,12 +1153,10 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
 
        }
 
-       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;
-               }
+       if (plugcnt > 0) {
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2 plugcnt %3\n", in, out, plugcnt));
+       } else {
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\FAIL: no io configs match %1\n", in));
        }
 
        out.set (DataType::MIDI, 0);
@@ -1153,12 +1182,9 @@ AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
                free (buffers);
                buffers = 0;
        }
-       
-       buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
-                                             fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
 
-       Glib::Mutex::Lock em (_session.engine().process_lock());
-       IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
+       buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
+                                             fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
 
        return 0;
 }
@@ -1169,9 +1195,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);
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\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;
@@ -1188,7 +1214,7 @@ AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescriptio
        return 0;
 }
 
-OSStatus 
+OSStatus
 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                          const AudioTimeStamp*,
                          UInt32,
@@ -1213,12 +1239,12 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                        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;
+                               break;
                        }
-                       
+
                        default:
                                /* plugins do not get other stuff by default */
                                break;
@@ -1255,7 +1281,7 @@ int
 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;
@@ -1279,6 +1305,31 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                buffers->mBuffers[i].mData = 0;
        }
 
+       if (_has_midi_input) {
+
+               for (uint32_t i = 0; i < bufs.count().n_midi(); ++i) {
+                       
+                       /* one MIDI port/buffer only */
+                       
+                       MidiBuffer& m = bufs.get_midi (i);
+                       
+                       for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
+                               Evoral::MIDIEvent<framepos_t> ev (*i);
+                               
+                               if (ev.is_channel_event()) {
+                                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n",
+                                                                                       name(), ev));
+                                       unit->MIDIEvent (ev.type() << 8 | ev.channel(),
+                                                        ev.buffer()[1],
+                                                        ev.buffer()[2],
+                                                        ev.time());
+                               }
+
+                               /* XXX need to handle sysex and other message types */
+                       }
+               }
+       }
+
        ts.mSampleTime = frames_processed;
        ts.mFlags = kAudioTimeStampSampleTimeValid;
 
@@ -1286,7 +1337,7 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
 
                current_maxbuf = 0;
                frames_processed += nframes;
-               
+
                uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
                uint32_t i;
 
@@ -1308,22 +1359,22 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                }
 
                return 0;
-       } 
+       }
 
        cerr << name() << " render status " << err << endl;
        return -1;
 }
 
-OSStatus 
-AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat, 
+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");
+       DEBUG_TRACE (DEBUG::AudioUnits, "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 
+       /* 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.
        */
 
@@ -1331,7 +1382,7 @@ AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
                return kAudioUnitErr_CannotDoInCurrentContext;
        }
 
-       BBT_Time bbt;
+       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);
 
@@ -1339,7 +1390,7 @@ AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
                float beat;
                beat = metric.meter().beats_per_bar() * bbt.bars;
                beat += bbt.beats;
-               beat += bbt.ticks / Meter::ticks_per_beat;
+               beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
                *outCurrentBeat = beat;
        }
 
@@ -1351,7 +1402,7 @@ AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
 
 }
 
-OSStatus 
+OSStatus
 AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
                                              Float32*  outTimeSig_Numerator,
                                              UInt32*   outTimeSig_Denominator,
@@ -1359,10 +1410,10 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
 {
        TempoMap& tmap (_session.tempo_map());
 
-       TRACE_API ("AU calls ardour music time location callback\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "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 
+       /* 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.
        */
 
@@ -1370,7 +1421,7 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
                return kAudioUnitErr_CannotDoInCurrentContext;
        }
 
-       BBT_Time bbt;
+       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);
 
@@ -1379,11 +1430,12 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
                        /* on the beat */
                        *outDeltaSampleOffsetToNextBeat = 0;
                } else {
-                       *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((Meter::ticks_per_beat - bbt.ticks)/Meter::ticks_per_beat) * // fraction of a beat to next beat
-                                                                         metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
+                       *outDeltaSampleOffsetToNextBeat = (UInt32) 
+                               floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::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());
        }
@@ -1393,11 +1445,11 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
 
        if (outCurrentMeasureDownBeat) {
 
-               /* beat for the start of the bar. 
+               /* 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. 
+                  etc.
                */
 
                *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
@@ -1406,7 +1458,7 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
        return noErr;
 }
 
-OSStatus 
+OSStatus
 AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
                                        Boolean*  outTransportStateChanged,
                                        Float64*  outCurrentSampleInTimeLine,
@@ -1417,7 +1469,7 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
        bool rolling;
        float speed;
 
-       TRACE_API ("AU calls ardour transport state callback\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
 
        rolling = _session.transport_rolling();
        speed = _session.transport_speed ();
@@ -1454,15 +1506,15 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
 
                                TempoMap& tmap (_session.tempo_map());
 
-                               /* more than 1 meter means that a simplistic computation (and interpretation) of 
+                               /* 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;
                                }
-                               
-                               BBT_Time bbt;
+
+                               Timecode::BBT_Time bbt;
 
                                if (outCycleStartBeat) {
                                        TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
@@ -1471,20 +1523,20 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
                                        float beat;
                                        beat = metric.meter().beats_per_bar() * bbt.bars;
                                        beat += bbt.beats;
-                                       beat += bbt.ticks / Meter::ticks_per_beat;
-                                       
+                                       beat += bbt.ticks / Timecode::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 / Meter::ticks_per_beat;
-                                       
+                                       beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
+
                                        *outCycleEndBeat = beat;
                                }
                        }
@@ -1551,28 +1603,27 @@ AUPlugin::parameter_is_output (uint32_t) const
        return false;
 }
 
-XMLNode&
-AUPlugin::get_state()
+void
+AUPlugin::add_state (XMLNode* root) const
 {
        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");
+       DEBUG_TRACE (DEBUG::AudioUnits, "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) {
                error << _("Could not create XML version of property list") << endmsg;
-               return *root;
+               return;
        }
 
        /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
@@ -1597,12 +1648,10 @@ AUPlugin::get_state()
                seen_get_state_message = true;
        }
 #endif
-       
-       return *root;
 }
 
 int
-AUPlugin::set_state(const XMLNode& node, int /* version*/)
+AUPlugin::set_state(const XMLNode& node, int version)
 {
 #ifdef AU_STATE_SUPPORT
        int ret = -1;
@@ -1613,7 +1662,7 @@ AUPlugin::set_state(const XMLNode& node, int /* version*/)
                error << _("Bad node sent to AUPlugin::set_state") << endmsg;
                return -1;
        }
-       
+
        if (node.children().empty()) {
                return -1;
        }
@@ -1634,22 +1683,23 @@ AUPlugin::set_state(const XMLNode& node, int /* version*/)
                                                        &errorString);
 
        CFRelease (xmlData);
-       
+
        if (propertyList) {
-               TRACE_API ("set preset\n");
+               DEBUG_TRACE (DEBUG::AudioUnits, "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) {
@@ -1657,13 +1707,15 @@ AUPlugin::set_state(const XMLNode& node, int /* version*/)
                                        PROGRAM_NAME)
                     << endmsg;
        }
-       return 0;
+       return Plugin::set_state (node, version);
 #endif
 }
 
 bool
-AUPlugin::load_preset (const string& preset_label)
+AUPlugin::load_preset (PresetRecord r)
 {
+       Plugin::load_preset (r);
+
 #ifdef AU_STATE_SUPPORT
        bool ret = false;
        CFPropertyListRef propertyList;
@@ -1673,15 +1725,15 @@ AUPlugin::load_preset (const string& preset_label)
 
        /* look first in "user" presets */
 
-       if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
-       
+       if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
+
                if ((propertyList = load_property_list (ux->second)) != 0) {
-                       TRACE_API ("set preset from user presets\n");
+                       DEBUG_TRACE (DEBUG::AudioUnits, "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;
@@ -1690,14 +1742,14 @@ AUPlugin::load_preset (const string& preset_label)
                        CFRelease(propertyList);
                }
 
-       } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
-               
+       } else if ((fx = factory_preset_map.find (r.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");
+
+               DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
 
                if (unit->SetPresentPreset (preset) == 0) {
                        ret = true;
@@ -1710,7 +1762,7 @@ AUPlugin::load_preset (const string& preset_label)
                        AUParameterListenerNotify (NULL, NULL, &changedUnit);
                }
        }
-               
+
        return ret;
 #else
        if (!seen_loading_message) {
@@ -1723,8 +1775,13 @@ AUPlugin::load_preset (const string& preset_label)
 #endif
 }
 
-bool
-AUPlugin::save_preset (string preset_name)
+void
+AUPlugin::do_remove_preset (std::string) 
+{
+}
+
+string
+AUPlugin::do_save_preset (string preset_name)
 {
 #ifdef AU_STATE_SUPPORT
        CFPropertyListRef propertyList;
@@ -1734,7 +1791,7 @@ AUPlugin::save_preset (string preset_name)
 
        std::string m = maker();
        std::string n = name();
-       
+
        strip_whitespace_edges (m);
        strip_whitespace_edges (n);
 
@@ -1744,7 +1801,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) {
@@ -1752,7 +1809,7 @@ AUPlugin::save_preset (string preset_name)
                return false;
        }
 
-       TRACE_API ("get current preset\n");
+       DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
        if (unit->GetAUPreset (propertyList) != noErr) {
                return false;
        }
@@ -1760,11 +1817,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)) {
@@ -1774,7 +1831,7 @@ AUPlugin::save_preset (string preset_name)
 
        CFRelease(propertyList);
 
-       return ret;
+       return string ("file:///") + user_preset_path;
 #else
        if (!seen_saving_message) {
                info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
@@ -1782,13 +1839,13 @@ AUPlugin::save_preset (string preset_name)
                     << endmsg;
                seen_saving_message = true;
        }
-       return false;
+       return string();
 #endif
 }
 
 //-----------------------------------------------------------------------------
 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
-static SInt32 
+static SInt32
 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
 {
        CFNumberRef cfNumber;
@@ -1816,46 +1873,46 @@ GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDict
                return 0;
 }
 
-static OSStatus 
+static OSStatus
 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
 {
-        CFDictionaryRef auStateDictionary;
-        ComponentDescription tempDesc = {0,0,0,0,0};
-        SInt32 versionValue;
-        Boolean gotValue;
+       CFDictionaryRef auStateDictionary;
+       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;
+       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;
        }
 
-        auStateDictionary = (CFDictionaryRef)inAUStateData;
+       auStateDictionary = (CFDictionaryRef)inAUStateData;
 
-        // first check to make sure that the version of the AU state data is one that we know understand
-        // XXX should I really do this?  later versions would probably still hold these ID keys, right?
-        versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
+       // first check to make sure that the version of the AU state data is one that we know understand
+       // XXX should I really do this?  later versions would probably still hold these ID keys, right?
+       versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
 
-        if (!gotValue) {
-                return kAudioUnitErr_InvalidPropertyValue;
+       if (!gotValue) {
+               return kAudioUnitErr_InvalidPropertyValue;
        }
 #define kCurrentSavedStateVersion 0
-        if (versionValue != kCurrentSavedStateVersion) {
-                return kAudioUnitErr_InvalidPropertyValue;
+       if (versionValue != kCurrentSavedStateVersion) {
+               return kAudioUnitErr_InvalidPropertyValue;
        }
 
-        // grab the ComponentDescription values from the AU state data
-        tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
-        tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
-        tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
-        // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
-        if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
-                return kAudioUnitErr_InvalidPropertyValue;
+       // grab the ComponentDescription values from the AU state data
+       tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
+       tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
+       tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
+       // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
+       if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
+               return kAudioUnitErr_InvalidPropertyValue;
 
-        *outComponentDescription = tempDesc;
-        return noErr;
+       *outComponentDescription = tempDesc;
+       return noErr;
 }
 
 
@@ -1864,7 +1921,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) {
@@ -1889,32 +1946,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;
+       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)) {
 
@@ -1937,7 +1994,7 @@ check_and_get_preset_name (Component component, const string& pathstr, string& p
                                        }
                                }
                        }
-               } 
+               }
        }
 
        CFRelease (plist);
@@ -1949,11 +2006,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");
+       DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
        if (unit->GetAUPreset (propertyList) == noErr) {
                preset_name = get_preset_name_in_plist (propertyList);
                CFRelease(propertyList);
@@ -1962,11 +2019,9 @@ AUPlugin::current_preset() const
        return preset_name;
 }
 
-vector<Plugin::PresetRecord>
-AUPlugin::get_presets ()
+void
+AUPlugin::find_presets ()
 {
-       vector<Plugin::PresetRecord> presets;
-
 #ifdef AU_STATE_SUPPORT
        vector<string*>* preset_files;
        PathScanner scanner;
@@ -1974,9 +2029,9 @@ AUPlugin::get_presets ()
        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) {
@@ -1996,28 +2051,28 @@ AUPlugin::get_presets ()
 
                if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
                        user_preset_map[preset_name] = path;
-               } 
+               }
 
                delete *x;
        }
 
        delete preset_files;
 
-        /* now fill the vector<string> with the names we have */
+       /* 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.push_back (Plugin::PresetRecord (i->second, i->first));
+               _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
        }
 
-        /* add factory presets */
+       /* add factory presets */
 
        for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
-               presets.push_back (Plugin::PresetRecord ("", i->first));
+               /* XXX: dubious */
+               string const uri = string_compose ("%1", _presets.size ());
+               _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first)));
        }
 
 #endif
-       
-       return presets;
 }
 
 bool
@@ -2045,22 +2100,24 @@ AUPluginInfo::load (Session& session)
        try {
                PluginPtr plugin;
 
-               TRACE_API ("load AU as a component\n");
+               DEBUG_TRACE (DEBUG::AudioUnits, "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));
                }
-               
+
                AUPluginInfo *aup = new AUPluginInfo (*this);
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
                plugin->set_info (PluginInfoPtr (aup));
                boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
                return plugin;
        }
 
        catch (failed_constructor &err) {
+               DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
                return PluginPtr ();
        }
 }
@@ -2081,12 +2138,14 @@ AUPluginInfo::discover ()
        }
 
        PluginInfoList* plugs = new PluginInfoList;
-       
+
        discover_fx (*plugs);
        discover_music (*plugs);
        discover_generators (*plugs);
        discover_instruments (*plugs);
 
+       DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
+
        return plugs;
 }
 
@@ -2153,7 +2212,7 @@ 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))));
 
                /* although apple designed the subtype field to be a "category" indicator,
@@ -2161,7 +2220,7 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                   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
                 */
 
@@ -2195,7 +2254,7 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                }
 
                AUPluginInfo::get_names (temp, info->name, info->creator);
-               
+
                info->type = ARDOUR::AudioUnit;
                info->unique_id = stringify_descriptor (*info->descriptor);
 
@@ -2207,7 +2266,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
@@ -2219,23 +2278,24 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                        info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
                        info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
 
-                       cerr << "detected AU: " << info->name.c_str() << "  (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
+                                                                       info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
 
                        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;
@@ -2262,9 +2322,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) {
@@ -2274,25 +2334,25 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
        } catch (...) {
 
                warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
-               cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
                return false;
 
        }
-               
-       TRACE_API ("get AU channel info\n");
+
+       DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
        if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
                return false;
        }
 
        if (ret > 0) {
-               /* no explicit info available */
 
-               cinfo.io_configs.push_back (pair<int,int> (-1, -1));
+               /* no explicit info available, so default to 1in/1out */
+
+               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));
@@ -2322,7 +2382,7 @@ AUPluginInfo::save_cached_info ()
 
        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);
@@ -2358,7 +2418,7 @@ AUPluginInfo::load_cached_info ()
 {
        Glib::ustring path = au_cache_path ();
        XMLTree tree;
-       
+
        if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
                return 0;
        }
@@ -2367,28 +2427,28 @@ AUPluginInfo::load_cached_info ()
                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;
@@ -2398,7 +2458,7 @@ AUPluginInfo::load_cached_info ()
                        if (!prop) {
                                continue;
                        }
-                       
+
                        string id = prop->value();
                        string fixed;
                        string version;
@@ -2416,7 +2476,7 @@ AUPluginInfo::load_cached_info ()
                        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;
@@ -2438,7 +2498,7 @@ AUPluginInfo::load_cached_info ()
                                            ((oprop = gchild->property (X_("out"))) != 0)) {
                                                in = atoi (iprop->value());
                                                out = atoi (oprop->value());
-                                               
+
                                                cinfo.io_configs.push_back (pair<int,int> (in, out));
                                        }
                                }
@@ -2474,16 +2534,16 @@ AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, s
                        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)
@@ -2491,7 +2551,7 @@ AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, s
                if (compManufacturerString != NULL)
                        CFRelease(compManufacturerString);
        }
-       
+
        string str = CFStringRefToStdString(itemName);
        string::size_type colon = str.find (':');
 
@@ -2555,3 +2615,14 @@ AUPluginInfo::is_instrument () const
 {
        return descriptor->IsMusicDevice();
 }
+
+void
+AUPlugin::set_info (PluginInfoPtr info)
+{
+       Plugin::set_info (info);
+
+       AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
+
+       _has_midi_input = pinfo->needs_midi_input ();
+       _has_midi_output = false;
+}