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