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