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