API to count max multi-channel plugin outputs
[ardour.git] / libs / ardour / audio_unit.cc
index 230482551b31964f76e7ad2437d3f834f0be9318..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>
 #include <glibmm/miscutils.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"
@@ -71,7 +75,7 @@
 #define ArdourFindNext AudioComponentFindNext
 #endif
 
-#include "i18n.h"
+#include "pbd/i18n.h"
 
 using namespace std;
 using namespace PBD;
@@ -163,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;
 }
@@ -430,7 +434,8 @@ 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)
@@ -444,12 +449,14 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
        , cb_offsets (0)
        , input_buffers (0)
        , input_map (0)
-       , frames_processed (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();
@@ -469,8 +476,8 @@ 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)
@@ -481,14 +488,25 @@ AUPlugin::AUPlugin (const AUPlugin& other)
        , bus_outputs (0)
        , input_maxbuf (0)
        , input_offset (0)
+       , cb_offsets (0)
        , input_buffers (0)
        , input_map (0)
-       , frames_processed (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));
        }
@@ -600,7 +618,7 @@ AUPlugin::init ()
        DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
        unit->GetElementCount (kAudioUnitScope_Output, output_elements);
 
-       cb_offsets = (framecnt_t*) calloc (input_elements, sizeof(uint32_t));
+       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));
 
@@ -800,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);
@@ -946,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
@@ -1026,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;
                }
        }
@@ -1058,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;
        }
 
@@ -1076,8 +1097,6 @@ AUPlugin::set_block_size (pframes_t nframes)
                activate ();
        }
 
-       _current_block_size = nframes;
-
        return 0;
 }
 
@@ -1103,7 +1122,7 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
                }
        }
 
-       streamFormat.mSampleRate = _session.frame_rate();
+       streamFormat.mSampleRate = _session.sample_rate();
        streamFormat.mFormatID = kAudioFormatLinearPCM;
        streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
 
@@ -1255,7 +1274,52 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
                return false;
        }
 
-       vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
+       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;
+               }
+       }
+
+       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));
@@ -1268,9 +1332,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
 #endif
 
        // preferred setting (provided by plugin_insert)
-       const int preferred_out = out.n_audio ();
-       bool found = false;
-       bool exact_match = false;
+       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
@@ -1298,40 +1360,23 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
         *    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 possible_in = i->first;
-               int32_t possible_out = i->second;
-
-               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));
-
-                       // exact match
-                       _output_configs.insert (preferred_out);
-                       exact_match = true;
-                       found = true;
-                       break;
-               }
-       }
-
-       /* now allow potentially "imprecise" matches */
        int32_t audio_out = -1;
        float penalty = 9999;
-       int used_possible_in = 0;
+       int32_t used_possible_in = 0;
+       bool found = false;
 #if defined (__clang__)
-#      pragma clang diagnostic push
-#      pragma clang diagnostic ignored "-Wtautological-compare"
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wtautological-compare"
 #endif
 
-#define FOUNDCFG(nch) {                            \
-  float p = fabsf ((float)(nch) - preferred_out);  \
-  _output_configs.insert (nch);                    \
-  if ((nch) > preferred_out) { p *= 1.1; }         \
+#define FOUNDCFG_PENALTY(in, out, p) {             \
+  _output_configs.insert (out);                    \
   if (p < penalty) {                               \
     used_possible_in = possible_in;                \
-    audio_out = (nch);                             \
+    audio_out = (out);                             \
+    if (imprecise) {                               \
+      imprecise->set (DataType::AUDIO, (in));      \
+    }                                              \
     penalty = p;                                   \
     found = true;                                  \
     variable_inputs = possible_in < 0;             \
@@ -1339,15 +1384,31 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
   }                                                \
 }
 
+#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);                    \
+}
+
+#define FOUNDCFG(out)                              \
+  FOUNDCFG_IMPRECISE(audio_in, out)
+
 #define ANYTHINGGOES                               \
   _output_configs.insert (0);
 
 #define UPTO(nch) {                                \
-  for (int n = 1; n <= nch; ++n) {                 \
+  for (int32_t n = 1; n <= nch; ++n) {             \
     _output_configs.insert (n);                    \
   }                                                \
 }
 
+       if (imprecise) {
+               *imprecise = in;
+       }
+
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
                int32_t possible_in = i->first;
@@ -1355,45 +1416,38 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
 
                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) {
-                       /* no inputs, generators & instruments */
-                       if (possible_out == -1) {
-                               /* any configuration possible, provide stereo output */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out == -2) {
-                               /* invalid, should be (0, -1) */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out < -2) {
-                               /* variable number of outputs up to -N, */
-                               FOUNDCFG (min (-possible_out, preferred_out));
-                               UPTO (-possible_out);
-                       } else {
-                               /* exact number of outputs */
-                               FOUNDCFG (possible_out);
-                       }
-               }
-
-               if (possible_in == -1) {
+               /* now allow potentially "imprecise" matches */
+               if (possible_in == -1 || possible_in == -2) {
                        /* wildcard for input */
-                       if (possible_out == -1) {
-                               /* out must match in */
+                       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 == -2) {
-                               /* any configuration possible, pick matching */
+                       } 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 */
-                               FOUNDCFG (max (-possible_out, preferred_out));
-                               /* and try min, too, in case the penalty is lower */
+                               /* 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 {
@@ -1402,97 +1456,39 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
                        }
                }
 
-               if (possible_in == -2) {
-                       if (possible_out == -1) {
-                               /* any configuration possible, pick matching */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out == -2) {
-                               /* invalid. interpret as (-1, -1) */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out < -2) {
-                               /* invalid,  interpret as (<-2, <-2)
-                                * variable number of outputs up to -N, */
-                               FOUNDCFG (min (-possible_out, preferred_out));
-                               UPTO (-possible_out)
+               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 */
-                               FOUNDCFG (possible_out);
-                       }
-               }
-
-               if (possible_in < -2) {
-                       /* explicit variable number of inputs */
-                       if (audio_in > -possible_in && imprecise != NULL) {
-                               // hide inputs ports
-                               imprecise->set (DataType::AUDIO, -possible_in);
+                               /* configuration can match up to -possible_in */
+                               desired_in = min (-possible_in, audio_in);
                        }
-
-                       if (audio_in > -possible_in && imprecise == NULL) {
-                               /* request is too large */
-                       } else if (possible_out == -1) {
-                               /* any output configuration possible */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out == -2) {
-                               /* invalid. interpret as (<-2, -1) */
-                               FOUNDCFG (preferred_out);
+                       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) {
-                               /* variable number of outputs up to -N, */
-                               FOUNDCFG (min (-possible_out, preferred_out));
+                               /* 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 */
-                               FOUNDCFG (possible_out);
+                               /* 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 */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
-                               FOUNDCFG (preferred_out);
-                               ANYTHINGGOES;
-                       } else if (possible_out < -2) {
-                               /* > 0, < -2 is not specified
-                                * interpret as up to -N */
-                               FOUNDCFG (min (-possible_out, preferred_out));
-                               UPTO (-possible_out)
-                       } else {
-                               /* exact number of outputs */
-                               FOUNDCFG (possible_out);
-                       }
-               }
-       }
-
-       if (!found && imprecise) {
-               /* try harder */
-               for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
-                       int32_t possible_in = i->first;
-                       int32_t possible_out = i->second;
-
-                       assert (possible_in > 0); // all other cases will have been matched above
-                       assert (possible_out !=0 || possible_in !=0); // already handled above
-
-                       imprecise->set (DataType::AUDIO, possible_in);
-                       if (possible_out == -1 || possible_out == -2) {
-                               FOUNDCFG (2);
-                       } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs, pick maximum */
-                               FOUNDCFG (min (-possible_out, preferred_out));
-                       } else {
-                               /* exact number of outputs */
-                               FOUNDCFG (possible_out);
-                       }
-                       // ideally we'll also find the closest, best matching
-                       // input configuration with minimal output penalty...
-               }
        }
 
        if (!found) {
@@ -1500,22 +1496,17 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, Cha
                return false;
        }
 
-       if (exact_match) {
-               out.set (DataType::MIDI, 0); // currently always zero
-               out.set (DataType::AUDIO, preferred_out);
-       } else {
-               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
-               out.set (DataType::AUDIO, audio_out);
+       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));
 
 #if defined (__clang__)
-#      pragma clang diagnostic pop
+# pragma clang diagnostic pop
 #endif
        return true;
 }
@@ -1540,13 +1531,13 @@ OSStatus
 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                          const AudioTimeStamp*,
                          UInt32 bus,
-                         UInt32 inNumberFrames,
+                         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 bus %3 bufs %4\n",
-       // name(), inNumberFrames, bus, 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!");
@@ -1569,7 +1560,7 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
 
        for (uint32_t i = 0; i < limit; ++i) {
                ioData->mBuffers[i].mNumberChannels = 1;
-               ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
+               ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberSamples;
 
                bool valid = false;
                uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
@@ -1579,19 +1570,29 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                        ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
                }
        }
-       cb_offsets[bus] += 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;
@@ -1601,7 +1602,9 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
        bool inplace = true; // TODO check plugin-insert in-place ?
        ChanMapping::Mappings inmap (in_map.mappings ());
        ChanMapping::Mappings outmap (out_map.mappings ());
-       assert (outmap[DataType::AUDIO].size () > 0);
+       if (outmap[DataType::AUDIO].size () == 0 || inmap[DataType::AUDIO].size() == 0) {
+               inplace = false;
+       }
        if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
                inplace = false;
        }
@@ -1634,7 +1637,7 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                        /* 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));
@@ -1664,17 +1667,19 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
 
                for (uint32_t i = 0; i < cnt; ++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
+                       /* 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) {
@@ -1686,11 +1691,11 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                }
 
                /* does this really mean anything ?  */
-               ts.mSampleTime = frames_processed;
+               ts.mSampleTime = samples_processed;
                ts.mFlags = kAudioTimeStampSampleTimeValid;
 
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
-                                       name(), flags, frames_processed, nframes, bus, buffers->mNumberBuffers));
+                                       name(), flags, samples_processed, nframes, bus, buffers->mNumberBuffers));
 
                if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
 
@@ -1701,7 +1706,12 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                        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 (!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) {
@@ -1737,7 +1747,7 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
        input_maxbuf = 0;
 
        if (ok) {
-               frames_processed += nframes;
+               samples_processed += nframes;
                return 0;
        }
        return -1;
@@ -1751,30 +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) {
-               const double ppq_scaling = metric.meter().note_divisor() / 4.0;
-               float beat;
-               beat = metric.meter().divisions_per_bar() * (bbt.bars - 1);
-               beat += (bbt.beats - 1);
-               beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
-               *outCurrentBeat = beat * ppq_scaling;
+               *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;
@@ -1791,26 +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 {
-                       double const beat_frac_to_next = (Timecode::BBT_Time::ticks_per_beat - bbt.ticks) / Timecode::BBT_Time::ticks_per_beat;
-                       *outDeltaSampleOffsetToNextBeat = tmap.frame_at_beat (tmap.beat_at_frame (_session.transport_frame() + input_offset) + beat_frac_to_next);
+                       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);
                }
        }
 
@@ -1829,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;
@@ -1844,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;
@@ -1870,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) {
 
@@ -1884,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;
 }
@@ -1956,6 +1916,8 @@ AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
                        break;
        }
 
+       std::string busname;
+
        if (dt == DataType::AUDIO) {
                if (input) {
                        uint32_t pid = id;
@@ -1964,6 +1926,7 @@ AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
                                        id = pid;
                                        ss << _bus_name_in[bus];
                                        ss << " / Bus " << (1 + bus);
+                                       busname = _bus_name_in[bus];
                                        break;
                                }
                                pid -= bus_inputs[bus];
@@ -1976,6 +1939,7 @@ AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
                                        id = pid;
                                        ss << _bus_name_out[bus];
                                        ss << " / Bus " << (1 + bus);
+                                       busname = _bus_name_out[bus];
                                        break;
                                }
                                pid -= bus_outputs[bus];
@@ -1992,6 +1956,10 @@ AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
        ss << (id + 1);
 
        Plugin::IOPortDescription iod (ss.str());
+       if (!busname.empty()) {
+               iod.group_name = busname;
+               iod.group_channel = id;
+       }
        return iod;
 }
 
@@ -2005,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
 {
@@ -2099,7 +2061,6 @@ AUPlugin::set_state(const XMLNode& node, int version)
                return -1;
        }
 
-#ifndef NO_PLUGIN_STATE
        if (node.children().empty()) {
                return -1;
        }
@@ -2135,7 +2096,6 @@ AUPlugin::set_state(const XMLNode& node, int version)
                }
                CFRelease (propertyList);
        }
-#endif
 
        Plugin::set_state (node, version);
        return ret;
@@ -2144,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;
@@ -2191,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
@@ -2253,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;
 }
 
 //-----------------------------------------------------------------------------
@@ -2548,8 +2532,7 @@ 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 ());
+               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));
        }
@@ -2566,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;
 }
@@ -2608,7 +2587,7 @@ AUPluginInfo::get_presets (bool user_only) const
 {
        std::vector<Plugin::PresetRecord> p;
        boost::shared_ptr<CAComponent> comp;
-#ifndef NO_PLUGIN_STATE
+
        try {
                comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
                if (!comp->IsValid()) {
@@ -2679,7 +2658,6 @@ AUPluginInfo::get_presets (bool user_only) const
        CFRelease (presets);
        unit->Uninitialize ();
 
-#endif // NO_PLUGIN_STATE
        return p;
 }
 
@@ -2889,27 +2867,27 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                        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;
                }
 
@@ -2940,6 +2918,8 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
 
                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
@@ -2954,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);
@@ -3055,7 +3045,7 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
                 * bus configs as incremental options.
                 */
                Boolean* isWritable = 0;
-               UInt32  dataSize = 0;
+               UInt32   dataSize   = 0;
                OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
                                kAudioUnitProperty_SupportedNumChannels,
                                kAudioUnitScope_Global, 0,
@@ -3111,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);
                }
 
@@ -3183,13 +3170,12 @@ AUPluginInfo::load_cached_info ()
 
                        const XMLNode* gchild;
                        const XMLNodeList gchildren = child->children();
-                       XMLProperty const * 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;
 
@@ -3219,16 +3205,10 @@ AUPluginInfo::load_cached_info ()
 
                                if (gchild->name() == X_("io")) {
 
-                                       int in;
-                                       int out;
-                                       XMLProperty const * iprop;
-                                       XMLProperty const * 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));
                                        }
                                }
@@ -3293,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)
 {
@@ -3319,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;
 }
 
@@ -3415,6 +3415,15 @@ 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)
 {
+       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()) {
@@ -3432,7 +3441,11 @@ AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEv
                 /* 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.
                 */
-                ParameterChangedExternally (i->second, new_value);
+                if (preset_holdoff > 0) {
+                       ParameterChangedExternally (i->second, new_value);
+                } else {
+                        Plugin::parameter_changed_externally (i->second, new_value);
+               }
                 break;
         default:
                 break;