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