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