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