Remove unused per-port buffer offset
[ardour.git] / libs / ardour / io.cc
index f49692a910b9fd4e1449d87fdd1841d8db5d3482..7eb85477d705a122f814afabfe5dd6ac0af21103 100644 (file)
     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
-#include <fstream>
 #include <algorithm>
+#include <cmath>
+#include <vector>
+
 #include <unistd.h>
 #include <locale.h>
 #include <errno.h>
 
-#include <sigc++/bind.h>
-
 #include <glibmm.h>
-#include <glibmm/thread.h>
+#include <glibmm/threads.h>
 
 #include "pbd/xml++.h"
 #include "pbd/replace_all.h"
 #include "pbd/unknown_type.h"
 #include "pbd/enumwriter.h"
+#include "pbd/locale_guard.h"
+#include "pbd/types_convert.h"
 
 #include "ardour/audioengine.h"
 #include "ardour/buffer.h"
+#include "ardour/buffer_set.h"
+#include "ardour/debug.h"
 #include "ardour/io.h"
-#include "ardour/route.h"
 #include "ardour/port.h"
-#include "ardour/audio_port.h"
-#include "ardour/midi_port.h"
+#include "ardour/profile.h"
+#include "ardour/route.h"
 #include "ardour/session.h"
-#include "ardour/cycle_timer.h"
-#include "ardour/panner.h"
-#include "ardour/buffer_set.h"
-#include "ardour/meter.h"
-#include "ardour/amp.h"
+#include "ardour/types_convert.h"
 #include "ardour/user_bundle.h"
 
-#include "i18n.h"
-
-#include <cmath>
-
-/*
-  A bug in OS X's cmath that causes isnan() and isinf() to be
-  "undeclared". the following works around that
-*/
+#include "pbd/i18n.h"
 
-#if defined(__APPLE__) && defined(__MACH__)
-extern "C" int isnan (double);
-extern "C" int isinf (double);
-#endif
-
-#define BLOCK_PROCESS_CALLBACK() Glib::Mutex::Lock em (_session.engine().process_lock())
+#define BLOCK_PROCESS_CALLBACK() Glib::Threads::Mutex::Lock em (AudioEngine::instance()->process_lock())
 
 using namespace std;
 using namespace ARDOUR;
@@ -69,233 +56,238 @@ using namespace PBD;
 
 const string                 IO::state_node_name = "IO";
 bool                         IO::connecting_legal = false;
-sigc::signal<int>            IO::ConnectingLegal;
-sigc::signal<void,ChanCount> IO::PortCountChanged;
+PBD::Signal0<int>            IO::ConnectingLegal;
+PBD::Signal1<void,ChanCount> IO::PortCountChanged;
 
 /** @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, const string& name, Direction dir, DataType default_type)
+IO::IO (Session& s, const string& name, Direction dir, DataType default_type, bool sendish)
        : SessionObject (s, name)
        , _direction (dir)
        , _default_type (default_type)
+       , _sendish (sendish)
 {
        _active = true;
+       Port::PostDisconnect.connect_same_thread (*this, boost::bind (&IO::disconnect_check, this, _1, _2));
        pending_state_node = 0;
-       setup_bundles ();
+       setup_bundle ();
 }
 
-IO::IO (Session& s, const XMLNode& node, DataType dt)
+IO::IO (Session& s, const XMLNode& node, DataType dt, bool sendish)
        : SessionObject(s, "unnamed io")
        , _direction (Input)
        , _default_type (dt)
+       , _sendish (sendish)
 {
        _active = true;
        pending_state_node = 0;
+       Port::PostDisconnect.connect_same_thread (*this, boost::bind (&IO::disconnect_check, this, _1, _2));
 
-       set_state (node);
-       setup_bundles ();
+       set_state (node, Stateful::loading_state_version);
+       setup_bundle ();
 }
 
 IO::~IO ()
 {
-       Glib::Mutex::Lock lm (io_lock);
+       Glib::Threads::Mutex::Lock lm (io_lock);
+
+       DEBUG_TRACE (DEBUG::Ports, string_compose ("IO %1 unregisters %2 ports\n", name(), _ports.num_ports()));
 
        BLOCK_PROCESS_CALLBACK ();
 
        for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
                _session.engine().unregister_port (*i);
        }
+       delete pending_state_node; pending_state_node = 0;
 }
 
 void
-IO::silence (nframes_t nframes)
+IO::disconnect_check (boost::shared_ptr<Port> a, boost::shared_ptr<Port> b)
 {
-       /* io_lock, not taken: function must be called from Session::process() calltree */
-
-       for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
-               i->get_buffer(nframes).silence (nframes);
+       if (_session.state_of_the_state () & Session::Deletion) {
+               return;
        }
-}
+       /* this could be called from within our own ::disconnect() method(s)
+          or from somewhere that operates directly on a port. so, we don't
+          know for sure if we can take this lock or not. if we fail,
+          we assume that its safely locked by our own ::disconnect().
+       */
 
-void
-IO::check_bundles_connected ()
-{
-       check_bundles (_bundles_connected, ports());
+       Glib::Threads::Mutex::Lock tm (io_lock, Glib::Threads::TRY_LOCK);
+
+       if (tm.locked()) {
+               /* we took the lock, so we cannot be here from inside
+                * ::disconnect()
+                */
+               if (_ports.contains (a) || _ports.contains (b)) {
+                       changed (IOChange (IOChange::ConnectionsChanged), this); /* EMIT SIGNAL */
+               }
+       } else {
+               /* we didn't get the lock, so assume that we're inside
+                * ::disconnect(), and it will call changed() appropriately.
+                */
+       }
 }
 
 void
-IO::check_bundles (std::vector<UserBundleInfo>& list, const PortSet& ports)
+IO::silence (samplecnt_t nframes)
 {
-       std::vector<UserBundleInfo> new_list;
-
-       for (std::vector<UserBundleInfo>::iterator i = list.begin(); i != list.end(); ++i) {
-
-               uint32_t const N = i->bundle->nchannels ();
-
-               if (_ports.num_ports (default_type()) < N) {
-                       continue;
-               }
-
-               bool ok = true;
-
-               for (uint32_t j = 0; j < N; ++j) {
-                       /* Every port on bundle channel j must be connected to our input j */
-                       Bundle::PortList const pl = i->bundle->channel_ports (j);
-                       for (uint32_t k = 0; k < pl.size(); ++k) {
-                               if (ports.port(j)->connected_to (pl[k]) == false) {
-                                       ok = false;
-                                       break;
-                               }
-                       }
-
-                       if (ok == false) {
-                               break;
-                       }
-               }
+       /* io_lock, not taken: function must be called from Session::process() calltree */
 
-               if (ok) {
-                       new_list.push_back (*i);
-               } else {
-                       i->changed.disconnect ();
+       for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
+               if (i->port_handle ()) {
+                       i->get_buffer(nframes).silence (nframes);
                }
        }
-
-       list = new_list;
 }
 
-
 int
-IO::disconnect (Port* our_port, string other_port, void* src)
+IO::disconnect (boost::shared_ptr<Port> our_port, string other_port, void* src)
 {
        if (other_port.length() == 0 || our_port == 0) {
                return 0;
        }
 
        {
-               BLOCK_PROCESS_CALLBACK ();
-
-               {
-                       Glib::Mutex::Lock lm (io_lock);
+               Glib::Threads::Mutex::Lock lm (io_lock);
 
-                       /* check that our_port is really one of ours */
+               /* check that our_port is really one of ours */
 
-                       if ( ! _ports.contains(our_port)) {
-                               return -1;
-                       }
-
-                       /* disconnect it from the source */
+               if ( ! _ports.contains(our_port)) {
+                       return -1;
+               }
 
-                       if (our_port->disconnect (other_port)) {
-                               error << string_compose(_("IO: cannot disconnect port %1 from %2"), our_port->name(), other_port) << endmsg;
-                               return -1;
-                       }
+               /* disconnect it from the source */
 
-                       check_bundles_connected ();
+               if (our_port->disconnect (other_port)) {
+                       error << string_compose(_("IO: cannot disconnect port %1 from %2"), our_port->name(), other_port) << endmsg;
+                       return -1;
                }
        }
 
-       changed (ConnectionsChanged, src); /* EMIT SIGNAL */
+       changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
+
        _session.set_dirty ();
 
        return 0;
 }
 
 int
-IO::connect (Port* our_port, string other_port, void* src)
+IO::connect (boost::shared_ptr<Port> our_port, string other_port, void* src)
 {
        if (other_port.length() == 0 || our_port == 0) {
                return 0;
        }
 
        {
-               BLOCK_PROCESS_CALLBACK ();
+               Glib::Threads::Mutex::Lock lm (io_lock);
 
-               {
-                       Glib::Mutex::Lock lm (io_lock);
-
-                       /* check that our_port is really one of ours */
+               /* check that our_port is really one of ours */
 
-                       if ( ! _ports.contains(our_port) ) {
-                               return -1;
-                       }
+               if ( ! _ports.contains(our_port) ) {
+                       return -1;
+               }
 
-                       /* connect it to the source */
+               /* connect it to the source */
 
-                       if (our_port->connect (other_port)) {
-                               return -1;
-                       }
+               if (our_port->connect (other_port)) {
+                       return -1;
                }
        }
-
-       changed (ConnectionsChanged, src); /* EMIT SIGNAL */
+       changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
        _session.set_dirty ();
        return 0;
 }
 
 int
-IO::remove_port (Port* port, void* src)
+IO::remove_port (boost::shared_ptr<Port> port, void* src)
 {
-       IOChange change (NoChange);
+       ChanCount before = _ports.count ();
+       ChanCount after = before;
+       after.set (port->type(), after.get (port->type()) - 1);
+
+       boost::optional<bool> const r = PortCountChanging (after); /* EMIT SIGNAL */
+       if (r.get_value_or (false)) {
+               return -1;
+       }
+
+       IOChange change;
 
        {
                BLOCK_PROCESS_CALLBACK ();
 
-
                {
-                       Glib::Mutex::Lock lm (io_lock);
+                       Glib::Threads::Mutex::Lock lm (io_lock);
 
                        if (_ports.remove(port)) {
-                               change = IOChange (change|ConfigurationChanged);
+                               change.type = IOChange::Type (change.type | IOChange::ConfigurationChanged);
+                               change.before = before;
+                               change.after = _ports.count ();
 
                                if (port->connected()) {
-                                       change = IOChange (change|ConnectionsChanged);
+                                       change.type = IOChange::Type (change.type | IOChange::ConnectionsChanged);
                                }
 
-                               _session.engine().unregister_port (*port);
-                               check_bundles_connected ();
+                               _session.engine().unregister_port (port);
                        }
                }
 
                PortCountChanged (n_ports()); /* EMIT SIGNAL */
+
+               if (change.type != IOChange::NoChange) {
+                       changed (change, src);
+                       _buffers.attach_buffers (_ports);
+               }
        }
 
-       if (change & ConfigurationChanged) {
-               setup_bundles ();
+       if (change.type & IOChange::ConfigurationChanged) {
+               setup_bundle ();
        }
 
-       if (change != NoChange) {
-               changed (change, src);
-               _session.set_dirty ();
-               return 0;
+       if (change.type == IOChange::NoChange) {
+               return -1;
        }
 
-       return -1;
+       _session.set_dirty ();
+
+       return 0;
 }
 
-/** Add an output port.
+/** Add a port.
  *
- * @param destination Name of input port to connect new port to.
+ * @param destination Name of 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_port (string destination, void* src, DataType type)
 {
-       Port* our_port;
+       boost::shared_ptr<Port> our_port;
 
        if (type == DataType::NIL) {
                type = _default_type;
        }
 
+       ChanCount before = _ports.count ();
+       ChanCount after = before;
+       after.set (type, after.get (type) + 1);
+
+       bool const r = PortCountChanging (after); /* EMIT SIGNAL */
+       if (r) {
+               return -1;
+       }
+
+       IOChange change;
+
        {
                BLOCK_PROCESS_CALLBACK ();
 
 
                {
-                       Glib::Mutex::Lock lm (io_lock);
+                       Glib::Threads::Mutex::Lock lm (io_lock);
 
-                       /* Create a new output port */
+                       /* Create a new port */
 
                        string portname = build_legal_port_name (type);
 
@@ -311,21 +303,25 @@ IO::add_port (string destination, void* src, DataType type)
                                }
                        }
 
+                       change.before = _ports.count ();
                        _ports.add (our_port);
                }
 
                PortCountChanged (n_ports()); /* EMIT SIGNAL */
+               change.type = IOChange::ConfigurationChanged;
+               change.after = _ports.count ();
+               changed (change, src); /* EMIT SIGNAL */
+               _buffers.attach_buffers (_ports);
        }
 
-       if (destination.length()) {
+       if (!destination.empty()) {
                if (our_port->connect (destination)) {
                        return -1;
                }
        }
 
-       // pan_changed (src); /* EMIT SIGNAL */
-       changed (ConfigurationChanged, src); /* EMIT SIGNAL */
-       setup_bundles ();
+       apply_pretty_name ();
+       setup_bundle ();
        _session.set_dirty ();
 
        return 0;
@@ -335,29 +331,30 @@ int
 IO::disconnect (void* src)
 {
        {
-               BLOCK_PROCESS_CALLBACK ();
+               Glib::Threads::Mutex::Lock lm (io_lock);
 
-               {
-                       Glib::Mutex::Lock lm (io_lock);
-
-                       for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
-                               i->disconnect_all ();
-                       }
-
-                       check_bundles_connected ();
+               for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
+                       i->disconnect_all ();
                }
        }
 
-       changed (ConnectionsChanged, src); /* EMIT SIGNAL */
+       changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
 
        return 0;
 }
 
-bool
-IO::ensure_ports_locked (ChanCount count, bool clear, void* /*src*/)
+/** Caller must hold process lock */
+int
+IO::ensure_ports_locked (ChanCount count, bool clear, bool& changed)
 {
-       Port* port = 0;
-       bool  changed    = false;
+#ifndef PLATFORM_WINDOWS
+       assert (!AudioEngine::instance()->process_lock().trylock());
+#endif
+
+       boost::shared_ptr<Port> port;
+       vector<boost::shared_ptr<Port> > deleted_ports;
+
+       changed    = false;
 
        for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
 
@@ -369,11 +366,30 @@ IO::ensure_ports_locked (ChanCount count, bool clear, void* /*src*/)
 
                        assert(port);
                        _ports.remove(port);
-                       _session.engine().unregister_port (*port);
+
+                       /* hold a reference to the port so that we can ensure
+                        * that this thread, and not a JACK notification thread,
+                        * holds the final reference.
+                        */
+
+                       deleted_ports.push_back (port);
+                       _session.engine().unregister_port (port);
 
                        changed = true;
                }
 
+               /* this will drop the final reference to the deleted ports,
+                * which will in turn call their destructors, which will in
+                * turn call the backend to unregister them.
+                *
+                * There will no connect/disconnect or register/unregister
+                * callbacks from the backend until we get here, because
+                * they are driven by the Port destructor. The destructor
+                * will not execute until we drop the final reference,
+                * which all happens right .... here.
+                */
+               deleted_ports.clear ();
+
                /* create any necessary new ports */
                while (n_ports().get(*t) < n) {
 
@@ -396,7 +412,7 @@ IO::ensure_ports_locked (ChanCount count, bool clear, void* /*src*/)
 
                        catch (AudioEngine::PortRegistrationFailure& err) {
                                /* pass it on */
-                               throw AudioEngine::PortRegistrationFailure();
+                               throw;
                        }
 
                        _ports.add (port);
@@ -405,7 +421,6 @@ IO::ensure_ports_locked (ChanCount count, bool clear, void* /*src*/)
        }
 
        if (changed) {
-               check_bundles_connected ();
                PortCountChanged (n_ports()); /* EMIT SIGNAL */
                _session.set_dirty ();
        }
@@ -417,69 +432,77 @@ IO::ensure_ports_locked (ChanCount count, bool clear, void* /*src*/)
                }
        }
 
-       return changed;
+       return 0;
 }
 
-
+/** Caller must hold process lock */
 int
-IO::ensure_ports (ChanCount count, bool clear, bool lockit, void* src)
+IO::ensure_ports (ChanCount count, bool clear, void* src)
 {
+#ifndef PLATFORM_WINDOWS
+       assert (!AudioEngine::instance()->process_lock().trylock());
+#endif
+
        bool changed = false;
 
        if (count == n_ports() && !clear) {
                return 0;
        }
 
-       if (lockit) {
-               BLOCK_PROCESS_CALLBACK ();
-               Glib::Mutex::Lock im (io_lock);
-               changed = ensure_ports_locked (count, clear, src);
-       } else {
-               changed = ensure_ports_locked (count, clear, src);
+       IOChange change;
+
+       change.before = _ports.count ();
+
+       {
+               Glib::Threads::Mutex::Lock im (io_lock);
+               if (ensure_ports_locked (count, clear, changed)) {
+                       return -1;
+               }
        }
 
        if (changed) {
-               this->changed (ConfigurationChanged, src); /* EMIT SIGNAL */
-               setup_bundles ();
+               change.after = _ports.count ();
+               change.type = IOChange::ConfigurationChanged;
+               this->changed (change, src); /* EMIT SIGNAL */
+               _buffers.attach_buffers (_ports);
+               setup_bundle ();
                _session.set_dirty ();
        }
 
        return 0;
 }
 
+/** Caller must hold process lock */
 int
 IO::ensure_io (ChanCount count, bool clear, void* src)
 {
-       return ensure_ports (count, clear, true, src);
+#ifndef PLATFORM_WINDOWS
+       assert (!AudioEngine::instance()->process_lock().trylock());
+#endif
+
+       return ensure_ports (count, clear, src);
 }
 
 XMLNode&
-IO::get_state (void)
+IO::get_state ()
 {
-       return state (true);
+       return state ();
 }
 
 XMLNode&
-IO::state (bool /*full_state*/)
+IO::state ()
 {
        XMLNode* node = new XMLNode (state_node_name);
-       char buf[64];
-       string str;
-       vector<string>::iterator ci;
        int n;
-       LocaleGuard lg (X_("POSIX"));
-       Glib::Mutex::Lock lm (io_lock);
+       Glib::Threads::Mutex::Lock lm (io_lock);
 
-       node->add_property("name", _name);
-       id().print (buf, sizeof (buf));
-       node->add_property("id", buf);
-       node->add_property ("direction", enum_2_string (_direction));
-       node->add_property ("default-type", _default_type.to_string());
+       node->set_property ("name", name());
+       node->set_property ("id", id ());
+       node->set_property ("direction", _direction);
+       node->set_property ("default-type", _default_type);
 
-       for (std::vector<UserBundleInfo>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
-               XMLNode* n = new XMLNode ("Bundle");
-               n->add_property ("name", i->bundle->name ());
-               node->add_child_nocopy (*n);
+       if (!_pretty_name_prefix.empty ()) {
+               node->set_property("pretty-name", _pretty_name_prefix);
        }
 
        for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
@@ -487,10 +510,12 @@ IO::state (bool /*full_state*/)
                vector<string> connections;
 
                XMLNode* pnode = new XMLNode (X_("Port"));
-               pnode->add_property (X_("type"), i->type().to_string());
-               pnode->add_property (X_("name"), i->name());
+               pnode->set_property (X_("type"), i->type());
+               pnode->set_property (X_("name"), i->name());
 
                if (i->get_connections (connections)) {
+                       vector<string>::const_iterator ci;
+                       std::sort (connections.begin(), connections.end());
 
                        for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
 
@@ -503,7 +528,7 @@ IO::state (bool /*full_state*/)
 
                                XMLNode* cnode = new XMLNode (X_("Connection"));
 
-                               cnode->add_property (X_("other"), _session.engine().make_port_name_relative (*ci));
+                               cnode->set_property (X_("other"), _session.engine().make_port_name_relative (*ci));
                                pnode->add_child_nocopy (*cnode);
                        }
                }
@@ -511,6 +536,8 @@ IO::state (bool /*full_state*/)
                node->add_child_nocopy (*pnode);
        }
 
+       node->set_property (X_("user-latency"), _user_latency);
+
        return *node;
 }
 
@@ -522,10 +549,6 @@ IO::set_state (const XMLNode& node, int version)
         * by the caller.
         */
        assert (version >= 3000);
-       
-       const XMLProperty* prop;
-       XMLNodeConstIterator iter;
-       LocaleGuard lg (X_("POSIX"));
 
        /* force use of non-localized representation of decimal point,
           since we use it a lot in XML files and so forth.
@@ -536,27 +559,29 @@ IO::set_state (const XMLNode& node, int version)
                return -1;
        }
 
-       if ((prop = node.property ("name")) != 0) {
-               set_name (prop->value());
+       bool ignore_name = node.property ("ignore-name");
+       std::string name;
+       if (node.get_property ("name", name) && !ignore_name) {
+               set_name (name);
        }
 
-       if ((prop = node.property (X_("default-type"))) != 0) {
-               _default_type = DataType(prop->value());
+       if (node.get_property (X_("default-type"), _default_type)) {
                assert(_default_type != DataType::NIL);
        }
 
-       if ((prop = node.property ("id")) != 0) {
-               _id = prop->value ();
-       }
+       set_id (node);
 
-       if ((prop = node.property ("direction")) != 0) {
-               _direction = (Direction) string_2_enum (prop->value(), _direction);
-       }
+       node.get_property ("direction", _direction);
 
        if (create_ports (node, version)) {
                return -1;
        }
 
+       // after create_ports, updates names
+       if (node.get_property ("pretty-name", name)) {
+               set_pretty_name (name);
+       }
+
        if (connecting_legal) {
 
                if (make_connections (node, version, false)) {
@@ -565,12 +590,14 @@ IO::set_state (const XMLNode& node, int version)
 
        } else {
 
+               delete pending_state_node;
                pending_state_node = new XMLNode (node);
                pending_state_node_version = version;
                pending_state_node_in = false;
-               connection_legal_c = ConnectingLegal.connect (mem_fun (*this, &IO::connecting_became_legal));
+               ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
        }
 
+       node.get_property ("user-latency", _user_latency);
 
        return 0;
 }
@@ -578,9 +605,9 @@ IO::set_state (const XMLNode& node, int version)
 int
 IO::set_state_2X (const XMLNode& node, int version, bool in)
 {
-       const XMLProperty* prop;
+       XMLProperty const * prop;
        XMLNodeConstIterator iter;
-       LocaleGuard lg (X_("POSIX"));
+       LocaleGuard lg;
 
        /* force use of non-localized representation of decimal point,
           since we use it a lot in XML files and so forth.
@@ -590,7 +617,7 @@ IO::set_state_2X (const XMLNode& node, int version, bool in)
                error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
                return -1;
        }
-       
+
        if ((prop = node.property ("name")) != 0) {
                set_name (prop->value());
        }
@@ -600,9 +627,7 @@ IO::set_state_2X (const XMLNode& node, int version, bool in)
                assert(_default_type != DataType::NIL);
        }
 
-       if ((prop = node.property ("id")) != 0) {
-               _id = prop->value ();
-       }
+       set_id (node);
 
        _direction = in ? Input : Output;
 
@@ -611,17 +636,18 @@ IO::set_state_2X (const XMLNode& node, int version, bool in)
        }
 
        if (connecting_legal) {
-               
+
                if (make_connections_2X (node, version, in)) {
                        return -1;
                }
 
        } else {
 
+               delete pending_state_node;
                pending_state_node = new XMLNode (node);
                pending_state_node_version = version;
                pending_state_node_in = in;
-               connection_legal_c = ConnectingLegal.connect (mem_fun (*this, &IO::connecting_became_legal));
+               ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
        }
 
        return 0;
@@ -630,13 +656,16 @@ IO::set_state_2X (const XMLNode& node, int version, bool in)
 int
 IO::connecting_became_legal ()
 {
-       int ret;
+       int ret = 0;
 
        assert (pending_state_node);
 
        connection_legal_c.disconnect ();
 
-       ret = make_connections (*pending_state_node, pending_state_node_version, pending_state_node_in);
+       // it's not required for TracksLive, as long as TracksLive's session does all the connections when it's being loaded
+       if (!Profile->get_trx() ) {
+               ret = make_connections (*pending_state_node, pending_state_node_version, pending_state_node_in);
+       }
 
        delete pending_state_node;
        pending_state_node = 0;
@@ -658,6 +687,7 @@ IO::find_possible_bundle (const string &desired_name)
                string possible_name;
                bool stereo = false;
                string::size_type last_non_digit_pos;
+               std::string bundle_number_str;
 
                error << string_compose(_("Unknown bundle \"%1\" listed for %2 of %3"), desired_name, bundle_type_name, _name)
                      << endmsg;
@@ -668,23 +698,21 @@ IO::find_possible_bundle (const string &desired_name)
                last_non_digit_pos = desired_name.find_last_not_of(digits);
 
                if (last_non_digit_pos != string::npos) {
-                       stringstream s;
-                       s << desired_name.substr(last_non_digit_pos);
-                       s >> bundle_number;
+                       bundle_number_str = desired_name.substr(last_non_digit_pos);
+                       bundle_number = string_to<int32_t>(bundle_number_str);
                }
 
                // see if it's a stereo connection e.g. "in 3+4"
 
                if (last_non_digit_pos > 1 && desired_name[last_non_digit_pos] == '+') {
-                       int left_bundle_number = 0;
                        string::size_type left_last_non_digit_pos;
 
                        left_last_non_digit_pos = desired_name.find_last_not_of(digits, last_non_digit_pos-1);
 
                        if (left_last_non_digit_pos != string::npos) {
-                               stringstream s;
-                               s << desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
-                               s >> left_bundle_number;
+                               int left_bundle_number = 0;
+                               bundle_number_str = desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
+                               left_bundle_number = string_to<int32_t>(bundle_number_str);
 
                                if (left_bundle_number > 0 && left_bundle_number + 1 == bundle_number) {
                                        bundle_number--;
@@ -709,15 +737,12 @@ IO::find_possible_bundle (const string &desired_name)
                        if (bundle_number & mask) {
                                bundle_number &= ~mask;
 
-                               stringstream s;
-                               s << default_name << " " << bundle_number + 1;
+                               std::string possible_name = default_name + " " + to_string(bundle_number + 1);
 
                                if (stereo) {
-                                       s << "+" << bundle_number + 2;
+                                       possible_name += "+" + to_string(bundle_number + 2);
                                }
 
-                               possible_name = s.str();
-
                                if ((c = _session.bundle_by_name (possible_name)) != 0) {
                                        break;
                                }
@@ -739,19 +764,23 @@ IO::find_possible_bundle (const string &desired_name)
 }
 
 int
-IO::get_port_counts_2X (XMLNode const & node, int version, ChanCount& n, boost::shared_ptr<Bundle>& c)
+IO::get_port_counts_2X (XMLNode const & node, int /*version*/, ChanCount& n, boost::shared_ptr<Bundle>& /*c*/)
 {
        XMLProperty const * prop;
        XMLNodeList children = node.children ();
 
        uint32_t n_audio = 0;
-       
+
        for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
 
                if ((prop = node.property ("inputs")) != 0 && _direction == Input) {
                        n_audio = count (prop->value().begin(), prop->value().end(), '{');
+               } else if ((prop = node.property ("input-connection")) != 0 && _direction == Input) {
+                       n_audio = 1;
                } else if ((prop = node.property ("outputs")) != 0 && _direction == Output) {
                        n_audio = count (prop->value().begin(), prop->value().end(), '{');
+               } else if ((prop = node.property ("output-connection")) != 0 && _direction == Output) {
+                       n_audio = 2;
                }
        }
 
@@ -768,7 +797,7 @@ IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shar
        if (version < 3000) {
                return get_port_counts_2X (node, version, n, c);
        }
-       
+
        XMLProperty const * prop;
        XMLNodeConstIterator iter;
        uint32_t n_audio = 0;
@@ -780,7 +809,7 @@ IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shar
        if ((prop = node.property ("connection")) != 0) {
 
                if ((c = find_possible_bundle (prop->value())) != 0) {
-                       n = ChanCount::max (n, ChanCount(c->type(), c->nchannels()));
+                       n = ChanCount::max (n, c->nchannels());
                }
                return 0;
        }
@@ -788,8 +817,9 @@ IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shar
        for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
 
                if ((*iter)->name() == X_("Bundle")) {
+                       prop = (*iter)->property ("name");
                        if ((c = find_possible_bundle (prop->value())) != 0) {
-                               n = ChanCount::max (n, ChanCount(c->type(), c->nchannels()));
+                               n = ChanCount::max (n, c->nchannels());
                                return 0;
                        } else {
                                return -1;
@@ -820,12 +850,16 @@ IO::create_ports (const XMLNode& node, int version)
 {
        ChanCount n;
        boost::shared_ptr<Bundle> c;
-       
+
        get_port_counts (node, version, n, c);
-       
-       if (ensure_ports (n, true, true, this)) {
-               error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
-               return -1;
+
+       {
+               Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
+
+               if (ensure_ports (n, true, this)) {
+                       error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
+                       return -1;
+               }
        }
 
        /* XXX use c */
@@ -839,8 +873,8 @@ IO::make_connections (const XMLNode& node, int version, bool in)
        if (version < 3000) {
                return make_connections_2X (node, version, in);
        }
-                       
-       const XMLProperty* prop;
+
+       XMLProperty const * prop;
 
        for (XMLNodeConstIterator i = node.children().begin(); i != node.children().end(); ++i) {
 
@@ -849,7 +883,7 @@ IO::make_connections (const XMLNode& node, int version, bool in)
                        if (prop) {
                                boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value());
                                if (b) {
-                                       connect_ports_to_bundle (b, this);
+                                       connect_ports_to_bundle (b, true, this);
                                }
                        }
 
@@ -864,7 +898,7 @@ IO::make_connections (const XMLNode& node, int version, bool in)
                                continue;
                        }
 
-                       Port* p = port_by_name (prop->value());
+                       boost::shared_ptr<Port> p = port_by_name (prop->value());
 
                        if (p) {
                                for (XMLNodeConstIterator c = (*i)->children().begin(); c != (*i)->children().end(); ++c) {
@@ -880,7 +914,7 @@ IO::make_connections (const XMLNode& node, int version, bool in)
                                        }
 
                                        if (prop) {
-                                               p->connect (prop->value());
+                                               connect (p, prop->value(), this);
                                        }
                                }
                        }
@@ -890,14 +924,52 @@ IO::make_connections (const XMLNode& node, int version, bool in)
        return 0;
 }
 
+void
+IO::prepare_for_reset (XMLNode& node, const std::string& name)
+{
+       /* reset name */
+       node.set_property ("name", name);
+
+       /* now find connections and reset the name of the port
+          in one so that when we re-use it it will match
+          the name of the thing we're applying it to.
+       */
+
+       XMLProperty * prop;
+       XMLNodeList children = node.children();
+
+       for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
+
+               if ((*i)->name() == "Port") {
+
+                       prop = (*i)->property (X_("name"));
+
+                       if (prop) {
+                               string new_name;
+                               string old = prop->value();
+                               string::size_type slash = old.find ('/');
+
+                               if (slash != string::npos) {
+                                       /* port name is of form: <IO-name>/<port-name> */
+
+                                       new_name = name;
+                                       new_name += old.substr (old.find ('/'));
+
+                                       prop->set_value (new_name);
+                               }
+                       }
+               }
+       }
+}
+
 
 int
-IO::make_connections_2X (const XMLNode& node, int version, bool in)
+IO::make_connections_2X (const XMLNode& node, int /*version*/, bool in)
 {
-       const XMLProperty* prop;
+       XMLProperty const * prop;
 
        /* XXX: bundles ("connections" as was) */
-       
+
        if ((prop = node.property ("inputs")) != 0 && in) {
 
                string::size_type ostart = 0;
@@ -908,33 +980,34 @@ IO::make_connections_2X (const XMLNode& node, int version, bool in)
                vector<string> ports;
 
                string const str = prop->value ();
-               
+
                while ((start = str.find_first_of ('{', ostart)) != string::npos) {
                        start += 1;
-                       
+
                        if ((end = str.find_first_of ('}', start)) == string::npos) {
                                error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
                                return -1;
                        }
-                       
+
                        if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
                                error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
-                               
+
                                return -1;
-                               
+
                        } else if (n > 0) {
 
 
                                for (int x = 0; x < n; ++x) {
                                        /* XXX: this is a bit of a hack; need to check if it's always valid */
-                                       string::size_type const p = ports[x].find ("/out");
+                                       string::size_type const p = ports[x].find ("/out");
                                        if (p != string::npos) {
                                                ports[x].replace (p, 4, "/audio_out");
                                        }
-                                       nth(i)->connect (ports[x]);
+                                       if (NULL != nth(i).get())
+                                               nth(i)->connect (ports[x]);
                                }
                        }
-                       
+
                        ostart = end+1;
                        i++;
                }
@@ -949,34 +1022,35 @@ IO::make_connections_2X (const XMLNode& node, int version, bool in)
                int i = 0;
                int n;
                vector<string> ports;
-       
+
                string const str = prop->value ();
-               
+
                while ((start = str.find_first_of ('{', ostart)) != string::npos) {
                        start += 1;
-                       
+
                        if ((end = str.find_first_of ('}', start)) == string::npos) {
                                error << string_compose(_("IO: badly formed string in XML node for outputs \"%1\""), str) << endmsg;
                                return -1;
                        }
-                       
+
                        if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
                                error << string_compose(_("IO: bad output string in XML node \"%1\""), str) << endmsg;
-                               
+
                                return -1;
-                               
+
                        } else if (n > 0) {
-                               
+
                                for (int x = 0; x < n; ++x) {
                                        /* XXX: this is a bit of a hack; need to check if it's always valid */
-                                       string::size_type const p = ports[x].find ("/in");
+                                       string::size_type const p = ports[x].find ("/in");
                                        if (p != string::npos) {
                                                ports[x].replace (p, 3, "/audio_in");
                                        }
-                                       nth(i)->connect (ports[x]);
+                                       if (NULL != nth(i).get())
+                                               nth(i)->connect (ports[x]);
                                }
                        }
-                       
+
                        ostart = end+1;
                        i++;
                }
@@ -989,7 +1063,6 @@ int
 IO::set_ports (const string& str)
 {
        vector<string> ports;
-       int i;
        int n;
        uint32_t nports;
 
@@ -997,19 +1070,19 @@ IO::set_ports (const string& str)
                return 0;
        }
 
-       // FIXME: audio-only
-       if (ensure_ports (ChanCount(DataType::AUDIO, nports), true, true, this)) {
-               return -1;
-       }
-
-       string::size_type start, end, ostart;
+       {
+               Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
 
-       ostart = 0;
-       start = 0;
-       end = 0;
-       i = 0;
+               // FIXME: audio-only
+               if (ensure_ports (ChanCount(DataType::AUDIO, nports), true, this)) {
+                       return -1;
+               }
+       }
 
-       while ((start = str.find_first_of ('{', ostart)) != string::npos) {
+       string::size_type start  = 0;
+       string::size_type end    = 0;
+       string::size_type ostart = 0;
+       for (int i = 0; (start = str.find_first_of ('{', ostart)) != string::npos; ++i) {
                start += 1;
 
                if ((end = str.find_first_of ('}', start)) == string::npos) {
@@ -1030,7 +1103,6 @@ IO::set_ports (const string& str)
                }
 
                ostart = end+1;
-               i++;
        }
 
        return 0;
@@ -1045,7 +1117,6 @@ IO::parse_io_string (const string& str, vector<string>& ports)
                return 0;
        }
 
-       pos = 0;
        opos = 0;
 
        ports.clear ();
@@ -1067,7 +1138,6 @@ IO::parse_gain_string (const string& str, vector<string>& ports)
 {
        string::size_type pos, opos;
 
-       pos = 0;
        opos = 0;
        ports.clear ();
 
@@ -1088,125 +1158,174 @@ IO::set_name (const string& requested_name)
 {
        string name = requested_name;
 
-       if (name == _name) {
+       if (_name == name) {
                return true;
        }
 
        /* 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;
-       }
+       replace_all (name, ":", "-");
 
        for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
                string current_name = i->name();
-               current_name.replace (current_name.find (_name), _name.length(), name);
+               current_name.replace (current_name.find (_name), _name.val().length(), name);
                i->set_name (current_name);
        }
 
        bool const r = SessionObject::set_name (name);
 
-       setup_bundles ();
+       setup_bundle ();
 
        return r;
 }
 
 void
-IO::set_port_latency (nframes_t nframes)
+IO::set_pretty_name (const std::string& str)
 {
-       Glib::Mutex::Lock lm (io_lock);
+       if (_pretty_name_prefix == str) {
+               return;
+       }
+       _pretty_name_prefix = str;
+       apply_pretty_name ();
+}
 
-       for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
-               i->set_latency (nframes);
+void
+IO::apply_pretty_name ()
+{
+       uint32_t pn = 1;
+       if (_pretty_name_prefix.empty ()) {
+               return;
+       }
+       for (PortSet::iterator i = _ports.begin (); i != _ports.end(); ++i, ++pn) {
+               (*i)->set_pretty_name (string_compose (("%1/%2 %3"),
+                                       _pretty_name_prefix,
+                                       _direction == Output ? _("Out") : _("In"),
+                                       pn));
        }
 }
 
-nframes_t
+samplecnt_t
 IO::latency () const
 {
-       nframes_t max_latency;
-       nframes_t latency;
-
-       max_latency = 0;
+       samplecnt_t max_latency = 0;
 
        /* io lock not taken - must be protected by other means */
 
        for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
-               if ((latency = i->total_latency ()) > max_latency) {
+               samplecnt_t latency;
+               if ((latency = i->private_latency_range (_direction == Output).max) > max_latency) {
+                       DEBUG_TRACE (DEBUG::Latency, string_compose ("port %1 has %2 latency of %3 - use\n",
+                                                                    name(),
+                                                                    ((_direction == Output) ? "PLAYBACK" : "CAPTURE"),
+                                                                    latency));
                        max_latency = latency;
                }
        }
 
+       DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: max %4 latency from %2 ports = %3\n",
+                                                    name(), _ports.num_ports(), max_latency,
+                                                    ((_direction == Output) ? "PLAYBACK" : "CAPTURE")));
        return max_latency;
 }
 
-void
-IO::update_port_total_latencies ()
+samplecnt_t
+IO::public_latency () const
 {
-       /* io_lock, not taken: function must be called from Session::process() calltree */
+       samplecnt_t max_latency = 0;
 
-       for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
-               _session.engine().update_total_latency (*i);
+       /* io lock not taken - must be protected by other means */
+
+       for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
+               samplecnt_t latency;
+               if ((latency = i->public_latency_range (_direction == Output).max) > max_latency) {
+                       DEBUG_TRACE (DEBUG::Latency, string_compose ("port %1 has %2 latency of %3 - use\n",
+                                                                    name(),
+                                                                    ((_direction == Output) ? "PLAYBACK" : "CAPTURE"),
+                                                                    latency));
+                       max_latency = latency;
+               }
        }
+
+       DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: max %4 public latency from %2 ports = %3\n",
+                                                    name(), _ports.num_ports(), max_latency,
+                                                    ((_direction == Output) ? "PLAYBACK" : "CAPTURE")));
+       return max_latency;
 }
 
-int
-IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, void* src)
+samplecnt_t
+IO::connected_latency (bool for_playback) const
 {
-       {
-               BLOCK_PROCESS_CALLBACK ();
-               Glib::Mutex::Lock lm2 (io_lock);
+       /* io lock not taken - must be protected by other means */
+       samplecnt_t max_latency = 0;
+       bool connected = false;
 
-               c->connect (_bundle, _session.engine());
+       /* if output is not connected to anything, use private latency */
+       for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
+               if (i->connected()) {
+                       connected = true;
+                       max_latency = 0;
+                       break;
+               }
+               samplecnt_t latency;
+               if ((latency = i->private_latency_range (for_playback).max) > max_latency) {
+                       max_latency = latency;
+               }
+       }
+       if (connected) {
+               for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
+                       LatencyRange lr;
+                       i->get_connected_latency_range (lr, for_playback);
+                       if (lr.max > max_latency) {
+                               max_latency = lr.max;
+                       }
+               }
+       }
+       return max_latency;
+}
 
-               /* If this is a UserBundle, make a note of what we've done */
+int
+IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, bool exclusive, void* src) {
+       return connect_ports_to_bundle(c, exclusive, false, src);
+}
 
-               boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
-               if (ub) {
+int
+IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, bool exclusive,
+                             bool allow_partial, void* src)
+{
+       BLOCK_PROCESS_CALLBACK ();
 
-                       /* See if we already know about this one */
-                       std::vector<UserBundleInfo>::iterator i = _bundles_connected.begin();
-                       while (i != _bundles_connected.end() && i->bundle != ub) {
-                               ++i;
-                       }
+       {
+               Glib::Threads::Mutex::Lock lm2 (io_lock);
 
-                       if (i == _bundles_connected.end()) {
-                               /* We don't, so make a note */
-                               _bundles_connected.push_back (UserBundleInfo (this, ub));
+               if (exclusive) {
+                       for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
+                               i->disconnect_all ();
                        }
                }
+
+               c->connect (_bundle, _session.engine(), allow_partial);
+
        }
 
-       changed (IOChange (ConfigurationChanged|ConnectionsChanged), src); /* EMIT SIGNAL */
+       changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
        return 0;
 }
 
 int
 IO::disconnect_ports_from_bundle (boost::shared_ptr<Bundle> c, void* src)
 {
+       BLOCK_PROCESS_CALLBACK ();
+
        {
-               BLOCK_PROCESS_CALLBACK ();
-               Glib::Mutex::Lock lm2 (io_lock);
+               Glib::Threads::Mutex::Lock lm2 (io_lock);
 
                c->disconnect (_bundle, _session.engine());
 
                /* If this is a UserBundle, make a note of what we've done */
 
-               boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
-               if (ub) {
-
-                       std::vector<UserBundleInfo>::iterator i = _bundles_connected.begin();
-                       while (i != _bundles_connected.end() && i->bundle != ub) {
-                               ++i;
-                       }
-
-                       if (i != _bundles_connected.end()) {
-                               _bundles_connected.erase (i);
-                       }
-               }
        }
 
-       changed (IOChange (ConfigurationChanged|ConnectionsChanged), src); /* EMIT SIGNAL */
+       changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
        return 0;
 }
 
@@ -1221,14 +1340,16 @@ IO::disable_connecting ()
 int
 IO::enable_connecting ()
 {
+       Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
        connecting_legal = true;
-       return ConnectingLegal ();
+       boost::optional<int> r = ConnectingLegal ();
+       return r.get_value_or (0);
 }
 
 void
 IO::bundle_changed (Bundle::Change /*c*/)
 {
-       //XXX
+       /* XXX */
 //     connect_input_ports_to_bundle (_input_bundle, this);
 }
 
@@ -1236,14 +1357,14 @@ IO::bundle_changed (Bundle::Change /*c*/)
 string
 IO::build_legal_port_name (DataType type)
 {
-       const int name_size = jack_port_name_size();
+       const int name_size = AudioEngine::instance()->port_name_size();
        int limit;
        string suffix;
 
        if (type == DataType::AUDIO) {
-               suffix = _("audio");
+               suffix = X_("audio");
        } else if (type == DataType::MIDI) {
-               suffix = _("midi");
+               suffix = X_("midi");
        } else {
                throw unknown_type();
        }
@@ -1254,25 +1375,38 @@ IO::build_legal_port_name (DataType type)
           use the (new) translated name.
        */
 
-       if (_direction == Input) {
-               suffix += X_("_in");
+       if (_sendish) {
+               if (_direction == Input) {
+                       suffix += X_("_return");
+               } else {
+                       suffix += X_("_send");
+               }
        } else {
-               suffix += X_("_out");
+               if (_direction == Input) {
+                       suffix += X_("_in");
+               } else {
+                       suffix += X_("_out");
+               }
        }
 
        // allow up to 4 digits for the output port number, plus the slash, suffix and extra space
 
-       limit = name_size - _session.engine().client_name().length() - (suffix.length() + 5);
+       limit = name_size - AudioEngine::instance()->my_name().length() - (suffix.length() + 5);
+
+       std::vector<char> buf1(name_size+1);
+       std::vector<char> buf2(name_size+1);
+
+       /* colons are illegal in port names, so fix that */
 
-       char buf1[name_size+1];
-       char buf2[name_size+1];
+       string nom = _name.val();
+       replace_all (nom, ":", ";");
 
-       snprintf (buf1, name_size+1, ("%.*s/%s"), limit, _name.c_str(), suffix.c_str());
+       snprintf (&buf1[0], name_size+1, ("%.*s/%s"), limit, nom.c_str(), suffix.c_str());
 
-       int port_number = find_port_hole (buf1);
-       snprintf (buf2, name_size+1, "%s %d", buf1, port_number);
+       int port_number = find_port_hole (&buf1[0]);
+       snprintf (&buf2[0], name_size+1, "%s %d", &buf1[0], port_number);
 
-       return string (buf2);
+       return string (&buf2[0]);
 }
 
 int32_t
@@ -1290,13 +1424,13 @@ IO::find_port_hole (const char* base)
         */
 
        for (n = 1; n < 9999; ++n) {
-               char buf[jack_port_name_size()];
+               std::vector<char> buf (AudioEngine::instance()->port_name_size());
                PortSet::iterator i = _ports.begin();
 
-               snprintf (buf, jack_port_name_size(), _("%s %u"), base, n);
+               snprintf (&buf[0], buf.size()+1, _("%s %u"), base, n);
 
                for ( ; i != _ports.end(); ++i) {
-                       if (i->name() == buf) {
+                       if (string(i->name()) == string(&buf[0])) {
                                break;
                        }
                }
@@ -1309,27 +1443,26 @@ IO::find_port_hole (const char* base)
 }
 
 
-AudioPort*
+boost::shared_ptr<AudioPort>
 IO::audio(uint32_t n) const
 {
        return _ports.nth_audio_port (n);
 
 }
 
-MidiPort*
+boost::shared_ptr<MidiPort>
 IO::midi(uint32_t n) const
 {
        return _ports.nth_midi_port (n);
 }
 
 /**
- *  Setup bundles that describe our inputs and outputs. Also creates bundles if necessary.
+ *  Setup a bundle that describe our inputs or outputs. Also creates the bundle if necessary.
  */
-
 void
-IO::setup_bundles ()
+IO::setup_bundle ()
 {
-        char buf[32];
+       char buf[32];
 
        if (!_bundle) {
                _bundle.reset (new Bundle (_direction == Input));
@@ -1337,20 +1470,25 @@ IO::setup_bundles ()
 
        _bundle->suspend_signals ();
 
-       _bundle->set_type (default_type ());
-
        _bundle->remove_channels ();
 
        if (_direction == Input) {
-               snprintf(buf, sizeof (buf), _("%s in"), _name.c_str());
+               snprintf(buf, sizeof (buf), _("%s in"), _name.val().c_str());
        } else {
-               snprintf(buf, sizeof (buf), _("%s out"), _name.c_str());
+               snprintf(buf, sizeof (buf), _("%s out"), _name.val().c_str());
        }
-        _bundle->set_name (buf);
-       uint32_t const ni = _ports.num_ports();
-       for (uint32_t i = 0; i < ni; ++i) {
-               _bundle->add_channel (bundle_channel_name (i, ni));
-               _bundle->set_port (i, _session.engine().make_port_name_non_relative (_ports.port(i)->name()));
+       _bundle->set_name (buf);
+
+       int c = 0;
+       for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
+
+               uint32_t const N = _ports.count().get (*i);
+               for (uint32_t j = 0; j < N; ++j) {
+                       _bundle->add_channel (bundle_channel_name (j, N, *i), *i);
+                       _bundle->set_port (c, _session.engine().make_port_name_non_relative (_ports.port(*i, j)->name()));
+                       ++c;
+               }
+
        }
 
        _bundle->resume_signals ();
@@ -1362,11 +1500,6 @@ IO::bundles_connected ()
 {
        BundleList bundles;
 
-       /* User bundles */
-       for (std::vector<UserBundleInfo>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
-               bundles.push_back (i->bundle);
-       }
-
        /* Session bundles */
        boost::shared_ptr<ARDOUR::BundleList> b = _session.bundles ();
        for (ARDOUR::BundleList::iterator i = b->begin(); i != b->end(); ++i) {
@@ -1400,24 +1533,31 @@ IO::bundles_connected ()
 IO::UserBundleInfo::UserBundleInfo (IO* io, boost::shared_ptr<UserBundle> b)
 {
        bundle = b;
-       changed = b->Changed.connect (
-               sigc::mem_fun (*io, &IO::bundle_changed)
-               );
+       b->Changed.connect_same_thread (changed, boost::bind (&IO::bundle_changed, io, _1));
 }
 
 std::string
-IO::bundle_channel_name (uint32_t c, uint32_t n) const
+IO::bundle_channel_name (uint32_t c, uint32_t n, DataType t) const
 {
        char buf[32];
 
-       switch (n) {
-       case 1:
-               return _("mono");
-       case 2:
-               return c == 0 ? _("L") : _("R");
-       default:
-               snprintf (buf, sizeof(buf), _("%d"), (c + 1));
+       if (t == DataType::AUDIO) {
+
+               switch (n) {
+               case 1:
+                       return _("mono");
+               case 2:
+                       return c == 0 ? _("L") : _("R");
+               default:
+                       snprintf (buf, sizeof(buf), "%d", (c + 1));
+                       return buf;
+               }
+
+       } else {
+
+               snprintf (buf, sizeof(buf), "%d", (c + 1));
                return buf;
+
        }
 
        return "";
@@ -1426,7 +1566,7 @@ IO::bundle_channel_name (uint32_t c, uint32_t n) const
 string
 IO::name_from_state (const XMLNode& node)
 {
-       const XMLProperty* prop;
+       XMLProperty const * prop;
 
        if ((prop = node.property ("name")) != 0) {
                return prop->value();
@@ -1438,26 +1578,36 @@ IO::name_from_state (const XMLNode& node)
 void
 IO::set_name_in_state (XMLNode& node, const string& new_name)
 {
-       const XMLProperty* prop;
-
-       if ((prop = node.property ("name")) != 0) {
-               node.add_property ("name", new_name);
+       node.set_property (X_("name"), new_name);
+       XMLNodeList children = node.children ();
+       for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
+               if ((*i)->name() == X_("Port")) {
+                       string const old_name = (*i)->property(X_("name"))->value();
+                       string const old_name_second_part = old_name.substr (old_name.find_first_of ("/") + 1);
+                       (*i)->set_property (X_("name"), string_compose ("%1/%2", new_name, old_name_second_part));
+               }
        }
 }
 
 bool
-IO::connected_to (boost::shared_ptr<const IO> other) const
+IO::connected () const
 {
-       if (!other) {
-               /* do we have any connections at all? */
+       /* do we have any connections at all? */
 
-               for (PortSet::const_iterator p = _ports.begin(); p != _ports.end(); ++p) {
-                       if (p->connected()) {
-                               return true;
-                       }
+       for (PortSet::const_iterator p = _ports.begin(); p != _ports.end(); ++p) {
+               if (p->connected()) {
+                       return true;
                }
+       }
 
-               return false;
+       return false;
+}
+
+bool
+IO::connected_to (boost::shared_ptr<const IO> other) const
+{
+       if (!other) {
+               return connected ();
        }
 
        assert (_direction != other->direction());
@@ -1468,8 +1618,10 @@ IO::connected_to (boost::shared_ptr<const IO> other) const
 
        for (i = 0; i < no; ++i) {
                for (j = 0; j < ni; ++j) {
-                       if (nth(i)->connected_to (other->nth(j)->name())) {
-                               return true;
+                       if ((NULL != nth(i).get()) && (NULL != other->nth(j).get())) {
+                               if (nth(i)->connected_to (other->nth(j)->name())) {
+                                       return true;
+                               }
                        }
                }
        }
@@ -1477,19 +1629,20 @@ IO::connected_to (boost::shared_ptr<const IO> other) const
        return false;
 }
 
-void
-IO::process_input (boost::shared_ptr<Processor> proc, sframes_t start_frame, sframes_t end_frame, nframes_t nframes)
+bool
+IO::connected_to (const string& str) const
 {
-       BufferSet bufs;
-
-       /* don't read the data into new buffers - just use the port buffers directly */
+       for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
+               if (i->connected_to (str)) {
+                       return true;
+               }
+       }
 
-       bufs.attach_buffers (_ports, nframes, 0);
-       proc->run (bufs, start_frame, end_frame, nframes);
+       return false;
 }
 
 void
-IO::collect_input (BufferSet& bufs, nframes_t nframes, ChanCount offset)
+IO::collect_input (BufferSet& bufs, pframes_t nframes, ChanCount offset)
 {
        assert(bufs.available() >= _ports.count());
 
@@ -1510,21 +1663,23 @@ IO::collect_input (BufferSet& bufs, nframes_t nframes, ChanCount offset)
                }
 
                for ( ; i != _ports.end(*t); ++i, ++b) {
-                       Buffer& bb (i->get_buffer (nframes));
+                       const Buffer& bb (i->get_buffer (nframes));
                        b->read_from (bb, nframes);
                }
        }
 }
 
 void
-IO::copy_to_outputs (BufferSet& bufs, DataType type, nframes_t nframes, nframes_t offset)
+IO::copy_to_outputs (BufferSet& bufs, DataType type, pframes_t nframes, samplecnt_t offset)
 {
-       // Copy any buffers 1:1 to outputs
-
        PortSet::iterator o = _ports.begin(type);
        BufferSet::iterator i = bufs.begin(type);
        BufferSet::iterator prev = i;
 
+       assert(i != bufs.end(type)); // or second loop will crash
+
+       // Copy any buffers 1:1 to outputs
+
        while (i != bufs.end(type) && o != _ports.end (type)) {
                Buffer& port_buffer (o->get_buffer (nframes));
                port_buffer.read_from (*i, nframes, offset);
@@ -1542,19 +1697,36 @@ IO::copy_to_outputs (BufferSet& bufs, DataType type, nframes_t nframes, nframes_
        }
 }
 
-Port*
+boost::shared_ptr<Port>
 IO::port_by_name (const std::string& str) const
 {
        /* to be called only from ::set_state() - no locking */
 
        for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
 
-               const Port& p(*i);
+               if (i->name() == str) {
+                       return boost::const_pointer_cast<Port> (*i);
+               }
+       }
+
+       return boost::shared_ptr<Port> ();
+}
 
-               if (p.name() == str) {
-                       return const_cast<Port*>(&p);
+bool
+IO::physically_connected () const
+{
+       for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
+               if (i->physically_connected()) {
+                       return true;
                }
        }
 
-       return 0;
+       return false;
+}
+
+bool
+IO::has_port (boost::shared_ptr<Port> p) const
+{
+       Glib::Threads::Mutex::Lock lm (io_lock);
+       return _ports.contains (p);
 }