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