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