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