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