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