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