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