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