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