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