Minor cleanups to IO.
[ardour.git] / libs / ardour / io.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <fstream>
20 #include <algorithm>
21 #include <cmath>
22
23 #include <unistd.h>
24 #include <locale.h>
25 #include <errno.h>
26
27 #include <glibmm.h>
28 #include <glibmm/thread.h>
29
30 #include "pbd/xml++.h"
31 #include "pbd/replace_all.h"
32 #include "pbd/unknown_type.h"
33 #include "pbd/enumwriter.h"
34
35 #include "ardour/audioengine.h"
36 #include "ardour/buffer.h"
37 #include "ardour/debug.h"
38 #include "ardour/io.h"
39 #include "ardour/route.h"
40 #include "ardour/port.h"
41 #include "ardour/audio_port.h"
42 #include "ardour/midi_port.h"
43 #include "ardour/session.h"
44 #include "ardour/cycle_timer.h"
45 #include "ardour/buffer_set.h"
46 #include "ardour/meter.h"
47 #include "ardour/amp.h"
48 #include "ardour/user_bundle.h"
49
50 #include "i18n.h"
51
52 #define BLOCK_PROCESS_CALLBACK() Glib::Mutex::Lock em (AudioEngine::instance()->process_lock())
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57
58 const string                 IO::state_node_name = "IO";
59 bool                         IO::connecting_legal = false;
60 PBD::Signal0<int>            IO::ConnectingLegal;
61 PBD::Signal1<void,ChanCount> IO::PortCountChanged;
62
63 /** @param default_type The type of port that will be created by ensure_io
64  * and friends if no type is explicitly requested (to avoid breakage).
65  */
66 IO::IO (Session& s, const string& name, Direction dir, DataType default_type)
67         : SessionObject (s, name)
68         , _direction (dir)
69         , _default_type (default_type)
70 {
71         _active = true;
72         pending_state_node = 0;
73         setup_bundle ();
74 }
75
76 IO::IO (Session& s, const XMLNode& node, DataType dt)
77         : SessionObject(s, "unnamed io")
78         , _direction (Input)
79         , _default_type (dt)
80 {
81         _active = true;
82         pending_state_node = 0;
83
84         set_state (node, Stateful::loading_state_version);
85         setup_bundle ();
86 }
87
88 IO::~IO ()
89 {
90         Glib::Mutex::Lock lm (io_lock);
91
92         BLOCK_PROCESS_CALLBACK ();
93
94         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
95                 _session.engine().unregister_port (*i);
96         }
97 }
98
99 void
100 IO::increment_port_buffer_offset (pframes_t offset)
101 {
102         /* io_lock, not taken: function must be called from Session::process() calltree */
103
104         if (_direction == Output) {
105                 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
106                         i->increment_port_buffer_offset (offset);
107                 }
108         }
109 }
110
111 void
112 IO::silence (framecnt_t nframes)
113 {
114         /* io_lock, not taken: function must be called from Session::process() calltree */
115
116         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
117                 i->get_buffer(nframes).silence (nframes);
118         }
119 }
120
121 /** Set _bundles_connected to those bundles that are connected such that every
122  *  port on every bundle channel x is connected to port x in _ports.
123  */
124 void
125 IO::check_bundles_connected ()
126 {
127         std::vector<UserBundleInfo*> new_list;
128
129         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
130
131                 uint32_t const N = (*i)->bundle->nchannels().n_total();
132
133                 if (_ports.num_ports() < N) {
134                         continue;
135                 }
136
137                 bool ok = true;
138
139                 for (uint32_t j = 0; j < N; ++j) {
140                         /* Every port on bundle channel j must be connected to our input j */
141                         Bundle::PortList const pl = (*i)->bundle->channel_ports (j);
142                         for (uint32_t k = 0; k < pl.size(); ++k) {
143                                 if (_ports.port(j)->connected_to (pl[k]) == false) {
144                                         ok = false;
145                                         break;
146                                 }
147                         }
148
149                         if (ok == false) {
150                                 break;
151                         }
152                 }
153
154                 if (ok) {
155                         new_list.push_back (*i);
156                 } else {
157                         delete *i;
158                 }
159         }
160
161         _bundles_connected = new_list;
162 }
163
164
165 int
166 IO::disconnect (Port* our_port, string other_port, void* src)
167 {
168         if (other_port.length() == 0 || our_port == 0) {
169                 return 0;
170         }
171
172         {
173                 Glib::Mutex::Lock lm (io_lock);
174
175                 /* check that our_port is really one of ours */
176
177                 if ( ! _ports.contains(our_port)) {
178                         return -1;
179                 }
180
181                 /* disconnect it from the source */
182
183                 if (our_port->disconnect (other_port)) {
184                         error << string_compose(_("IO: cannot disconnect port %1 from %2"), our_port->name(), other_port) << endmsg;
185                         return -1;
186                 }
187
188                 check_bundles_connected ();
189         }
190
191         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
192
193         _session.set_dirty ();
194
195         return 0;
196 }
197
198 int
199 IO::connect (Port* our_port, string other_port, void* src)
200 {
201         if (other_port.length() == 0 || our_port == 0) {
202                 return 0;
203         }
204
205         {
206                 Glib::Mutex::Lock lm (io_lock);
207
208                 /* check that our_port is really one of ours */
209
210                 if ( ! _ports.contains(our_port) ) {
211                         return -1;
212                 }
213
214                 /* connect it to the source */
215
216                 if (our_port->connect (other_port)) {
217                         return -1;
218                 }
219         }
220         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
221         _session.set_dirty ();
222         return 0;
223 }
224
225 int
226 IO::remove_port (Port* port, void* src)
227 {
228         ChanCount before = _ports.count ();
229         ChanCount after = before;
230         after.set (port->type(), after.get (port->type()) - 1);
231
232         bool const r = PortCountChanging (after); /* EMIT SIGNAL */
233         if (r) {
234                 return -1;
235         }
236
237         IOChange change;
238
239         {
240                 BLOCK_PROCESS_CALLBACK ();
241
242                 {
243                         Glib::Mutex::Lock lm (io_lock);
244
245                         if (_ports.remove(port)) {
246                                 change.type = IOChange::Type (change.type | IOChange::ConfigurationChanged);
247                                 change.before = before;
248                                 change.after = _ports.count ();
249
250                                 if (port->connected()) {
251                                         change.type = IOChange::Type (change.type | IOChange::ConnectionsChanged);
252                                 }
253
254                                 _session.engine().unregister_port (*port);
255                                 check_bundles_connected ();
256                         }
257                 }
258
259                 PortCountChanged (n_ports()); /* EMIT SIGNAL */
260
261                 if (change.type != IOChange::NoChange) {
262                         changed (change, src);
263                         _buffers.attach_buffers (_ports);
264                 }
265         }
266
267         if (change.type & IOChange::ConfigurationChanged) {
268                 setup_bundle ();
269         }
270
271         if (change.type == IOChange::NoChange) {
272                 return -1;
273         }
274
275         _session.set_dirty ();
276         
277         return 0;
278 }
279
280 /** Add a port.
281  *
282  * @param destination Name of port to connect new port to.
283  * @param src Source for emitted ConfigurationChanged signal.
284  * @param type Data type of port.  Default value (NIL) will use this IO's default type.
285  */
286 int
287 IO::add_port (string destination, void* src, DataType type)
288 {
289         Port* our_port;
290
291         if (type == DataType::NIL) {
292                 type = _default_type;
293         }
294
295         IOChange change;
296
297         {
298                 BLOCK_PROCESS_CALLBACK ();
299
300
301                 {
302                         Glib::Mutex::Lock lm (io_lock);
303
304                         /* Create a new port */
305
306                         string portname = build_legal_port_name (type);
307                         
308                         if (_direction == Input) {
309                                 if ((our_port = _session.engine().register_input_port (type, portname)) == 0) {
310                                         error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
311                                         return -1;
312                                 }
313                         } else {
314                                 if ((our_port = _session.engine().register_output_port (type, portname)) == 0) {
315                                         error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
316                                         return -1;
317                                 }
318                         }
319
320                         change.before = _ports.count ();
321                         _ports.add (our_port);
322                 }
323                 
324                 PortCountChanged (n_ports()); /* EMIT SIGNAL */
325                 change.type = IOChange::ConfigurationChanged;
326                 change.after = _ports.count ();
327                 changed (change, src); /* EMIT SIGNAL */
328                 _buffers.attach_buffers (_ports);
329         }
330
331         if (!destination.empty()) {
332                 if (our_port->connect (destination)) {
333                         return -1;
334                 }
335         }
336
337         setup_bundle ();
338         _session.set_dirty ();
339
340         return 0;
341 }
342
343 int
344 IO::disconnect (void* src)
345 {
346         {
347                 Glib::Mutex::Lock lm (io_lock);
348
349                 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
350                         i->disconnect_all ();
351                 }
352
353                 check_bundles_connected ();
354         }
355
356         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
357
358         return 0;
359 }
360
361 /** Caller must hold process lock */
362 int
363 IO::ensure_ports_locked (ChanCount count, bool clear, bool& changed)
364 {
365         assert (!AudioEngine::instance()->process_lock().trylock());
366
367         Port* port = 0;
368
369         changed    = false;
370
371         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
372
373                 const size_t n = count.get(*t);
374
375                 /* remove unused ports */
376                 for (size_t i = n_ports().get(*t); i > n; --i) {
377                         port = _ports.port(*t, i-1);
378
379                         assert(port);
380                         _ports.remove(port);
381                         _session.engine().unregister_port (*port);
382
383                         changed = true;
384                 }
385
386                 /* create any necessary new ports */
387                 while (n_ports().get(*t) < n) {
388
389                         string portname = build_legal_port_name (*t);
390
391                         try {
392
393                                 if (_direction == Input) {
394                                         if ((port = _session.engine().register_input_port (*t, portname)) == 0) {
395                                                 error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
396                                                 return -1;
397                                         }
398                                 } else {
399                                         if ((port = _session.engine().register_output_port (*t, portname)) == 0) {
400                                                 error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
401                                                 return -1;
402                                         }
403                                 }
404                         }
405
406                         catch (AudioEngine::PortRegistrationFailure& err) {
407                                 /* pass it on */
408                                 throw;
409                         }
410
411                         _ports.add (port);
412                         changed = true;
413                 }
414         }
415
416         if (changed) {
417                 check_bundles_connected ();
418                 PortCountChanged (n_ports()); /* EMIT SIGNAL */
419                 _session.set_dirty ();
420         }
421
422         if (clear) {
423                 /* disconnect all existing ports so that we get a fresh start */
424                 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
425                         i->disconnect_all ();
426                 }
427         }
428
429         return 0;
430 }
431
432 /** Caller must hold process lock */
433 int
434 IO::ensure_ports (ChanCount count, bool clear, void* src)
435 {
436         assert (!AudioEngine::instance()->process_lock().trylock());
437
438         bool changed = false;
439
440         if (count == n_ports() && !clear) {
441                 return 0;
442         }
443
444         IOChange change;
445
446         change.before = _ports.count ();
447
448         {
449                 Glib::Mutex::Lock im (io_lock);
450                 if (ensure_ports_locked (count, clear, changed)) {
451                         return -1;
452                 }
453         }
454
455         if (changed) {
456                 change.after = _ports.count ();
457                 change.type = IOChange::ConfigurationChanged;
458                 this->changed (change, src); /* EMIT SIGNAL */
459                 _buffers.attach_buffers (_ports);
460                 setup_bundle ();
461                 _session.set_dirty ();
462         }
463
464         return 0;
465 }
466
467 /** Caller must hold process lock */
468 int
469 IO::ensure_io (ChanCount count, bool clear, void* src)
470 {
471         assert (!AudioEngine::instance()->process_lock().trylock());
472
473         return ensure_ports (count, clear, src);
474 }
475
476 XMLNode&
477 IO::get_state ()
478 {
479         return state (true);
480 }
481
482 XMLNode&
483 IO::state (bool /*full_state*/)
484 {
485         XMLNode* node = new XMLNode (state_node_name);
486         char buf[64];
487         string str;
488         vector<string>::iterator ci;
489         int n;
490         LocaleGuard lg (X_("POSIX"));
491         Glib::Mutex::Lock lm (io_lock);
492
493         node->add_property("name", _name);
494         id().print (buf, sizeof (buf));
495         node->add_property("id", buf);
496         node->add_property ("direction", enum_2_string (_direction));
497         node->add_property ("default-type", _default_type.to_string());
498
499         for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
500                 XMLNode* n = new XMLNode ("Bundle");
501                 n->add_property ("name", (*i)->bundle->name ());
502                 node->add_child_nocopy (*n);
503         }
504
505         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
506
507                 vector<string> connections;
508
509                 XMLNode* pnode = new XMLNode (X_("Port"));
510                 pnode->add_property (X_("type"), i->type().to_string());
511                 pnode->add_property (X_("name"), i->name());
512
513                 if (i->get_connections (connections)) {
514
515                         for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
516
517                                 /* if its a connection to our own port,
518                                    return only the port name, not the
519                                    whole thing. this allows connections
520                                    to be re-established even when our
521                                    client name is different.
522                                 */
523
524                                 XMLNode* cnode = new XMLNode (X_("Connection"));
525
526                                 cnode->add_property (X_("other"), _session.engine().make_port_name_relative (*ci));
527                                 pnode->add_child_nocopy (*cnode);
528                         }
529                 }
530
531                 node->add_child_nocopy (*pnode);
532         }
533
534         snprintf (buf, sizeof (buf), "%" PRId64, _user_latency);
535         node->add_property (X_("user-latency"), buf);
536         
537         return *node;
538 }
539
540 int
541 IO::set_state (const XMLNode& node, int version)
542 {
543         /* callers for version < 3000 need to call set_state_2X directly, as A3 IOs
544          * are input OR output, not both, so the direction needs to be specified
545          * by the caller.
546          */
547         assert (version >= 3000);
548
549         const XMLProperty* prop;
550         XMLNodeConstIterator iter;
551         LocaleGuard lg (X_("POSIX"));
552
553         /* force use of non-localized representation of decimal point,
554            since we use it a lot in XML files and so forth.
555         */
556
557         if (node.name() != state_node_name) {
558                 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
559                 return -1;
560         }
561
562         if ((prop = node.property ("name")) != 0) {
563                 set_name (prop->value());
564         }
565
566         if ((prop = node.property (X_("default-type"))) != 0) {
567                 _default_type = DataType(prop->value());
568                 assert(_default_type != DataType::NIL);
569         }
570
571         set_id (node);
572
573         if ((prop = node.property ("direction")) != 0) {
574                 _direction = (Direction) string_2_enum (prop->value(), _direction);
575         }
576
577         if (create_ports (node, version)) {
578                 return -1;
579         }
580
581         if (connecting_legal) {
582
583                 if (make_connections (node, version, false)) {
584                         return -1;
585                 }
586
587         } else {
588
589                 pending_state_node = new XMLNode (node);
590                 pending_state_node_version = version;
591                 pending_state_node_in = false;
592                 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
593         }
594
595         if ((prop = node.property ("user-latency")) != 0) {
596                 _user_latency = atoi (prop->value ());
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         set_id (node);
628
629         _direction = in ? Input : Output;
630
631         if (create_ports (node, version)) {
632                 return -1;
633         }
634
635         if (connecting_legal) {
636
637                 if (make_connections_2X (node, version, in)) {
638                         return -1;
639                 }
640
641         } else {
642
643                 pending_state_node = new XMLNode (node);
644                 pending_state_node_version = version;
645                 pending_state_node_in = in;
646                 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
647         }
648
649         return 0;
650 }
651
652 int
653 IO::connecting_became_legal ()
654 {
655         int ret;
656
657         assert (pending_state_node);
658
659         connection_legal_c.disconnect ();
660
661         ret = make_connections (*pending_state_node, pending_state_node_version, pending_state_node_in);
662
663         delete pending_state_node;
664         pending_state_node = 0;
665
666         return ret;
667 }
668
669 boost::shared_ptr<Bundle>
670 IO::find_possible_bundle (const string &desired_name)
671 {
672         static const string digits = "0123456789";
673         const string &default_name = (_direction == Input ? _("in") : _("out"));
674         const string &bundle_type_name = (_direction == Input ? _("input") : _("output"));
675
676         boost::shared_ptr<Bundle> c = _session.bundle_by_name (desired_name);
677
678         if (!c) {
679                 int bundle_number, mask;
680                 string possible_name;
681                 bool stereo = false;
682                 string::size_type last_non_digit_pos;
683
684                 error << string_compose(_("Unknown bundle \"%1\" listed for %2 of %3"), desired_name, bundle_type_name, _name)
685                       << endmsg;
686
687                 // find numeric suffix of desired name
688                 bundle_number = 0;
689
690                 last_non_digit_pos = desired_name.find_last_not_of(digits);
691
692                 if (last_non_digit_pos != string::npos) {
693                         stringstream s;
694                         s << desired_name.substr(last_non_digit_pos);
695                         s >> bundle_number;
696                 }
697
698                 // see if it's a stereo connection e.g. "in 3+4"
699
700                 if (last_non_digit_pos > 1 && desired_name[last_non_digit_pos] == '+') {
701                         string::size_type left_last_non_digit_pos;
702
703                         left_last_non_digit_pos = desired_name.find_last_not_of(digits, last_non_digit_pos-1);
704
705                         if (left_last_non_digit_pos != string::npos) {
706                                 int left_bundle_number = 0;
707                                 stringstream s;
708                                 s << desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
709                                 s >> left_bundle_number;
710
711                                 if (left_bundle_number > 0 && left_bundle_number + 1 == bundle_number) {
712                                         bundle_number--;
713                                         stereo = true;
714                                 }
715                         }
716                 }
717
718                 // make 0-based
719                 if (bundle_number)
720                         bundle_number--;
721
722                 // find highest set bit
723                 mask = 1;
724                 while ((mask <= bundle_number) && (mask <<= 1)) {}
725
726                 // "wrap" bundle number into largest possible power of 2
727                 // that works...
728
729                 while (mask) {
730
731                         if (bundle_number & mask) {
732                                 bundle_number &= ~mask;
733
734                                 stringstream s;
735                                 s << default_name << " " << bundle_number + 1;
736
737                                 if (stereo) {
738                                         s << "+" << bundle_number + 2;
739                                 }
740
741                                 possible_name = s.str();
742
743                                 if ((c = _session.bundle_by_name (possible_name)) != 0) {
744                                         break;
745                                 }
746                         }
747                         mask >>= 1;
748                 }
749                 if (c) {
750                         info << string_compose (_("Bundle %1 was not available - \"%2\" used instead"), desired_name, possible_name)
751                              << endmsg;
752                 } else {
753                         error << string_compose(_("No %1 bundles available as a replacement"), bundle_type_name)
754                               << endmsg;
755                 }
756
757         }
758
759         return c;
760
761 }
762
763 int
764 IO::get_port_counts_2X (XMLNode const & node, int /*version*/, ChanCount& n, boost::shared_ptr<Bundle>& /*c*/)
765 {
766         XMLProperty const * prop;
767         XMLNodeList children = node.children ();
768
769         uint32_t n_audio = 0;
770
771         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
772
773                 if ((prop = node.property ("inputs")) != 0 && _direction == Input) {
774                         n_audio = count (prop->value().begin(), prop->value().end(), '{');
775                 } else if ((prop = node.property ("input-connection")) != 0 && _direction == Input) {
776                         n_audio = 1;
777                 } else if ((prop = node.property ("outputs")) != 0 && _direction == Output) {
778                         n_audio = count (prop->value().begin(), prop->value().end(), '{');
779                 } else if ((prop = node.property ("output-connection")) != 0 && _direction == Output) {
780                         n_audio = 2;
781                 }
782         }
783
784         ChanCount cnt;
785         cnt.set_audio (n_audio);
786         n = ChanCount::max (n, cnt);
787
788         return 0;
789 }
790
791 int
792 IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shared_ptr<Bundle>& c)
793 {
794         if (version < 3000) {
795                 return get_port_counts_2X (node, version, n, c);
796         }
797
798         XMLProperty const * prop;
799         XMLNodeConstIterator iter;
800         uint32_t n_audio = 0;
801         uint32_t n_midi = 0;
802         ChanCount cnt;
803
804         n = n_ports();
805
806         if ((prop = node.property ("connection")) != 0) {
807
808                 if ((c = find_possible_bundle (prop->value())) != 0) {
809                         n = ChanCount::max (n, c->nchannels());
810                 }
811                 return 0;
812         }
813
814         for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
815
816                 if ((*iter)->name() == X_("Bundle")) {
817                         if ((c = find_possible_bundle (prop->value())) != 0) {
818                                 n = ChanCount::max (n, c->nchannels());
819                                 return 0;
820                         } else {
821                                 return -1;
822                         }
823                 }
824
825                 if ((*iter)->name() == X_("Port")) {
826                         prop = (*iter)->property (X_("type"));
827
828                         if (!prop) {
829                                 continue;
830                         }
831
832                         if (prop->value() == X_("audio")) {
833                                 cnt.set_audio (++n_audio);
834                         } else if (prop->value() == X_("midi")) {
835                                 cnt.set_midi (++n_midi);
836                         }
837                 }
838         }
839
840         n = ChanCount::max (n, cnt);
841         return 0;
842 }
843
844 int
845 IO::create_ports (const XMLNode& node, int version)
846 {
847         ChanCount n;
848         boost::shared_ptr<Bundle> c;
849
850         get_port_counts (node, version, n, c);
851
852         {
853                 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
854
855                 if (ensure_ports (n, true, this)) {
856                         error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
857                         return -1;
858                 }
859         }
860
861         /* XXX use c */
862
863         return 0;
864 }
865
866 int
867 IO::make_connections (const XMLNode& node, int version, bool in)
868 {
869         if (version < 3000) {
870                 return make_connections_2X (node, version, in);
871         }
872
873         const XMLProperty* prop;
874
875         for (XMLNodeConstIterator i = node.children().begin(); i != node.children().end(); ++i) {
876
877                 if ((*i)->name() == "Bundle") {
878                         XMLProperty const * prop = (*i)->property ("name");
879                         if (prop) {
880                                 boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value());
881                                 if (b) {
882                                         connect_ports_to_bundle (b, this);
883                                 }
884                         }
885
886                         return 0;
887                 }
888
889                 if ((*i)->name() == "Port") {
890
891                         prop = (*i)->property (X_("name"));
892
893                         if (!prop) {
894                                 continue;
895                         }
896
897                         Port* p = port_by_name (prop->value());
898
899                         if (p) {
900                                 for (XMLNodeConstIterator c = (*i)->children().begin(); c != (*i)->children().end(); ++c) {
901
902                                         XMLNode* cnode = (*c);
903
904                                         if (cnode->name() != X_("Connection")) {
905                                                 continue;
906                                         }
907
908                                         if ((prop = cnode->property (X_("other"))) == 0) {
909                                                 continue;
910                                         }
911
912                                         if (prop) {
913                                                 connect (p, prop->value(), this);
914                                         }
915                                 }
916                         }
917                 }
918         }
919
920         return 0;
921 }
922
923
924 int
925 IO::make_connections_2X (const XMLNode& node, int /*version*/, bool in)
926 {
927         const XMLProperty* prop;
928
929         /* XXX: bundles ("connections" as was) */
930
931         if ((prop = node.property ("inputs")) != 0 && in) {
932
933                 string::size_type ostart = 0;
934                 string::size_type start = 0;
935                 string::size_type end = 0;
936                 int i = 0;
937                 int n;
938                 vector<string> ports;
939
940                 string const str = prop->value ();
941
942                 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
943                         start += 1;
944
945                         if ((end = str.find_first_of ('}', start)) == string::npos) {
946                                 error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
947                                 return -1;
948                         }
949
950                         if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
951                                 error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
952
953                                 return -1;
954
955                         } else if (n > 0) {
956
957
958                                 for (int x = 0; x < n; ++x) {
959                                         /* XXX: this is a bit of a hack; need to check if it's always valid */
960                                         string::size_type const p = ports[x].find ("/out");
961                                         if (p != string::npos) {
962                                                 ports[x].replace (p, 4, "/audio_out");
963                                         }
964                                         nth(i)->connect (ports[x]);
965                                 }
966                         }
967
968                         ostart = end+1;
969                         i++;
970                 }
971
972         }
973
974         if ((prop = node.property ("outputs")) != 0 && !in) {
975
976                 string::size_type ostart = 0;
977                 string::size_type start = 0;
978                 string::size_type end = 0;
979                 int i = 0;
980                 int n;
981                 vector<string> ports;
982
983                 string const str = prop->value ();
984
985                 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
986                         start += 1;
987
988                         if ((end = str.find_first_of ('}', start)) == string::npos) {
989                                 error << string_compose(_("IO: badly formed string in XML node for outputs \"%1\""), str) << endmsg;
990                                 return -1;
991                         }
992
993                         if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
994                                 error << string_compose(_("IO: bad output string in XML node \"%1\""), str) << endmsg;
995
996                                 return -1;
997
998                         } else if (n > 0) {
999
1000                                 for (int x = 0; x < n; ++x) {
1001                                         /* XXX: this is a bit of a hack; need to check if it's always valid */
1002                                         string::size_type const p = ports[x].find ("/in");
1003                                         if (p != string::npos) {
1004                                                 ports[x].replace (p, 3, "/audio_in");
1005                                         }
1006                                         nth(i)->connect (ports[x]);
1007                                 }
1008                         }
1009
1010                         ostart = end+1;
1011                         i++;
1012                 }
1013         }
1014
1015         return 0;
1016 }
1017
1018 int
1019 IO::set_ports (const string& str)
1020 {
1021         vector<string> ports;
1022         int i;
1023         int n;
1024         uint32_t nports;
1025
1026         if ((nports = count (str.begin(), str.end(), '{')) == 0) {
1027                 return 0;
1028         }
1029
1030         {
1031                 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1032
1033                 // FIXME: audio-only
1034                 if (ensure_ports (ChanCount(DataType::AUDIO, nports), true, this)) {
1035                         return -1;
1036                 }
1037         }
1038
1039         string::size_type start, end, ostart;
1040
1041         ostart = 0;
1042         start = 0;
1043         end = 0;
1044         i = 0;
1045
1046         while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1047                 start += 1;
1048
1049                 if ((end = str.find_first_of ('}', start)) == string::npos) {
1050                         error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1051                         return -1;
1052                 }
1053
1054                 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1055                         error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1056
1057                         return -1;
1058
1059                 } else if (n > 0) {
1060
1061                         for (int x = 0; x < n; ++x) {
1062                                 connect (nth (i), ports[x], this);
1063                         }
1064                 }
1065
1066                 ostart = end+1;
1067                 i++;
1068         }
1069
1070         return 0;
1071 }
1072
1073 int
1074 IO::parse_io_string (const string& str, vector<string>& ports)
1075 {
1076         string::size_type pos, opos;
1077
1078         if (str.length() == 0) {
1079                 return 0;
1080         }
1081
1082         pos = 0;
1083         opos = 0;
1084
1085         ports.clear ();
1086
1087         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1088                 ports.push_back (str.substr (opos, pos - opos));
1089                 opos = pos + 1;
1090         }
1091
1092         if (opos < str.length()) {
1093                 ports.push_back (str.substr(opos));
1094         }
1095
1096         return ports.size();
1097 }
1098
1099 int
1100 IO::parse_gain_string (const string& str, vector<string>& ports)
1101 {
1102         string::size_type pos, opos;
1103
1104         pos = 0;
1105         opos = 0;
1106         ports.clear ();
1107
1108         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1109                 ports.push_back (str.substr (opos, pos - opos));
1110                 opos = pos + 1;
1111         }
1112
1113         if (opos < str.length()) {
1114                 ports.push_back (str.substr(opos));
1115         }
1116
1117         return ports.size();
1118 }
1119
1120 bool
1121 IO::set_name (const string& requested_name)
1122 {
1123         string name = requested_name;
1124
1125         if (_name == name) {
1126                 return true;
1127         }
1128
1129         /* replace all colons in the name. i wish we didn't have to do this */
1130
1131         replace_all (name, ":", "-");
1132
1133         for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
1134                 string current_name = i->name();
1135                 current_name.replace (current_name.find (_name), _name.val().length(), name);
1136                 i->set_name (current_name);
1137         }
1138
1139         bool const r = SessionObject::set_name (name);
1140
1141         setup_bundle ();
1142
1143         return r;
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->private_latency_range (_direction == Output).max) > max_latency) {
1158                         DEBUG_TRACE (DEBUG::Latency, string_compose ("port %1 has %2 latency of %3 - use\n",
1159                                                                      name(),
1160                                                                      ((_direction == Output) ? "PLAYBACK" : "CAPTURE"),
1161                                                                      latency));
1162                         max_latency = latency;
1163                 }
1164         }
1165
1166         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: max %4 latency from %2 ports = %3\n",
1167                                                      name(), _ports.num_ports(), max_latency,
1168                                                      ((_direction == Output) ? "PLAYBACK" : "CAPTURE")));
1169         return max_latency;
1170 }
1171
1172 int
1173 IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, void* src)
1174 {
1175         BLOCK_PROCESS_CALLBACK ();
1176
1177         {
1178                 Glib::Mutex::Lock lm2 (io_lock);
1179
1180                 c->connect (_bundle, _session.engine());
1181
1182                 /* If this is a UserBundle, make a note of what we've done */
1183
1184                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1185                 if (ub) {
1186
1187                         /* See if we already know about this one */
1188                         std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1189                         while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1190                                 ++i;
1191                         }
1192
1193                         if (i == _bundles_connected.end()) {
1194                                 /* We don't, so make a note */
1195                                 _bundles_connected.push_back (new UserBundleInfo (this, ub));
1196                         }
1197                 }
1198         }
1199
1200         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1201         return 0;
1202 }
1203
1204 int
1205 IO::disconnect_ports_from_bundle (boost::shared_ptr<Bundle> c, void* src)
1206 {
1207         BLOCK_PROCESS_CALLBACK ();
1208
1209         {
1210                 Glib::Mutex::Lock lm2 (io_lock);
1211
1212                 c->disconnect (_bundle, _session.engine());
1213
1214                 /* If this is a UserBundle, make a note of what we've done */
1215
1216                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1217                 if (ub) {
1218
1219                         std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1220                         while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1221                                 ++i;
1222                         }
1223
1224                         if (i != _bundles_connected.end()) {
1225                                 delete *i;
1226                                 _bundles_connected.erase (i);
1227                         }
1228                 }
1229         }
1230
1231         changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1232         return 0;
1233 }
1234
1235
1236 int
1237 IO::disable_connecting ()
1238 {
1239         connecting_legal = false;
1240         return 0;
1241 }
1242
1243 int
1244 IO::enable_connecting ()
1245 {
1246         connecting_legal = true;
1247         boost::optional<int> r = ConnectingLegal ();
1248         return r.get_value_or (0);
1249 }
1250
1251 void
1252 IO::bundle_changed (Bundle::Change /*c*/)
1253 {
1254         /* XXX */
1255 //      connect_input_ports_to_bundle (_input_bundle, this);
1256 }
1257
1258
1259 string
1260 IO::build_legal_port_name (DataType type)
1261 {
1262         const int name_size = jack_port_name_size();
1263         int limit;
1264         string suffix;
1265
1266         if (type == DataType::AUDIO) {
1267                 suffix = _("audio");
1268         } else if (type == DataType::MIDI) {
1269                 suffix = _("midi");
1270         } else {
1271                 throw unknown_type();
1272         }
1273
1274         /* note that if "in" or "out" are translated it will break a session
1275            across locale switches because a port's connection list will
1276            show (old) translated names, but the current port name will
1277            use the (new) translated name.
1278         */
1279
1280         if (_direction == Input) {
1281                 suffix += X_("_in");
1282         } else {
1283                 suffix += X_("_out");
1284         }
1285
1286         // allow up to 4 digits for the output port number, plus the slash, suffix and extra space
1287
1288         limit = name_size - _session.engine().client_name().length() - (suffix.length() + 5);
1289
1290         char buf1[name_size+1];
1291         char buf2[name_size+1];
1292
1293         /* colons are illegal in port names, so fix that */
1294
1295         string nom = _name.val();
1296         replace_all (nom, ":", ";");
1297
1298         snprintf (buf1, name_size+1, ("%.*s/%s"), limit, nom.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 bool
1527 IO::connected_to (const string& str) const
1528 {
1529         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1530                 if (i->connected_to (str)) {
1531                         return true;
1532                 }
1533         }
1534
1535         return false;
1536 }
1537
1538 /** Caller must hold process lock */
1539 void
1540 IO::process_input (boost::shared_ptr<Processor> proc, framepos_t start_frame, framepos_t end_frame, pframes_t nframes)
1541 {
1542         /* don't read the data into new buffers - just use the port buffers directly */
1543
1544         _buffers.get_jack_port_addresses (_ports, nframes);
1545         proc->run (_buffers, start_frame, end_frame, nframes, true);
1546 }
1547
1548 void
1549 IO::collect_input (BufferSet& bufs, pframes_t nframes, ChanCount offset)
1550 {
1551         assert(bufs.available() >= _ports.count());
1552
1553         if (_ports.count() == ChanCount::ZERO) {
1554                 return;
1555         }
1556
1557         bufs.set_count (_ports.count());
1558
1559         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1560                 PortSet::iterator   i = _ports.begin(*t);
1561                 BufferSet::iterator b = bufs.begin(*t);
1562
1563                 for (uint32_t off = 0; off < offset.get(*t); ++off, ++b) {
1564                         if (b == bufs.end(*t)) {
1565                                 continue;
1566                         }
1567                 }
1568
1569                 for ( ; i != _ports.end(*t); ++i, ++b) {
1570                         Buffer& bb (i->get_buffer (nframes));
1571                         b->read_from (bb, nframes);
1572                 }
1573         }
1574 }
1575
1576 void
1577 IO::copy_to_outputs (BufferSet& bufs, DataType type, pframes_t nframes, framecnt_t offset)
1578 {
1579         // Copy any buffers 1:1 to outputs
1580
1581         PortSet::iterator o = _ports.begin(type);
1582         BufferSet::iterator i = bufs.begin(type);
1583         BufferSet::iterator prev = i;
1584
1585         while (i != bufs.end(type) && o != _ports.end (type)) {
1586                 Buffer& port_buffer (o->get_buffer (nframes));
1587                 port_buffer.read_from (*i, nframes, offset);
1588                 prev = i;
1589                 ++i;
1590                 ++o;
1591         }
1592
1593         // Copy last buffer to any extra outputs
1594
1595         while (o != _ports.end(type)) {
1596                 Buffer& port_buffer (o->get_buffer (nframes));
1597                 port_buffer.read_from (*prev, nframes, offset);
1598                 ++o;
1599         }
1600 }
1601
1602 Port*
1603 IO::port_by_name (const std::string& str) const
1604 {
1605         /* to be called only from ::set_state() - no locking */
1606
1607         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1608
1609                 const Port& p(*i);
1610
1611                 if (p.name() == str) {
1612                         return const_cast<Port*>(&p);
1613                 }
1614         }
1615
1616         return 0;
1617 }
1618
1619 bool
1620 IO::physically_connected () const
1621 {
1622         for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1623                 if (i->physically_connected()) {
1624                         return true;
1625                 }
1626         }
1627
1628         return false;
1629 }
1630
1631 bool
1632 IO::has_port (Port* p) const
1633 {
1634         Glib::Mutex::Lock lm (io_lock);
1635         return _ports.contains (p);
1636 }