66aaaee68e39b20f6e8185a1f8de20651b5d3cf5
[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         id().print (buf, sizeof (buf));
561         node->add_property("id", buf);
562         node->add_property ("direction", enum_2_string (_direction));
563         node->add_property ("default-type", _default_type.to_string());
564
565         if (!_pretty_name_prefix.empty ()) {
566                 node->add_property("pretty-name", _pretty_name_prefix);
567         }
568
569         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
570                 XMLNode* n = new XMLNode ("Bundle");
571                 n->add_property ("name", (*i)->bundle->name ());
572                 node->add_child_nocopy (*n);
573         }
574
575         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
576
577                 vector<string> connections;
578
579                 XMLNode* pnode = new XMLNode (X_("Port"));
580                 pnode->add_property (X_("type"), i->type().to_string());
581                 pnode->add_property (X_("name"), i->name());
582
583                 if (i->get_connections (connections)) {
584                         vector<string>::const_iterator ci;
585                         std::sort (connections.begin(), connections.end());
586
587                         for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
588
589                                 /* if its a connection to our own port,
590                                    return only the port name, not the
591                                    whole thing. this allows connections
592                                    to be re-established even when our
593                                    client name is different.
594                                 */
595
596                                 XMLNode* cnode = new XMLNode (X_("Connection"));
597
598                                 cnode->add_property (X_("other"), _session.engine().make_port_name_relative (*ci));
599                                 pnode->add_child_nocopy (*cnode);
600                         }
601                 }
602
603                 node->add_child_nocopy (*pnode);
604         }
605
606         snprintf (buf, sizeof (buf), "%" PRId64, _user_latency);
607         node->add_property (X_("user-latency"), buf);
608
609         return *node;
610 }
611
612 int
613 IO::set_state (const XMLNode& node, int version)
614 {
615         /* callers for version < 3000 need to call set_state_2X directly, as A3 IOs
616          * are input OR output, not both, so the direction needs to be specified
617          * by the caller.
618          */
619         assert (version >= 3000);
620
621         XMLProperty const * prop;
622         XMLNodeConstIterator iter;
623         LocaleGuard lg;
624
625         /* force use of non-localized representation of decimal point,
626            since we use it a lot in XML files and so forth.
627         */
628
629         if (node.name() != state_node_name) {
630                 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
631                 return -1;
632         }
633
634         bool ignore_name = node.property ("ignore-name");
635         if ((prop = node.property ("name")) != 0 && !ignore_name) {
636                 set_name (prop->value());
637         }
638
639         if ((prop = node.property (X_("default-type"))) != 0) {
640                 _default_type = DataType(prop->value());
641                 assert(_default_type != DataType::NIL);
642         }
643
644         set_id (node);
645
646         if ((prop = node.property ("direction")) != 0) {
647                 _direction = (Direction) string_2_enum (prop->value(), _direction);
648         }
649
650         if (create_ports (node, version)) {
651                 return -1;
652         }
653
654         // after create_ports, updates names
655         if ((prop = node.property ("pretty-name")) != 0) {
656                 set_pretty_name (prop->value());
657         }
658
659         if (connecting_legal) {
660
661                 if (make_connections (node, version, false)) {
662                         return -1;
663                 }
664
665         } else {
666
667                 delete pending_state_node;
668                 pending_state_node = new XMLNode (node);
669                 pending_state_node_version = version;
670                 pending_state_node_in = false;
671                 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
672         }
673
674         if ((prop = node.property ("user-latency")) != 0) {
675                 _user_latency = atoi (prop->value ());
676         }
677
678         return 0;
679 }
680
681 int
682 IO::set_state_2X (const XMLNode& node, int version, bool in)
683 {
684         XMLProperty const * prop;
685         XMLNodeConstIterator iter;
686         LocaleGuard lg;
687
688         /* force use of non-localized representation of decimal point,
689            since we use it a lot in XML files and so forth.
690         */
691
692         if (node.name() != state_node_name) {
693                 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
694                 return -1;
695         }
696
697         if ((prop = node.property ("name")) != 0) {
698                 set_name (prop->value());
699         }
700
701         if ((prop = node.property (X_("default-type"))) != 0) {
702                 _default_type = DataType(prop->value());
703                 assert(_default_type != DataType::NIL);
704         }
705
706         set_id (node);
707
708         _direction = in ? Input : Output;
709
710         if (create_ports (node, version)) {
711                 return -1;
712         }
713
714         if (connecting_legal) {
715
716                 if (make_connections_2X (node, version, in)) {
717                         return -1;
718                 }
719
720         } else {
721
722                 delete pending_state_node;
723                 pending_state_node = new XMLNode (node);
724                 pending_state_node_version = version;
725                 pending_state_node_in = in;
726                 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
727         }
728
729         return 0;
730 }
731
732 int
733 IO::connecting_became_legal ()
734 {
735         int ret = 0;
736
737         assert (pending_state_node);
738
739         connection_legal_c.disconnect ();
740
741     // it's not required for TracksLive, as long as TracksLive's session does all the connections when it's being loaded
742     if (!Profile->get_trx() ) {
743         ret = make_connections (*pending_state_node, pending_state_node_version, pending_state_node_in);
744     }
745
746         delete pending_state_node;
747         pending_state_node = 0;
748
749         return ret;
750 }
751
752 boost::shared_ptr<Bundle>
753 IO::find_possible_bundle (const string &desired_name)
754 {
755         static const string digits = "0123456789";
756         const string &default_name = (_direction == Input ? _("in") : _("out"));
757         const string &bundle_type_name = (_direction == Input ? _("input") : _("output"));
758
759         boost::shared_ptr<Bundle> c = _session.bundle_by_name (desired_name);
760
761         if (!c) {
762                 int bundle_number, mask;
763                 string possible_name;
764                 bool stereo = false;
765                 string::size_type last_non_digit_pos;
766
767                 error << string_compose(_("Unknown bundle \"%1\" listed for %2 of %3"), desired_name, bundle_type_name, _name)
768                       << endmsg;
769
770                 // find numeric suffix of desired name
771                 bundle_number = 0;
772
773                 last_non_digit_pos = desired_name.find_last_not_of(digits);
774
775                 if (last_non_digit_pos != string::npos) {
776                         stringstream s;
777                         s << desired_name.substr(last_non_digit_pos);
778                         s >> bundle_number;
779                 }
780
781                 // see if it's a stereo connection e.g. "in 3+4"
782
783                 if (last_non_digit_pos > 1 && desired_name[last_non_digit_pos] == '+') {
784                         string::size_type left_last_non_digit_pos;
785
786                         left_last_non_digit_pos = desired_name.find_last_not_of(digits, last_non_digit_pos-1);
787
788                         if (left_last_non_digit_pos != string::npos) {
789                                 int left_bundle_number = 0;
790                                 stringstream s;
791                                 s << desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
792                                 s >> left_bundle_number;
793
794                                 if (left_bundle_number > 0 && left_bundle_number + 1 == bundle_number) {
795                                         bundle_number--;
796                                         stereo = true;
797                                 }
798                         }
799                 }
800
801                 // make 0-based
802                 if (bundle_number)
803                         bundle_number--;
804
805                 // find highest set bit
806                 mask = 1;
807                 while ((mask <= bundle_number) && (mask <<= 1)) {}
808
809                 // "wrap" bundle number into largest possible power of 2
810                 // that works...
811
812                 while (mask) {
813
814                         if (bundle_number & mask) {
815                                 bundle_number &= ~mask;
816
817                                 stringstream s;
818                                 s << default_name << " " << bundle_number + 1;
819
820                                 if (stereo) {
821                                         s << "+" << bundle_number + 2;
822                                 }
823
824                                 possible_name = s.str();
825
826                                 if ((c = _session.bundle_by_name (possible_name)) != 0) {
827                                         break;
828                                 }
829                         }
830                         mask >>= 1;
831                 }
832                 if (c) {
833                         info << string_compose (_("Bundle %1 was not available - \"%2\" used instead"), desired_name, possible_name)
834                              << endmsg;
835                 } else {
836                         error << string_compose(_("No %1 bundles available as a replacement"), bundle_type_name)
837                               << endmsg;
838                 }
839
840         }
841
842         return c;
843
844 }
845
846 int
847 IO::get_port_counts_2X (XMLNode const & node, int /*version*/, ChanCount& n, boost::shared_ptr<Bundle>& /*c*/)
848 {
849         XMLProperty const * prop;
850         XMLNodeList children = node.children ();
851
852         uint32_t n_audio = 0;
853
854         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
855
856                 if ((prop = node.property ("inputs")) != 0 && _direction == Input) {
857                         n_audio = count (prop->value().begin(), prop->value().end(), '{');
858                 } else if ((prop = node.property ("input-connection")) != 0 && _direction == Input) {
859                         n_audio = 1;
860                 } else if ((prop = node.property ("outputs")) != 0 && _direction == Output) {
861                         n_audio = count (prop->value().begin(), prop->value().end(), '{');
862                 } else if ((prop = node.property ("output-connection")) != 0 && _direction == Output) {
863                         n_audio = 2;
864                 }
865         }
866
867         ChanCount cnt;
868         cnt.set_audio (n_audio);
869         n = ChanCount::max (n, cnt);
870
871         return 0;
872 }
873
874 int
875 IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shared_ptr<Bundle>& c)
876 {
877         if (version < 3000) {
878                 return get_port_counts_2X (node, version, n, c);
879         }
880
881         XMLProperty const * prop;
882         XMLNodeConstIterator iter;
883         uint32_t n_audio = 0;
884         uint32_t n_midi = 0;
885         ChanCount cnt;
886
887         n = n_ports();
888
889         if ((prop = node.property ("connection")) != 0) {
890
891                 if ((c = find_possible_bundle (prop->value())) != 0) {
892                         n = ChanCount::max (n, c->nchannels());
893                 }
894                 return 0;
895         }
896
897         for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
898
899                 if ((*iter)->name() == X_("Bundle")) {
900                         prop = (*iter)->property ("name");
901                         if ((c = find_possible_bundle (prop->value())) != 0) {
902                                 n = ChanCount::max (n, c->nchannels());
903                                 return 0;
904                         } else {
905                                 return -1;
906                         }
907                 }
908
909                 if ((*iter)->name() == X_("Port")) {
910                         prop = (*iter)->property (X_("type"));
911
912                         if (!prop) {
913                                 continue;
914                         }
915
916                         if (prop->value() == X_("audio")) {
917                                 cnt.set_audio (++n_audio);
918                         } else if (prop->value() == X_("midi")) {
919                                 cnt.set_midi (++n_midi);
920                         }
921                 }
922         }
923
924         n = ChanCount::max (n, cnt);
925         return 0;
926 }
927
928 int
929 IO::create_ports (const XMLNode& node, int version)
930 {
931         ChanCount n;
932         boost::shared_ptr<Bundle> c;
933
934         get_port_counts (node, version, n, c);
935
936         {
937                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
938
939                 if (ensure_ports (n, true, this)) {
940                         error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
941                         return -1;
942                 }
943         }
944
945         /* XXX use c */
946
947         return 0;
948 }
949
950 int
951 IO::make_connections (const XMLNode& node, int version, bool in)
952 {
953         if (version < 3000) {
954                 return make_connections_2X (node, version, in);
955         }
956
957         XMLProperty const * prop;
958
959         for (XMLNodeConstIterator i = node.children().begin(); i != node.children().end(); ++i) {
960
961                 if ((*i)->name() == "Bundle") {
962                         XMLProperty const * prop = (*i)->property ("name");
963                         if (prop) {
964                                 boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value());
965                                 if (b) {
966                                         connect_ports_to_bundle (b, true, this);
967                                 }
968                         }
969
970                         return 0;
971                 }
972
973                 if ((*i)->name() == "Port") {
974
975                         prop = (*i)->property (X_("name"));
976
977                         if (!prop) {
978                                 continue;
979                         }
980
981                         boost::shared_ptr<Port> p = port_by_name (prop->value());
982
983                         if (p) {
984                                 for (XMLNodeConstIterator c = (*i)->children().begin(); c != (*i)->children().end(); ++c) {
985
986                                         XMLNode* cnode = (*c);
987
988                                         if (cnode->name() != X_("Connection")) {
989                                                 continue;
990                                         }
991
992                                         if ((prop = cnode->property (X_("other"))) == 0) {
993                                                 continue;
994                                         }
995
996                                         if (prop) {
997                                                 connect (p, prop->value(), this);
998                                         }
999                                 }
1000                         }
1001                 }
1002         }
1003
1004         return 0;
1005 }
1006
1007 void
1008 IO::prepare_for_reset (XMLNode& node, const std::string& name)
1009 {
1010         /* reset name */
1011         node.add_property ("name", name);
1012
1013         /* now find connections and reset the name of the port
1014            in one so that when we re-use it it will match
1015            the name of the thing we're applying it to.
1016         */
1017
1018         XMLProperty * prop;
1019         XMLNodeList children = node.children();
1020
1021         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
1022
1023                 if ((*i)->name() == "Port") {
1024
1025                         prop = (*i)->property (X_("name"));
1026
1027                         if (prop) {
1028                                 string new_name;
1029                                 string old = prop->value();
1030                                 string::size_type slash = old.find ('/');
1031
1032                                 if (slash != string::npos) {
1033                                         /* port name is of form: <IO-name>/<port-name> */
1034
1035                                         new_name = name;
1036                                         new_name += old.substr (old.find ('/'));
1037
1038                                         prop->set_value (new_name);
1039                                 }
1040                         }
1041                 }
1042         }
1043 }
1044
1045
1046 int
1047 IO::make_connections_2X (const XMLNode& node, int /*version*/, bool in)
1048 {
1049         XMLProperty const * prop;
1050
1051         /* XXX: bundles ("connections" as was) */
1052
1053         if ((prop = node.property ("inputs")) != 0 && in) {
1054
1055                 string::size_type ostart = 0;
1056                 string::size_type start = 0;
1057                 string::size_type end = 0;
1058                 int i = 0;
1059                 int n;
1060                 vector<string> ports;
1061
1062                 string const str = prop->value ();
1063
1064                 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1065                         start += 1;
1066
1067                         if ((end = str.find_first_of ('}', start)) == string::npos) {
1068                                 error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1069                                 return -1;
1070                         }
1071
1072                         if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1073                                 error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1074
1075                                 return -1;
1076
1077                         } else if (n > 0) {
1078
1079
1080                                 for (int x = 0; x < n; ++x) {
1081                                         /* XXX: this is a bit of a hack; need to check if it's always valid */
1082                                         string::size_type const p = ports[x].find ("/out");
1083                                         if (p != string::npos) {
1084                                                 ports[x].replace (p, 4, "/audio_out");
1085                                         }
1086                                         if (NULL != nth(i).get())
1087                                                 nth(i)->connect (ports[x]);
1088                                 }
1089                         }
1090
1091                         ostart = end+1;
1092                         i++;
1093                 }
1094
1095         }
1096
1097         if ((prop = node.property ("outputs")) != 0 && !in) {
1098
1099                 string::size_type ostart = 0;
1100                 string::size_type start = 0;
1101                 string::size_type end = 0;
1102                 int i = 0;
1103                 int n;
1104                 vector<string> ports;
1105
1106                 string const str = prop->value ();
1107
1108                 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1109                         start += 1;
1110
1111                         if ((end = str.find_first_of ('}', start)) == string::npos) {
1112                                 error << string_compose(_("IO: badly formed string in XML node for outputs \"%1\""), str) << endmsg;
1113                                 return -1;
1114                         }
1115
1116                         if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1117                                 error << string_compose(_("IO: bad output string in XML node \"%1\""), str) << endmsg;
1118
1119                                 return -1;
1120
1121                         } else if (n > 0) {
1122
1123                                 for (int x = 0; x < n; ++x) {
1124                                         /* XXX: this is a bit of a hack; need to check if it's always valid */
1125                                         string::size_type const p = ports[x].find ("/in");
1126                                         if (p != string::npos) {
1127                                                 ports[x].replace (p, 3, "/audio_in");
1128                                         }
1129                                         if (NULL != nth(i).get())
1130                                                 nth(i)->connect (ports[x]);
1131                                 }
1132                         }
1133
1134                         ostart = end+1;
1135                         i++;
1136                 }
1137         }
1138
1139         return 0;
1140 }
1141
1142 int
1143 IO::set_ports (const string& str)
1144 {
1145         vector<string> ports;
1146         int n;
1147         uint32_t nports;
1148
1149         if ((nports = count (str.begin(), str.end(), '{')) == 0) {
1150                 return 0;
1151         }
1152
1153         {
1154                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1155
1156                 // FIXME: audio-only
1157                 if (ensure_ports (ChanCount(DataType::AUDIO, nports), true, this)) {
1158                         return -1;
1159                 }
1160         }
1161
1162         string::size_type start  = 0;
1163         string::size_type end    = 0;
1164         string::size_type ostart = 0;
1165         for (int i = 0; (start = str.find_first_of ('{', ostart)) != string::npos; ++i) {
1166                 start += 1;
1167
1168                 if ((end = str.find_first_of ('}', start)) == string::npos) {
1169                         error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1170                         return -1;
1171                 }
1172
1173                 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1174                         error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1175
1176                         return -1;
1177
1178                 } else if (n > 0) {
1179
1180                         for (int x = 0; x < n; ++x) {
1181                                 connect (nth (i), ports[x], this);
1182                         }
1183                 }
1184
1185                 ostart = end+1;
1186         }
1187
1188         return 0;
1189 }
1190
1191 int
1192 IO::parse_io_string (const string& str, vector<string>& ports)
1193 {
1194         string::size_type pos, opos;
1195
1196         if (str.length() == 0) {
1197                 return 0;
1198         }
1199
1200         opos = 0;
1201
1202         ports.clear ();
1203
1204         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1205                 ports.push_back (str.substr (opos, pos - opos));
1206                 opos = pos + 1;
1207         }
1208
1209         if (opos < str.length()) {
1210                 ports.push_back (str.substr(opos));
1211         }
1212
1213         return ports.size();
1214 }
1215
1216 int
1217 IO::parse_gain_string (const string& str, vector<string>& ports)
1218 {
1219         string::size_type pos, opos;
1220
1221         opos = 0;
1222         ports.clear ();
1223
1224         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1225                 ports.push_back (str.substr (opos, pos - opos));
1226                 opos = pos + 1;
1227         }
1228
1229         if (opos < str.length()) {
1230                 ports.push_back (str.substr(opos));
1231         }
1232
1233         return ports.size();
1234 }
1235
1236 bool
1237 IO::set_name (const string& requested_name)
1238 {
1239         string name = requested_name;
1240
1241         if (_name == name) {
1242                 return true;
1243         }
1244
1245         /* replace all colons in the name. i wish we didn't have to do this */
1246
1247         replace_all (name, ":", "-");
1248
1249         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
1250                 string current_name = i->name();
1251                 current_name.replace (current_name.find (_name), _name.val().length(), name);
1252                 i->set_name (current_name);
1253         }
1254
1255         bool const r = SessionObject::set_name (name);
1256
1257         setup_bundle ();
1258
1259         return r;
1260 }
1261
1262 void
1263 IO::set_pretty_name (const std::string& str)
1264 {
1265         if (_pretty_name_prefix == str) {
1266                 return;
1267         }
1268         _pretty_name_prefix = str;
1269         apply_pretty_name ();
1270 }
1271
1272 void
1273 IO::apply_pretty_name ()
1274 {
1275         uint32_t pn = 1;
1276         if (_pretty_name_prefix.empty ()) {
1277                 return;
1278         }
1279         for (PortSet::iterator i = _ports.begin (); i != _ports.end(); ++i, ++pn) {
1280                 (*i)->set_pretty_name (string_compose (("%1/%2 %3"),
1281                                         _pretty_name_prefix,
1282                                         _direction == Output ? _("Out") : _("In"),
1283                                         pn));
1284         }
1285 }
1286
1287 framecnt_t
1288 IO::latency () const
1289 {
1290         framecnt_t max_latency;
1291         framecnt_t latency;
1292
1293         max_latency = 0;
1294
1295         /* io lock not taken - must be protected by other means */
1296
1297         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1298                 if ((latency = i->private_latency_range (_direction == Output).max) > max_latency) {
1299                         DEBUG_TRACE (DEBUG::Latency, string_compose ("port %1 has %2 latency of %3 - use\n",
1300                                                                      name(),
1301                                                                      ((_direction == Output) ? "PLAYBACK" : "CAPTURE"),
1302                                                                      latency));
1303                         max_latency = latency;
1304                 }
1305         }
1306
1307         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: max %4 latency from %2 ports = %3\n",
1308                                                      name(), _ports.num_ports(), max_latency,
1309                                                      ((_direction == Output) ? "PLAYBACK" : "CAPTURE")));
1310         return max_latency;
1311 }
1312
1313 int
1314 IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, bool exclusive, void* src)
1315 {
1316         BLOCK_PROCESS_CALLBACK ();
1317
1318         {
1319                 Glib::Threads::Mutex::Lock lm2 (io_lock);
1320
1321                 if (exclusive) {
1322                         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
1323                                 i->disconnect_all ();
1324                         }
1325                 }
1326
1327                 c->connect (_bundle, _session.engine());
1328
1329                 /* If this is a UserBundle, make a note of what we've done */
1330
1331                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1332                 if (ub) {
1333
1334                         /* See if we already know about this one */
1335                         std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1336                         while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1337                                 ++i;
1338                         }
1339
1340                         if (i == _bundles_connected.end()) {
1341                                 /* We don't, so make a note */
1342                                 _bundles_connected.push_back (new UserBundleInfo (this, ub));
1343                         }
1344                 }
1345         }
1346
1347         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1348         return 0;
1349 }
1350
1351 int
1352 IO::disconnect_ports_from_bundle (boost::shared_ptr<Bundle> c, void* src)
1353 {
1354         BLOCK_PROCESS_CALLBACK ();
1355
1356         {
1357                 Glib::Threads::Mutex::Lock lm2 (io_lock);
1358
1359                 c->disconnect (_bundle, _session.engine());
1360
1361                 /* If this is a UserBundle, make a note of what we've done */
1362
1363                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1364                 if (ub) {
1365
1366                         std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1367                         while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1368                                 ++i;
1369                         }
1370
1371                         if (i != _bundles_connected.end()) {
1372                                 delete *i;
1373                                 _bundles_connected.erase (i);
1374                         }
1375                 }
1376         }
1377
1378         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1379         return 0;
1380 }
1381
1382
1383 int
1384 IO::disable_connecting ()
1385 {
1386         connecting_legal = false;
1387         return 0;
1388 }
1389
1390 int
1391 IO::enable_connecting ()
1392 {
1393         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
1394         connecting_legal = true;
1395         boost::optional<int> r = ConnectingLegal ();
1396         return r.get_value_or (0);
1397 }
1398
1399 void
1400 IO::bundle_changed (Bundle::Change /*c*/)
1401 {
1402         /* XXX */
1403 //      connect_input_ports_to_bundle (_input_bundle, this);
1404 }
1405
1406
1407 string
1408 IO::build_legal_port_name (DataType type)
1409 {
1410         const int name_size = AudioEngine::instance()->port_name_size();
1411         int limit;
1412         string suffix;
1413
1414         if (type == DataType::AUDIO) {
1415                 suffix = X_("audio");
1416         } else if (type == DataType::MIDI) {
1417                 suffix = X_("midi");
1418         } else {
1419                 throw unknown_type();
1420         }
1421
1422         /* note that if "in" or "out" are translated it will break a session
1423            across locale switches because a port's connection list will
1424            show (old) translated names, but the current port name will
1425            use the (new) translated name.
1426         */
1427
1428         if (_sendish) {
1429                 if (_direction == Input) {
1430                         suffix += X_("_return");
1431                 } else {
1432                         suffix += X_("_send");
1433                 }
1434         } else {
1435                 if (_direction == Input) {
1436                         suffix += X_("_in");
1437                 } else {
1438                         suffix += X_("_out");
1439                 }
1440         }
1441
1442         // allow up to 4 digits for the output port number, plus the slash, suffix and extra space
1443
1444         limit = name_size - AudioEngine::instance()->my_name().length() - (suffix.length() + 5);
1445
1446         std::vector<char> buf1(name_size+1);
1447         std::vector<char> buf2(name_size+1);
1448
1449         /* colons are illegal in port names, so fix that */
1450
1451         string nom = _name.val();
1452         replace_all (nom, ":", ";");
1453
1454         snprintf (&buf1[0], name_size+1, ("%.*s/%s"), limit, nom.c_str(), suffix.c_str());
1455
1456         int port_number = find_port_hole (&buf1[0]);
1457         snprintf (&buf2[0], name_size+1, "%s %d", &buf1[0], port_number);
1458
1459         return string (&buf2[0]);
1460 }
1461
1462 int32_t
1463 IO::find_port_hole (const char* base)
1464 {
1465         /* CALLER MUST HOLD IO LOCK */
1466
1467         uint32_t n;
1468
1469         if (_ports.empty()) {
1470                 return 1;
1471         }
1472
1473         /* we only allow up to 4 characters for the port number
1474          */
1475
1476         for (n = 1; n < 9999; ++n) {
1477                 std::vector<char> buf (AudioEngine::instance()->port_name_size());
1478                 PortSet::iterator i = _ports.begin();
1479
1480                 snprintf (&buf[0], buf.size()+1, _("%s %u"), base, n);
1481
1482                 for ( ; i != _ports.end(); ++i) {
1483                         if (string(i->name()) == string(&buf[0])) {
1484                                 break;
1485                         }
1486                 }
1487
1488                 if (i == _ports.end()) {
1489                         break;
1490                 }
1491         }
1492         return n;
1493 }
1494
1495
1496 boost::shared_ptr<AudioPort>
1497 IO::audio(uint32_t n) const
1498 {
1499         return _ports.nth_audio_port (n);
1500
1501 }
1502
1503 boost::shared_ptr<MidiPort>
1504 IO::midi(uint32_t n) const
1505 {
1506         return _ports.nth_midi_port (n);
1507 }
1508
1509 /**
1510  *  Setup a bundle that describe our inputs or outputs. Also creates the bundle if necessary.
1511  */
1512
1513 void
1514 IO::setup_bundle ()
1515 {
1516         char buf[32];
1517
1518         if (!_bundle) {
1519                 _bundle.reset (new Bundle (_direction == Input));
1520         }
1521
1522         _bundle->suspend_signals ();
1523
1524         _bundle->remove_channels ();
1525
1526         if (_direction == Input) {
1527                 snprintf(buf, sizeof (buf), _("%s in"), _name.val().c_str());
1528         } else {
1529                 snprintf(buf, sizeof (buf), _("%s out"), _name.val().c_str());
1530         }
1531         _bundle->set_name (buf);
1532
1533         int c = 0;
1534         for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
1535
1536                 uint32_t const N = _ports.count().get (*i);
1537                 for (uint32_t j = 0; j < N; ++j) {
1538                         _bundle->add_channel (bundle_channel_name (j, N, *i), *i);
1539                         _bundle->set_port (c, _session.engine().make_port_name_non_relative (_ports.port(*i, j)->name()));
1540                         ++c;
1541                 }
1542
1543         }
1544
1545         _bundle->resume_signals ();
1546 }
1547
1548 /** @return Bundles connected to our ports */
1549 BundleList
1550 IO::bundles_connected ()
1551 {
1552         BundleList bundles;
1553
1554         /* User bundles */
1555         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
1556                 bundles.push_back ((*i)->bundle);
1557         }
1558
1559         /* Session bundles */
1560         boost::shared_ptr<ARDOUR::BundleList> b = _session.bundles ();
1561         for (ARDOUR::BundleList::iterator i = b->begin(); i != b->end(); ++i) {
1562                 if ((*i)->connected_to (_bundle, _session.engine())) {
1563                         bundles.push_back (*i);
1564                 }
1565         }
1566
1567         /* Route bundles */
1568
1569         boost::shared_ptr<ARDOUR::RouteList> r = _session.get_routes ();
1570
1571         if (_direction == Input) {
1572                 for (ARDOUR::RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1573                         if ((*i)->output()->bundle()->connected_to (_bundle, _session.engine())) {
1574                                 bundles.push_back ((*i)->output()->bundle());
1575                         }
1576                 }
1577         } else {
1578                 for (ARDOUR::RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1579                         if ((*i)->input()->bundle()->connected_to (_bundle, _session.engine())) {
1580                                 bundles.push_back ((*i)->input()->bundle());
1581                         }
1582                 }
1583         }
1584
1585         return bundles;
1586 }
1587
1588
1589 IO::UserBundleInfo::UserBundleInfo (IO* io, boost::shared_ptr<UserBundle> b)
1590 {
1591         bundle = b;
1592         b->Changed.connect_same_thread (changed, boost::bind (&IO::bundle_changed, io, _1));
1593 }
1594
1595 std::string
1596 IO::bundle_channel_name (uint32_t c, uint32_t n, DataType t) const
1597 {
1598         char buf[32];
1599
1600         if (t == DataType::AUDIO) {
1601
1602                 switch (n) {
1603                 case 1:
1604                         return _("mono");
1605                 case 2:
1606                         return c == 0 ? _("L") : _("R");
1607                 default:
1608                         snprintf (buf, sizeof(buf), "%d", (c + 1));
1609                         return buf;
1610                 }
1611
1612         } else {
1613
1614                 snprintf (buf, sizeof(buf), "%d", (c + 1));
1615                 return buf;
1616
1617         }
1618
1619         return "";
1620 }
1621
1622 string
1623 IO::name_from_state (const XMLNode& node)
1624 {
1625         XMLProperty const * prop;
1626
1627         if ((prop = node.property ("name")) != 0) {
1628                 return prop->value();
1629         }
1630
1631         return string();
1632 }
1633
1634 void
1635 IO::set_name_in_state (XMLNode& node, const string& new_name)
1636 {
1637         node.add_property (X_("name"), new_name);
1638         XMLNodeList children = node.children ();
1639         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
1640                 if ((*i)->name() == X_("Port")) {
1641                         string const old_name = (*i)->property(X_("name"))->value();
1642                         string const old_name_second_part = old_name.substr (old_name.find_first_of ("/") + 1);
1643                         (*i)->add_property (X_("name"), string_compose ("%1/%2", new_name, old_name_second_part));
1644                 }
1645         }
1646 }
1647
1648 bool
1649 IO::connected () const
1650 {
1651         /* do we have any connections at all? */
1652
1653         for (PortSet::const_iterator p = _ports.begin(); p != _ports.end(); ++p) {
1654                 if (p->connected()) {
1655                         return true;
1656                 }
1657         }
1658
1659         return false;
1660 }
1661
1662 bool
1663 IO::connected_to (boost::shared_ptr<const IO> other) const
1664 {
1665         if (!other) {
1666                 return connected ();
1667         }
1668
1669         assert (_direction != other->direction());
1670
1671         uint32_t i, j;
1672         uint32_t no = n_ports().n_total();
1673         uint32_t ni = other->n_ports ().n_total();
1674
1675         for (i = 0; i < no; ++i) {
1676                 for (j = 0; j < ni; ++j) {
1677                         if ((NULL != nth(i).get()) && (NULL != other->nth(j).get())) {
1678                                 if (nth(i)->connected_to (other->nth(j)->name())) {
1679                                         return true;
1680                                 }
1681                         }
1682                 }
1683         }
1684
1685         return false;
1686 }
1687
1688 bool
1689 IO::connected_to (const string& str) const
1690 {
1691         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1692                 if (i->connected_to (str)) {
1693                         return true;
1694                 }
1695         }
1696
1697         return false;
1698 }
1699
1700 /** Call a processor's ::run() method, giving it our buffers
1701  *  Caller must hold process lock.
1702  */
1703 void
1704 IO::process_input (boost::shared_ptr<Processor> proc, framepos_t start_frame, framepos_t end_frame, double speed, pframes_t nframes)
1705 {
1706         /* don't read the data into new buffers - just use the port buffers directly */
1707
1708         if (n_ports().n_total() == 0) {
1709                 /* We have no ports, so nothing to process */
1710                 return;
1711         }
1712
1713         _buffers.get_backend_port_addresses (_ports, nframes);
1714         if (proc) {
1715                 proc->run (_buffers, start_frame, end_frame, speed, nframes, true);
1716         }
1717 }
1718
1719 void
1720 IO::collect_input (BufferSet& bufs, pframes_t nframes, ChanCount offset)
1721 {
1722         assert(bufs.available() >= _ports.count());
1723
1724         if (_ports.count() == ChanCount::ZERO) {
1725                 return;
1726         }
1727
1728         bufs.set_count (_ports.count());
1729
1730         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1731                 PortSet::iterator   i = _ports.begin(*t);
1732                 BufferSet::iterator b = bufs.begin(*t);
1733
1734                 for (uint32_t off = 0; off < offset.get(*t); ++off, ++b) {
1735                         if (b == bufs.end(*t)) {
1736                                 continue;
1737                         }
1738                 }
1739
1740                 for ( ; i != _ports.end(*t); ++i, ++b) {
1741                         const Buffer& bb (i->get_buffer (nframes));
1742                         b->read_from (bb, nframes);
1743                 }
1744         }
1745 }
1746
1747 void
1748 IO::copy_to_outputs (BufferSet& bufs, DataType type, pframes_t nframes, framecnt_t offset)
1749 {
1750         PortSet::iterator o = _ports.begin(type);
1751         BufferSet::iterator i = bufs.begin(type);
1752         BufferSet::iterator prev = i;
1753
1754         assert(i != bufs.end(type)); // or second loop will crash
1755
1756         // Copy any buffers 1:1 to outputs
1757
1758         while (i != bufs.end(type) && o != _ports.end (type)) {
1759                 Buffer& port_buffer (o->get_buffer (nframes));
1760                 port_buffer.read_from (*i, nframes, offset);
1761                 prev = i;
1762                 ++i;
1763                 ++o;
1764         }
1765
1766         // Copy last buffer to any extra outputs
1767
1768         while (o != _ports.end(type)) {
1769                 Buffer& port_buffer (o->get_buffer (nframes));
1770                 port_buffer.read_from (*prev, nframes, offset);
1771                 ++o;
1772         }
1773 }
1774
1775 boost::shared_ptr<Port>
1776 IO::port_by_name (const std::string& str) const
1777 {
1778         /* to be called only from ::set_state() - no locking */
1779
1780         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1781
1782                 if (i->name() == str) {
1783                         return boost::const_pointer_cast<Port> (*i);
1784                 }
1785         }
1786
1787         return boost::shared_ptr<Port> ();
1788 }
1789
1790 bool
1791 IO::physically_connected () const
1792 {
1793         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1794                 if (i->physically_connected()) {
1795                         return true;
1796                 }
1797         }
1798
1799         return false;
1800 }
1801
1802 bool
1803 IO::has_port (boost::shared_ptr<Port> p) const
1804 {
1805         Glib::Threads::Mutex::Lock lm (io_lock);
1806         return _ports.contains (p);
1807 }