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