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