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