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