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