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