add IOProcessors pretty name support
[ardour.git] / libs / ardour / io.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <algorithm>
20 #include <cmath>
21 #include <vector>
22
23 #include <unistd.h>
24 #include <locale.h>
25 #include <errno.h>
26
27 #include <glibmm.h>
28 #include <glibmm/threads.h>
29
30 #include "pbd/xml++.h"
31 #include "pbd/replace_all.h"
32 #include "pbd/unknown_type.h"
33 #include "pbd/enumwriter.h"
34
35 #include "ardour/audioengine.h"
36 #include "ardour/buffer.h"
37 #include "ardour/buffer_set.h"
38 #include "ardour/debug.h"
39 #include "ardour/io.h"
40 #include "ardour/port.h"
41 #include "ardour/profile.h"
42 #include "ardour/route.h"
43 #include "ardour/session.h"
44 #include "ardour/user_bundle.h"
45
46 #include "i18n.h"
47
48 #define BLOCK_PROCESS_CALLBACK() Glib::Threads::Mutex::Lock em (AudioEngine::instance()->process_lock())
49
50 using namespace std;
51 using namespace ARDOUR;
52 using namespace PBD;
53
54 const string                 IO::state_node_name = "IO";
55 bool                         IO::connecting_legal = false;
56 PBD::Signal0<int>            IO::ConnectingLegal;
57 PBD::Signal1<void,ChanCount> IO::PortCountChanged;
58
59 /** @param default_type The type of port that will be created by ensure_io
60  * and friends if no type is explicitly requested (to avoid breakage).
61  */
62 IO::IO (Session& s, const string& name, Direction dir, DataType default_type, bool sendish)
63         : SessionObject (s, name)
64         , _direction (dir)
65         , _default_type (default_type)
66         , _sendish (sendish)
67 {
68         _active = true;
69         Port::PostDisconnect.connect_same_thread (*this, boost::bind (&IO::disconnect_check, this, _1, _2));
70         pending_state_node = 0;
71         setup_bundle ();
72 }
73
74 IO::IO (Session& s, const XMLNode& node, DataType dt, bool sendish)
75         : SessionObject(s, "unnamed io")
76         , _direction (Input)
77         , _default_type (dt)
78         , _sendish (sendish)
79 {
80         _active = true;
81         pending_state_node = 0;
82         Port::PostDisconnect.connect_same_thread (*this, boost::bind (&IO::disconnect_check, this, _1, _2));
83
84         set_state (node, Stateful::loading_state_version);
85         setup_bundle ();
86 }
87
88 IO::~IO ()
89 {
90         Glib::Threads::Mutex::Lock lm (io_lock);
91
92         BLOCK_PROCESS_CALLBACK ();
93
94         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
95                 _session.engine().unregister_port (*i);
96         }
97 }
98
99 void
100 IO::disconnect_check (boost::shared_ptr<Port> a, boost::shared_ptr<Port> b)
101 {
102         /* this could be called from within our own ::disconnect() method(s)
103            or from somewhere that operates directly on a port. so, we don't
104            know for sure if we can take this lock or not. if we fail,
105            we assume that its safely locked by our own ::disconnect().
106         */
107
108         Glib::Threads::Mutex::Lock tm (io_lock, Glib::Threads::TRY_LOCK);
109
110         if (tm.locked()) {
111                 /* we took the lock, so we cannot be here from inside
112                  * ::disconnect()
113                  */
114                 if (_ports.contains (a) || _ports.contains (b)) {
115                         changed (IOChange (IOChange::ConnectionsChanged), this); /* EMIT SIGNAL */
116                 }
117         } else {
118                 /* we didn't get the lock, so assume that we're inside
119                  * ::disconnect(), and it will call changed() appropriately.
120                  */
121         }
122 }
123
124 void
125 IO::increment_port_buffer_offset (pframes_t offset)
126 {
127         /* io_lock, not taken: function must be called from Session::process() calltree */
128
129         if (_direction == Output) {
130                 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
131                         i->increment_port_buffer_offset (offset);
132                 }
133         }
134 }
135
136 void
137 IO::silence (framecnt_t nframes)
138 {
139         /* io_lock, not taken: function must be called from Session::process() calltree */
140
141         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
142                 i->get_buffer(nframes).silence (nframes);
143         }
144 }
145
146 /** Set _bundles_connected to those bundles that are connected such that every
147  *  port on every bundle channel x is connected to port x in _ports.
148  */
149 void
150 IO::check_bundles_connected ()
151 {
152         std::vector<UserBundleInfo*> new_list;
153
154         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
155
156                 uint32_t const N = (*i)->bundle->nchannels().n_total();
157
158                 if (_ports.num_ports() < N) {
159                         continue;
160                 }
161
162                 bool ok = true;
163
164                 for (uint32_t j = 0; j < N; ++j) {
165                         /* Every port on bundle channel j must be connected to our input j */
166                         Bundle::PortList const pl = (*i)->bundle->channel_ports (j);
167                         for (uint32_t k = 0; k < pl.size(); ++k) {
168                                 if (_ports.port(j)->connected_to (pl[k]) == false) {
169                                         ok = false;
170                                         break;
171                                 }
172                         }
173
174                         if (ok == false) {
175                                 break;
176                         }
177                 }
178
179                 if (ok) {
180                         new_list.push_back (*i);
181                 } else {
182                         delete *i;
183                 }
184         }
185
186         _bundles_connected = new_list;
187 }
188
189
190 int
191 IO::disconnect (boost::shared_ptr<Port> our_port, string other_port, void* src)
192 {
193         if (other_port.length() == 0 || our_port == 0) {
194                 return 0;
195         }
196
197         {
198                 Glib::Threads::Mutex::Lock lm (io_lock);
199
200                 /* check that our_port is really one of ours */
201
202                 if ( ! _ports.contains(our_port)) {
203                         return -1;
204                 }
205
206                 /* disconnect it from the source */
207
208                 if (our_port->disconnect (other_port)) {
209                         error << string_compose(_("IO: cannot disconnect port %1 from %2"), our_port->name(), other_port) << endmsg;
210                         return -1;
211                 }
212
213                 check_bundles_connected ();
214         }
215
216         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
217
218         _session.set_dirty ();
219
220         return 0;
221 }
222
223 int
224 IO::connect (boost::shared_ptr<Port> our_port, string other_port, void* src)
225 {
226         if (other_port.length() == 0 || our_port == 0) {
227                 return 0;
228         }
229
230         {
231                 Glib::Threads::Mutex::Lock lm (io_lock);
232
233                 /* check that our_port is really one of ours */
234
235                 if ( ! _ports.contains(our_port) ) {
236                         return -1;
237                 }
238
239                 /* connect it to the source */
240
241                 if (our_port->connect (other_port)) {
242                         return -1;
243                 }
244         }
245         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
246         _session.set_dirty ();
247         return 0;
248 }
249
250 int
251 IO::remove_port (boost::shared_ptr<Port> port, void* src)
252 {
253         ChanCount before = _ports.count ();
254         ChanCount after = before;
255         after.set (port->type(), after.get (port->type()) - 1);
256
257         boost::optional<bool> const r = PortCountChanging (after); /* EMIT SIGNAL */
258         if (r.get_value_or (false)) {
259                 return -1;
260         }
261
262         IOChange change;
263
264         {
265                 BLOCK_PROCESS_CALLBACK ();
266
267                 {
268                         Glib::Threads::Mutex::Lock lm (io_lock);
269
270                         if (_ports.remove(port)) {
271                                 change.type = IOChange::Type (change.type | IOChange::ConfigurationChanged);
272                                 change.before = before;
273                                 change.after = _ports.count ();
274
275                                 if (port->connected()) {
276                                         change.type = IOChange::Type (change.type | IOChange::ConnectionsChanged);
277                                 }
278
279                                 _session.engine().unregister_port (port);
280                                 check_bundles_connected ();
281                         }
282                 }
283
284                 PortCountChanged (n_ports()); /* EMIT SIGNAL */
285
286                 if (change.type != IOChange::NoChange) {
287                         changed (change, src);
288                         _buffers.attach_buffers (_ports);
289                 }
290         }
291
292         if (change.type & IOChange::ConfigurationChanged) {
293                 setup_bundle ();
294         }
295
296         if (change.type == IOChange::NoChange) {
297                 return -1;
298         }
299
300         _session.set_dirty ();
301
302         return 0;
303 }
304
305 /** Add a port.
306  *
307  * @param destination Name of port to connect new port to.
308  * @param src Source for emitted ConfigurationChanged signal.
309  * @param type Data type of port.  Default value (NIL) will use this IO's default type.
310  */
311 int
312 IO::add_port (string destination, void* src, DataType type)
313 {
314         boost::shared_ptr<Port> our_port;
315
316         if (type == DataType::NIL) {
317                 type = _default_type;
318         }
319
320         ChanCount before = _ports.count ();
321         ChanCount after = before;
322         after.set (type, after.get (type) + 1);
323
324         bool const r = PortCountChanging (after); /* EMIT SIGNAL */
325         if (r) {
326                 return -1;
327         }
328
329         IOChange change;
330
331         {
332                 BLOCK_PROCESS_CALLBACK ();
333
334
335                 {
336                         Glib::Threads::Mutex::Lock lm (io_lock);
337
338                         /* Create a new port */
339
340                         string portname = build_legal_port_name (type);
341
342                         if (_direction == Input) {
343                                 if ((our_port = _session.engine().register_input_port (type, portname)) == 0) {
344                                         error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
345                                         return -1;
346                                 }
347                         } else {
348                                 if ((our_port = _session.engine().register_output_port (type, portname)) == 0) {
349                                         error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
350                                         return -1;
351                                 }
352                         }
353
354                         change.before = _ports.count ();
355                         _ports.add (our_port);
356                 }
357
358                 PortCountChanged (n_ports()); /* EMIT SIGNAL */
359                 change.type = IOChange::ConfigurationChanged;
360                 change.after = _ports.count ();
361                 changed (change, src); /* EMIT SIGNAL */
362                 _buffers.attach_buffers (_ports);
363         }
364
365         if (!destination.empty()) {
366                 if (our_port->connect (destination)) {
367                         return -1;
368                 }
369         }
370
371         apply_pretty_name ();
372         setup_bundle ();
373         _session.set_dirty ();
374
375         return 0;
376 }
377
378 int
379 IO::disconnect (void* src)
380 {
381         {
382                 Glib::Threads::Mutex::Lock lm (io_lock);
383
384                 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
385                         i->disconnect_all ();
386                 }
387
388                 check_bundles_connected ();
389         }
390
391         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
392
393         return 0;
394 }
395
396 /** Caller must hold process lock */
397 int
398 IO::ensure_ports_locked (ChanCount count, bool clear, bool& changed)
399 {
400 #ifndef PLATFORM_WINDOWS
401         assert (!AudioEngine::instance()->process_lock().trylock());
402 #endif
403
404         boost::shared_ptr<Port> port;
405
406         changed    = false;
407
408         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
409
410                 const size_t n = count.get(*t);
411
412                 /* remove unused ports */
413                 for (size_t i = n_ports().get(*t); i > n; --i) {
414                         port = _ports.port(*t, i-1);
415
416                         assert(port);
417                         _ports.remove(port);
418                         _session.engine().unregister_port (port);
419
420                         changed = true;
421                 }
422
423                 /* create any necessary new ports */
424                 while (n_ports().get(*t) < n) {
425
426                         string portname = build_legal_port_name (*t);
427
428                         try {
429
430                                 if (_direction == Input) {
431                                         if ((port = _session.engine().register_input_port (*t, portname)) == 0) {
432                                                 error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
433                                                 return -1;
434                                         }
435                                 } else {
436                                         if ((port = _session.engine().register_output_port (*t, portname)) == 0) {
437                                                 error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
438                                                 return -1;
439                                         }
440                                 }
441                         }
442
443                         catch (AudioEngine::PortRegistrationFailure& err) {
444                                 /* pass it on */
445                                 throw;
446                         }
447
448                         _ports.add (port);
449                         changed = true;
450                 }
451         }
452
453         if (changed) {
454                 check_bundles_connected ();
455                 PortCountChanged (n_ports()); /* EMIT SIGNAL */
456                 _session.set_dirty ();
457         }
458
459         if (clear) {
460                 /* disconnect all existing ports so that we get a fresh start */
461                 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
462                         i->disconnect_all ();
463                 }
464         }
465
466         return 0;
467 }
468
469 /** Caller must hold process lock */
470 int
471 IO::ensure_ports (ChanCount count, bool clear, void* src)
472 {
473 #ifndef PLATFORM_WINDOWS
474         assert (!AudioEngine::instance()->process_lock().trylock());
475 #endif
476
477         bool changed = false;
478
479         if (count == n_ports() && !clear) {
480                 return 0;
481         }
482
483         IOChange change;
484
485         change.before = _ports.count ();
486
487         {
488                 Glib::Threads::Mutex::Lock im (io_lock);
489                 if (ensure_ports_locked (count, clear, changed)) {
490                         return -1;
491                 }
492         }
493
494         if (changed) {
495                 change.after = _ports.count ();
496                 change.type = IOChange::ConfigurationChanged;
497                 this->changed (change, src); /* EMIT SIGNAL */
498                 _buffers.attach_buffers (_ports);
499                 setup_bundle ();
500                 _session.set_dirty ();
501         }
502
503         return 0;
504 }
505
506 /** Caller must hold process lock */
507 int
508 IO::ensure_io (ChanCount count, bool clear, void* src)
509 {
510 #ifndef PLATFORM_WINDOWS
511         assert (!AudioEngine::instance()->process_lock().trylock());
512 #endif
513
514         return ensure_ports (count, clear, src);
515 }
516
517 XMLNode&
518 IO::get_state ()
519 {
520         return state (true);
521 }
522
523 XMLNode&
524 IO::state (bool /*full_state*/)
525 {
526         XMLNode* node = new XMLNode (state_node_name);
527         char buf[64];
528         string str;
529         int n;
530         LocaleGuard lg (X_("C"));
531         Glib::Threads::Mutex::Lock lm (io_lock);
532
533         node->add_property("name", _name);
534         id().print (buf, sizeof (buf));
535         node->add_property("id", buf);
536         node->add_property ("direction", enum_2_string (_direction));
537         node->add_property ("default-type", _default_type.to_string());
538
539         if (!_pretty_name_prefix.empty ()) {
540                 node->add_property("pretty-name", _pretty_name_prefix);
541         }
542
543         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
544                 XMLNode* n = new XMLNode ("Bundle");
545                 n->add_property ("name", (*i)->bundle->name ());
546                 node->add_child_nocopy (*n);
547         }
548
549         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
550
551                 vector<string> connections;
552
553                 XMLNode* pnode = new XMLNode (X_("Port"));
554                 pnode->add_property (X_("type"), i->type().to_string());
555                 pnode->add_property (X_("name"), i->name());
556
557                 if (i->get_connections (connections)) {
558                         vector<string>::const_iterator ci;
559                         std::sort (connections.begin(), connections.end());
560
561                         for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
562
563                                 /* if its a connection to our own port,
564                                    return only the port name, not the
565                                    whole thing. this allows connections
566                                    to be re-established even when our
567                                    client name is different.
568                                 */
569
570                                 XMLNode* cnode = new XMLNode (X_("Connection"));
571
572                                 cnode->add_property (X_("other"), _session.engine().make_port_name_relative (*ci));
573                                 pnode->add_child_nocopy (*cnode);
574                         }
575                 }
576
577                 node->add_child_nocopy (*pnode);
578         }
579
580         snprintf (buf, sizeof (buf), "%" PRId64, _user_latency);
581         node->add_property (X_("user-latency"), buf);
582
583         return *node;
584 }
585
586 int
587 IO::set_state (const XMLNode& node, int version)
588 {
589         /* callers for version < 3000 need to call set_state_2X directly, as A3 IOs
590          * are input OR output, not both, so the direction needs to be specified
591          * by the caller.
592          */
593         assert (version >= 3000);
594
595         const XMLProperty* prop;
596         XMLNodeConstIterator iter;
597         LocaleGuard lg (X_("C"));
598
599         /* force use of non-localized representation of decimal point,
600            since we use it a lot in XML files and so forth.
601         */
602
603         if (node.name() != state_node_name) {
604                 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
605                 return -1;
606         }
607
608         if ((prop = node.property ("name")) != 0) {
609                 set_name (prop->value());
610         }
611
612         if ((prop = node.property (X_("default-type"))) != 0) {
613                 _default_type = DataType(prop->value());
614                 assert(_default_type != DataType::NIL);
615         }
616
617         set_id (node);
618
619         if ((prop = node.property ("direction")) != 0) {
620                 _direction = (Direction) string_2_enum (prop->value(), _direction);
621         }
622
623         if (create_ports (node, version)) {
624                 return -1;
625         }
626
627         // after create_ports, updates names
628         if ((prop = node.property ("pretty-name")) != 0) {
629                 set_pretty_name (prop->value());
630         }
631
632         if (connecting_legal) {
633
634                 if (make_connections (node, version, false)) {
635                         return -1;
636                 }
637
638         } else {
639
640                 pending_state_node = new XMLNode (node);
641                 pending_state_node_version = version;
642                 pending_state_node_in = false;
643                 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
644         }
645
646         if ((prop = node.property ("user-latency")) != 0) {
647                 _user_latency = atoi (prop->value ());
648         }
649
650         return 0;
651 }
652
653 int
654 IO::set_state_2X (const XMLNode& node, int version, bool in)
655 {
656         const XMLProperty* prop;
657         XMLNodeConstIterator iter;
658         LocaleGuard lg (X_("C"));
659
660         /* force use of non-localized representation of decimal point,
661            since we use it a lot in XML files and so forth.
662         */
663
664         if (node.name() != state_node_name) {
665                 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
666                 return -1;
667         }
668
669         if ((prop = node.property ("name")) != 0) {
670                 set_name (prop->value());
671         }
672
673         if ((prop = node.property (X_("default-type"))) != 0) {
674                 _default_type = DataType(prop->value());
675                 assert(_default_type != DataType::NIL);
676         }
677
678         set_id (node);
679
680         _direction = in ? Input : Output;
681
682         if (create_ports (node, version)) {
683                 return -1;
684         }
685
686         if (connecting_legal) {
687
688                 if (make_connections_2X (node, version, in)) {
689                         return -1;
690                 }
691
692         } else {
693
694                 pending_state_node = new XMLNode (node);
695                 pending_state_node_version = version;
696                 pending_state_node_in = in;
697                 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
698         }
699
700         return 0;
701 }
702
703 int
704 IO::connecting_became_legal ()
705 {
706         int ret = 0;
707
708         assert (pending_state_node);
709
710         connection_legal_c.disconnect ();
711
712     // it's not required for TracksLive, as long as TracksLive's session does all the connections when it's being loaded
713     if (!Profile->get_trx() ) {
714         ret = make_connections (*pending_state_node, pending_state_node_version, pending_state_node_in);
715     }
716
717         delete pending_state_node;
718         pending_state_node = 0;
719
720         return ret;
721 }
722
723 boost::shared_ptr<Bundle>
724 IO::find_possible_bundle (const string &desired_name)
725 {
726         static const string digits = "0123456789";
727         const string &default_name = (_direction == Input ? _("in") : _("out"));
728         const string &bundle_type_name = (_direction == Input ? _("input") : _("output"));
729
730         boost::shared_ptr<Bundle> c = _session.bundle_by_name (desired_name);
731
732         if (!c) {
733                 int bundle_number, mask;
734                 string possible_name;
735                 bool stereo = false;
736                 string::size_type last_non_digit_pos;
737
738                 error << string_compose(_("Unknown bundle \"%1\" listed for %2 of %3"), desired_name, bundle_type_name, _name)
739                       << endmsg;
740
741                 // find numeric suffix of desired name
742                 bundle_number = 0;
743
744                 last_non_digit_pos = desired_name.find_last_not_of(digits);
745
746                 if (last_non_digit_pos != string::npos) {
747                         stringstream s;
748                         s << desired_name.substr(last_non_digit_pos);
749                         s >> bundle_number;
750                 }
751
752                 // see if it's a stereo connection e.g. "in 3+4"
753
754                 if (last_non_digit_pos > 1 && desired_name[last_non_digit_pos] == '+') {
755                         string::size_type left_last_non_digit_pos;
756
757                         left_last_non_digit_pos = desired_name.find_last_not_of(digits, last_non_digit_pos-1);
758
759                         if (left_last_non_digit_pos != string::npos) {
760                                 int left_bundle_number = 0;
761                                 stringstream s;
762                                 s << desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
763                                 s >> left_bundle_number;
764
765                                 if (left_bundle_number > 0 && left_bundle_number + 1 == bundle_number) {
766                                         bundle_number--;
767                                         stereo = true;
768                                 }
769                         }
770                 }
771
772                 // make 0-based
773                 if (bundle_number)
774                         bundle_number--;
775
776                 // find highest set bit
777                 mask = 1;
778                 while ((mask <= bundle_number) && (mask <<= 1)) {}
779
780                 // "wrap" bundle number into largest possible power of 2
781                 // that works...
782
783                 while (mask) {
784
785                         if (bundle_number & mask) {
786                                 bundle_number &= ~mask;
787
788                                 stringstream s;
789                                 s << default_name << " " << bundle_number + 1;
790
791                                 if (stereo) {
792                                         s << "+" << bundle_number + 2;
793                                 }
794
795                                 possible_name = s.str();
796
797                                 if ((c = _session.bundle_by_name (possible_name)) != 0) {
798                                         break;
799                                 }
800                         }
801                         mask >>= 1;
802                 }
803                 if (c) {
804                         info << string_compose (_("Bundle %1 was not available - \"%2\" used instead"), desired_name, possible_name)
805                              << endmsg;
806                 } else {
807                         error << string_compose(_("No %1 bundles available as a replacement"), bundle_type_name)
808                               << endmsg;
809                 }
810
811         }
812
813         return c;
814
815 }
816
817 int
818 IO::get_port_counts_2X (XMLNode const & node, int /*version*/, ChanCount& n, boost::shared_ptr<Bundle>& /*c*/)
819 {
820         XMLProperty const * prop;
821         XMLNodeList children = node.children ();
822
823         uint32_t n_audio = 0;
824
825         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
826
827                 if ((prop = node.property ("inputs")) != 0 && _direction == Input) {
828                         n_audio = count (prop->value().begin(), prop->value().end(), '{');
829                 } else if ((prop = node.property ("input-connection")) != 0 && _direction == Input) {
830                         n_audio = 1;
831                 } else if ((prop = node.property ("outputs")) != 0 && _direction == Output) {
832                         n_audio = count (prop->value().begin(), prop->value().end(), '{');
833                 } else if ((prop = node.property ("output-connection")) != 0 && _direction == Output) {
834                         n_audio = 2;
835                 }
836         }
837
838         ChanCount cnt;
839         cnt.set_audio (n_audio);
840         n = ChanCount::max (n, cnt);
841
842         return 0;
843 }
844
845 int
846 IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shared_ptr<Bundle>& c)
847 {
848         if (version < 3000) {
849                 return get_port_counts_2X (node, version, n, c);
850         }
851
852         XMLProperty const * prop;
853         XMLNodeConstIterator iter;
854         uint32_t n_audio = 0;
855         uint32_t n_midi = 0;
856         ChanCount cnt;
857
858         n = n_ports();
859
860         if ((prop = node.property ("connection")) != 0) {
861
862                 if ((c = find_possible_bundle (prop->value())) != 0) {
863                         n = ChanCount::max (n, c->nchannels());
864                 }
865                 return 0;
866         }
867
868         for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
869
870                 if ((*iter)->name() == X_("Bundle")) {
871                         prop = (*iter)->property ("name");
872                         if ((c = find_possible_bundle (prop->value())) != 0) {
873                                 n = ChanCount::max (n, c->nchannels());
874                                 return 0;
875                         } else {
876                                 return -1;
877                         }
878                 }
879
880                 if ((*iter)->name() == X_("Port")) {
881                         prop = (*iter)->property (X_("type"));
882
883                         if (!prop) {
884                                 continue;
885                         }
886
887                         if (prop->value() == X_("audio")) {
888                                 cnt.set_audio (++n_audio);
889                         } else if (prop->value() == X_("midi")) {
890                                 cnt.set_midi (++n_midi);
891                         }
892                 }
893         }
894
895         n = ChanCount::max (n, cnt);
896         return 0;
897 }
898
899 int
900 IO::create_ports (const XMLNode& node, int version)
901 {
902         ChanCount n;
903         boost::shared_ptr<Bundle> c;
904
905         get_port_counts (node, version, n, c);
906
907         {
908                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
909
910                 if (ensure_ports (n, true, this)) {
911                         error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
912                         return -1;
913                 }
914         }
915
916         /* XXX use c */
917
918         return 0;
919 }
920
921 int
922 IO::make_connections (const XMLNode& node, int version, bool in)
923 {
924         if (version < 3000) {
925                 return make_connections_2X (node, version, in);
926         }
927
928         const XMLProperty* prop;
929
930         for (XMLNodeConstIterator i = node.children().begin(); i != node.children().end(); ++i) {
931
932                 if ((*i)->name() == "Bundle") {
933                         XMLProperty const * prop = (*i)->property ("name");
934                         if (prop) {
935                                 boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value());
936                                 if (b) {
937                                         connect_ports_to_bundle (b, true, this);
938                                 }
939                         }
940
941                         return 0;
942                 }
943
944                 if ((*i)->name() == "Port") {
945
946                         prop = (*i)->property (X_("name"));
947
948                         if (!prop) {
949                                 continue;
950                         }
951
952                         boost::shared_ptr<Port> p = port_by_name (prop->value());
953
954                         if (p) {
955                                 for (XMLNodeConstIterator c = (*i)->children().begin(); c != (*i)->children().end(); ++c) {
956
957                                         XMLNode* cnode = (*c);
958
959                                         if (cnode->name() != X_("Connection")) {
960                                                 continue;
961                                         }
962
963                                         if ((prop = cnode->property (X_("other"))) == 0) {
964                                                 continue;
965                                         }
966
967                                         if (prop) {
968                                                 connect (p, prop->value(), this);
969                                         }
970                                 }
971                         }
972                 }
973         }
974
975         return 0;
976 }
977
978 void
979 IO::prepare_for_reset (XMLNode& node, const std::string& name)
980 {
981         /* reset name */
982         node.add_property ("name", name);
983
984         /* now find connections and reset the name of the port
985            in one so that when we re-use it it will match
986            the name of the thing we're applying it to.
987         */
988
989         XMLProperty* prop;
990         XMLNodeList children = node.children();
991
992         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
993
994                 if ((*i)->name() == "Port") {
995
996                         prop = (*i)->property (X_("name"));
997
998                         if (prop) {
999                                 string new_name;
1000                                 string old = prop->value();
1001                                 string::size_type slash = old.find ('/');
1002
1003                                 if (slash != string::npos) {
1004                                         /* port name is of form: <IO-name>/<port-name> */
1005
1006                                         new_name = name;
1007                                         new_name += old.substr (old.find ('/'));
1008
1009                                         prop->set_value (new_name);
1010                                 }
1011                         }
1012                 }
1013         }
1014 }
1015
1016
1017 int
1018 IO::make_connections_2X (const XMLNode& node, int /*version*/, bool in)
1019 {
1020         const XMLProperty* prop;
1021
1022         /* XXX: bundles ("connections" as was) */
1023
1024         if ((prop = node.property ("inputs")) != 0 && in) {
1025
1026                 string::size_type ostart = 0;
1027                 string::size_type start = 0;
1028                 string::size_type end = 0;
1029                 int i = 0;
1030                 int n;
1031                 vector<string> ports;
1032
1033                 string const str = prop->value ();
1034
1035                 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1036                         start += 1;
1037
1038                         if ((end = str.find_first_of ('}', start)) == string::npos) {
1039                                 error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1040                                 return -1;
1041                         }
1042
1043                         if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1044                                 error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1045
1046                                 return -1;
1047
1048                         } else if (n > 0) {
1049
1050
1051                                 for (int x = 0; x < n; ++x) {
1052                                         /* XXX: this is a bit of a hack; need to check if it's always valid */
1053                                         string::size_type const p = ports[x].find ("/out");
1054                                         if (p != string::npos) {
1055                                                 ports[x].replace (p, 4, "/audio_out");
1056                                         }
1057                                         if (NULL != nth(i).get())
1058                                                 nth(i)->connect (ports[x]);
1059                                 }
1060                         }
1061
1062                         ostart = end+1;
1063                         i++;
1064                 }
1065
1066         }
1067
1068         if ((prop = node.property ("outputs")) != 0 && !in) {
1069
1070                 string::size_type ostart = 0;
1071                 string::size_type start = 0;
1072                 string::size_type end = 0;
1073                 int i = 0;
1074                 int n;
1075                 vector<string> ports;
1076
1077                 string const str = prop->value ();
1078
1079                 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1080                         start += 1;
1081
1082                         if ((end = str.find_first_of ('}', start)) == string::npos) {
1083                                 error << string_compose(_("IO: badly formed string in XML node for outputs \"%1\""), str) << endmsg;
1084                                 return -1;
1085                         }
1086
1087                         if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1088                                 error << string_compose(_("IO: bad output string in XML node \"%1\""), str) << endmsg;
1089
1090                                 return -1;
1091
1092                         } else if (n > 0) {
1093
1094                                 for (int x = 0; x < n; ++x) {
1095                                         /* XXX: this is a bit of a hack; need to check if it's always valid */
1096                                         string::size_type const p = ports[x].find ("/in");
1097                                         if (p != string::npos) {
1098                                                 ports[x].replace (p, 3, "/audio_in");
1099                                         }
1100                                         if (NULL != nth(i).get())
1101                                                 nth(i)->connect (ports[x]);
1102                                 }
1103                         }
1104
1105                         ostart = end+1;
1106                         i++;
1107                 }
1108         }
1109
1110         return 0;
1111 }
1112
1113 int
1114 IO::set_ports (const string& str)
1115 {
1116         vector<string> ports;
1117         int n;
1118         uint32_t nports;
1119
1120         if ((nports = count (str.begin(), str.end(), '{')) == 0) {
1121                 return 0;
1122         }
1123
1124         {
1125                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1126
1127                 // FIXME: audio-only
1128                 if (ensure_ports (ChanCount(DataType::AUDIO, nports), true, this)) {
1129                         return -1;
1130                 }
1131         }
1132
1133         string::size_type start  = 0;
1134         string::size_type end    = 0;
1135         string::size_type ostart = 0;
1136         for (int i = 0; (start = str.find_first_of ('{', ostart)) != string::npos; ++i) {
1137                 start += 1;
1138
1139                 if ((end = str.find_first_of ('}', start)) == string::npos) {
1140                         error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1141                         return -1;
1142                 }
1143
1144                 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1145                         error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1146
1147                         return -1;
1148
1149                 } else if (n > 0) {
1150
1151                         for (int x = 0; x < n; ++x) {
1152                                 connect (nth (i), ports[x], this);
1153                         }
1154                 }
1155
1156                 ostart = end+1;
1157         }
1158
1159         return 0;
1160 }
1161
1162 int
1163 IO::parse_io_string (const string& str, vector<string>& ports)
1164 {
1165         string::size_type pos, opos;
1166
1167         if (str.length() == 0) {
1168                 return 0;
1169         }
1170
1171         opos = 0;
1172
1173         ports.clear ();
1174
1175         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1176                 ports.push_back (str.substr (opos, pos - opos));
1177                 opos = pos + 1;
1178         }
1179
1180         if (opos < str.length()) {
1181                 ports.push_back (str.substr(opos));
1182         }
1183
1184         return ports.size();
1185 }
1186
1187 int
1188 IO::parse_gain_string (const string& str, vector<string>& ports)
1189 {
1190         string::size_type pos, opos;
1191
1192         opos = 0;
1193         ports.clear ();
1194
1195         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1196                 ports.push_back (str.substr (opos, pos - opos));
1197                 opos = pos + 1;
1198         }
1199
1200         if (opos < str.length()) {
1201                 ports.push_back (str.substr(opos));
1202         }
1203
1204         return ports.size();
1205 }
1206
1207 bool
1208 IO::set_name (const string& requested_name)
1209 {
1210         string name = requested_name;
1211
1212         if (_name == name) {
1213                 return true;
1214         }
1215
1216         /* replace all colons in the name. i wish we didn't have to do this */
1217
1218         replace_all (name, ":", "-");
1219
1220         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
1221                 string current_name = i->name();
1222                 current_name.replace (current_name.find (_name), _name.val().length(), name);
1223                 i->set_name (current_name);
1224         }
1225
1226         bool const r = SessionObject::set_name (name);
1227
1228         setup_bundle ();
1229
1230         return r;
1231 }
1232
1233 void
1234 IO::set_pretty_name (const std::string& str)
1235 {
1236         if (_pretty_name_prefix == str) {
1237                 return;
1238         }
1239         _pretty_name_prefix = str;
1240         apply_pretty_name ();
1241 }
1242
1243 void
1244 IO::apply_pretty_name ()
1245 {
1246         uint32_t pn = 1;
1247         if (_pretty_name_prefix.empty ()) {
1248                 return;
1249         }
1250         for (PortSet::iterator i = _ports.begin (); i != _ports.end(); ++i, ++pn) {
1251                 (*i)->set_pretty_name (string_compose (("%1/%2 %3"),
1252                                         _pretty_name_prefix,
1253                                         _direction == Output ? _("Out") : _("In"),
1254                                         pn));
1255         }
1256 }
1257
1258 framecnt_t
1259 IO::latency () const
1260 {
1261         framecnt_t max_latency;
1262         framecnt_t latency;
1263
1264         max_latency = 0;
1265
1266         /* io lock not taken - must be protected by other means */
1267
1268         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1269                 if ((latency = i->private_latency_range (_direction == Output).max) > max_latency) {
1270                         DEBUG_TRACE (DEBUG::Latency, string_compose ("port %1 has %2 latency of %3 - use\n",
1271                                                                      name(),
1272                                                                      ((_direction == Output) ? "PLAYBACK" : "CAPTURE"),
1273                                                                      latency));
1274                         max_latency = latency;
1275                 }
1276         }
1277
1278         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: max %4 latency from %2 ports = %3\n",
1279                                                      name(), _ports.num_ports(), max_latency,
1280                                                      ((_direction == Output) ? "PLAYBACK" : "CAPTURE")));
1281         return max_latency;
1282 }
1283
1284 int
1285 IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, bool exclusive, void* src)
1286 {
1287         BLOCK_PROCESS_CALLBACK ();
1288
1289         {
1290                 Glib::Threads::Mutex::Lock lm2 (io_lock);
1291
1292                 if (exclusive) {
1293                         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
1294                                 i->disconnect_all ();
1295                         }
1296                 }
1297
1298                 c->connect (_bundle, _session.engine());
1299
1300                 /* If this is a UserBundle, make a note of what we've done */
1301
1302                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1303                 if (ub) {
1304
1305                         /* See if we already know about this one */
1306                         std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1307                         while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1308                                 ++i;
1309                         }
1310
1311                         if (i == _bundles_connected.end()) {
1312                                 /* We don't, so make a note */
1313                                 _bundles_connected.push_back (new UserBundleInfo (this, ub));
1314                         }
1315                 }
1316         }
1317
1318         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1319         return 0;
1320 }
1321
1322 int
1323 IO::disconnect_ports_from_bundle (boost::shared_ptr<Bundle> c, void* src)
1324 {
1325         BLOCK_PROCESS_CALLBACK ();
1326
1327         {
1328                 Glib::Threads::Mutex::Lock lm2 (io_lock);
1329
1330                 c->disconnect (_bundle, _session.engine());
1331
1332                 /* If this is a UserBundle, make a note of what we've done */
1333
1334                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1335                 if (ub) {
1336
1337                         std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1338                         while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1339                                 ++i;
1340                         }
1341
1342                         if (i != _bundles_connected.end()) {
1343                                 delete *i;
1344                                 _bundles_connected.erase (i);
1345                         }
1346                 }
1347         }
1348
1349         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1350         return 0;
1351 }
1352
1353
1354 int
1355 IO::disable_connecting ()
1356 {
1357         connecting_legal = false;
1358         return 0;
1359 }
1360
1361 int
1362 IO::enable_connecting ()
1363 {
1364         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
1365         connecting_legal = true;
1366         boost::optional<int> r = ConnectingLegal ();
1367         return r.get_value_or (0);
1368 }
1369
1370 void
1371 IO::bundle_changed (Bundle::Change /*c*/)
1372 {
1373         /* XXX */
1374 //      connect_input_ports_to_bundle (_input_bundle, this);
1375 }
1376
1377
1378 string
1379 IO::build_legal_port_name (DataType type)
1380 {
1381         const int name_size = AudioEngine::instance()->port_name_size();
1382         int limit;
1383         string suffix;
1384
1385         if (type == DataType::AUDIO) {
1386                 suffix = X_("audio");
1387         } else if (type == DataType::MIDI) {
1388                 suffix = X_("midi");
1389         } else {
1390                 throw unknown_type();
1391         }
1392
1393         /* note that if "in" or "out" are translated it will break a session
1394            across locale switches because a port's connection list will
1395            show (old) translated names, but the current port name will
1396            use the (new) translated name.
1397         */
1398
1399         if (_sendish) {
1400                 if (_direction == Input) {
1401                         suffix += X_("_return");
1402                 } else {
1403                         suffix += X_("_send");
1404                 }
1405         } else {
1406                 if (_direction == Input) {
1407                         suffix += X_("_in");
1408                 } else {
1409                         suffix += X_("_out");
1410                 }
1411         }
1412
1413         // allow up to 4 digits for the output port number, plus the slash, suffix and extra space
1414
1415         limit = name_size - AudioEngine::instance()->my_name().length() - (suffix.length() + 5);
1416
1417         std::vector<char> buf1(name_size+1);
1418         std::vector<char> buf2(name_size+1);
1419
1420         /* colons are illegal in port names, so fix that */
1421
1422         string nom = _name.val();
1423         replace_all (nom, ":", ";");
1424
1425         snprintf (&buf1[0], name_size+1, ("%.*s/%s"), limit, nom.c_str(), suffix.c_str());
1426
1427         int port_number = find_port_hole (&buf1[0]);
1428         snprintf (&buf2[0], name_size+1, "%s %d", &buf1[0], port_number);
1429
1430         return string (&buf2[0]);
1431 }
1432
1433 int32_t
1434 IO::find_port_hole (const char* base)
1435 {
1436         /* CALLER MUST HOLD IO LOCK */
1437
1438         uint32_t n;
1439
1440         if (_ports.empty()) {
1441                 return 1;
1442         }
1443
1444         /* we only allow up to 4 characters for the port number
1445          */
1446
1447         for (n = 1; n < 9999; ++n) {
1448                 std::vector<char> buf (AudioEngine::instance()->port_name_size());
1449                 PortSet::iterator i = _ports.begin();
1450
1451                 snprintf (&buf[0], buf.size()+1, _("%s %u"), base, n);
1452
1453                 for ( ; i != _ports.end(); ++i) {
1454                         if (string(i->name()) == string(&buf[0])) {
1455                                 break;
1456                         }
1457                 }
1458
1459                 if (i == _ports.end()) {
1460                         break;
1461                 }
1462         }
1463         return n;
1464 }
1465
1466
1467 boost::shared_ptr<AudioPort>
1468 IO::audio(uint32_t n) const
1469 {
1470         return _ports.nth_audio_port (n);
1471
1472 }
1473
1474 boost::shared_ptr<MidiPort>
1475 IO::midi(uint32_t n) const
1476 {
1477         return _ports.nth_midi_port (n);
1478 }
1479
1480 /**
1481  *  Setup a bundle that describe our inputs or outputs. Also creates the bundle if necessary.
1482  */
1483
1484 void
1485 IO::setup_bundle ()
1486 {
1487         char buf[32];
1488
1489         if (!_bundle) {
1490                 _bundle.reset (new Bundle (_direction == Input));
1491         }
1492
1493         _bundle->suspend_signals ();
1494
1495         _bundle->remove_channels ();
1496
1497         if (_direction == Input) {
1498                 snprintf(buf, sizeof (buf), _("%s in"), _name.val().c_str());
1499         } else {
1500                 snprintf(buf, sizeof (buf), _("%s out"), _name.val().c_str());
1501         }
1502         _bundle->set_name (buf);
1503
1504         int c = 0;
1505         for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
1506
1507                 uint32_t const N = _ports.count().get (*i);
1508                 for (uint32_t j = 0; j < N; ++j) {
1509                         _bundle->add_channel (bundle_channel_name (j, N, *i), *i);
1510                         _bundle->set_port (c, _session.engine().make_port_name_non_relative (_ports.port(*i, j)->name()));
1511                         ++c;
1512                 }
1513
1514         }
1515
1516         _bundle->resume_signals ();
1517 }
1518
1519 /** @return Bundles connected to our ports */
1520 BundleList
1521 IO::bundles_connected ()
1522 {
1523         BundleList bundles;
1524
1525         /* User bundles */
1526         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
1527                 bundles.push_back ((*i)->bundle);
1528         }
1529
1530         /* Session bundles */
1531         boost::shared_ptr<ARDOUR::BundleList> b = _session.bundles ();
1532         for (ARDOUR::BundleList::iterator i = b->begin(); i != b->end(); ++i) {
1533                 if ((*i)->connected_to (_bundle, _session.engine())) {
1534                         bundles.push_back (*i);
1535                 }
1536         }
1537
1538         /* Route bundles */
1539
1540         boost::shared_ptr<ARDOUR::RouteList> r = _session.get_routes ();
1541
1542         if (_direction == Input) {
1543                 for (ARDOUR::RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1544                         if ((*i)->output()->bundle()->connected_to (_bundle, _session.engine())) {
1545                                 bundles.push_back ((*i)->output()->bundle());
1546                         }
1547                 }
1548         } else {
1549                 for (ARDOUR::RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1550                         if ((*i)->input()->bundle()->connected_to (_bundle, _session.engine())) {
1551                                 bundles.push_back ((*i)->input()->bundle());
1552                         }
1553                 }
1554         }
1555
1556         return bundles;
1557 }
1558
1559
1560 IO::UserBundleInfo::UserBundleInfo (IO* io, boost::shared_ptr<UserBundle> b)
1561 {
1562         bundle = b;
1563         b->Changed.connect_same_thread (changed, boost::bind (&IO::bundle_changed, io, _1));
1564 }
1565
1566 std::string
1567 IO::bundle_channel_name (uint32_t c, uint32_t n, DataType t) const
1568 {
1569         char buf[32];
1570
1571         if (t == DataType::AUDIO) {
1572
1573                 switch (n) {
1574                 case 1:
1575                         return _("mono");
1576                 case 2:
1577                         return c == 0 ? _("L") : _("R");
1578                 default:
1579                         snprintf (buf, sizeof(buf), _("%d"), (c + 1));
1580                         return buf;
1581                 }
1582
1583         } else {
1584
1585                 snprintf (buf, sizeof(buf), _("%d"), (c + 1));
1586                 return buf;
1587
1588         }
1589
1590         return "";
1591 }
1592
1593 string
1594 IO::name_from_state (const XMLNode& node)
1595 {
1596         const XMLProperty* prop;
1597
1598         if ((prop = node.property ("name")) != 0) {
1599                 return prop->value();
1600         }
1601
1602         return string();
1603 }
1604
1605 void
1606 IO::set_name_in_state (XMLNode& node, const string& new_name)
1607 {
1608         node.add_property (X_("name"), new_name);
1609         XMLNodeList children = node.children ();
1610         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
1611                 if ((*i)->name() == X_("Port")) {
1612                         string const old_name = (*i)->property(X_("name"))->value();
1613                         string const old_name_second_part = old_name.substr (old_name.find_first_of ("/") + 1);
1614                         (*i)->add_property (X_("name"), string_compose ("%1/%2", new_name, old_name_second_part));
1615                 }
1616         }
1617 }
1618
1619 bool
1620 IO::connected () const
1621 {
1622         /* do we have any connections at all? */
1623
1624         for (PortSet::const_iterator p = _ports.begin(); p != _ports.end(); ++p) {
1625                 if (p->connected()) {
1626                         return true;
1627                 }
1628         }
1629
1630         return false;
1631 }
1632
1633 bool
1634 IO::connected_to (boost::shared_ptr<const IO> other) const
1635 {
1636         if (!other) {
1637                 return connected ();
1638         }
1639
1640         assert (_direction != other->direction());
1641
1642         uint32_t i, j;
1643         uint32_t no = n_ports().n_total();
1644         uint32_t ni = other->n_ports ().n_total();
1645
1646         for (i = 0; i < no; ++i) {
1647                 for (j = 0; j < ni; ++j) {
1648                         if ((NULL != nth(i).get()) && (NULL != other->nth(j).get())) {
1649                                 if (nth(i)->connected_to (other->nth(j)->name())) {
1650                                         return true;
1651                                 }
1652                         }
1653                 }
1654         }
1655
1656         return false;
1657 }
1658
1659 bool
1660 IO::connected_to (const string& str) const
1661 {
1662         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1663                 if (i->connected_to (str)) {
1664                         return true;
1665                 }
1666         }
1667
1668         return false;
1669 }
1670
1671 /** Call a processor's ::run() method, giving it our buffers
1672  *  Caller must hold process lock.
1673  */
1674 void
1675 IO::process_input (boost::shared_ptr<Processor> proc, framepos_t start_frame, framepos_t end_frame, pframes_t nframes)
1676 {
1677         /* don't read the data into new buffers - just use the port buffers directly */
1678
1679         if (n_ports().n_total() == 0) {
1680                 /* We have no ports, so nothing to process */
1681                 return;
1682         }
1683
1684         _buffers.get_backend_port_addresses (_ports, nframes);
1685         if (proc) {
1686                 proc->run (_buffers, start_frame, end_frame, nframes, true);
1687         }
1688 }
1689
1690 void
1691 IO::collect_input (BufferSet& bufs, pframes_t nframes, ChanCount offset)
1692 {
1693         assert(bufs.available() >= _ports.count());
1694
1695         if (_ports.count() == ChanCount::ZERO) {
1696                 return;
1697         }
1698
1699         bufs.set_count (_ports.count());
1700
1701         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1702                 PortSet::iterator   i = _ports.begin(*t);
1703                 BufferSet::iterator b = bufs.begin(*t);
1704
1705                 for (uint32_t off = 0; off < offset.get(*t); ++off, ++b) {
1706                         if (b == bufs.end(*t)) {
1707                                 continue;
1708                         }
1709                 }
1710
1711                 for ( ; i != _ports.end(*t); ++i, ++b) {
1712                         const Buffer& bb (i->get_buffer (nframes));
1713                         b->read_from (bb, nframes);
1714                 }
1715         }
1716 }
1717
1718 void
1719 IO::copy_to_outputs (BufferSet& bufs, DataType type, pframes_t nframes, framecnt_t offset)
1720 {
1721         // Copy any buffers 1:1 to outputs
1722
1723         PortSet::iterator o = _ports.begin(type);
1724         BufferSet::iterator i = bufs.begin(type);
1725         BufferSet::iterator prev = i;
1726
1727         while (i != bufs.end(type) && o != _ports.end (type)) {
1728                 Buffer& port_buffer (o->get_buffer (nframes));
1729                 port_buffer.read_from (*i, nframes, offset);
1730                 prev = i;
1731                 ++i;
1732                 ++o;
1733         }
1734
1735         // Copy last buffer to any extra outputs
1736
1737         while (o != _ports.end(type)) {
1738                 Buffer& port_buffer (o->get_buffer (nframes));
1739                 port_buffer.read_from (*prev, nframes, offset);
1740                 ++o;
1741         }
1742 }
1743
1744 boost::shared_ptr<Port>
1745 IO::port_by_name (const std::string& str) const
1746 {
1747         /* to be called only from ::set_state() - no locking */
1748
1749         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1750
1751                 if (i->name() == str) {
1752                         return boost::const_pointer_cast<Port> (*i);
1753                 }
1754         }
1755
1756         return boost::shared_ptr<Port> ();
1757 }
1758
1759 bool
1760 IO::physically_connected () const
1761 {
1762         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1763                 if (i->physically_connected()) {
1764                         return true;
1765                 }
1766         }
1767
1768         return false;
1769 }
1770
1771 bool
1772 IO::has_port (boost::shared_ptr<Port> p) const
1773 {
1774         Glib::Threads::Mutex::Lock lm (io_lock);
1775         return _ports.contains (p);
1776 }