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