optimize some performance bottlenecks; remove jack_nframes_t that crept back into...
[ardour.git] / libs / ardour / io.cc
index dff0990f1a2313c2a061f0522fa463da0098c72d..67f365a400ab6b61316463f15b506bb2fb08b548 100644 (file)
@@ -1,5 +1,5 @@
 /*
-    Copyright (C) 2000 Paul Davis 
+    Copyright (C) 2000-2006 Paul Davis 
 
     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
     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.
-
-    $Id$
 */
 
 #include <fstream>
 #include <algorithm>
 #include <unistd.h>
 #include <locale.h>
+#include <errno.h>
 
 #include <sigc++/bind.h>
 
-#include <pbd/lockmonitor.h>
+#include <glibmm/thread.h>
+
 #include <pbd/xml++.h>
+#include <pbd/replace_all.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/io.h>
 #include <ardour/port.h>
+#include <ardour/audio_port.h>
+#include <ardour/midi_port.h>
 #include <ardour/connection.h>
 #include <ardour/session.h>
 #include <ardour/cycle_timer.h>
 #include <ardour/panner.h>
-#include <ardour/dB.h>
+#include <ardour/buffer_set.h>
+#include <ardour/meter.h>
+#include <ardour/amp.h>
 
 #include "i18n.h"
 
@@ -51,493 +56,263 @@ extern "C" int isnan (double);
 extern "C" int isinf (double);
 #endif
 
+#define BLOCK_PROCESS_CALLBACK() Glib::Mutex::Lock em (_session.engine().process_lock())
 
 using namespace std;
 using namespace ARDOUR;
-//using namespace sigc;
-
-static float current_automation_version_number = 1.0;
-
-jack_nframes_t IO::_automation_interval = 0;
-const string IO::state_node_name = "IO";
-bool         IO::connecting_legal = false;
-bool         IO::ports_legal = false;
-bool         IO::panners_legal = false;
-sigc::signal<void>                IO::GrabPeakPower;
-sigc::signal<int>                 IO::ConnectingLegal;
-sigc::signal<int>                 IO::PortsLegal;
-sigc::signal<int>                 IO::PannersLegal;
-sigc::signal<void,uint32_t>  IO::MoreOutputs;
-sigc::signal<int>                 IO::PortsCreated;
-
-/* this is a default mapper of MIDI control values to a gain coefficient.
-   others can be imagined. see IO::set_midi_to_gain_function().
+using namespace PBD;
+
+nframes_t    IO::_automation_interval = 0;
+
+const string                 IO::state_node_name = "IO";
+bool                         IO::connecting_legal = false;
+bool                         IO::ports_legal = false;
+bool                         IO::panners_legal = false;
+sigc::signal<void>           IO::Meter;
+sigc::signal<int>            IO::ConnectingLegal;
+sigc::signal<int>            IO::PortsLegal;
+sigc::signal<int>            IO::PannersLegal;
+sigc::signal<void,ChanCount> IO::MoreChannels;
+sigc::signal<int>            IO::PortsCreated;
+
+Glib::StaticMutex IO::m_meter_signal_lock = GLIBMM_STATIC_MUTEX_INIT;
+
+/* this is a default mapper of [0 .. 1.0] control values to a gain coefficient.
+   others can be imagined. 
 */
 
-static gain_t direct_midi_to_gain (double fract) { 
+static gain_t direct_control_to_gain (double fract) { 
        /* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
        /* this maxes at +6dB */
        return pow (2.0,(sqrt(sqrt(sqrt(fract)))*198.0-192.0)/6.0);
 }
 
-static double direct_gain_to_midi (gain_t gain) { 
+static double direct_gain_to_control (gain_t gain) { 
        /* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
        if (gain == 0) return 0.0;
        
        return pow((6.0*log(gain)/log(2.0)+192.0)/198.0, 8.0);
 }
 
-static bool sort_ports_by_name (Port* a, Port* b)
-{
-       return a->name() < b->name();
-}
-
 
+/** @param default_type The type of port that will be created by ensure_io
+ * and friends if no type is explicitly requested (to avoid breakage).
+ */
 IO::IO (Session& s, string name,
-
-       int input_min, int input_max, int output_min, int output_max)
+       int input_min, int input_max, int output_min, int output_max,
+       DataType default_type)
        : _session (s),
+      _output_buffers(new BufferSet()),
          _name (name),
-         _midi_gain_control (*this, _session.midi_port()),
+         _default_type(default_type),
+         _gain_control (X_("gaincontrol"), *this),
          _gain_automation_curve (0.0, 2.0, 1.0),
-         _input_minimum (input_min),
-         _input_maximum (input_max),
-         _output_minimum (output_min),
-         _output_maximum (output_max)
+         _input_minimum (ChanCount::ZERO),
+         _input_maximum (ChanCount::INFINITE),
+         _output_minimum (ChanCount::ZERO),
+         _output_maximum (ChanCount::INFINITE)
 {
-       _id = new_id();
        _panner = new Panner (name, _session);
+       _meter = new PeakMeter (_session);
+
+       if (input_min > 0) {
+               _input_minimum = ChanCount(_default_type, input_min);
+       }
+       if (input_max >= 0) {
+               _input_maximum = ChanCount(_default_type, input_max);
+       }
+       if (output_min > 0) {
+               _output_minimum = ChanCount(_default_type, output_min);
+       }
+       if (output_max >= 0) {
+               _output_maximum = ChanCount(_default_type, output_max);
+       }
+
        _gain = 1.0;
        _desired_gain = 1.0;
        _input_connection = 0;
        _output_connection = 0;
        pending_state_node = 0;
-       _ninputs = 0;
-       _noutputs = 0;
        no_panner_reset = false;
+       _phase_invert = false;
        deferred_state = 0;
 
-       _midi_gain_control.midi_to_gain = direct_midi_to_gain;
-       _midi_gain_control.gain_to_midi = direct_gain_to_midi;
-
        apply_gain_automation = false;
-
+       
        last_automation_snapshot = 0;
 
        _gain_automation_state = Off;
        _gain_automation_style = Absolute;
 
-       GrabPeakPower.connect (mem_fun (*this, &IO::grab_peak_power));
-}
-
-IO::~IO ()
-{
-       LockMonitor lm (io_lock, __LINE__, __FILE__);
-       vector<Port *>::iterator i;
-
-       for (i = _inputs.begin(); i != _inputs.end(); ++i) {
-               _session.engine().unregister_port (*i);
-       }
-
-       for (i = _outputs.begin(); i != _outputs.end(); ++i) {
-               _session.engine().unregister_port (*i);
-       }
-}
-
-void
-IO::silence (jack_nframes_t nframes, jack_nframes_t offset)
-{
-       /* io_lock, not taken: function must be called from Session::process() calltree */
-
-       for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
-               (*i)->silence (nframes, offset);
+       {
+               // IO::Meter is emitted from another thread so the
+               // Meter signal must be protected.
+               Glib::Mutex::Lock guard (m_meter_signal_lock);
+               m_meter_connection = Meter.connect (mem_fun (*this, &IO::meter));
        }
-}
-
-void
-IO::apply_declick (vector<Sample *>& bufs, uint32_t nbufs, jack_nframes_t nframes, gain_t initial, gain_t target, bool invert_polarity)
-{
-       jack_nframes_t declick = min ((jack_nframes_t)4096, nframes);
-       gain_t delta;
-       Sample *buffer;
-       double fractional_shift;
-       double fractional_pos;
-       gain_t polscale = invert_polarity ? -1.0f : 1.0f;
        
-       fractional_shift = -1.0/declick;
-
-       if (target < initial) {
-               /* fade out: remove more and more of delta from initial */
-               delta = -(initial - target);
-       } else {
-               /* fade in: add more and more of delta from initial */
-               delta = target - initial;
-       }
-
-       for (uint32_t n = 0; n < nbufs; ++n) {
-
-               buffer = bufs[n];
-               fractional_pos = 1.0;
-
-               for (jack_nframes_t nx = 0; nx < declick; ++nx) {
-                       buffer[nx] *= polscale * (initial + (delta * (0.5 + 0.5 * cos (M_PI * fractional_pos))));
-                       fractional_pos += fractional_shift;
-               }
-               
-               /* now ensure the rest of the buffer has the target value
-                  applied, if necessary.
-               */
-               
-               if (declick != nframes) {
-
-                       if (invert_polarity) {
-                               target = -target;
-                       }
+       // Connect to our own MoreChannels signal to connect output buffers
+       IO::MoreChannels.connect (mem_fun (*this, &IO::attach_buffers));
 
-                       if (target == 0.0) {
-                               memset (&buffer[declick], 0, sizeof (Sample) * (nframes - declick));
-                       } else if (target != 1.0) {
-                               for (jack_nframes_t nx = declick; nx < nframes; ++nx) {
-                                       buffer[nx] *= target;
-                               }
-                       }
-               }
-       }
+       _session.add_controllable (&_gain_control);
 }
 
-void
-IO::pan_automated (vector<Sample*>& bufs, uint32_t nbufs, jack_nframes_t start, jack_nframes_t end, jack_nframes_t nframes, jack_nframes_t offset)
+IO::IO (Session& s, const XMLNode& node, DataType dt)
+       : _session (s),
+      _output_buffers(new BufferSet()),
+         _default_type (dt),
+         _gain_control (X_("gaincontrol"), *this),
+         _gain_automation_curve (0, 0, 0) // all reset in set_state()
 {
-       Sample* dst;
-
-       /* io_lock, not taken: function must be called from Session::process() calltree */
-
-       if (_noutputs == 0) {
-               return;
-       }
-
-       if (_noutputs == 1) {
-
-               dst = output(0)->get_buffer (nframes) + offset;
+       // FIXME: hack
+       _meter = new PeakMeter (_session);
 
-               for (uint32_t n = 0; n < nbufs; ++n) {
-                       if (bufs[n] != dst) {
-                               memcpy (dst, bufs[n], sizeof (Sample) * nframes);
-                       } 
-               }
-
-               output(0)->mark_silence (false);
-
-               return;
-       }
+       _panner = 0;
+       deferred_state = 0;
+       no_panner_reset = false;
+       _desired_gain = 1.0;
+       _gain = 1.0;
+       _input_connection = 0;
+       _output_connection = 0;
 
-       uint32_t o;
-       vector<Port *>::iterator out;
-       vector<Sample *>::iterator in;
-       Panner::iterator pan;
-       Sample* obufs[_noutputs];
+       apply_gain_automation = false;
 
-       /* the terrible silence ... */
+       set_state (node);
 
-       for (out = _outputs.begin(), o = 0; out != _outputs.end(); ++out, ++o) {
-               obufs[o] = (*out)->get_buffer (nframes) + offset;
-               memset (obufs[o], 0, sizeof (Sample) * nframes);
-               (*out)->mark_silence (false);
+       {
+               // IO::Meter is emitted from another thread so the
+               // Meter signal must be protected.
+               Glib::Mutex::Lock guard (m_meter_signal_lock);
+               m_meter_connection = Meter.connect (mem_fun (*this, &IO::meter));
        }
+       
+       // Connect to our own MoreChannels signal to connect output buffers
+       IO::MoreChannels.connect (mem_fun (*this, &IO::attach_buffers));
 
-       uint32_t n;
-
-       for (pan = _panner->begin(), n = 0; n < nbufs; ++n, ++pan) {
-               (*pan)->distribute_automated (bufs[n], obufs, start, end, nframes, _session.pan_automation_buffer());
-       }
+       _session.add_controllable (&_gain_control);
 }
 
-void
-IO::pan (vector<Sample*>& bufs, uint32_t nbufs, jack_nframes_t nframes, jack_nframes_t offset, gain_t gain_coeff)
+IO::~IO ()
 {
-       Sample* dst;
-       Sample* src;
-
-       /* io_lock, not taken: function must be called from Session::process() calltree */
-
-       if (_noutputs == 0) {
-               return;
-       }
-
-       /* the panner can be empty if there are no inputs to the 
-          route, but still outputs
-       */
-
-       if (_panner->bypassed() || _panner->empty()) {
-               deliver_output_no_pan (bufs, nbufs, nframes, offset);
-               return;
-       }
-
-       if (_noutputs == 1) {
-
-               dst = output(0)->get_buffer (nframes) + offset;
-
-               if (gain_coeff == 0.0f) {
-
-                       /* only one output, and gain was zero, so make it silent */
-
-                       memset (dst, 0, sizeof (Sample) * nframes); 
-                       
-               } else if (gain_coeff == 1.0f){
-
-                       /* mix all buffers into the output */
-
-                       uint32_t n;
-                       
-                       memcpy (dst, bufs[0], sizeof (Sample) * nframes);
-                       
-                       for (n = 1; n < nbufs; ++n) {
-                               src = bufs[n];
-                               
-                               for (jack_nframes_t n = 0; n < nframes; ++n) {
-                                       dst[n] += src[n];
-                               }
-                       }
-
-                       output(0)->mark_silence (false);
-
-               } else {
-
-                       /* mix all buffers into the output, scaling them all by the gain */
-
-                       uint32_t n;
-
-                       src = bufs[0];
-                       
-                       for (jack_nframes_t n = 0; n < nframes; ++n) {
-                               dst[n] = src[n] * gain_coeff;
-                       }       
-
-                       for (n = 1; n < nbufs; ++n) {
-                               src = bufs[n];
-                               
-                               for (jack_nframes_t n = 0; n < nframes; ++n) {
-                                       dst[n] += src[n] * gain_coeff;
-                               }       
-                       }
-                       
-                       output(0)->mark_silence (false);
-               }
+       Glib::Mutex::Lock guard (m_meter_signal_lock);
+       
+       Glib::Mutex::Lock lm (io_lock);
 
-               return;
+       for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+               _session.engine().unregister_port (*i);
        }
 
-       uint32_t o;
-       vector<Port *>::iterator out;
-       vector<Sample *>::iterator in;
-       Panner::iterator pan;
-       Sample* obufs[_noutputs];
-
-       /* the terrible silence ... */
-
-       /* XXX this is wasteful but i see no way to avoid it */
-       
-       for (out = _outputs.begin(), o = 0; out != _outputs.end(); ++out, ++o) {
-               obufs[o] = (*out)->get_buffer (nframes) + offset;
-               memset (obufs[o], 0, sizeof (Sample) * nframes);
-               (*out)->mark_silence (false);
+       for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               _session.engine().unregister_port (*i);
        }
 
-       uint32_t n;
-
-       for (pan = _panner->begin(), n = 0; n < nbufs; ++n) {
-               Panner::iterator tmp;
+       m_meter_connection.disconnect();
 
-               tmp = pan;
-               ++tmp;
-
-               (*pan)->distribute (bufs[n], obufs, gain_coeff, nframes);
-
-               if (tmp != _panner->end()) {
-                       pan = tmp;
-               }
-       }
+       delete _meter;
+       delete _panner;
+       delete _output_buffers;
 }
 
 void
-IO::deliver_output (vector<Sample *>& bufs, uint32_t nbufs, jack_nframes_t nframes, jack_nframes_t offset)
+IO::silence (nframes_t nframes, nframes_t offset)
 {
        /* io_lock, not taken: function must be called from Session::process() calltree */
 
-       if (_noutputs == 0) {
-               return;
-       }
-       
-       if (_panner->bypassed()) {
-               deliver_output_no_pan (bufs, nbufs, nframes, offset);
-               return;
-       }
-
-
-       gain_t dg;
-       gain_t pangain = _gain;
-       
-       {
-               TentativeLockMonitor dm (declick_lock, __LINE__, __FILE__);
-               
-               if (dm.locked()) {
-                       dg = _desired_gain;
-               } else {
-                       dg = _gain;
-               }
-       }
-
-       if (dg != _gain) {
-               apply_declick (bufs, nbufs, nframes, _gain, dg, false);
-               _gain = dg;
-               pangain = 1.0f;
-       } 
-
-       /* simple, non-automation panning to outputs */
-
-       if (_session.transport_speed() > 1.5f || _session.transport_speed() < -1.5f) {
-               pan (bufs, nbufs, nframes, offset, pangain * speed_quietning);
-       } else {
-               pan (bufs, nbufs, nframes, offset, pangain);
+       for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               i->get_buffer().silence (nframes, offset);
        }
 }
 
+/** Deliver bufs to the IO's Jack outputs.
+ *
+ * This function should automatically do whatever it necessary to correctly deliver bufs
+ * to the outputs, eg applying gain or pan or whatever else needs to be done.
+ */
 void
-IO::deliver_output_no_pan (vector<Sample *>& bufs, uint32_t nbufs, jack_nframes_t nframes, jack_nframes_t offset)
+IO::deliver_output (BufferSet& bufs, nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset)
 {
-       /* io_lock, not taken: function must be called from Session::process() calltree */
-
-       if (_noutputs == 0) {
-               return;
-       }
-
-       gain_t dg;
-       gain_t old_gain = _gain;
-
-       if (apply_gain_automation) {
+       // FIXME: type specific code doesn't actually need to be here, it will go away in time
 
-               /* gain has already been applied by automation code. do nothing here except
-                  speed quietning.
-               */
+       /* ********** AUDIO ********** */
 
-               _gain = 1.0f;
-               dg = _gain;
+       // Apply gain if gain automation isn't playing
+       if ( ! apply_gain_automation) {
                
-       } else {
+               gain_t dg = _gain; // desired gain
 
-               TentativeLockMonitor dm (declick_lock, __LINE__, __FILE__);
-               
-               if (dm.locked()) {
-                       dg = _desired_gain;
-               } else {
-                       dg = _gain;
-               }
-       }
+               {
+                       Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
 
-       Sample* src;
-       Sample* dst;
-       uint32_t i;
-       vector<Port*>::iterator o;
-       vector<Sample*> outs;
-       gain_t actual_gain;
+                       if (dm.locked()) {
+                               dg = _desired_gain;
+                       }
 
-       if (dg != _gain) {
-               /* unlikely condition */
-               for (o = _outputs.begin(), i = 0; o != _outputs.end(); ++o, ++i) {
-                       outs.push_back ((*o)->get_buffer (nframes) + offset);
                }
-       }
-
-       /* reduce nbufs to the index of the last input buffer */
 
-       nbufs--;
-
-       if (_session.transport_speed() > 1.5f || _session.transport_speed() < -1.5f) {
-               actual_gain = _gain * speed_quietning;
-       } else {
-               actual_gain = _gain;
+               Amp::run(bufs, nframes, _gain, dg, _phase_invert);
        }
        
-       for (o = _outputs.begin(), i = 0; o != _outputs.end(); ++o, ++i) {
-
-               dst = (*o)->get_buffer (nframes) + offset;
-               src = bufs[min(nbufs,i)];
+       // Use the panner to distribute audio to output port buffers
+       if (_panner && !_panner->empty() && !_panner->bypassed()) {
+               _panner->distribute(bufs, output_buffers(), start_frame, end_frame, nframes, offset);
+       } else {
+               const DataType type = DataType::AUDIO;
 
-               if (dg != _gain || actual_gain == 1.0f) {
-                       memcpy (dst, src, sizeof (Sample) * nframes);
-               } else if (actual_gain == 0.0f) {
-                       memset (dst, 0, sizeof (Sample) * nframes);
-               } else {
-                       for (jack_nframes_t x = 0; x < nframes; ++x) {
-                               dst[x] = src[x] * actual_gain;
-                       }
+               // Copy any audio 1:1 to outputs
+               assert(bufs.count().get(DataType::AUDIO) == output_buffers().count().get(DataType::AUDIO));
+               BufferSet::iterator o = output_buffers().begin(type);
+               for (BufferSet::iterator i = bufs.begin(type); i != bufs.end(type); ++i, ++o) {
+                       o->read_from(*i, nframes, offset);
                }
-               
-               (*o)->mark_silence (false);
        }
 
-       if (dg != _gain) {
-               apply_declick (outs, outs.size(), nframes, _gain, dg, false);
-               _gain = dg;
+
+       /* ********** MIDI ********** */
+
+       // No MIDI, we're done here
+       if (bufs.count().get(DataType::MIDI) == 0) {
+               return;
        }
 
-       if (apply_gain_automation) {
-               _gain = old_gain;
+       const DataType type = DataType::MIDI;
+
+       // Copy any MIDI 1:1 to outputs
+       assert(bufs.count().get(DataType::MIDI) == output_buffers().count().get(DataType::MIDI));
+       BufferSet::iterator o = output_buffers().begin(type);
+       for (BufferSet::iterator i = bufs.begin(type); i != bufs.end(type); ++i, ++o) {
+               o->read_from(*i, nframes, offset);
        }
 }
 
 void
-IO::collect_input (vector<Sample *>& bufs, uint32_t nbufs, jack_nframes_t nframes, jack_nframes_t offset)
+IO::collect_input (BufferSet& outs, nframes_t nframes, nframes_t offset)
 {
-       /* io_lock, not taken: function must be called from Session::process() calltree */
+       assert(outs.available() >= n_inputs());
 
-       vector<Port *>::iterator i;
-       uint32_t n;
-       Sample *last = 0;
+       outs.set_count(n_inputs());
        
-       /* we require that bufs.size() >= 1 */
+       if (outs.count() == ChanCount::ZERO)
+               return;
 
-       for (n = 0, i = _inputs.begin(); n < nbufs; ++i, ++n) {
-               if (i == _inputs.end()) {
-                       break;
-               }
+       for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
                
-               /* XXX always read the full extent of the port buffer that
-                  we need. One day, we may use jack_port_get_buffer_at_offset()
-                  or something similar. For now, this simple hack will
-                  have to do.
-
-                  Hack? Why yes .. we only need to read nframes-worth of
-                  data, but the data we want is at `offset' within the
-                  buffer.
-               */
-
-               last = (*i)->get_buffer (nframes+offset) + offset;
-               // the dest buffer's offset has already been applied
-               memcpy (bufs[n], last, sizeof (Sample) * nframes);
-       }
+               BufferSet::iterator o = outs.begin(*t);
+               for (PortSet::iterator i = _inputs.begin(*t); i != _inputs.end(*t); ++i, ++o) {
+                       o->read_from(i->get_buffer(), nframes, offset);
+               }
 
-       /* fill any excess outputs with the last input */
-       
-       while (n < nbufs && last) {
-               // the dest buffer's offset has already been applied
-               memcpy (bufs[n], last, sizeof (Sample) * nframes);
-               ++n;
        }
 }
 
 void
-IO::just_meter_input (jack_nframes_t start_frame, jack_nframes_t end_frame, 
-                     jack_nframes_t nframes, jack_nframes_t offset)
+IO::just_meter_input (nframes_t start_frame, nframes_t end_frame, 
+                     nframes_t nframes, nframes_t offset)
 {
-       vector<Sample*>& bufs = _session.get_passthru_buffers ();
-       uint32_t nbufs = n_process_buffers ();
+       BufferSet& bufs = _session.get_scratch_buffers (n_inputs());
 
-       collect_input (bufs, nbufs, nframes, offset);
+       collect_input (bufs, nframes, offset);
 
-       for (uint32_t n = 0; n < nbufs; ++n) {
-               _peak_power[n] = Session::compute_peak (bufs[n], nframes, _peak_power[n]);
-       }
+       _meter->run(bufs, nframes);
 }
 
 void
@@ -566,14 +341,14 @@ IO::disconnect_input (Port* our_port, string other_port, void* src)
        }
 
        { 
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
                        /* check that our_port is really one of ours */
                        
-                       if (find (_inputs.begin(), _inputs.end(), our_port) == _inputs.end()) {
+                       if ( ! _inputs.contains(our_port)) {
                                return -1;
                        }
                        
@@ -602,14 +377,14 @@ IO::connect_input (Port* our_port, string other_port, void* src)
        }
 
        {
-               LockMonitor em(_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
                        /* check that our_port is really one of ours */
                        
-                       if (find (_inputs.begin(), _inputs.end(), our_port) == _inputs.end()) {
+                       if ( ! _inputs.contains(our_port) ) {
                                return -1;
                        }
                        
@@ -636,12 +411,14 @@ IO::disconnect_output (Port* our_port, string other_port, void* src)
        }
 
        {
-               LockMonitor em(_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
+                       
+                       /* check that our_port is really one of ours */
                        
-                       if (find (_outputs.begin(), _outputs.end(), our_port) == _outputs.end()) {
+                       if ( ! _outputs.contains(our_port) ) {
                                return -1;
                        }
                        
@@ -669,14 +446,15 @@ IO::connect_output (Port* our_port, string other_port, void* src)
        }
 
        {
-               LockMonitor em(_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
                        /* check that our_port is really one of ours */
                        
-                       if (find (_outputs.begin(), _outputs.end(), our_port) == _outputs.end()) {
+                       if ( ! _outputs.contains(our_port) ) {
                                return -1;
                        }
                        
@@ -702,24 +480,24 @@ IO::set_input (Port* other_port, void* src)
           to the specified source.
        */
 
-       if (_input_minimum > 1 || _input_minimum == 0) {
+       if (_input_minimum.get_total() > 1) {
                /* sorry, you can't do this */
                return -1;
        }
 
        if (other_port == 0) {
-               if (_input_minimum < 0) {
-                       return ensure_inputs (0, false, true, src);
+               if (_input_minimum == ChanCount::ZERO) {
+                       return ensure_inputs (ChanCount::ZERO, false, true, src);
                } else {
                        return -1;
                }
        }
 
-       if (ensure_inputs (1, true, true, src)) {
+       if (ensure_inputs (ChanCount(other_port->type(), 1), true, true, src)) {
                return -1;
        }
 
-       return connect_input (_inputs.front(), other_port->name(), src);
+       return connect_input (_inputs.port(0), other_port->name(), src);
 }
 
 int
@@ -728,86 +506,89 @@ IO::remove_output_port (Port* port, void* src)
        IOChange change (NoChange);
 
        {
-               LockMonitor em(_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
-                       
-                       if (_noutputs - 1 == (uint32_t) _output_minimum) {
+                       Glib::Mutex::Lock lm (io_lock);
+
+                       if (n_outputs() <= _output_minimum) {
                                /* sorry, you can't do this */
                                return -1;
                        }
-                       
-                       for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
-                               if (*i == port) {
-                                       change = IOChange (change|ConfigurationChanged);
-                                       if (port->connected()) {
-                                               change = IOChange (change|ConnectionsChanged);
-                                       } 
-
-                                       _session.engine().unregister_port (*i);
-                                       _outputs.erase (i);
-                                       _noutputs--;
-                                       drop_output_connection ();
-
-                                       break;
-                               }
-                       }
 
-                       if (change != NoChange) {
+                       if (_outputs.remove(port)) {
+                               change = IOChange (change|ConfigurationChanged);
+
+                               if (port->connected()) {
+                                       change = IOChange (change|ConnectionsChanged);
+                               } 
+
+                               _session.engine().unregister_port (*port);
+                               drop_output_connection ();
+                               
                                setup_peak_meters ();
                                reset_panner ();
                        }
                }
        }
-       
+
        if (change != NoChange) {
-               output_changed (change, src); /* EMIT SIGNAL */
+               output_changed (change, src);
                _session.set_dirty ();
                return 0;
-       }
-
+       } 
+       
        return -1;
 }
 
+/** Add an output port.
+ *
+ * @param destination Name of input port to connect new port to.
+ * @param src Source for emitted ConfigurationChanged signal.
+ * @param type Data type of port.  Default value (NIL) will use this IO's default type.
+ */
 int
-IO::add_output_port (string destination, void* src)
+IO::add_output_port (string destination, void* src, DataType type)
 {
        Port* our_port;
-       char buf[64];
+       char name[64];
+
+       if (type == DataType::NIL)
+               type = _default_type;
 
        {
-               LockMonitor em(_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+
                
                { 
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
-                       if (_output_maximum >= 0 && (int) _noutputs == _output_maximum) {
+                       if (n_outputs() >= _output_maximum) {
                                return -1;
                        }
                
                        /* Create a new output port */
                        
-                       if (_output_maximum == 1) {
-                               snprintf (buf, sizeof (buf), _("%s/out"), _name.c_str());
+                       // FIXME: naming scheme for differently typed ports?
+                       if (_output_maximum.get(type) == 1) {
+                               snprintf (name, sizeof (name), _("%s/out"), _name.c_str());
                        } else {
-                               snprintf (buf, sizeof (buf), _("%s/out %u"), _name.c_str(), find_output_port_hole());
+                               snprintf (name, sizeof (name), _("%s/out %u"), _name.c_str(), find_output_port_hole());
                        }
                        
-                       if ((our_port = _session.engine().register_audio_output_port (buf)) == 0) {
-                               error << string_compose(_("IO: cannot register output port %1"), buf) << endmsg;
+                       if ((our_port = _session.engine().register_output_port (type, name)) == 0) {
+                               error << string_compose(_("IO: cannot register output port %1"), name) << endmsg;
                                return -1;
                        }
                        
-                       _outputs.push_back (our_port);
-                       sort (_outputs.begin(), _outputs.end(), sort_ports_by_name);
-                       ++_noutputs;
+                       _outputs.add (our_port);
                        drop_output_connection ();
                        setup_peak_meters ();
                        reset_panner ();
                }
 
-               MoreOutputs (_noutputs); /* EMIT SIGNAL */
+               MoreChannels (n_outputs()); /* EMIT SIGNAL */
        }
 
        if (destination.length()) {
@@ -819,6 +600,7 @@ IO::add_output_port (string destination, void* src)
        // pan_changed (src); /* EMIT SIGNAL */
        output_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
        _session.set_dirty ();
+       
        return 0;
 }
 
@@ -828,34 +610,27 @@ IO::remove_input_port (Port* port, void* src)
        IOChange change (NoChange);
 
        {
-               LockMonitor em(_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
 
-                       if (((int)_ninputs - 1) < _input_minimum) {
+                       if (n_inputs() <= _input_minimum) {
                                /* sorry, you can't do this */
                                return -1;
                        }
-                       for (vector<Port *>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
-
-                               if (*i == port) {
-                                       change = IOChange (change|ConfigurationChanged);
 
-                                       if (port->connected()) {
-                                               change = IOChange (change|ConnectionsChanged);
-                                       } 
+                       if (_inputs.remove(port)) {
+                               change = IOChange (change|ConfigurationChanged);
 
-                                       _session.engine().unregister_port (*i);
-                                       _inputs.erase (i);
-                                       _ninputs--;
-                                       drop_input_connection ();
+                               if (port->connected()) {
+                                       change = IOChange (change|ConnectionsChanged);
+                               } 
 
-                                       break;
-                               }
-                       }
-                       
-                       if (change != NoChange) {
+                               _session.engine().unregister_port (*port);
+                               drop_input_connection ();
+                               
                                setup_peak_meters ();
                                reset_panner ();
                        }
@@ -867,48 +642,57 @@ IO::remove_input_port (Port* port, void* src)
                _session.set_dirty ();
                return 0;
        } 
-
+       
        return -1;
 }
 
+
+/** Add an input port.
+ *
+ * @param type Data type of port.  The appropriate Jack port type, and @ref Port will be created.
+ * @param destination Name of input port to connect new port to.
+ * @param src Source for emitted ConfigurationChanged signal.
+ */
 int
-IO::add_input_port (string source, void* src)
+IO::add_input_port (string source, void* src, DataType type)
 {
        Port* our_port;
-       char buf[64];
+       char name[64];
+       
+       if (type == DataType::NIL)
+               type = _default_type;
 
        {
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
                
                { 
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
-                       if (_input_maximum >= 0 && (int) _ninputs == _input_maximum) {
+                       if (n_inputs() >= _input_maximum) {
                                return -1;
                        }
 
                        /* Create a new input port */
                        
-                       if (_input_maximum == 1) {
-                               snprintf (buf, sizeof (buf), _("%s/in"), _name.c_str());
+                       // FIXME: naming scheme for differently typed ports?
+                       if (_input_maximum.get(type) == 1) {
+                               snprintf (name, sizeof (name), _("%s/in"), _name.c_str());
                        } else {
-                               snprintf (buf, sizeof (buf), _("%s/in %u"), _name.c_str(), find_input_port_hole());
+                               snprintf (name, sizeof (name), _("%s/in %u"), _name.c_str(), find_input_port_hole());
                        }
                        
-                       if ((our_port = _session.engine().register_audio_input_port (buf)) == 0) {
-                               error << string_compose(_("IO: cannot register input port %1"), buf) << endmsg;
+                       if ((our_port = _session.engine().register_input_port (type, name)) == 0) {
+                               error << string_compose(_("IO: cannot register input port %1"), name) << endmsg;
                                return -1;
                        }
-                       
-                       _inputs.push_back (our_port);
-                       sort (_inputs.begin(), _inputs.end(), sort_ports_by_name);
-                       ++_ninputs;
+
+                       _inputs.add (our_port);
                        drop_input_connection ();
                        setup_peak_meters ();
                        reset_panner ();
                }
 
-               MoreOutputs (_ninputs); /* EMIT SIGNAL */
+               MoreChannels (n_inputs()); /* EMIT SIGNAL */
        }
 
        if (source.length()) {
@@ -921,7 +705,7 @@ IO::add_input_port (string source, void* src)
        // pan_changed (src); /* EMIT SIGNAL */
        input_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
        _session.set_dirty ();
-
+       
        return 0;
 }
 
@@ -929,19 +713,21 @@ int
 IO::disconnect_inputs (void* src)
 {
        { 
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
-                       for (vector<Port *>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+                       for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
                                _session.engine().disconnect (*i);
                        }
 
                        drop_input_connection ();
                }
        }
-        input_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
+       
+       input_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
+       
        return 0;
 }
 
@@ -949,12 +735,12 @@ int
 IO::disconnect_outputs (void* src)
 {
        {
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
                
                {
-                       LockMonitor lm (io_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (io_lock);
                        
-                       for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+                       for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
                                _session.engine().disconnect (*i);
                        }
 
@@ -964,74 +750,74 @@ IO::disconnect_outputs (void* src)
 
        output_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
        _session.set_dirty ();
+       
        return 0;
 }
 
 bool
-IO::ensure_inputs_locked (uint32_t n, bool clear, void* src)
+IO::ensure_inputs_locked (ChanCount count, bool clear, void* src)
 {
-       Port* input_port;
-       bool changed = false;
-       bool reduced = false;
-       
-       /* remove unused ports */
+       Port* input_port = 0;
+       bool  changed    = false;
 
-       while (_ninputs > n) {
-               _session.engine().unregister_port (_inputs.back());
-               _inputs.pop_back();
-               _ninputs--;
-               reduced = true;
-               changed = true;
-       }
-               
-       /* create any necessary new ports */
-               
-       while (_ninputs < n) {
-               
-               char buf[64];
-               
-               /* Create a new input port */
-               
-               if (_input_maximum == 1) {
-                       snprintf (buf, sizeof (buf), _("%s/in"), _name.c_str());
-               }
-               else {
-                       snprintf (buf, sizeof (buf), _("%s/in %u"), _name.c_str(), find_input_port_hole());
-               }
-               
-               try {
-                       
-                       if ((input_port = _session.engine().register_audio_input_port (buf)) == 0) {
-                               error << string_compose(_("IO: cannot register input port %1"), buf) << endmsg;
-                               return -1;
-                       }
-               }
 
-               catch (AudioEngine::PortRegistrationFailure& err) {
-                       setup_peak_meters ();
-                       reset_panner ();
-                       /* pass it on */
-                       throw err;
-               }
+       for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
                
-               _inputs.push_back (input_port);
-               sort (_inputs.begin(), _inputs.end(), sort_ports_by_name);
-               ++_ninputs;
-               changed = true;
-       }
+               const size_t n = count.get(*t);
        
-       if (changed) {
-               drop_input_connection ();
+               /* remove unused ports */
+               for (size_t i = n_inputs().get(*t); i > n; --i) {
+                       input_port = _inputs.port(*t, i-1);
+
+                       assert(input_port);
+                       _inputs.remove(input_port);
+                       _session.engine().unregister_port (*input_port);
+
+                       changed = true;
+               }
+
+               /* create any necessary new ports */
+               while (n_inputs().get(*t) < n) {
+
+                       char buf[64];
+
+                       if (_input_maximum.get(*t) == 1) {
+                               snprintf (buf, sizeof (buf), _("%s/in"), _name.c_str());
+                       } else {
+                               snprintf (buf, sizeof (buf), _("%s/in %u"), _name.c_str(), find_input_port_hole());
+                       }
+
+                       try {
+
+                               if ((input_port = _session.engine().register_input_port (*t, buf)) == 0) {
+                                       error << string_compose(_("IO: cannot register input port %1"), buf) << endmsg;
+                                       return -1;
+                               }
+                       }
+
+                       catch (AudioEngine::PortRegistrationFailure& err) {
+                               setup_peak_meters ();
+                               reset_panner ();
+                               /* pass it on */
+                               throw AudioEngine::PortRegistrationFailure();
+                       }
+
+                       _inputs.add (input_port);
+                       changed = true;
+               }
+       }
+       
+       if (changed) {
+               drop_input_connection ();
                setup_peak_meters ();
                reset_panner ();
-               MoreOutputs (_ninputs); /* EMIT SIGNAL */
+               MoreChannels (n_inputs()); /* EMIT SIGNAL */
                _session.set_dirty ();
        }
        
        if (clear) {
                /* disconnect all existing ports so that we get a fresh start */
-                       
-               for (vector<Port *>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+               for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
                        _session.engine().disconnect (*i);
                }
        }
@@ -1039,157 +825,167 @@ IO::ensure_inputs_locked (uint32_t n, bool clear, void* src)
        return changed;
 }
 
+/** Attach output_buffers to port buffers.
+ * 
+ * Connected to IO's own MoreChannels signal.
+ */
+void
+IO::attach_buffers(ChanCount ignored)
+{
+       _output_buffers->attach_buffers(_outputs);
+}
+
 int
-IO::ensure_io (uint32_t nin, uint32_t nout, bool clear, void* src)
+IO::ensure_io (ChanCount in, ChanCount out, bool clear, void* src)
 {
-       bool in_changed = false;
-       bool out_changed = false;
-       bool in_reduced = false;
-       bool out_reduced = false;
-       bool need_pan_reset;
+       bool in_changed     = false;
+       bool out_changed    = false;
+       bool need_pan_reset = false;
 
-       if (_input_maximum >= 0) {
-               nin = min (_input_maximum, (int) nin);
-       }
+       in = min (_input_maximum, in);
 
-       if (_output_maximum >= 0) {
-               nout = min (_output_maximum, (int) nout);
-       }
+       out = min (_output_maximum, out);
 
-       if (nin == _ninputs && nout == _noutputs && !clear) {
+       if (in == n_inputs() && out == n_outputs() && !clear) {
                return 0;
        }
 
        {
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
-               LockMonitor lm (io_lock, __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+               Glib::Mutex::Lock lm (io_lock);
 
                Port* port;
                
-               if (_noutputs == nout) {
-                       need_pan_reset = false;
-               } else {
+               if (n_outputs() != out) {
                        need_pan_reset = true;
                }
                
-               /* remove unused ports */
-               
-               while (_ninputs > nin) {
-                       _session.engine().unregister_port (_inputs.back());
-                       _inputs.pop_back();
-                       _ninputs--;
-                       in_reduced = true;
-                       in_changed = true;
-               }
-               
-               while (_noutputs > nout) {
-                       _session.engine().unregister_port (_outputs.back());
-                       _outputs.pop_back();
-                       _noutputs--;
-                       out_reduced = true;
-                       out_changed = true;
-               }
-               
-               /* create any necessary new ports */
-               
-               while (_ninputs < nin) {
-                       
-                       char buf[64];
+               for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
 
-                       /* Create a new input port */
-                       
-                       if (_input_maximum == 1) {
-                               snprintf (buf, sizeof (buf), _("%s/in"), _name.c_str());
+                       const size_t nin = in.get(*t);
+                       const size_t nout = out.get(*t);
+
+                       Port* output_port = 0;
+                       Port* input_port = 0;
+
+                       /* remove unused output ports */
+                       for (size_t i = n_outputs().get(*t); i > nout; --i) {
+                               output_port = _outputs.port(*t, i-1);
+
+                               assert(output_port);
+                               _outputs.remove(output_port);
+                               _session.engine().unregister_port (*output_port);
+
+                               out_changed = true;
                        }
-                       else {
-                               snprintf (buf, sizeof (buf), _("%s/in %u"), _name.c_str(), find_input_port_hole());
+
+                       /* remove unused input ports */
+                       for (size_t i = n_inputs().get(*t); i > nin; --i) {
+                               input_port = _inputs.port(*t, i-1);
+
+                               assert(input_port);
+                               _inputs.remove(input_port);
+                               _session.engine().unregister_port (*input_port);
+
+                               in_changed = true;
                        }
-                       
-                       try {
-                               if ((port = _session.engine().register_audio_input_port (buf)) == 0) {
-                                       error << string_compose(_("IO: cannot register input port %1"), buf) << endmsg;
-                                       return -1;
+
+                       /* create any necessary new input ports */
+
+                       while (n_inputs().get(*t) < nin) {
+
+                               char buf[64];
+
+                               /* Create a new input port */
+
+                               if (_input_maximum.get(*t) == 1) {
+                                       snprintf (buf, sizeof (buf), _("%s/in"), _name.c_str());
+                               } else {
+                                       snprintf (buf, sizeof (buf), _("%s/in %u"), _name.c_str(), find_input_port_hole());
                                }
-                       }
 
-                       catch (AudioEngine::PortRegistrationFailure& err) {
-                               setup_peak_meters ();
-                               reset_panner ();
-                               /* pass it on */
-                               throw err;
-                       }
-               
-                       _inputs.push_back (port);
-                       ++_ninputs;
-                       in_changed = true;
-               }
+                               try {
+                                       if ((port = _session.engine().register_input_port (*t, buf)) == 0) {
+                                               error << string_compose(_("IO: cannot register input port %1"), buf) << endmsg;
+                                               return -1;
+                                       }
+                               }
+                               
+                               catch (AudioEngine::PortRegistrationFailure& err) {
+                                       setup_peak_meters ();
+                                       reset_panner ();
+                                       /* pass it on */
+                                       throw AudioEngine::PortRegistrationFailure();
+                               }
 
-               /* create any necessary new ports */
-               
-               while (_noutputs < nout) {
-                       
-                       char buf[64];
-                       
-                       /* Create a new output port */
-                       
-                       if (_output_maximum == 1) {
-                               snprintf (buf, sizeof (buf), _("%s/out"), _name.c_str());
-                       } else {
-                               snprintf (buf, sizeof (buf), _("%s/out %u"), _name.c_str(), find_output_port_hole());
+                               _inputs.add (port);
+                               in_changed = true;
                        }
-                       
-                       try { 
-                               if ((port = _session.engine().register_audio_output_port (buf)) == 0) {
-                                       error << string_compose(_("IO: cannot register output port %1"), buf) << endmsg;
-                                       return -1;
+
+                       /* create any necessary new output ports */
+
+                       while (n_outputs().get(*t) < nout) {
+
+                               char buf[64];
+
+                               /* Create a new output port */
+
+                               if (_output_maximum.get(*t) == 1) {
+                                       snprintf (buf, sizeof (buf), _("%s/out"), _name.c_str());
+                               } else {
+                                       snprintf (buf, sizeof (buf), _("%s/out %u"), _name.c_str(), find_output_port_hole());
                                }
+
+                               try { 
+                                       if ((port = _session.engine().register_output_port (*t, buf)) == 0) {
+                                               error << string_compose(_("IO: cannot register output port %1"), buf) << endmsg;
+                                               return -1;
+                                       }
+                               }
+
+                               catch (AudioEngine::PortRegistrationFailure& err) {
+                                       setup_peak_meters ();
+                                       reset_panner ();
+                                       /* pass it on */
+                                       throw AudioEngine::PortRegistrationFailure ();
+                               }
+
+                               _outputs.add (port);
+                               out_changed = true;
                        }
-                       
-                       catch (AudioEngine::PortRegistrationFailure& err) {
-                               setup_peak_meters ();
-                               reset_panner ();
-                               /* pass it on */
-                               throw err;
-                       }
-               
-                       _outputs.push_back (port);
-                       ++_noutputs;
-                       out_changed = true;
                }
                
                if (clear) {
                        
                        /* disconnect all existing ports so that we get a fresh start */
                        
-                       for (vector<Port *>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+                       for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
                                _session.engine().disconnect (*i);
                        }
                        
-                       for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+                       for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
                                _session.engine().disconnect (*i);
                        }
                }
-       }
-
-       if (in_changed || out_changed) {
-               setup_peak_meters ();
-               reset_panner ();
+               
+               if (in_changed || out_changed) {
+                       setup_peak_meters ();
+                       reset_panner ();
+               }
        }
 
        if (out_changed) {
-               sort (_outputs.begin(), _outputs.end(), sort_ports_by_name);
                drop_output_connection ();
                output_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
        }
        
        if (in_changed) {
-               sort (_inputs.begin(), _inputs.end(), sort_ports_by_name);
                drop_input_connection ();
                input_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
        }
 
        if (in_changed || out_changed) {
-               MoreOutputs (max (_noutputs, _ninputs)); /* EMIT SIGNAL */
+               MoreChannels (max (n_outputs(), n_inputs())); /* EMIT SIGNAL */
                _session.set_dirty ();
        }
 
@@ -1197,98 +993,92 @@ IO::ensure_io (uint32_t nin, uint32_t nout, bool clear, void* src)
 }
 
 int
-IO::ensure_inputs (uint32_t n, bool clear, bool lockit, void* src)
+IO::ensure_inputs (ChanCount count, bool clear, bool lockit, void* src)
 {
        bool changed = false;
 
-       if (_input_maximum >= 0) {
-               n = min (_input_maximum, (int) n);
-               
-               if (n == _ninputs && !clear) {
-                       return 0;
-               }
+       count = min (_input_maximum, count);
+
+       if (count == n_inputs() && !clear) {
+               return 0;
        }
-       
+
        if (lockit) {
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
-               changed = ensure_inputs_locked (n, clear, src);
+               BLOCK_PROCESS_CALLBACK ();
+               Glib::Mutex::Lock im (io_lock);
+               changed = ensure_inputs_locked (count, clear, src);
        } else {
-               changed = ensure_inputs_locked (n, clear, src);
+               changed = ensure_inputs_locked (count, clear, src);
        }
 
        if (changed) {
                input_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
                _session.set_dirty ();
        }
-
        return 0;
 }
 
 bool
-IO::ensure_outputs_locked (uint32_t n, bool clear, void* src)
+IO::ensure_outputs_locked (ChanCount count, bool clear, void* src)
 {
-       Port* output_port;
-       bool changed = false;
-       bool reduced = false;
-       bool need_pan_reset;
+       Port* output_port    = 0;
+       bool  changed        = false;
+       bool  need_pan_reset = false;
 
-       if (_noutputs == n) {
-               need_pan_reset = false;
-       } else {
+       if (n_outputs() != count) {
                need_pan_reset = true;
        }
        
-       /* remove unused ports */
-       
-       while (_noutputs > n) {
-               
-               _session.engine().unregister_port (_outputs.back());
-               _outputs.pop_back();
-               _noutputs--;
-               reduced = true;
-               changed = true;
-       }
-       
-       /* create any necessary new ports */
-       
-       while (_noutputs < n) {
-               
-               char buf[64];
-               
-               /* Create a new output port */
-               
-               if (_output_maximum == 1) {
-                       snprintf (buf, sizeof (buf), _("%s/out"), _name.c_str());
-               } else {
-                       snprintf (buf, sizeof (buf), _("%s/out %u"), _name.c_str(), find_output_port_hole());
-               }
-               
-               if ((output_port = _session.engine().register_audio_output_port (buf)) == 0) {
-                       error << string_compose(_("IO: cannot register output port %1"), buf) << endmsg;
-                       return -1;
+       for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
+
+               const size_t n = count.get(*t);
+
+               /* remove unused ports */
+               for (size_t i = n_outputs().get(*t); i > n; --i) {
+                       output_port = _outputs.port(*t, i-1);
+
+                       assert(output_port);
+                       _outputs.remove(output_port);
+                       _session.engine().unregister_port (*output_port);
+
+                       changed = true;
                }
-               
-               _outputs.push_back (output_port);
-               sort (_outputs.begin(), _outputs.end(), sort_ports_by_name);
-               ++_noutputs;
-               changed = true;
-               setup_peak_meters ();
 
-               if (need_pan_reset) {
-                       reset_panner ();
+               /* create any necessary new ports */
+               while (n_outputs().get(*t) < n) {
+
+                       char buf[64];
+
+                       if (_output_maximum.get(*t) == 1) {
+                               snprintf (buf, sizeof (buf), _("%s/out"), _name.c_str());
+                       } else {
+                               snprintf (buf, sizeof (buf), _("%s/out %u"), _name.c_str(), find_output_port_hole());
+                       }
+
+                       if ((output_port = _session.engine().register_output_port (*t, buf)) == 0) {
+                               error << string_compose(_("IO: cannot register output port %1"), buf) << endmsg;
+                               return -1;
+                       }
+
+                       _outputs.add (output_port);
+                       changed = true;
+                       setup_peak_meters ();
+
+                       if (need_pan_reset) {
+                               reset_panner ();
+                       }
                }
        }
        
        if (changed) {
                drop_output_connection ();
-               MoreOutputs (_noutputs); /* EMIT SIGNAL */
+               MoreChannels (n_outputs()); /* EMIT SIGNAL */
                _session.set_dirty ();
        }
        
        if (clear) {
                /* disconnect all existing ports so that we get a fresh start */
-               
-               for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
                        _session.engine().disconnect (*i);
                }
        }
@@ -1297,13 +1087,13 @@ IO::ensure_outputs_locked (uint32_t n, bool clear, void* src)
 }
 
 int
-IO::ensure_outputs (uint32_t n, bool clear, bool lockit, void* src)
+IO::ensure_outputs (ChanCount count, bool clear, bool lockit, void* src)
 {
        bool changed = false;
 
-       if (_output_maximum >= 0) {
-               n = min (_output_maximum, (int) n);
-               if (n == _noutputs && !clear) {
+       if (_output_maximum < ChanCount::INFINITE) {
+               count = min (_output_maximum, count);
+               if (count == n_outputs() && !clear) {
                        return 0;
                }
        }
@@ -1311,10 +1101,11 @@ IO::ensure_outputs (uint32_t n, bool clear, bool lockit, void* src)
        /* XXX caller should hold io_lock, but generally doesn't */
 
        if (lockit) {
-               LockMonitor em (_session.engine().process_lock(), __LINE__, __FILE__);
-               changed = ensure_outputs_locked (n, clear, src);
+               BLOCK_PROCESS_CALLBACK ();
+               Glib::Mutex::Lock im (io_lock);
+               changed = ensure_outputs_locked (count, clear, src);
        } else {
-               changed = ensure_outputs_locked (n, clear, src);
+               changed = ensure_outputs_locked (count, clear, src);
        }
 
        if (changed) {
@@ -1339,7 +1130,7 @@ IO::reset_panner ()
 {
        if (panners_legal) {
                if (!no_panner_reset) {
-                       _panner->reset (_noutputs, pans_required());
+                       _panner->reset (n_outputs().get(DataType::AUDIO), pans_required());
                }
        } else {
                panner_legal_c.disconnect ();
@@ -1350,7 +1141,7 @@ IO::reset_panner ()
 int
 IO::panners_became_legal ()
 {
-       _panner->reset (_noutputs, pans_required());
+       _panner->reset (n_outputs().get(DataType::AUDIO), pans_required());
        _panner->load (); // automation
        panner_legal_c.disconnect ();
        return 0;
@@ -1380,15 +1171,15 @@ XMLNode&
 IO::state (bool full_state)
 {
        XMLNode* node = new XMLNode (state_node_name);
-       char buf[32];
+       char buf[64];
        string str;
        bool need_ins = true;
        bool need_outs = true;
        LocaleGuard lg (X_("POSIX"));
-       LockMonitor lm (io_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (io_lock);
 
        node->add_property("name", _name);
-       snprintf (buf, sizeof(buf), "%" PRIu64, id());
+       id().print (buf, sizeof (buf));
        node->add_property("id", buf);
 
        str = "";
@@ -1404,9 +1195,9 @@ IO::state (bool full_state)
        }
 
        if (need_ins) {
-               for (vector<Port *>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+               for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
                        
-                       const char **connections = (*i)->get_connections();
+                       const char **connections = i->get_connections();
                        
                        if (connections && connections[0]) {
                                str += '{';
@@ -1441,9 +1232,9 @@ IO::state (bool full_state)
        if (need_outs) {
                str = "";
                
-               for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
                        
-                       const char **connections = (*i)->get_connections();
+                       const char **connections = i->get_connections();
                        
                        if (connections && connections[0]) {
                                
@@ -1470,103 +1261,43 @@ IO::state (bool full_state)
        }
 
        node->add_child_nocopy (_panner->state (full_state));
+       node->add_child_nocopy (_gain_control.get_state ());
 
        snprintf (buf, sizeof(buf), "%2.12f", gain());
        node->add_property ("gain", buf);
 
-       snprintf (buf, sizeof(buf)-1, "%d,%d,%d,%d",
-                 _input_minimum,
-                 _input_maximum,
-                 _output_minimum,
-                 _output_maximum);
-
-       node->add_property ("iolimits", buf);
-
-       /* MIDI control */
+       // FIXME: this is NOT sufficient!
+       const int in_min  = (_input_minimum == ChanCount::ZERO) ? -1 : _input_minimum.get(_default_type);
+       const int in_max  = (_input_maximum == ChanCount::INFINITE) ? -1 : _input_maximum.get(_default_type);
+       const int out_min = (_output_minimum == ChanCount::ZERO) ? -1 : _output_minimum.get(_default_type);
+       const int out_max = (_output_maximum == ChanCount::INFINITE) ? -1 : _output_maximum.get(_default_type);
 
-       MIDI::channel_t chn;
-       MIDI::eventType ev;
-       MIDI::byte      additional;
-       XMLNode*        midi_node = 0;
-       XMLNode*        child;
+       snprintf (buf, sizeof(buf)-1, "%d,%d,%d,%d", in_min, in_max, out_min, out_max);
 
-       if (_midi_gain_control.get_control_info (chn, ev, additional)) {
-
-               midi_node = node->add_child ("MIDI");
-
-               child = midi_node->add_child ("gain");
-               set_midi_node_info (child, ev, chn, additional);
-       }
+       node->add_property ("iolimits", buf);
 
        /* automation */
 
        if (full_state) {
+
+               XMLNode* autonode = new XMLNode (X_("Automation"));
+               autonode->add_child_nocopy (get_automation_state());
+               node->add_child_nocopy (*autonode);
+
                snprintf (buf, sizeof (buf), "0x%x", (int) _gain_automation_curve.automation_state());
        } else {
                /* never store anything except Off for automation state in a template */
                snprintf (buf, sizeof (buf), "0x%x", ARDOUR::Off); 
        }
-       node->add_property ("automation-state", buf);
-       snprintf (buf, sizeof (buf), "0x%x", (int) _gain_automation_curve.automation_style());
-       node->add_property ("automation-style", buf);
-
-       /* XXX same for pan etc. */
 
        return *node;
 }
 
-int
-IO::connecting_became_legal ()
-{
-       int ret;
-
-       if (pending_state_node == 0) {
-               fatal << _("IO::connecting_became_legal() called without a pending state node") << endmsg;
-               /*NOTREACHED*/
-               return -1;
-       }
-
-       connection_legal_c.disconnect ();
-
-       ret = make_connections (*pending_state_node);
-
-       if (ports_legal) {
-               delete pending_state_node;
-               pending_state_node = 0;
-       }
-
-       return ret;
-}
-
-int
-IO::ports_became_legal ()
-{
-       int ret;
-
-       if (pending_state_node == 0) {
-               fatal << _("IO::ports_became_legal() called without a pending state node") << endmsg;
-               /*NOTREACHED*/
-               return -1;
-       }
-
-       port_legal_c.disconnect ();
-
-       ret = create_ports (*pending_state_node);
-
-       if (connecting_legal) {
-               delete pending_state_node;
-               pending_state_node = 0;
-       }
-
-       return ret;
-}
-
 int
 IO::set_state (const XMLNode& node)
 {
        const XMLProperty* prop;
        XMLNodeConstIterator iter;
-       XMLNodeList midi_kids;
        LocaleGuard lg (X_("POSIX"));
 
        /* force use of non-localized representation of decimal point,
@@ -1580,19 +1311,25 @@ IO::set_state (const XMLNode& node)
 
        if ((prop = node.property ("name")) != 0) {
                _name = prop->value();
-               _panner->set_name (_name);
+               /* used to set panner name with this, but no more */
        } 
 
        if ((prop = node.property ("id")) != 0) {
-               sscanf (prop->value().c_str(), "%" PRIu64, &_id);
+               _id = prop->value ();
        }
 
+       size_t in_min =  -1;
+       size_t in_max  = -1;
+       size_t out_min = -1;
+       size_t out_max = -1;
+
        if ((prop = node.property ("iolimits")) != 0) {
-               sscanf (prop->value().c_str(), "%d,%d,%d,%d", 
-                       &_input_minimum,
-                       &_input_maximum,
-                       &_output_minimum,
-                       &_output_maximum);
+               sscanf (prop->value().c_str(), "%zd,%zd,%zd,%zd",
+                       &in_min, &in_max, &out_min, &out_max);
+               _input_minimum = ChanCount(_default_type, in_min);
+               _input_maximum = ChanCount(_default_type, in_max);
+               _output_minimum = ChanCount(_default_type, out_min);
+               _output_maximum = ChanCount(_default_type, out_max);
        }
        
        if ((prop = node.property ("gain")) != 0) {
@@ -1600,88 +1337,201 @@ IO::set_state (const XMLNode& node)
                _gain = _desired_gain;
        }
 
+       if ((prop = node.property ("automation-state")) != 0 || (prop = node.property ("automation-style")) != 0) {
+               /* old school automation handling */
+       }
+
        for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
+
                if ((*iter)->name() == "Panner") {
+                       if (_panner == 0) {
+                               _panner = new Panner (_name, _session);
+                       }
                        _panner->set_state (**iter);
                }
+
+               if ((*iter)->name() == X_("Automation")) {
+
+                       set_automation_state (*(*iter)->children().front());
+               }
+
+               if ((*iter)->name() == X_("controllable")) {
+                       if ((prop = (*iter)->property("name")) != 0 && prop->value() == "gaincontrol") {
+                               _gain_control.set_state (**iter);
+                       }
+               }
        }
 
-       midi_kids = node.children ("MIDI");
-       
-       for (iter = midi_kids.begin(); iter != midi_kids.end(); ++iter) {
-       
-               XMLNodeList kids;
-               XMLNodeConstIterator miter;
-               XMLNode*    child;
+       if (ports_legal) {
+
+               if (create_ports (node)) {
+                       return -1;
+               }
 
-               kids = (*iter)->children ();
+       } else {
 
-               for (miter = kids.begin(); miter != kids.end(); ++miter) {
+               port_legal_c = PortsLegal.connect (mem_fun (*this, &IO::ports_became_legal));
+       }
 
-                       child =* miter;
+       if (panners_legal) {
+               reset_panner ();
+       } else {
+               panner_legal_c = PannersLegal.connect (mem_fun (*this, &IO::panners_became_legal));
+       }
 
-                       if (child->name() == "gain") {
-                       
-                               MIDI::eventType ev = MIDI::on; /* initialize to keep gcc happy */
-                               MIDI::byte additional = 0;  /* ditto */
-                               MIDI::channel_t chn = 0;    /* ditto */
+       if (connecting_legal) {
 
-                               if (get_midi_node_info (child, ev, chn, additional)) {
-                                       _midi_gain_control.set_control_type (chn, ev, additional);
-                               } else {
-                                       error << string_compose(_("MIDI gain control specification for %1 is incomplete, so it has been ignored"), _name) << endmsg;
+               if (make_connections (node)) {
+                       return -1;
+               }
+
+       } else {
+               
+               connection_legal_c = ConnectingLegal.connect (mem_fun (*this, &IO::connecting_became_legal));
+       }
+
+       if (!ports_legal || !connecting_legal) {
+               pending_state_node = new XMLNode (node);
+       }
+
+       last_automation_snapshot = 0;
+
+       return 0;
+}
+
+int
+IO::set_automation_state (const XMLNode& node)
+{
+       return _gain_automation_curve.set_state (node);
+}
+
+XMLNode&
+IO::get_automation_state ()
+{
+       return (_gain_automation_curve.get_state ());
+}
+
+int
+IO::load_automation (string path)
+{
+       string fullpath;
+       ifstream in;
+       char line[128];
+       uint32_t linecnt = 0;
+       float version;
+       LocaleGuard lg (X_("POSIX"));
+
+       fullpath = _session.automation_dir();
+       fullpath += path;
+
+       in.open (fullpath.c_str());
+
+       if (!in) {
+               fullpath = _session.automation_dir();
+               fullpath += _session.snap_name();
+               fullpath += '-';
+               fullpath += path;
+
+               in.open (fullpath.c_str());
+
+               if (!in) {
+                       error << string_compose(_("%1: cannot open automation event file \"%2\""), _name, fullpath) << endmsg;
+                       return -1;
+               }
+       }
+
+       clear_automation ();
+
+       while (in.getline (line, sizeof(line), '\n')) {
+               char type;
+               nframes_t when;
+               double value;
+
+               if (++linecnt == 1) {
+                       if (memcmp (line, "version", 7) == 0) {
+                               if (sscanf (line, "version %f", &version) != 1) {
+                                       error << string_compose(_("badly formed version number in automation event file \"%1\""), path) << endmsg;
+                                       return -1;
                                }
+                       } else {
+                               error << string_compose(_("no version information in automation event file \"%1\""), path) << endmsg;
+                               return -1;
                        }
+
+                       continue;
+               }
+
+               if (sscanf (line, "%c %" PRIu32 " %lf", &type, &when, &value) != 3) {
+                       warning << string_compose(_("badly formatted automation event record at line %1 of %2 (ignored)"), linecnt, path) << endmsg;
+                       continue;
+               }
+
+               switch (type) {
+               case 'g':
+                       _gain_automation_curve.fast_simple_add (when, value);
+                       break;
+
+               case 's':
+                       break;
+
+               case 'm':
+                       break;
+
+               case 'p':
+                       /* older (pre-1.0) versions of ardour used this */
+                       break;
+
+               default:
+                       warning << _("dubious automation event found (and ignored)") << endmsg;
                }
        }
-                       
-       if ((prop = node.property ("automation-state")) != 0) {
 
-               long int x;
-               x = strtol (prop->value().c_str(), 0, 16);
-               set_gain_automation_state (AutoState (x));
-       }
+       return 0;
+}
 
-       if ((prop = node.property ("automation-style")) != 0) {
+int
+IO::connecting_became_legal ()
+{
+       int ret;
 
-              long int x;
-               x = strtol (prop->value().c_str(), 0, 16);
-               set_gain_automation_style (AutoStyle (x));
+       if (pending_state_node == 0) {
+               fatal << _("IO::connecting_became_legal() called without a pending state node") << endmsg;
+               /*NOTREACHED*/
+               return -1;
        }
-       
-       if (ports_legal) {
 
-               if (create_ports (node)) {
-                       return -1;
-               }
+       connection_legal_c.disconnect ();
 
-       } else {
+       ret = make_connections (*pending_state_node);
 
-               port_legal_c = PortsLegal.connect (mem_fun (*this, &IO::ports_became_legal));
+       if (ports_legal) {
+               delete pending_state_node;
+               pending_state_node = 0;
        }
 
-       if (panners_legal) {
-               reset_panner ();
-       } else {
-               panner_legal_c = PannersLegal.connect (mem_fun (*this, &IO::panners_became_legal));
-       }
+       return ret;
+}
+int
+IO::ports_became_legal ()
+{
+       int ret;
 
-       if (connecting_legal) {
+       if (pending_state_node == 0) {
+               fatal << _("IO::ports_became_legal() called without a pending state node") << endmsg;
+               /*NOTREACHED*/
+               return -1;
+       }
 
-               if (make_connections (node)) {
-                       return -1;
-               }
+       port_legal_c.disconnect ();
 
-       } else {
-               
-               connection_legal_c = ConnectingLegal.connect (mem_fun (*this, &IO::connecting_became_legal));
-       }
+       ret = create_ports (*pending_state_node);
 
-       if (!ports_legal || !connecting_legal) {
-               pending_state_node = new XMLNode (node);
+       if (connecting_legal) {
+               delete pending_state_node;
+               pending_state_node = 0;
        }
 
-       return 0;
+       return ret;
 }
 
 int
@@ -1739,7 +1589,8 @@ IO::create_ports (const XMLNode& node)
 
        no_panner_reset = true;
 
-       if (ensure_io (num_inputs, num_outputs, true, this)) {
+       // FIXME: audio-only
+       if (ensure_io (ChanCount(DataType::AUDIO, num_inputs), ChanCount(DataType::AUDIO, num_outputs), true, this)) {
                error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
                return -1;
        }
@@ -1752,50 +1603,6 @@ IO::create_ports (const XMLNode& node)
        return 0;
 }
 
-bool
-IO::get_midi_node_info (XMLNode * node, MIDI::eventType & ev, MIDI::channel_t & chan, MIDI::byte & additional)
-{
-       bool ok = true;
-       const XMLProperty* prop;
-       int xx;
-
-       if ((prop = node->property ("event")) != 0) {
-               sscanf (prop->value().c_str(), "0x%x", &xx);
-               ev = (MIDI::eventType) xx;
-       } else {
-               ok = false;
-       }
-
-       if (ok && ((prop = node->property ("channel")) != 0)) {
-               sscanf (prop->value().c_str(), "%d", &xx);
-               chan = (MIDI::channel_t) xx;
-       } else {
-               ok = false;
-       }
-
-       if (ok && ((prop = node->property ("additional")) != 0)) {
-               sscanf (prop->value().c_str(), "0x%x", &xx);
-               additional = (MIDI::byte) xx;
-       }
-
-       return ok;
-}
-
-bool
-IO::set_midi_node_info (XMLNode * node, MIDI::eventType ev, MIDI::channel_t chan, MIDI::byte additional)
-{
-       char buf[32];
-
-       snprintf (buf, sizeof(buf), "0x%x", ev);
-       node->add_property ("event", buf);
-       snprintf (buf, sizeof(buf), "%d", chan);
-       node->add_property ("channel", buf);
-       snprintf (buf, sizeof(buf), "0x%x", additional);
-       node->add_property ("additional", buf);
-
-       return true;
-}
-
 
 int
 IO::make_connections (const XMLNode& node)
@@ -1867,7 +1674,8 @@ IO::set_inputs (const string& str)
                return 0;
        }
 
-       if (ensure_inputs (nports, true, true, this)) {
+       // FIXME: audio-only
+       if (ensure_inputs (ChanCount(DataType::AUDIO, nports), true, true, this)) {
                return -1;
        }
 
@@ -1917,7 +1725,8 @@ IO::set_outputs (const string& str)
                return 0;
        }
 
-       if (ensure_outputs (nports, true, true, this)) {
+       // FIXME: audio-only
+       if (ensure_outputs (ChanCount(DataType::AUDIO, nports), true, true, this)) {
                return -1;
        }
 
@@ -2009,16 +1818,22 @@ IO::set_name (string name, void* src)
                return 0;
        }
 
-       for (vector<Port *>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
-               string current_name = (*i)->short_name();
+       /* replace all colons in the name. i wish we didn't have to do this */
+
+       if (replace_all (name, ":", "-")) {
+               warning << _("you cannot use colons to name objects with I/O connections") << endmsg;
+       }
+
+       for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+               string current_name = i->short_name();
                current_name.replace (current_name.find (_name), _name.length(), name);
-               (*i)->set_name (current_name);
+               i->set_name (current_name);
        }
 
-       for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
-               string current_name = (*i)->short_name();
+       for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               string current_name = i->short_name();
                current_name.replace (current_name.find (_name), _name.length(), name);
-               (*i)->set_name (current_name);
+               i->set_name (current_name);
        }
 
        _name = name;
@@ -2028,51 +1843,51 @@ IO::set_name (string name, void* src)
 }
 
 void
-IO::set_input_minimum (int n)
+IO::set_input_minimum (ChanCount n)
 {
        _input_minimum = n;
 }
 
 void
-IO::set_input_maximum (int n)
+IO::set_input_maximum (ChanCount n)
 {
        _input_maximum = n;
 }
 
 void
-IO::set_output_minimum (int n)
+IO::set_output_minimum (ChanCount n)
 {
        _output_minimum = n;
 }
 
 void
-IO::set_output_maximum (int n)
+IO::set_output_maximum (ChanCount n)
 {
        _output_maximum = n;
 }
 
 void
-IO::set_port_latency (jack_nframes_t nframes)
+IO::set_port_latency (nframes_t nframes)
 {
-       LockMonitor lm (io_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (io_lock);
 
-       for (vector<Port *>::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
-               (*i)->set_latency (nframes);
+       for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               i->set_latency (nframes);
        }
 }
 
-jack_nframes_t
+nframes_t
 IO::output_latency () const
 {
-       jack_nframes_t max_latency;
-       jack_nframes_t latency;
+       nframes_t max_latency;
+       nframes_t latency;
 
        max_latency = 0;
 
        /* io lock not taken - must be protected by other means */
 
-       for (vector<Port *>::const_iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
-               if ((latency = _session.engine().get_port_total_latency (*(*i))) > max_latency) {
+       for (PortSet::const_iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
+               if ((latency = _session.engine().get_port_total_latency (*i)) > max_latency) {
                        max_latency = latency;
                }
        }
@@ -2080,18 +1895,18 @@ IO::output_latency () const
        return max_latency;
 }
 
-jack_nframes_t
+nframes_t
 IO::input_latency () const
 {
-       jack_nframes_t max_latency;
-       jack_nframes_t latency;
+       nframes_t max_latency;
+       nframes_t latency;
 
        max_latency = 0;
 
        /* io lock not taken - must be protected by other means */
 
-       for (vector<Port *>::const_iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
-               if ((latency = _session.engine().get_port_total_latency (*(*i))) > max_latency) {
+       for (PortSet::const_iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
+               if ((latency = _session.engine().get_port_total_latency (*i)) > max_latency) {
                        max_latency = latency;
                }
        }
@@ -2105,14 +1920,15 @@ IO::use_input_connection (Connection& c, void* src)
        uint32_t limit;
 
        {
-               LockMonitor lm (_session.engine().process_lock(), __LINE__, __FILE__);
-               LockMonitor lm2 (io_lock, __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+               Glib::Mutex::Lock lm2 (io_lock);
                
                limit = c.nports();
                
                drop_input_connection ();
                
-               if (ensure_inputs (limit, false, false, src)) {
+               // FIXME connections only work for audio-only
+               if (ensure_inputs (ChanCount(DataType::AUDIO, limit), false, false, src)) {
                        return -1;
                }
 
@@ -2125,13 +1941,13 @@ IO::use_input_connection (Connection& c, void* src)
                        
                        for (Connection::PortList::const_iterator i = pl.begin(); i != pl.end(); ++i) {
                                
-                               if (!_inputs[n]->connected_to ((*i))) {
+                               if (!_inputs.port(n)->connected_to ((*i))) {
                                        
                                        /* clear any existing connections */
                                        
-                                       _session.engine().disconnect (_inputs[n]);
+                                       _session.engine().disconnect (*_inputs.port(n));
                                        
-                               } else if (_inputs[n]->connected() > 1) {
+                               } else if (_inputs.port(n)->connected() > 1) {
                                        
                                        /* OK, it is connected to the port we want,
                                           but its also connected to other ports.
@@ -2142,7 +1958,7 @@ IO::use_input_connection (Connection& c, void* src)
                                           the one we want.
                                        */
                                        
-                                       _session.engine().disconnect (_inputs[n]);
+                                       _session.engine().disconnect (*_inputs.port(n));
                                        
                                }
                        }
@@ -2155,9 +1971,9 @@ IO::use_input_connection (Connection& c, void* src)
                        
                        for (Connection::PortList::const_iterator i = pl.begin(); i != pl.end(); ++i) {
                                
-                               if (!_inputs[n]->connected_to ((*i))) {
+                               if (!_inputs.port(n)->connected_to ((*i))) {
                                        
-                                       if (_session.engine().connect (*i, _inputs[n]->name())) {
+                                       if (_session.engine().connect (*i, _inputs.port(n)->name())) {
                                                return -1;
                                        }
                                }
@@ -2183,14 +1999,15 @@ IO::use_output_connection (Connection& c, void* src)
        uint32_t limit; 
 
        {
-               LockMonitor lm (_session.engine().process_lock(), __LINE__, __FILE__);
-               LockMonitor lm2 (io_lock, __LINE__, __FILE__);
+               BLOCK_PROCESS_CALLBACK ();
+               Glib::Mutex::Lock lm2 (io_lock);
 
                limit = c.nports();
                        
                drop_output_connection ();
 
-               if (ensure_outputs (limit, false, false, src)) {
+               // FIXME: audio-only
+               if (ensure_outputs (ChanCount(DataType::AUDIO, limit), false, false, src)) {
                        return -1;
                }
 
@@ -2204,13 +2021,13 @@ IO::use_output_connection (Connection& c, void* src)
                                
                        for (Connection::PortList::const_iterator i = pl.begin(); i != pl.end(); ++i) {
                                        
-                               if (!_outputs[n]->connected_to ((*i))) {
+                               if (!_outputs.port(n)->connected_to ((*i))) {
 
                                        /* clear any existing connections */
 
-                                       _session.engine().disconnect (_outputs[n]);
+                                       _session.engine().disconnect (*_outputs.port(n));
 
-                               } else if (_outputs[n]->connected() > 1) {
+                               } else if (_outputs.port(n)->connected() > 1) {
 
                                        /* OK, it is connected to the port we want,
                                           but its also connected to other ports.
@@ -2221,7 +2038,7 @@ IO::use_output_connection (Connection& c, void* src)
                                           the one we want.
                                        */
                                                
-                                       _session.engine().disconnect (_outputs[n]);
+                                       _session.engine().disconnect (*_outputs.port(n));
                                }
                        }
                }
@@ -2234,9 +2051,9 @@ IO::use_output_connection (Connection& c, void* src)
                                
                        for (Connection::PortList::const_iterator i = pl.begin(); i != pl.end(); ++i) {
                                        
-                               if (!_outputs[n]->connected_to ((*i))) {
+                               if (!_outputs.port(n)->connected_to ((*i))) {
                                                
-                                       if (_session.engine().connect (_outputs[n]->name(), *i)) {
+                                       if (_session.engine().connect (_outputs.port(n)->name(), *i)) {
                                                return -1;
                                        }
                                }
@@ -2322,264 +2139,53 @@ IO::output_connection_configuration_changed ()
        use_output_connection (*_output_connection, this);
 }
 
-IO::MIDIGainControl::MIDIGainControl (IO& i, MIDI::Port* port)
-       : MIDI::Controllable (port, 0), io (i), setting(false)
-{
-       midi_to_gain = 0;
-       gain_to_midi = 0;
-       setting = false;
-       last_written = 0; /* XXX need a good out-of-bound-value */
-}
-
-void
-IO::MIDIGainControl::set_value (float val)
-{
-       if (midi_to_gain == 0) return;
-       
-       setting = true;
-       io.set_gain (midi_to_gain (val), this);
-       setting = false;
-}
-
 void
-IO::MIDIGainControl::send_feedback (gain_t gain)
-{
-       if (!setting && get_midi_feedback() && gain_to_midi) {
-               MIDI::byte val = (MIDI::byte) (gain_to_midi (gain) * 127.0);
-               MIDI::channel_t ch = 0;
-               MIDI::eventType ev = MIDI::none;
-               MIDI::byte additional = 0;
-               MIDI::EventTwoBytes data;
-           
-               if (get_control_info (ch, ev, additional)) {
-                       data.controller_number = additional;
-                       data.value = val;
-                       last_written = val;
-                       
-                       io._session.send_midi_message (get_port(), ev, ch, data);
-               }
-               //send_midi_feedback (gain_to_midi (gain));
-       }
-}
-
-MIDI::byte*
-IO::MIDIGainControl::write_feedback (MIDI::byte* buf, int32_t& bufsize, gain_t val, bool force)
+IO::GainControllable::set_value (float val)
 {
-       if (get_midi_feedback() && gain_to_midi && bufsize > 2) {
-               MIDI::channel_t ch = 0;
-               MIDI::eventType ev = MIDI::none;
-               MIDI::byte additional = 0;
-               MIDI::byte gm;
-
-               if (get_control_info (ch, ev, additional)) {
-                       gm = (MIDI::byte) (gain_to_midi (val) * 127.0);
-                       
-                       if (gm != last_written) {
-                               *buf++ = (0xF0 & ev) | (0xF & ch);
-                               *buf++ = additional; /* controller number */
-                               *buf++ = gm;
-                               last_written = gm;
-                               bufsize -= 3;
-                       }
-               }
-       }
-       
-       return buf;
+       io.set_gain (direct_control_to_gain (val), this);
 }
 
-void
-IO::reset_peak_meters ()
+float
+IO::GainControllable::get_value (void) const
 {
-       uint32_t limit = max (_ninputs, _noutputs);
-
-       for (uint32_t i = 0; i < limit; ++i) {
-               _peak_power[i] = 0;
-       }
+       return direct_gain_to_control (io.effective_gain());
 }
 
 void
-IO::setup_peak_meters ()
-{
-       uint32_t limit = max (_ninputs, _noutputs);
-
-       while (_peak_power.size() < limit) {
-               _peak_power.push_back (0);
-               _stored_peak_power.push_back (0);
-       }
-}
-
-UndoAction
-IO::get_memento() const
-{
-  return sigc::bind (mem_fun (*(const_cast<IO *>(this)), &StateManager::use_state), _current_state_id);
-}
-
-Change
-IO::restore_state (StateManager::State& state)
-{
-       return Change (0);
-}
-
-StateManager::State*
-IO::state_factory (std::string why) const
+IO::setup_peak_meters()
 {
-       StateManager::State* state = new StateManager::State (why);
-       return state;
+       _meter->setup(std::max(_inputs.count(), _outputs.count()));
 }
 
-void
-IO::send_state_changed ()
-{
-       return;
-}
+/**
+    Update the peak meters.
 
+    The meter signal lock is taken to prevent modification of the 
+    Meter signal while updating the meters, taking the meter signal
+    lock prior to taking the io_lock ensures that all IO will remain 
+    valid while metering.
+*/   
 void
-IO::grab_peak_power ()
+IO::update_meters()
 {
-       LockMonitor lm (io_lock, __LINE__, __FILE__);
-
-       uint32_t limit = max (_ninputs, _noutputs);
-
-       for (uint32_t n = 0; n < limit; ++n) {
-               /* XXX should we use atomic exchange here ? */
-               _stored_peak_power[n] = _peak_power[n];
-               _peak_power[n] = 0;
-       }
+    Glib::Mutex::Lock guard (m_meter_signal_lock);
+    
+    Meter(); /* EMIT SIGNAL */
 }
 
 void
-IO::reset_midi_control (MIDI::Port* port, bool on)
-{
-       MIDI::channel_t chn;
-       MIDI::eventType ev;
-       MIDI::byte extra;
-
-       _midi_gain_control.get_control_info (chn, ev, extra);
-       if (!on) {
-               chn = -1;
-       }
-       _midi_gain_control.midi_rebind (port, chn);
-       
-       _panner->reset_midi_control (port, on);
-}
-
-
-int
-IO::save_automation (const string& path)
+IO::meter ()
 {
-       string fullpath;
-       ofstream out;
-
-       fullpath = _session.automation_dir();
-       fullpath += path;
-
-       out.open (fullpath.c_str());
-
-       if (!out) {
-               error << string_compose(_("%1: could not open automation event file \"%2\""), _name, fullpath) << endmsg;
-               return -1;
-       }
-
-       out << X_("version ") << current_automation_version_number << endl;
-
-       /* XXX use apply_to_points to get thread safety */
+       // FIXME: Ugly.  Meter should manage the lock, if it's necessary
        
-       for (AutomationList::iterator i = _gain_automation_curve.begin(); i != _gain_automation_curve.end(); ++i) {
-               out << "g " << (jack_nframes_t) floor ((*i)->when) << ' ' << (*i)->value << endl;
-       }
-
-       _panner->save ();
-
-       return 0;
+       Glib::Mutex::Lock lm (io_lock); // READER: meter thread.
+       _meter->meter();
 }
 
-int
-IO::load_automation (const string& path)
-{
-       string fullpath;
-       ifstream in;
-       char line[128];
-       uint32_t linecnt = 0;
-       float version;
-       LocaleGuard lg (X_("POSIX"));
-
-       fullpath = _session.automation_dir();
-       fullpath += path;
-
-       in.open (fullpath.c_str());
-
-       if (!in) {
-               fullpath = _session.automation_dir();
-               fullpath += _session.snap_name();
-               fullpath += '-';
-               fullpath += path;
-               in.open (fullpath.c_str());
-               if (!in) {
-                               error << string_compose(_("%1: cannot open automation event file \"%2\""), _name, fullpath) << endmsg;
-                               return -1;
-               }
-       }
-
-       clear_automation ();
-
-       while (in.getline (line, sizeof(line), '\n')) {
-               char type;
-               jack_nframes_t when;
-               double value;
-
-               if (++linecnt == 1) {
-                       if (memcmp (line, "version", 7) == 0) {
-                               if (sscanf (line, "version %f", &version) != 1) {
-                                       error << string_compose(_("badly formed version number in automation event file \"%1\""), path) << endmsg;
-                                       return -1;
-                               }
-                       } else {
-                               error << string_compose(_("no version information in automation event file \"%1\""), path) << endmsg;
-                               return -1;
-                       }
-
-                       if (version != current_automation_version_number) {
-                               error << string_compose(_("mismatched automation event file version (%1)"), version) << endmsg;
-                               return -1;
-                       }
-
-                       continue;
-               }
-
-               if (sscanf (line, "%c %" PRIu32 " %lf", &type, &when, &value) != 3) {
-                       warning << string_compose(_("badly formatted automation event record at line %1 of %2 (ignored)"), linecnt, path) << endmsg;
-                       continue;
-               }
-
-               switch (type) {
-               case 'g':
-                       _gain_automation_curve.add (when, value, true);
-                       break;
-
-               case 's':
-                       break;
-
-               case 'm':
-                       break;
-
-               case 'p':
-                       /* older (pre-1.0) versions of ardour used this */
-                       break;
-
-               default:
-                       warning << _("dubious automation event found (and ignored)") << endmsg;
-               }
-       }
-
-       _gain_automation_curve.save_state (_("loaded from disk"));
-
-       return 0;
-}
-       
 void
 IO::clear_automation ()
 {
-       LockMonitor lm (automation_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (automation_lock);
        _gain_automation_curve.clear ();
        _panner->clear_automation ();
 }
@@ -2590,7 +2196,7 @@ IO::set_gain_automation_state (AutoState state)
        bool changed = false;
 
        {
-               LockMonitor lm (automation_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (automation_lock);
 
                if (state != _gain_automation_curve.automation_state()) {
                        changed = true;
@@ -2615,7 +2221,7 @@ IO::set_gain_automation_style (AutoStyle style)
        bool changed = false;
 
        {
-               LockMonitor lm (automation_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (automation_lock);
 
                if (style != _gain_automation_curve.automation_style()) {
                        changed = true;
@@ -2643,7 +2249,7 @@ IO::set_gain (gain_t val, void *src)
        if (val>1.99526231f) val=1.99526231f;
 
        {
-               LockMonitor dm (declick_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock dm (declick_lock);
                _desired_gain = val;
        }
 
@@ -2653,10 +2259,7 @@ IO::set_gain (gain_t val, void *src)
        }
 
        gain_changed (src);
-
-       if (_session.get_midi_feedback()) {
-               _midi_gain_control.send_feedback (_desired_gain);
-       }
+       _gain_control.Changed (); /* EMIT SIGNAL */
        
        if (_session.transport_stopped() && src != 0 && src != this && gain_automation_recording()) {
                _gain_automation_curve.add (_session.transport_frame(), val);
@@ -2666,30 +2269,6 @@ IO::set_gain (gain_t val, void *src)
        _session.set_dirty();
 }
 
-void
-IO::send_all_midi_feedback ()
-{
-       if (_session.get_midi_feedback()) {
-               _midi_gain_control.send_feedback (_effective_gain);
-
-               // panners
-               _panner->send_all_midi_feedback();
-       }
-}
-
-MIDI::byte*
-IO::write_midi_feedback (MIDI::byte* buf, int32_t& bufsize)
-{
-       if (_session.get_midi_feedback()) {
-               if (gain_automation_playback ()) {
-                       buf = _midi_gain_control.write_feedback (buf, bufsize, _effective_gain);
-               }
-               buf = _panner->write_midi_feedback (buf, bufsize);
-       }
-
-       return buf;
-}
-
 void
 IO::start_gain_touch ()
 {
@@ -2720,7 +2299,7 @@ IO::end_pan_touch (uint32_t which)
 }
 
 void
-IO::automation_snapshot (jack_nframes_t now)
+IO::automation_snapshot (nframes_t now)
 {
        if (last_automation_snapshot > now || (now - last_automation_snapshot) > _automation_interval) {
 
@@ -2735,16 +2314,12 @@ IO::automation_snapshot (jack_nframes_t now)
 }
 
 void
-IO::transport_stopped (jack_nframes_t frame)
+IO::transport_stopped (nframes_t frame)
 {
        _gain_automation_curve.reposition_for_rt_add (frame);
 
        if (_gain_automation_curve.automation_state() != Off) {
                
-               if (gain_automation_recording()) {
-                       _gain_automation_curve.save_state (_("automation write/touch"));
-               }
-
                /* the src=0 condition is a special signal to not propagate 
                   automation gain changes into the mix group when locating.
                */
@@ -2768,12 +2343,12 @@ IO::find_input_port_hole ()
 
        for (n = 1; n < UINT_MAX; ++n) {
                char buf[jack_port_name_size()];
-               vector<Port*>::iterator i;
+               PortSet::iterator i = _inputs.begin();
 
                snprintf (buf, jack_port_name_size(), _("%s/in %u"), _name.c_str(), n);
 
-               for (i = _inputs.begin(); i != _inputs.end(); ++i) {
-                       if ((*i)->short_name() == buf) {
+               for ( ; i != _inputs.end(); ++i) {
+                       if (i->short_name() == buf) {
                                break;
                        }
                }
@@ -2798,12 +2373,12 @@ IO::find_output_port_hole ()
 
        for (n = 1; n < UINT_MAX; ++n) {
                char buf[jack_port_name_size()];
-               vector<Port*>::iterator i;
+               PortSet::iterator i = _outputs.begin();
 
                snprintf (buf, jack_port_name_size(), _("%s/out %u"), _name.c_str(), n);
 
-               for (i = _outputs.begin(); i != _outputs.end(); ++i) {
-                       if ((*i)->short_name() == buf) {
+               for ( ; i != _outputs.end(); ++i) {
+                       if (i->short_name() == buf) {
                                break;
                        }
                }
@@ -2815,3 +2390,37 @@ IO::find_output_port_hole ()
        
        return n;
 }
+
+AudioPort*
+IO::audio_input(uint32_t n) const
+{
+       return dynamic_cast<AudioPort*>(input(n));
+}
+
+AudioPort*
+IO::audio_output(uint32_t n) const
+{
+       return dynamic_cast<AudioPort*>(output(n));
+}
+
+MidiPort*
+IO::midi_input(uint32_t n) const
+{
+       return dynamic_cast<MidiPort*>(input(n));
+}
+
+MidiPort*
+IO::midi_output(uint32_t n) const
+{
+       return dynamic_cast<MidiPort*>(output(n));
+}
+
+void
+IO::set_phase_invert (bool yn, void *src)
+{
+       if (_phase_invert != yn) {
+               _phase_invert = yn;
+       }
+       //  phase_invert_changed (src); /* EMIT SIGNAL */
+}
+