API to count max multi-channel plugin outputs
[ardour.git] / libs / ardour / audio_unit.cc
index 485e4ef56a6243f72eabc859d8ca89164ed76060..bf9ea888ab9ef975c9d6148007505d6c03fd100a 100644 (file)
@@ -1,22 +1,26 @@
 /*
-    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
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-*/
+ * Copyright (C) 2006-2016 David Robillard <d@drobilla.net>
+ * Copyright (C) 2007-2017 Paul Davis <paul@linuxaudiosystems.com>
+ * Copyright (C) 2010 Carl Hetherington <carl@carlh.net>
+ * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
+ * Copyright (C) 2014-2017 Tim Mayberry <mojofunk@gmail.com>
+ * Copyright (C) 2015-2016 Nick Mainsbridge <mainsbridge@gmail.com>
+ * Copyright (C) 2018 Julien "_FrnchFrgg_" RIVAUD <frnchfrgg@free.fr>
+ *
+ * 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
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
 
 #include <sstream>
 #include <fstream>
@@ -25,6 +29,7 @@
 #include <math.h>
 #include <ctype.h>
 
+#include "pbd/gstdio_compat.h"
 #include "pbd/transmitter.h"
 #include "pbd/xml++.h"
 #include "pbd/convert.h"
 #include <glibmm/threads.h>
 #include <glibmm/fileutils.h>
 #include <glibmm/miscutils.h>
-#include <pbd/gstdio_compat.h>
 
 #include "ardour/ardour.h"
+#include "ardour/audio_unit.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"
-#include "ardour/audio_unit.h"
+#include "ardour/midi_buffer.h"
 #include "ardour/route.h"
 #include "ardour/session.h"
 #include "ardour/tempo.h"
 #include "ardour/utils.h"
 
-#include "appleutility/CAAudioUnit.h"
-#include "appleutility/CAAUParameter.h"
+#include "CAAudioUnit.h"
+#include "CAAUParameter.h"
 
 #include <CoreFoundation/CoreFoundation.h>
 #include <CoreServices/CoreServices.h>
 #include <Carbon/Carbon.h>
 #endif
 
-#include "i18n.h"
+#ifdef COREAUDIO105
+#define ArdourComponent Component
+#define ArdourDescription ComponentDescription
+#define ArdourFindNext FindNextComponent
+#else
+#define ArdourComponent AudioComponent
+#define ArdourDescription AudioComponentDescription
+#define ArdourFindNext AudioComponentFindNext
+#endif
+
+#include "pbd/i18n.h"
 
 using namespace std;
 using namespace PBD;
@@ -153,11 +167,11 @@ _render_callback(void *userData,
                 AudioUnitRenderActionFlags *ioActionFlags,
                 const AudioTimeStamp    *inTimeStamp,
                 UInt32       inBusNumber,
-                UInt32       inNumberFrames,
+                UInt32       inNumberSamples,
                 AudioBufferList*       ioData)
 {
        if (userData) {
-               return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
+               return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberSamples, ioData);
        }
        return paramErr;
 }
@@ -339,8 +353,8 @@ get_preset_name_in_plist (CFPropertyListRef plist)
 //--------------------------------------------------------------------------
 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
-Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
-Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
+Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
+Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
 {
        if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
                return FALSE;
@@ -362,17 +376,21 @@ Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inCompon
 //--------------------------------------------------------------------------
 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
-Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
-Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
+Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
+Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
 {
        OSErr status;
-       ComponentDescription desc;
+       ArdourDescription desc;
 
        if ( (inComponent == NULL) || (inComponentDescription == NULL) )
                return FALSE;
 
        // get the ComponentDescription of the input Component
+#ifdef COREAUDIO105
        status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
+#else
+       status = AudioComponentGetDescription (inComponent, &desc);
+#endif
        if (status != noErr)
                return FALSE;
 
@@ -384,28 +402,28 @@ 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,
 // but not the ComponentDescription flags)
-Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
+Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
 {
        return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
 }
 
 //--------------------------------------------------------------------------
 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
-Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
+Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
 {
        return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
 }
 
 //--------------------------------------------------------------------------
 // determine if a ComponentDescription basically matches that of a particular Component
-Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
+Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
 {
        return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
 }
 
 //--------------------------------------------------------------------------
 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
-Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
+Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
 {
        return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
 }
@@ -416,18 +434,29 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
        , comp (_comp)
        , unit (new CAAudioUnit)
        , initialized (false)
-       , _current_block_size (0)
+       , _last_nframes (0)
+       , _current_latency (UINT_MAX)
        , _requires_fixed_size_buffers (false)
        , buffers (0)
+       , variable_inputs (false)
+       , variable_outputs (false)
+       , configured_input_busses (0)
+       , configured_output_busses (0)
+       , bus_inputs (0)
+       , bus_outputs (0)
        , input_maxbuf (0)
        , input_offset (0)
+       , cb_offsets (0)
        , input_buffers (0)
-       , frames_processed (0)
+       , input_map (0)
+       , samples_processed (0)
        , audio_input_cnt (0)
        , _parameter_listener (0)
        , _parameter_listener_arg (0)
-       , last_transport_rolling (false)
+       , transport_sample (0)
+       , transport_speed (0)
        , last_transport_speed (0.0)
+       , preset_holdoff (0)
 {
        if (!preset_search_path_initialized) {
                Glib::ustring p = Glib::get_home_dir();
@@ -447,19 +476,37 @@ AUPlugin::AUPlugin (const AUPlugin& other)
        , comp (other.get_comp())
        , unit (new CAAudioUnit)
        , initialized (false)
-       , _current_block_size (0)
        , _last_nframes (0)
+       , _current_latency (UINT_MAX)
        , _requires_fixed_size_buffers (false)
        , buffers (0)
+       , variable_inputs (false)
+       , variable_outputs (false)
+       , configured_input_busses (0)
+       , configured_output_busses (0)
+       , bus_inputs (0)
+       , bus_outputs (0)
        , input_maxbuf (0)
        , input_offset (0)
+       , cb_offsets (0)
        , input_buffers (0)
-       , frames_processed (0)
+       , input_map (0)
+       , samples_processed (0)
+       , audio_input_cnt (0)
        , _parameter_listener (0)
        , _parameter_listener_arg (0)
+       , transport_sample (0)
+       , transport_speed (0)
+       , last_transport_speed (0.0)
+       , preset_holdoff (0)
 
 {
        init ();
+
+       XMLNode root (other.state_node_name ());
+       other.add_state (&root);
+       set_state (root, Stateful::loading_state_version);
+
        for (size_t i = 0; i < descriptors.size(); ++i) {
                set_parameter (i, other.get_parameter (i));
        }
@@ -477,9 +524,10 @@ AUPlugin::~AUPlugin ()
                unit->Uninitialize ();
        }
 
-       if (buffers) {
-               free (buffers);
-       }
+       free (buffers);
+       free (bus_inputs);
+       free (bus_outputs);
+       free (cb_offsets);
 }
 
 void
@@ -533,7 +581,11 @@ AUPlugin::init ()
        output_channels = -1;
        {
                CAComponentDescription temp;
+#ifdef COREAUDIO105
                GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
+#else
+               AudioComponentGetDescription (comp.get()->Comp(), &temp);
+#endif
                CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
                CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
                CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
@@ -566,18 +618,56 @@ AUPlugin::init ()
        DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
        unit->GetElementCount (kAudioUnitScope_Output, output_elements);
 
-       if (input_elements > 0) {
-               /* setup render callback: the plugin calls this to get input data
-                */
+       cb_offsets = (samplecnt_t*) calloc (input_elements, sizeof(samplecnt_t));
+       bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
+       bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
 
-               AURenderCallbackStruct renderCallbackInfo;
+       for (size_t i = 0; i < output_elements; ++i) {
+               unit->Reset (kAudioUnitScope_Output, i);
+               AudioStreamBasicDescription fmt;
+               err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
+               if (err == noErr) {
+                       bus_outputs[i] = fmt.mChannelsPerFrame;
+               }
+               CFStringRef name;
+               UInt32 sz = sizeof (CFStringRef);
+               if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
+                                       i, &name, &sz) == noErr
+                               && sz > 0) {
+                       _bus_name_out.push_back (CFStringRefToStdString (name));
+                       CFRelease(name);
+               } else {
+                       _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
+               }
+       }
+
+       for (size_t i = 0; i < input_elements; ++i) {
+               unit->Reset (kAudioUnitScope_Input, i);
+               AudioStreamBasicDescription fmt;
+               err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
+               if (err == noErr) {
+                       bus_inputs[i] = fmt.mChannelsPerFrame;
+               }
+               CFStringRef name;
+               UInt32 sz = sizeof (CFStringRef);
+               if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
+                                       i, &name, &sz) == noErr
+                               && sz > 0) {
+                       _bus_name_in.push_back (CFStringRefToStdString (name));
+                       CFRelease(name);
+               } else {
+                       _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
+               }
+       }
 
+       for (size_t i = 0; i < input_elements; ++i) {
+               /* setup render callback: the plugin calls this to get input data */
+               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) {
+                                             i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
                        error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
                        throw failed_constructor();
                }
@@ -641,9 +731,9 @@ AUPlugin::discover_parameters ()
                        const CAAUParameter* param = param_info.GetParamInfo (d.id);
                        const AudioUnitParameterInfo& info (param->ParamInfo());
 
-                       const int len = CFStringGetLength (param->GetName());;
+                       const int len = CFStringGetLength (param->GetName());
                        char local_buffer[len*2];
-                       Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
+                       Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
                        if (!good) {
                                d.label = "???";
                        } else {
@@ -728,8 +818,6 @@ AUPlugin::discover_parameters ()
                                break;
                        }
 
-                       d.min_unbound = 0; // lower is bound
-                       d.max_unbound = 0; // upper is bound
                        d.update_steps();
 
                        descriptors.push_back (d);
@@ -842,7 +930,7 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& id)
 
        return s.str();
 
-  err:
+err:
        return string();
 }
 
@@ -874,10 +962,15 @@ AUPlugin::default_value (uint32_t port)
        return 0;
 }
 
-framecnt_t
-AUPlugin::signal_latency () const
+samplecnt_t
+AUPlugin::plugin_latency () const
 {
-       return unit->Latency() * _session.frame_rate();
+       guint lat = g_atomic_int_get (&_current_latency);;
+       if (lat == UINT_MAX) {
+               lat = unit->Latency() * _session.sample_rate();
+               g_atomic_int_set (&_current_latency, lat);
+       }
+       return lat;
 }
 
 void
@@ -906,7 +999,8 @@ AUPlugin::set_parameter (uint32_t which, float val)
        theEvent.mArgument.mParameter.mElement = d.element;
 
        DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
-       AUEventListenerNotify (NULL, NULL, &theEvent);
+        /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
+        AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
 
        Plugin::set_parameter (which, val);
 }
@@ -953,7 +1047,7 @@ AUPlugin::activate ()
                if ((err = unit->Initialize()) != noErr) {
                        error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
                } else {
-                       frames_processed = 0;
+                       samples_processed = 0;
                        initialized = true;
                }
        }
@@ -985,17 +1079,17 @@ int
 AUPlugin::set_block_size (pframes_t nframes)
 {
        bool was_initialized = initialized;
-       UInt32 numFrames = nframes;
+       UInt32 numSamples = nframes;
        OSErr err;
 
        if (initialized) {
                deactivate ();
        }
 
-       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numSamples));
        if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
-                                     0, &numFrames, sizeof (numFrames))) != noErr) {
-               error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
+                                     0, &numSamples, sizeof (numSamples))) != noErr) {
+               error << string_compose (_("AU: cannot set max samples (err = %1)"), err) << endmsg;
                return -1;
        }
 
@@ -1003,8 +1097,6 @@ AUPlugin::set_block_size (pframes_t nframes)
                activate ();
        }
 
-       _current_block_size = nframes;
-
        return 0;
 }
 
@@ -1017,20 +1109,20 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
        if (audio_input_cnt > 0) {
                in.set (DataType::AUDIO, audio_input_cnt);
        }
-       int32_t audio_in = in.n_audio();
+       const int32_t audio_in = in.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) ) {
-                       return 0;
+                       return true;
                } else {
                        deactivate ();
                }
        }
 
-       streamFormat.mSampleRate = _session.frame_rate();
+       streamFormat.mSampleRate = _session.sample_rate();
        streamFormat.mFormatID = kAudioFormatLinearPCM;
        streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
 
@@ -1044,41 +1136,104 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
        streamFormat.mFramesPerPacket = 1;
 
        /* apple says that for non-interleaved data, these
-          values always refer to a single channel.
-       */
+        * values always refer to a single channel.
+        */
        streamFormat.mBytesPerPacket = 4;
        streamFormat.mBytesPerFrame = 4;
 
-       streamFormat.mChannelsPerFrame = audio_in;
+       configured_input_busses = 0;
+       configured_output_busses = 0;
+       /* reset busses */
+       for (size_t i = 0; i < output_elements; ++i) {
+               unit->Reset (kAudioUnitScope_Output, i);
+       }
+       for (size_t i = 0; i < input_elements; ++i) {
+               unit->Reset (kAudioUnitScope_Input, i);
+       }
+
+       /* now assign the channels to available busses */
+       uint32_t used_in = 0;
+       uint32_t used_out = 0;
 
-       if (set_input_format (streamFormat) != 0) {
-               return -1;
+       if (variable_inputs || input_elements == 1) {
+               // we only ever use the first bus
+               if (input_elements > 1) {
+                       warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
+               }
+               streamFormat.mChannelsPerFrame = audio_in;
+               if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
+                       return false;
+               }
+               configured_input_busses = 1;
+               used_in = audio_in;
+       } else {
+               configured_input_busses = 0;
+               uint32_t remain = audio_in;
+               for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
+                       uint32_t cnt = std::min (remain, bus_inputs[bus]);
+                       if (cnt == 0) { continue; }
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
+
+                       streamFormat.mChannelsPerFrame = cnt;
+                       if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
+                               return false;
+                       }
+                       used_in += cnt;
+                       ++configured_input_busses;
+                       remain -= cnt;
+               }
        }
 
-       streamFormat.mChannelsPerFrame = audio_out;
+       if (variable_outputs || output_elements == 1) {
+               if (output_elements > 1) {
+                       warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
+               }
 
-       if (set_output_format (streamFormat) != 0) {
-               return -1;
+               streamFormat.mChannelsPerFrame = audio_out;
+               if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
+                       return false;
+               }
+               configured_output_busses = 1;
+               used_out = audio_out;
+       } else {
+               uint32_t remain = audio_out;
+               configured_output_busses = 0;
+               for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
+                       uint32_t cnt = std::min (remain, bus_outputs[bus]);
+                       if (cnt == 0) { continue; }
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
+                       streamFormat.mChannelsPerFrame = cnt;
+                       if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
+                               return false;
+                       }
+                       used_out += cnt;
+                       remain -= cnt;
+                       ++configured_output_busses;
+               }
        }
 
+       free (buffers);
+       buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
+                                             used_out * sizeof(::AudioBuffer));
+
+       input_channels = used_in;
+       output_channels = used_out;
        /* reset plugin info to show currently configured state */
 
-       _info->n_inputs = in;
-       _info->n_outputs = out;
+       _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
+       _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
 
        if (was_initialized) {
                activate ();
        }
 
-       return 0;
+       return true;
 }
 
 ChanCount
 AUPlugin::input_streams() const
 {
        ChanCount c;
-
-
        if (input_channels < 0) {
                // force PluginIoReConfigure -- see also commit msg e38eb06
                c.set (DataType::AUDIO, 0);
@@ -1087,7 +1242,6 @@ AUPlugin::input_streams() const
                c.set (DataType::AUDIO, input_channels);
                c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
        }
-
        return c;
 }
 
@@ -1096,7 +1250,6 @@ ChanCount
 AUPlugin::output_streams() const
 {
        ChanCount c;
-
        if (output_channels < 0) {
                // force PluginIoReConfigure - see also commit msg e38eb06
                c.set (DataType::AUDIO, 0);
@@ -1105,43 +1258,81 @@ AUPlugin::output_streams() const
                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)
+AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
 {
-       // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
-
-       int32_t audio_in = in.n_audio();
-       int32_t audio_out;
-       bool found = false;
+       _output_configs.clear ();
+       const int32_t audio_in = in.n_audio();
        AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
 
        /* lets check MIDI first */
 
-       if (in.n_midi() > 0) {
-               if (!_has_midi_input) {
-                       return false;
+       if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
+               return false;
+       }
+
+       vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
+
+       if (input_elements > 1) {
+               const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
+               for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
+                       int32_t possible_in = i->first;
+                       int32_t possible_out = i->second;
+                       if (possible_in < 0) {
+                               continue;
+                       }
+                       for (uint32_t i = 1; i < input_elements; ++i) {
+                               // can't use up-to bus_inputs[]
+                               // waves' SC-C6(s) for example fails to configure with only 1 input
+                               // on the 2nd bus.
+                               io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
+                       }
+                       /* only add additional, optional busses to first available config.
+                        * AUPluginInfo::cached_io_configuration () already incrementally
+                        * adds busses (for instruments w/ multiple configurations)
+                        */
+                       break;
                }
        }
 
-       vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
+       if (output_elements > 1) {
+               const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
+               for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
+                       int32_t possible_in = i->first;
+                       int32_t possible_out = i->second;
+                       if (possible_out < 0) {
+                               continue;
+                       }
+                       for (uint32_t i = 1; i < output_elements; ++i) {
+                               int32_t c = bus_outputs[i];
+                               for (uint32_t j = 1; j < i; ++j) {
+                                       c += bus_outputs [j];
+                               }
+                               io_configs.push_back (pair<int,int> (possible_in, possible_out + c));
+                       }
+                       /* only add additional, optional busses to first available config.
+                        * AUPluginInfo::cached_io_configuration () already incrementally
+                        * adds busses (for instruments w/ multiple configurations)
+                        */
+                       break;
+               }
+       }
 
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
                                                        name(), io_configs.size(), in, out));
 
-       //Ardour expects the plugin to tell it the output
-       //configuration but AU plugins can have multiple I/O
-       //configurations in most cases. so first lets see
-       //if there's a configuration that keeps out==in
-
-       if (in.n_midi() > 0 && audio_in == 0) {
-               audio_out = 2; // prefer stereo version if available.
-       } else {
-               audio_out = audio_in;
+#if 0
+       printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
+       for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
+               printf ("- I/O  %d / %d\n", i->first, i->second);
        }
+#endif
+
+       // preferred setting (provided by plugin_insert)
+       const int32_t preferred_out = out.n_audio ();
 
        /* kAudioUnitProperty_SupportedNumChannels
         * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
@@ -1169,26 +1360,54 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
         *    Up to four input channels and up to eight output channels
         */
 
-       for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
+       int32_t audio_out = -1;
+       float penalty = 9999;
+       int32_t used_possible_in = 0;
+       bool found = false;
+#if defined (__clang__)
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wtautological-compare"
+#endif
 
-               int32_t possible_in = i->first;
-               int32_t possible_out = i->second;
+#define FOUNDCFG_PENALTY(in, out, p) {             \
+  _output_configs.insert (out);                    \
+  if (p < penalty) {                               \
+    used_possible_in = possible_in;                \
+    audio_out = (out);                             \
+    if (imprecise) {                               \
+      imprecise->set (DataType::AUDIO, (in));      \
+    }                                              \
+    penalty = p;                                   \
+    found = true;                                  \
+    variable_inputs = possible_in < 0;             \
+    variable_outputs = possible_out < 0;           \
+  }                                                \
+}
 
-               if ((possible_in == audio_in) && (possible_out == audio_out)) {
-                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
-                                                                       possible_in, possible_out,
-                                                                       in, out));
+#define FOUNDCFG_IMPRECISE(in, out) {              \
+  const float p =                                  \
+      fabsf ((float)(out) - preferred_out) *       \
+          (((out) > preferred_out) ? 1.1 : 1)      \
+      + fabsf ((float)(in) - audio_in) *           \
+          (((in) > audio_in) ? 275 : 250);         \
+  FOUNDCFG_PENALTY(in, out, p);                    \
+}
 
-                       out.set (DataType::MIDI, 0);
-                       out.set (DataType::AUDIO, audio_out);
+#define FOUNDCFG(out)                              \
+  FOUNDCFG_IMPRECISE(audio_in, out)
 
-                       return 1;
-               }
-       }
+#define ANYTHINGGOES                               \
+  _output_configs.insert (0);
 
-       /* now allow potentially "imprecise" matches */
+#define UPTO(nch) {                                \
+  for (int32_t n = 1; n <= nch; ++n) {             \
+    _output_configs.insert (n);                    \
+  }                                                \
+}
 
-       audio_out = -1;
+       if (imprecise) {
+               *imprecise = in;
+       }
 
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
@@ -1197,364 +1416,340 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
 
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
 
+               /* exact match */
+               if ((possible_in == audio_in) && (possible_out == preferred_out)) {
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
+                                               possible_in, possible_out,
+                                               in, out));
+                       /* Set penalty so low that this output configuration
+                        * will trump any other one */
+                       FOUNDCFG_PENALTY(audio_in, preferred_out, -1);
+                       break;
+               }
+
                if (possible_out == 0) {
                        warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
                        /* XXX surely this is just a send? (e.g. AUNetSend) */
                        continue;
                }
 
-               if (possible_in == 0) {
-
-                       /* instrument plugin, always legal but throws away inputs ...
-                       */
-
-                       if (possible_out == -1) {
-                               /* any configuration possible, provide stereo output */
-                               audio_out = 2;
-                               found = true;
-                       } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (0,-2) but might.
-                                  any configuration possible, provide stereo output
-                               */
-                               audio_out = 2;
-                               found = true;
-                       } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs.
-                                *
-                                * We really need to ask the user in this case.
-                                * stereo will be correct in 99.9% of all cases.
-                                */
-                               audio_out = 2;
-                               found = true;
-                       } else {
-                               /* exact number of outputs */
-                               audio_out = possible_out;
-                               found = true;
-                       }
-               }
-
-               if (possible_in == -1) {
-
+               /* now allow potentially "imprecise" matches */
+               if (possible_in == -1 || possible_in == -2) {
                        /* wildcard for input */
-
-                       if (possible_out == -1) {
-                               /* out much match in */
-                               audio_out = audio_in;
-                               found = true;
-                       } else if (possible_out == -2) {
-                               /* any configuration possible, pick matching */
-                               audio_out = audio_in;
-                               found = true;
+                       if (possible_out == possible_in) {
+                               /* either both -1 or both -2 (invalid and
+                                * interpreted as both -1): out must match in */
+                               FOUNDCFG (audio_in);
+                       } else if (possible_out == -3 - possible_in) {
+                               /* one is -1, the other is -2: any output configuration
+                                * possible, pick what the insert prefers */
+                               FOUNDCFG (preferred_out);
+                               ANYTHINGGOES;
                        } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs, pick maximum */
-                               audio_out = -possible_out;
-                               found = true;
+                               /* variable number of outputs up to -N,
+                                * invalid if in == -2 but we accept it anyway */
+                               FOUNDCFG (min (-possible_out, preferred_out));
+                               UPTO (-possible_out)
                        } else {
                                /* exact number of outputs */
-                               audio_out = possible_out;
-                               found = true;
+                               FOUNDCFG (possible_out);
                        }
                }
 
-               if (possible_in == -2) {
-
-                       if (possible_out == -1) {
-                               /* any configuration possible, pick matching */
-                               audio_out = audio_in;
-                               found = true;
-                       } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (-2,-2) but might.
-                                  interpret as (-1,-1).
-                               */
-                               audio_out = audio_in;
-                               found = true;
-                       } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs, pick maximum */
-                               audio_out = -possible_out;
-                               found = true;
+               if (possible_in < -2 || possible_in >= 0) {
+                       /* specified number, exact or up to */
+                       int32_t desired_in;
+                       if (possible_in >= 0) {
+                               /* configuration can only match possible_in */
+                               desired_in = possible_in;
                        } else {
-                               /* exact number of outputs */
-                               audio_out = possible_out;
-                               found = true;
+                               /* configuration can match up to -possible_in */
+                               desired_in = min (-possible_in, audio_in);
                        }
-               }
-
-               if (possible_in < -2) {
-
-                       /* explicit variable number of inputs */
-
-                       if (audio_in > -possible_in) {
-                               /* request is too large */
-                       }
-
-
-                       if (possible_out == -1) {
-                               /* any output configuration possible, provide stereo out */
-                               audio_out = 2;
-                               found = true;
-                       } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (<-2,-2) but might.
-                                  interpret as (<-2,-1): any configuration possible, provide stereo output
-                               */
-                               audio_out = 2;
-                               found = true;
+                       if (!imprecise && audio_in != desired_in) {
+                               /* skip that configuration, it cannot match
+                                * the required audio input count, and we
+                                * cannot ask for change via \imprecise */
+                       } else if (possible_out == -1 || possible_out == -2) {
+                               /* any output configuration possible
+                                * out == -2 is invalid, interpreted as out == -1
+                                * Really imprecise only if desired_in != audio_in */
+                               FOUNDCFG_IMPRECISE (desired_in, preferred_out);
+                               ANYTHINGGOES;
                        } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs.
-                                *
-                                * We really need to ask the user in this case.
-                                * stereo will be correct in 99.9% of all cases.
-                                */
-                               audio_out = 2;
-                               found = true;
+                               /* variable number of outputs up to -N
+                                * not specified if in > 0, but we accept it anyway
+                                * Really imprecise only if desired_in != audio_in */
+                               FOUNDCFG_IMPRECISE (desired_in, min (-possible_out, preferred_out));
+                               UPTO (-possible_out)
                        } else {
-                               /* exact number of outputs */
-                               audio_out = possible_out;
-                               found = true;
+                               /* exact number of outputs
+                                * Really imprecise only if desired_in != audio_in */
+                               FOUNDCFG_IMPRECISE (desired_in, possible_out);
                        }
                }
 
-               if (possible_in && (possible_in == audio_in)) {
-
-                       /* exact number of inputs ... must match obviously */
-
-                       if (possible_out == -1) {
-                               /* any output configuration possible, provide stereo output */
-                               audio_out = 2;
-                               found = true;
-                       } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (>0,-2) but might.
-                                  interpret as (>0,-1):
-                                  any output configuration possible, provide stereo output
-                               */
-                               audio_out = 2;
-                               found = true;
-                       } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs, pick maximum */
-                               audio_out = -possible_out;
-                               found = true;
-                       } else {
-                               /* exact number of outputs */
-                               audio_out = possible_out;
-                               found = true;
-                       }
-               }
-
-               if (found) {
-                       if (possible_in < -2 && audio_in == 0) {
-                               // input-port count cannot be zero, use as many ports
-                               // as outputs, but at most abs(possible_in)
-                               audio_input_cnt = max (1, min (audio_out, -possible_in));
-                       }
-                       break;
-               }
-
        }
 
-       if (found) {
-               out.set (DataType::MIDI, 0); /// XXX
-               out.set (DataType::AUDIO, audio_out);
-               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
-       } else {
+       if (!found) {
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
                return false;
        }
 
-       return true;
-}
-
-int
-AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
-{
-       return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
-}
-
-int
-AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
-{
-       if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
-               return -1;
-       }
-
-       if (buffers) {
-               free (buffers);
-               buffers = 0;
+       if (used_possible_in < -2 && audio_in == 0) {
+               // input-port count cannot be zero, use as many ports
+               // as outputs, but at most abs(possible_in)
+               audio_input_cnt = max (1, min (audio_out, -used_possible_in));
        }
+       out.set (DataType::MIDI, 0); /// XXX currently always zero
+       out.set (DataType::AUDIO, audio_out);
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
 
-       buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
-                                             fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
-
-       return 0;
+#if defined (__clang__)
+# pragma clang diagnostic pop
+#endif
+       return true;
 }
 
 int
-AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
+AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
 {
        OSErr result;
 
-       for (uint32_t i = 0; i < cnt; ++i) {
-               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;
-                       return -1;
-               }
-       }
-
-       if (scope == kAudioUnitScope_Input) {
-               input_channels = fmt.mChannelsPerFrame;
-       } else {
-               output_channels = fmt.mChannelsPerFrame;
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
+                               (scope == kAudioUnitScope_Input ? "input" : "output"),
+                               scope, bus));
+       if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
+               error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
+                               (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
+               return -1;
        }
-
        return 0;
 }
 
 OSStatus
 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                          const AudioTimeStamp*,
-                         UInt32,
-                         UInt32       inNumberFrames,
-                         AudioBufferList*       ioData)
+                         UInt32 bus,
+                         UInt32 inNumberSamples,
+                         AudioBufferList* ioData)
 {
        /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
 
-       // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
-        // name(), inNumberFrames, ioData->mNumberBuffers));
+       // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, samples %2 bus %3 bufs %4\n",
+       // name(), inNumberSamples, bus, ioData->mNumberBuffers));
 
        if (input_maxbuf == 0) {
+               DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
                error << _("AUPlugin: render callback called illegally!") << endmsg;
                return kAudioUnitErr_CannotDoInCurrentContext;
        }
+
+       assert (bus < input_elements);
+       uint32_t busoff = 0;
+       for (uint32_t i = 0; i < bus; ++i) {
+               busoff += bus_inputs[i];
+       }
+
        uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
 
+       ChanCount bufs_count (DataType::AUDIO, 1);
+       BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
+
+       /* apply bus offsets */
+
        for (uint32_t i = 0; i < limit; ++i) {
                ioData->mBuffers[i].mNumberChannels = 1;
-               ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
-
-               /* 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].mDataByteSize = sizeof (Sample) * inNumberSamples;
 
-               ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
+               bool valid = false;
+               uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
+               if (valid) {
+                       ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
+               } else {
+                       ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
+               }
        }
-
-       cb_offset += inNumberFrames;
-
+       cb_offsets[bus] += inNumberSamples;
        return noErr;
 }
 
 int
-AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
+AUPlugin::connect_and_run (BufferSet& bufs,
+               samplepos_t start, samplepos_t end, double speed,
+               ChanMapping const& in_map, ChanMapping const& out_map,
+               pframes_t nframes, samplecnt_t offset)
 {
-       Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
+       Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
+
+       transport_sample = start;
+       transport_speed = speed;
 
        AudioUnitRenderActionFlags flags = 0;
        AudioTimeStamp ts;
        OSErr err;
 
+       if (preset_holdoff > 0) {
+               preset_holdoff -= std::min (nframes, preset_holdoff);
+       }
+
        if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
                unit->GlobalReset();
                _last_nframes = nframes;
        }
 
-       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
-                                                       name(), input_channels, output_channels, _has_midi_input,
-                                                       bufs.count(), bufs.available()));
+       /* test if we can run in-place; only compare audio buffers */
+       bool inplace = true; // TODO check plugin-insert in-place ?
+       ChanMapping::Mappings inmap (in_map.mappings ());
+       ChanMapping::Mappings outmap (out_map.mappings ());
+       if (outmap[DataType::AUDIO].size () == 0 || inmap[DataType::AUDIO].size() == 0) {
+               inplace = false;
+       }
+       if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
+               inplace = false;
+       }
+
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6) InBus %7 OutBus %8 Inplace: %9 var-i/o %10 %11\n",
+                               name(), input_channels, output_channels, _has_midi_input,
+                               bufs.count(), bufs.available(),
+                               configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
 
        /* the apparent number of buffers matches our input configuration, but we know that the bufferset
-          has the capacity to handle our outputs.
-       */
+        * has the capacity to handle our outputs.
+        */
 
        assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
 
        input_buffers = &bufs;
+       input_map = &in_map;
        input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
        input_offset = offset;
-       cb_offset = 0;
-
-       buffers->mNumberBuffers = output_channels;
-
-       for (int32_t i = 0; i < output_channels; ++i) {
-               buffers->mBuffers[i].mNumberChannels = 1;
-               buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
-               /* setting this to 0 indicates to the AU that it can provide buffers here
-                  if necessary. if it can process in-place, it will use the buffers provided
-                  as input by ::render_callback() above.
-
-                   a non-null values tells the plugin to render into the buffer pointed
-                   at by the value.
-               */
-               buffers->mBuffers[i].mData = 0;
+       for (size_t i = 0; i < input_elements; ++i) {
+               cb_offsets[i] = 0;
        }
 
-       if (_has_midi_input) {
+       ChanCount bufs_count (DataType::AUDIO, 1);
+       BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
 
+       if (_has_midi_input) {
                uint32_t nmidi = bufs.count().n_midi();
-
                for (uint32_t i = 0; i < nmidi; ++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);
-
+                               Evoral::Event<samplepos_t> ev (*i);
                                if (ev.is_channel_event()) {
                                        const uint8_t* b = ev.buffer();
                                        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
                                        unit->MIDIEvent (b[0], b[1], b[2], ev.time());
                                }
-
                                /* XXX need to handle sysex and other message types */
                        }
                }
        }
 
-       /* does this really mean anything ?
-        */
-
-       ts.mSampleTime = frames_processed;
-       ts.mFlags = kAudioTimeStampSampleTimeValid;
+       assert (input_maxbuf < 512);
+       std::bitset<512> used_outputs;
 
-       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
-                                                        name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
+       bool ok = true;
+       uint32_t busoff = 0;
+       uint32_t remain = output_channels;
+       for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
+               uint32_t cnt;
+               if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
+                       cnt = output_channels;
+               } else {
+                       cnt = std::min (remain, bus_outputs[bus]);
+               }
+               assert (cnt > 0);
+
+               buffers->mNumberBuffers = cnt;
+
+               for (uint32_t i = 0; i < cnt; ++i) {
+                       buffers->mBuffers[i].mNumberChannels = 1;
+                       /* setting this to 0 indicates to the AU that it *can* provide buffers here
+                        * if necessary. if it can process in-place, it will use the buffers provided
+                        * as input by ::render_callback() above.
+                        *
+                        * a non-null values tells the plugin to render into the buffer pointed
+                        * at by the value.
+                        * https://developer.apple.com/documentation/audiotoolbox/1438430-audiounitrender?language=objc
+                        */
+                       if (inplace) {
+                               buffers->mBuffers[i].mDataByteSize = 0;
+                               buffers->mBuffers[i].mData = 0;
+                       } else {
+                               buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
+                               bool valid = false;
+                               uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
+                               if (valid) {
+                                       buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
+                               } else {
+                                       buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
+                               }
+                       }
+               }
 
-       if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
+               /* does this really mean anything ?  */
+               ts.mSampleTime = samples_processed;
+               ts.mFlags = kAudioTimeStampSampleTimeValid;
 
-               input_maxbuf = 0;
-               frames_processed += nframes;
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
+                                       name(), flags, samples_processed, nframes, bus, buffers->mNumberBuffers));
 
-               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
-                                                               name(), buffers->mNumberBuffers, output_channels));
+               if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
 
-               int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
-               int32_t i;
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
+                                               name(), buffers->mNumberBuffers, output_channels));
 
-               for (i = 0; i < limit; ++i) {
-                       Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
-                       if (expected_buffer_address != buffers->mBuffers[i].mData) {
-                               /* plugin provided its own buffer for output so copy it back to where we want it
-                                */
-                               memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
+                       uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
+                       for (uint32_t i = 0; i < limit; ++i) {
+                               bool valid = false;
+                               uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
+                               if (!valid) {
+                                       continue;
+                               }
+                               if (buffers->mBuffers[i].mData == 0 || buffers->mBuffers[i].mNumberChannels != 1) {
+                                       continue;
+                               }
+                               used_outputs.set (i + busoff);
+                               Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
+                               if (expected_buffer_address != buffers->mBuffers[i].mData) {
+                                       /* plugin provided its own buffer for output so copy it back to where we want it */
+                                       memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
+                               }
                        }
+               } else {
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
+                       error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
+                       ok = false;
+                       break;
                }
 
-               /* now silence any buffers that were passed in but the that the plugin
-                  did not fill/touch/use.
-               */
+               remain -= cnt;
+               busoff += bus_outputs[bus];
+       }
 
-               for (;i < output_channels; ++i) {
-                       memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
-               }
+       /* now silence any buffers that were passed in but the that the plugin
+        * did not fill/touch/use.
+        *
+        * TODO: optimize, when plugin-insert is processing in-place
+        * unconnected buffers are (also) cleared there.
+        */
+       for (uint32_t i = 0; i < input_maxbuf; ++i) {
+               if (used_outputs.test (i)) { continue; }
+               bool valid = false;
+               uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
+               if (!valid) continue;
+               memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
+       }
 
+       input_maxbuf = 0;
+
+       if (ok) {
+               samples_processed += nframes;
                return 0;
        }
-
-       error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
        return -1;
 }
 
@@ -1566,29 +1761,12 @@ AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
 
        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
-          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() + input_offset);
-       tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
-
        if (outCurrentBeat) {
-               float beat;
-               beat = metric.meter().divisions_per_bar() * bbt.bars;
-               beat += bbt.beats;
-               beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
-               *outCurrentBeat = beat;
+               *outCurrentBeat = tmap.quarter_note_at_sample (transport_sample + input_offset);
        }
 
        if (outCurrentTempo) {
-               *outCurrentTempo = floor (metric.tempo().beats_per_minute());
+               *outCurrentTempo = tmap.tempo_at_sample (transport_sample + input_offset).quarter_notes_per_minute();
        }
 
        return noErr;
@@ -1605,27 +1783,18 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
 
        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
-          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() + input_offset);
-       tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
+       TempoMetric metric = tmap.metric_at (transport_sample + input_offset);
+       Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_sample (transport_sample + input_offset);
 
        if (outDeltaSampleOffsetToNextBeat) {
                if (bbt.ticks == 0) {
                        /* on the beat */
                        *outDeltaSampleOffsetToNextBeat = 0;
                } else {
-                       *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())); // frames per beat
+                       double const next_beat = ceil (tmap.quarter_note_at_sample (transport_sample + input_offset));
+                       samplepos_t const next_beat_sample = tmap.sample_at_quarter_note (next_beat);
+
+                       *outDeltaSampleOffsetToNextBeat = next_beat_sample - (transport_sample + input_offset);
                }
        }
 
@@ -1644,8 +1813,10 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
                   3|1|0 -> 1 + (2 * divisions_per_bar)
                   etc.
                */
+               bbt.beats = 1;
+               bbt.ticks = 0;
 
-               *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
+               *outCurrentMeasureDownBeat = tmap.quarter_note_at_bbt (bbt);
        }
 
        return noErr;
@@ -1659,22 +1830,20 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
                                        Float64*  outCycleStartBeat,
                                        Float64*  outCycleEndBeat)
 {
-       bool rolling;
-       float speed;
+       const bool rolling = (transport_speed != 0);
+       const bool last_transport_rolling = (last_transport_speed != 0);
 
        DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
 
-       rolling = _session.transport_rolling();
-       speed = _session.transport_speed ();
 
        if (outIsPlaying) {
-               *outIsPlaying = _session.transport_rolling();
+               *outIsPlaying = rolling;
        }
 
        if (outTransportStateChanged) {
                if (rolling != last_transport_rolling) {
                        *outTransportStateChanged = true;
-               } else if (speed != last_transport_speed) {
+               } else if (transport_speed != last_transport_speed) {
                        *outTransportStateChanged = true;
                } else {
                        *outTransportStateChanged = false;
@@ -1685,13 +1854,14 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
                /* this assumes that the AU can only call this host callback from render context,
                   where input_offset is valid.
                */
-               *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
+               *outCurrentSampleInTimeLine = transport_sample + input_offset;
        }
 
        if (outIsCycling) {
+               // TODO check bounce-processing
                Location* loc = _session.locations()->auto_loop_location();
 
-               *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
+               *outIsCycling = (loc && rolling && _session.get_play_loop());
 
                if (*outIsCycling) {
 
@@ -1699,45 +1869,20 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
 
                                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() + input_offset);
-                                       _session.tempo_map().bbt_time (loc->start(), bbt);
-
-                                       float beat;
-                                       beat = metric.meter().divisions_per_bar() * bbt.bars;
-                                       beat += bbt.beats;
-                                       beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
-
-                                       *outCycleStartBeat = beat;
+                                       *outCycleStartBeat = tmap.quarter_note_at_sample (loc->start() + input_offset);
                                }
 
                                if (outCycleEndBeat) {
-                                       TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
-                                       _session.tempo_map().bbt_time (loc->end(), bbt);
-
-                                       float beat;
-                                       beat = metric.meter().divisions_per_bar() * bbt.bars;
-                                       beat += bbt.beats;
-                                       beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
-
-                                       *outCycleEndBeat = beat;
+                                       *outCycleEndBeat = tmap.quarter_note_at_sample (loc->end() + input_offset);
                                }
                        }
                }
        }
 
-       last_transport_rolling = rolling;
-       last_transport_speed = speed;
+       last_transport_speed = transport_speed;
 
        return noErr;
 }
@@ -1756,6 +1901,68 @@ AUPlugin::automatable() const
        return automates;
 }
 
+Plugin::IOPortDescription
+AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
+{
+       std::stringstream ss;
+       switch (dt) {
+               case DataType::AUDIO:
+                       break;
+               case DataType::MIDI:
+                       ss << _("Midi");
+                       break;
+               default:
+                       ss << _("?");
+                       break;
+       }
+
+       std::string busname;
+
+       if (dt == DataType::AUDIO) {
+               if (input) {
+                       uint32_t pid = id;
+                       for (uint32_t bus = 0; bus < input_elements; ++bus) {
+                               if (pid < bus_inputs[bus]) {
+                                       id = pid;
+                                       ss << _bus_name_in[bus];
+                                       ss << " / Bus " << (1 + bus);
+                                       busname = _bus_name_in[bus];
+                                       break;
+                               }
+                               pid -= bus_inputs[bus];
+                       }
+               }
+               else {
+                       uint32_t pid = id;
+                       for (uint32_t bus = 0; bus < output_elements; ++bus) {
+                               if (pid < bus_outputs[bus]) {
+                                       id = pid;
+                                       ss << _bus_name_out[bus];
+                                       ss << " / Bus " << (1 + bus);
+                                       busname = _bus_name_out[bus];
+                                       break;
+                               }
+                               pid -= bus_outputs[bus];
+                       }
+               }
+       }
+
+       if (input) {
+               ss << " " << _("In") << " ";
+       } else {
+               ss << " " << _("Out") << " ";
+       }
+
+       ss << (id + 1);
+
+       Plugin::IOPortDescription iod (ss.str());
+       if (!busname.empty()) {
+               iod.group_name = busname;
+               iod.group_channel = id;
+       }
+       return iod;
+}
+
 string
 AUPlugin::describe_parameter (Evoral::Parameter param)
 {
@@ -1766,12 +1973,6 @@ AUPlugin::describe_parameter (Evoral::Parameter param)
        }
 }
 
-void
-AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
-{
-       // NameValue stuff here
-}
-
 bool
 AUPlugin::parameter_is_audio (uint32_t) const
 {
@@ -1814,7 +2015,7 @@ AUPlugin::parameter_is_output (uint32_t param) const
 void
 AUPlugin::add_state (XMLNode* root) const
 {
-       LocaleGuard lg (X_("C"));
+       LocaleGuard lg;
        CFDataRef xmlData;
        CFPropertyListRef propertyList;
 
@@ -1853,14 +2054,13 @@ AUPlugin::set_state(const XMLNode& node, int version)
 {
        int ret = -1;
        CFPropertyListRef propertyList;
-       LocaleGuard lg (X_("C"));
+       LocaleGuard lg;
 
        if (node.name() != state_node_name()) {
                error << _("Bad node sent to AUPlugin::set_state") << endmsg;
                return -1;
        }
 
-#ifndef NO_PLUGIN_STATE
        if (node.children().empty()) {
                return -1;
        }
@@ -1896,7 +2096,6 @@ AUPlugin::set_state(const XMLNode& node, int version)
                }
                CFRelease (propertyList);
        }
-#endif
 
        Plugin::set_state (node, version);
        return ret;
@@ -1905,8 +2104,6 @@ AUPlugin::set_state(const XMLNode& node, int version)
 bool
 AUPlugin::load_preset (PresetRecord r)
 {
-       Plugin::load_preset (r);
-
        bool ret = false;
        CFPropertyListRef propertyList;
        Glib::ustring path;
@@ -1952,13 +2149,39 @@ AUPlugin::load_preset (PresetRecord r)
                        AUParameterListenerNotify (NULL, NULL, &changedUnit);
                }
        }
+       if (ret) {
+               preset_holdoff = std::max (_session.get_block_size() * 2.0, _session.sample_rate() * .2);
+       }
 
-       return ret;
+       return ret && Plugin::load_preset (r);
 }
 
 void
-AUPlugin::do_remove_preset (std::string)
+AUPlugin::do_remove_preset (std::string preset_name)
 {
+       vector<Glib::ustring> v;
+
+       std::string m = maker();
+       std::string n = name();
+
+       strip_whitespace_edges (m);
+       strip_whitespace_edges (n);
+
+       v.push_back (Glib::get_home_dir());
+       v.push_back ("Library");
+       v.push_back ("Audio");
+       v.push_back ("Presets");
+       v.push_back (m);
+       v.push_back (n);
+       v.push_back (preset_name + preset_suffix);
+
+       Glib::ustring user_preset_path = Glib::build_filename (v);
+
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Deleting Preset file %1\n", user_preset_path));
+
+       if (g_unlink (user_preset_path.c_str())) {
+               error << string_compose (X_("Could not delete preset at \"%1\": %2"), user_preset_path, strerror (errno)) << endmsg;
+       }
 }
 
 string
@@ -2014,7 +2237,7 @@ AUPlugin::do_save_preset (string preset_name)
 
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
 
-       return string ("file:///") + user_preset_path;
+       return user_preset_path;
 }
 
 //-----------------------------------------------------------------------------
@@ -2048,10 +2271,10 @@ GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDict
 }
 
 static OSStatus
-GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
+GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
 {
        CFDictionaryRef auStateDictionary;
-       ComponentDescription tempDesc = {0,0,0,0,0};
+       ArdourDescription tempDesc = {0,0,0,0,0};
        SInt32 versionValue;
        Boolean gotValue;
 
@@ -2105,16 +2328,16 @@ static bool au_preset_filter (const string& str, void* arg)
                   include "<manufacturer>/<plugin-name>" in their path.
                */
 
-               Plugin* p = (Plugin *) arg;
-               string match = p->maker();
+               AUPluginInfo* p = (AUPluginInfo *) arg;
+               string match = p->creator;
                match += '/';
-               match += p->name();
+               match += p->name;
 
                ret = str.find (match) != string::npos;
 
                if (ret == false) {
-                       string m = p->maker ();
-                       string n = p->name ();
+                       string m = p->creator;
+                       string n = p->name;
                        strip_whitespace_edges (m);
                        strip_whitespace_edges (n);
                        match = m;
@@ -2128,12 +2351,12 @@ static bool au_preset_filter (const string& str, void* arg)
        return ret;
 }
 
-bool
-check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
+static bool
+check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
 {
        OSStatus status;
        CFPropertyListRef plist;
-       ComponentDescription presetDesc;
+       ArdourDescription presetDesc;
        bool ret = false;
 
        plist = load_property_list (pathstr);
@@ -2176,6 +2399,73 @@ check_and_get_preset_name (Component component, const string& pathstr, string& p
        return true;
 }
 
+
+static void
+#ifdef COREAUDIO105
+get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
+#else
+get_names (ArdourComponent& comp, std::string& name, std::string& maker)
+#endif
+{
+       CFStringRef itemName = NULL;
+       // Marc Poirier-style item name
+#ifdef COREAUDIO105
+       CAComponent auComponent (comp_desc);
+       if (auComponent.IsValid()) {
+               CAComponentDescription dummydesc;
+               Handle nameHandle = NewHandle(sizeof(void*));
+               if (nameHandle != NULL) {
+                       OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
+                       if (err == noErr) {
+                               ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
+                               if (nameString != NULL) {
+                                       itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
+                               }
+                       }
+                       DisposeHandle(nameHandle);
+               }
+       }
+#else
+       assert (comp);
+       AudioComponentCopyName (comp, &itemName);
+#endif
+
+       // if Marc-style fails, do the original way
+       if (itemName == NULL) {
+#ifndef COREAUDIO105
+               CAComponentDescription comp_desc;
+               AudioComponentGetDescription (comp, &comp_desc);
+#endif
+               CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
+               CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
+               CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
+
+               itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
+                               compTypeString, compManufacturerString, compSubTypeString);
+
+               if (compTypeString != NULL)
+                       CFRelease(compTypeString);
+               if (compSubTypeString != NULL)
+                       CFRelease(compSubTypeString);
+               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);
+       } else {
+               name = str;
+               maker = "unknown";
+               strip_whitespace_edges (name);
+       }
+}
+
 std::string
 AUPlugin::current_preset() const
 {
@@ -2199,11 +2489,13 @@ AUPlugin::find_presets ()
 
        user_preset_map.clear ();
 
-       find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
+       PluginInfoPtr nfo = get_info();
+       find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
+                       boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
+                       true, true, true);
 
        if (preset_files.empty()) {
                DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
-               return;
        }
 
        for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
@@ -2240,9 +2532,8 @@ AUPlugin::find_presets ()
        /* 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.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
+               string const uri = string_compose ("AU2:%1", std::setw(4), std::setfill('0'), i->second);
+               _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
        }
 }
@@ -2258,11 +2549,7 @@ AUPlugin::has_editor () const
 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
        : descriptor (d)
        , version (0)
-{
-       type = ARDOUR::AudioUnit;
-}
-
-AUPluginInfo::~AUPluginInfo ()
+       , max_outputs (0)
 {
        type = ARDOUR::AudioUnit;
 }
@@ -2295,10 +2582,89 @@ AUPluginInfo::load (Session& session)
        }
 }
 
+std::vector<Plugin::PresetRecord>
+AUPluginInfo::get_presets (bool user_only) const
+{
+       std::vector<Plugin::PresetRecord> p;
+       boost::shared_ptr<CAComponent> comp;
+
+       try {
+               comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
+               if (!comp->IsValid()) {
+                       throw failed_constructor();
+               }
+       } catch (failed_constructor& err) {
+               return p;
+       }
+
+       // user presets
+
+       if (!preset_search_path_initialized) {
+               Glib::ustring p = Glib::get_home_dir();
+               p += "/Library/Audio/Presets:";
+               p += preset_search_path;
+               preset_search_path = p;
+               preset_search_path_initialized = true;
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
+       }
+
+       vector<string> preset_files;
+       find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
+
+       for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
+               string path = *x;
+               string preset_name;
+               preset_name = Glib::path_get_basename (path);
+               preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
+               if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
+                       p.push_back (Plugin::PresetRecord (path, preset_name));
+               }
+       }
+
+       if (user_only) {
+               return p;
+       }
+
+       // factory presets
+
+       CFArrayRef presets;
+       UInt32 dataSize;
+       Boolean isWritable;
+
+       boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
+       if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
+               return p;
+       }
+       if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
+               unit->Uninitialize ();
+               return p;
+       }
+       if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
+               unit->Uninitialize ();
+               return p;
+       }
+       if (!presets) {
+               unit->Uninitialize ();
+               return p;
+       }
+
+       CFIndex cnt = CFArrayGetCount (presets);
+       for (CFIndex i = 0; i < cnt; ++i) {
+               AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
+               string const uri = string_compose ("%1", i);
+               string name = CFStringRefToStdString (preset->presetName);
+               p.push_back (Plugin::PresetRecord (uri, name, false));
+       }
+       CFRelease (presets);
+       unit->Uninitialize ();
+
+       return p;
+}
+
 Glib::ustring
 AUPluginInfo::au_cache_path ()
 {
-       return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
+       return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
 }
 
 PluginInfoList*
@@ -2317,6 +2683,8 @@ AUPluginInfo::discover (bool scan_only)
 
        if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
                ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
+               // flush RAM cache -- after clear_cache()
+               cached_info.clear();
        }
        // create crash log file
        au_start_crashlog ();
@@ -2441,14 +2809,18 @@ AUPluginInfo::au_crashlog (std::string msg)
 void
 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
 {
-       Component comp = 0;
+       ArdourComponent comp = 0;
        au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
 
-       comp = FindNextComponent (NULL, &desc);
+       comp = ArdourFindNext (NULL, &desc);
 
        while (comp != NULL) {
                CAComponentDescription temp;
+#ifdef COREAUDIO105
                GetComponentInfo (comp, &temp, NULL, NULL, NULL);
+#else
+               AudioComponentGetDescription (comp, &temp);
+#endif
                CFStringRef itemName = NULL;
 
                {
@@ -2469,10 +2841,12 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
 
                if (is_blacklisted(CFStringRefToStdString(itemName))) {
                        info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
-                       comp = FindNextComponent (comp, &desc);
+                       comp = ArdourFindNext (comp, &desc);
                        continue;
                }
 
+               bool has_midi_in = false;
+
                AUPluginInfoPtr info (new AUPluginInfo
                                      (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
 
@@ -2489,51 +2863,63 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                case kAudioUnitType_Panner:
                case kAudioUnitType_OfflineEffect:
                case kAudioUnitType_FormatConverter:
-                       comp = FindNextComponent (comp, &desc);
+                       comp = ArdourFindNext (comp, &desc);
                        continue;
 
                case kAudioUnitType_Output:
-                       info->category = _("AudioUnit Outputs");
+                       info->category = _("Output");
                        break;
                case kAudioUnitType_MusicDevice:
-                       info->category = _("AudioUnit Instruments");
+                       info->category = _("Instrument");
+                       has_midi_in = true;
                        break;
                case kAudioUnitType_MusicEffect:
-                       info->category = _("AudioUnit MusicEffects");
+                       info->category = _("Effect");
+                       has_midi_in = true;
                        break;
                case kAudioUnitType_Effect:
-                       info->category = _("AudioUnit Effects");
+                       info->category = _("Effect");
                        break;
                case kAudioUnitType_Mixer:
-                       info->category = _("AudioUnit Mixers");
+                       info->category = _("Mixer");
                        break;
                case kAudioUnitType_Generator:
-                       info->category = _("AudioUnit Generators");
+                       info->category = _("Generator");
                        break;
                default:
-                       info->category = _("AudioUnit (Unknown)");
+                       info->category = _("(Unknown)");
                        break;
                }
 
                au_blacklist(CFStringRefToStdString(itemName));
-               AUPluginInfo::get_names (temp, info->name, info->creator);
+#ifdef COREAUDIO105
+               get_names (temp, info->name, info->creator);
+#else
+               get_names (comp, info->name, info->creator);
+#endif
                ARDOUR::PluginScanMessage(_("AU"), info->name, false);
                au_crashlog(string_compose("Plugin: %1", info->name));
 
                info->type = ARDOUR::AudioUnit;
                info->unique_id = stringify_descriptor (*info->descriptor);
 
-               /* XXX not sure of the best way to handle plugin versioning yet
-                */
+               /* XXX not sure of the best way to handle plugin versioning yet */
 
                CAComponent cacomp (*info->descriptor);
 
-               if (cacomp.GetResourceVersion (info->version) != noErr) {
+#ifdef COREAUDIO105
+               if (cacomp.GetResourceVersion (info->version) != noErr)
+#else
+               if (cacomp.GetVersion (info->version) != noErr)
+#endif
+               {
                        info->version = 0;
                }
 
                const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
 
+               info.max_outputs = 0;
+
                if (rv == 0) {
                        /* here we have to map apple's wildcard system to a simple pair
                           of values. in ::can_do() we use the whole system, but here
@@ -2548,8 +2934,18 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                           info to the user, which should perhaps be revisited.
                        */
 
-                       int32_t possible_in = info->cache.io_configs.front().first;
-                       int32_t possible_out = info->cache.io_configs.front().second;
+                       const vector<pair<int,int> >& ioc (info->cache.io_configs);
+                       for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
+                               int32_t possible_out = i->second;
+                               if (possible_out < 0) {
+                                       continue;
+                               } else if (possible_out > info.max_outputs) {
+                                       info.max_outputs = possible_out;
+                               }
+                       }
+
+                       int32_t possible_in = ioc.front().first;
+                       int32_t possible_out = ioc.font().second;
 
                        if (possible_in > 0) {
                                info->n_inputs.set (DataType::AUDIO, possible_in);
@@ -2557,6 +2953,8 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                                info->n_inputs.set (DataType::AUDIO, 1);
                        }
 
+                       info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
+
                        if (possible_out > 0) {
                                info->n_outputs.set (DataType::AUDIO, possible_out);
                        } else {
@@ -2575,7 +2973,7 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
 
                au_unblacklist(CFStringRefToStdString(itemName));
                au_crashlog("Success.");
-               comp = FindNextComponent (comp, &desc);
+               comp = ArdourFindNext (comp, &desc);
                if (itemName != NULL) CFRelease(itemName); itemName = NULL;
        }
        au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
@@ -2639,20 +3037,34 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
        }
 
        if (ret > 0) {
-
-               /* no explicit info available, so default to 1in/1out */
-
-               /* XXX this is wrong. we should be indicating wildcard values */
-
+               /* AU is expected to deal with same channel valance in and out */
                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));
+               /* CAAudioUnit::GetChannelInfo silently merges bus formats
+                * check if this was the case and if so, add
+                * bus configs as incremental options.
+                */
+               Boolean* isWritable = 0;
+               UInt32   dataSize   = 0;
+               OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
+                               kAudioUnitProperty_SupportedNumChannels,
+                               kAudioUnitScope_Global, 0,
+                               &dataSize, isWritable);
+               if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
+                       /* incrementally add busses */
+                       int in = 0;
+                       int out = 0;
+                       for (uint32_t n = 0; n < cnt; ++n) {
+                               in += channel_info[n].inChannels;
+                               out += channel_info[n].outChannels;
+                               cinfo.io_configs.push_back (pair<int,int> (in, out));
+                       }
+               } 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));
+                       }
                }
 
                free (channel_info);
@@ -2664,6 +3076,17 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
        return 0;
 }
 
+void
+AUPluginInfo::clear_cache ()
+{
+       const string& fn = au_cache_path();
+       if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
+               ::g_unlink(fn.c_str());
+       }
+       // keep cached_info in RAM until restart or re-scan
+       cached_info.clear();
+}
+
 void
 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
 {
@@ -2678,22 +3101,19 @@ AUPluginInfo::save_cached_info ()
        XMLNode* node;
 
        node = new XMLNode (X_("AudioUnitPluginCache"));
-       node->add_property( "version", AU_CACHE_VERSION );
+       node->set_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);
+               parent->set_property ("id", i->first);
                node->add_child_nocopy (*parent);
 
                for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
 
                        XMLNode* child = new XMLNode (X_("io"));
-                       char buf[32];
 
-                       snprintf (buf, sizeof (buf), "%d", j->first);
-                       child->add_property (X_("in"), buf);
-                       snprintf (buf, sizeof (buf), "%d", j->second);
-                       child->add_property (X_("out"), buf);
+                       child->set_property (X_("in"), j->first);
+                       child->set_property (X_("out"), j->second);
                        parent->add_child_nocopy (*child);
                }
 
@@ -2732,7 +3152,7 @@ AUPluginInfo::load_cached_info ()
        }
 
        //initial version has incorrectly stored i/o info, and/or garbage chars.
-       const XMLProperty* version = root->property(X_("version"));
+       XMLProperty const * 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;
@@ -2750,13 +3170,12 @@ AUPluginInfo::load_cached_info ()
 
                        const XMLNode* gchild;
                        const XMLNodeList gchildren = child->children();
-                       const XMLProperty* prop = child->property (X_("id"));
 
-                       if (!prop) {
+                       string id;
+                       if (!child->get_property (X_("id"), id)) {
                                continue;
                        }
 
-                       string id = prop->value();
                        string fixed;
                        string version;
 
@@ -2786,16 +3205,10 @@ AUPluginInfo::load_cached_info ()
 
                                if (gchild->name() == X_("io")) {
 
-                                       int in;
-                                       int out;
-                                       const XMLProperty* iprop;
-                                       const XMLProperty* oprop;
-
-                                       if (((iprop = gchild->property (X_("in"))) != 0) &&
-                                           ((oprop = gchild->property (X_("out"))) != 0)) {
-                                               in = atoi (iprop->value());
-                                               out = atoi (oprop->value());
+                                       int32_t in;
+                                       int32_t out;
 
+                                       if (gchild->get_property (X_("in"), in) && gchild->get_property (X_("out"), out)) {
                                                cinfo.io_configs.push_back (pair<int,int> (in, out));
                                        }
                                }
@@ -2810,59 +3223,6 @@ AUPluginInfo::load_cached_info ()
        return 0;
 }
 
-void
-AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
-{
-       CFStringRef itemName = NULL;
-
-       // Marc Poirier-style item name
-       CAComponent auComponent (comp_desc);
-       if (auComponent.IsValid()) {
-               CAComponentDescription dummydesc;
-               Handle nameHandle = NewHandle(sizeof(void*));
-               if (nameHandle != NULL) {
-                       OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
-                       if (err == noErr) {
-                               ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
-                               if (nameString != NULL) {
-                                       itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
-                               }
-                       }
-                       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("%@ - %@ - %@"),
-                       compTypeString, compManufacturerString, compSubTypeString);
-
-               if (compTypeString != NULL)
-                       CFRelease(compTypeString);
-               if (compSubTypeString != NULL)
-                       CFRelease(compSubTypeString);
-               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);
-       } else {
-               name = str;
-               maker = "unknown";
-               strip_whitespace_edges (name);
-       }
-}
 
 std::string
 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
@@ -2884,7 +3244,7 @@ AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
 }
 
 bool
-AUPluginInfo::needs_midi_input ()
+AUPluginInfo::needs_midi_input () const
 {
        return is_effect_with_midi_input () || is_instrument ();
 }
@@ -2913,6 +3273,13 @@ AUPluginInfo::is_instrument () const
        return descriptor->IsMusicDevice();
 }
 
+bool
+AUPluginInfo::is_utility () const
+{
+       return (descriptor->IsGenerator() || descriptor->componentType == 'aumi');
+       // kAudioUnitType_MidiProcessor  ..looks like we aren't even scanning for these yet?
+}
+
 void
 AUPlugin::set_info (PluginInfoPtr info)
 {
@@ -2939,6 +3306,19 @@ AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float in
 
        _parameter_listener_arg = arg;
 
+       // listen for latency changes
+       AudioUnitEvent event;
+       event.mEventType = kAudioUnitEvent_PropertyChange;
+       event.mArgument.mProperty.mAudioUnit = unit->AU();
+       event.mArgument.mProperty.mPropertyID = kAudioUnitProperty_Latency;
+       event.mArgument.mProperty.mScope = kAudioUnitScope_Global;
+       event.mArgument.mProperty.mElement = 0;
+
+       if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
+               PBD::error << "Failed to create latency event listener\n";
+               // TODO don't cache _current_latency
+       }
+
        return 0;
 }
 
@@ -3033,8 +3413,17 @@ AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent
 }
 
 void
-AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
+AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
 {
+       if (event->mEventType == kAudioUnitEvent_PropertyChange) {
+               if (event->mArgument.mProperty.mPropertyID == kAudioUnitProperty_Latency) {
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Latency Change Event %1 <> %2\n", new_value, unit->Latency()));
+                       guint lat = unit->Latency() * _session.sample_rate();
+                       g_atomic_int_set (&_current_latency, lat);
+               }
+               return;
+       }
+
         ParameterMap::iterator i;
 
         if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
@@ -3049,7 +3438,14 @@ AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUn
                 EndTouch (i->second);
                 break;
         case kAudioUnitEvent_ParameterValueChange:
-                ParameterChanged (i->second, new_value);
+                /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
+                   means that something else (i.e. the plugin GUI) made the change.
+                */
+                if (preset_holdoff > 0) {
+                       ParameterChangedExternally (i->second, new_value);
+                } else {
+                        Plugin::parameter_changed_externally (i->second, new_value);
+               }
                 break;
         default:
                 break;