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