use std::vector::assign() in BufferSet::attach_buffers() rather than an explicit...
[ardour2.git] / libs / ardour / io.cc
blob0d9933cb0c369e5eebeb63b9b0c3606843c138df
1 /*
2 Copyright (C) 2000-2006 Paul Davis
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.
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.
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.
19 #include <fstream>
20 #include <algorithm>
21 #include <cmath>
23 #include <unistd.h>
24 #include <locale.h>
25 #include <errno.h>
27 #include <glibmm.h>
28 #include <glibmm/thread.h>
30 #include "pbd/xml++.h"
31 #include "pbd/replace_all.h"
32 #include "pbd/unknown_type.h"
33 #include "pbd/enumwriter.h"
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"
50 #include "i18n.h"
52 #define BLOCK_PROCESS_CALLBACK() Glib::Mutex::Lock em (AudioEngine::instance()->process_lock())
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
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;
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).
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)
71 _active = true;
72 pending_state_node = 0;
73 setup_bundle ();
76 IO::IO (Session& s, const XMLNode& node, DataType dt)
77 : SessionObject(s, "unnamed io")
78 , _direction (Input)
79 , _default_type (dt)
81 _active = true;
82 pending_state_node = 0;
84 set_state (node, Stateful::loading_state_version);
85 setup_bundle ();
88 IO::~IO ()
90 Glib::Mutex::Lock lm (io_lock);
92 BLOCK_PROCESS_CALLBACK ();
94 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
95 _session.engine().unregister_port (*i);
99 void
100 IO::increment_port_buffer_offset (pframes_t offset)
102 /* io_lock, not taken: function must be called from Session::process() calltree */
104 if (_direction == Output) {
105 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
106 i->increment_port_buffer_offset (offset);
111 void
112 IO::silence (framecnt_t nframes)
114 /* io_lock, not taken: function must be called from Session::process() calltree */
116 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
117 i->get_buffer(nframes).silence (nframes);
121 void
122 IO::check_bundles_connected ()
124 check_bundles (_bundles_connected, ports());
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.
131 void
132 IO::check_bundles (std::vector<UserBundleInfo*>& list, const PortSet& ports)
134 std::vector<UserBundleInfo*> new_list;
136 for (std::vector<UserBundleInfo*>::iterator i = list.begin(); i != list.end(); ++i) {
138 uint32_t const N = (*i)->bundle->nchannels().n_total();
140 if (_ports.num_ports() < N) {
141 continue;
144 bool ok = true;
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;
156 if (ok == false) {
157 break;
161 if (ok) {
162 new_list.push_back (*i);
163 } else {
164 delete *i;
168 list = new_list;
173 IO::disconnect (Port* our_port, string other_port, void* src)
175 if (other_port.length() == 0 || our_port == 0) {
176 return 0;
180 Glib::Mutex::Lock lm (io_lock);
182 /* check that our_port is really one of ours */
184 if ( ! _ports.contains(our_port)) {
185 return -1;
188 /* disconnect it from the source */
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;
195 check_bundles_connected ();
198 changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
200 _session.set_dirty ();
202 return 0;
206 IO::connect (Port* our_port, string other_port, void* src)
208 if (other_port.length() == 0 || our_port == 0) {
209 return 0;
213 Glib::Mutex::Lock lm (io_lock);
215 /* check that our_port is really one of ours */
217 if ( ! _ports.contains(our_port) ) {
218 return -1;
221 /* connect it to the source */
223 if (our_port->connect (other_port)) {
224 return -1;
227 changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
228 _session.set_dirty ();
229 return 0;
233 IO::remove_port (Port* port, void* src)
235 ChanCount before = _ports.count ();
236 ChanCount after = before;
237 after.set (port->type(), after.get (port->type()) - 1);
239 bool const r = PortCountChanging (after); /* EMIT SIGNAL */
240 if (r) {
241 return -1;
244 IOChange change;
247 BLOCK_PROCESS_CALLBACK ();
250 Glib::Mutex::Lock lm (io_lock);
252 if (_ports.remove(port)) {
253 change.type = IOChange::Type (change.type | IOChange::ConfigurationChanged);
254 change.before = before;
255 change.after = _ports.count ();
257 if (port->connected()) {
258 change.type = IOChange::Type (change.type | IOChange::ConnectionsChanged);
261 _session.engine().unregister_port (*port);
262 check_bundles_connected ();
266 PortCountChanged (n_ports()); /* EMIT SIGNAL */
268 if (change.type != IOChange::NoChange) {
269 changed (change, src);
270 _buffers.attach_buffers (_ports);
274 if (change.type & IOChange::ConfigurationChanged) {
275 setup_bundle ();
278 if (change.type == IOChange::NoChange) {
279 return -1;
282 _session.set_dirty ();
284 return 0;
287 /** Add a port.
289 * @param destination Name of port to connect new port to.
290 * @param src Source for emitted ConfigurationChanged signal.
291 * @param type Data type of port. Default value (NIL) will use this IO's default type.
294 IO::add_port (string destination, void* src, DataType type)
296 Port* our_port;
298 if (type == DataType::NIL) {
299 type = _default_type;
302 IOChange change;
305 BLOCK_PROCESS_CALLBACK ();
309 Glib::Mutex::Lock lm (io_lock);
311 /* Create a new port */
313 string portname = build_legal_port_name (type);
315 if (_direction == Input) {
316 if ((our_port = _session.engine().register_input_port (type, portname)) == 0) {
317 error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
318 return -1;
320 } else {
321 if ((our_port = _session.engine().register_output_port (type, portname)) == 0) {
322 error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
323 return -1;
327 change.before = _ports.count ();
328 _ports.add (our_port);
331 PortCountChanged (n_ports()); /* EMIT SIGNAL */
332 change.type = IOChange::ConfigurationChanged;
333 change.after = _ports.count ();
334 changed (change, src); /* EMIT SIGNAL */
335 _buffers.attach_buffers (_ports);
338 if (!destination.empty()) {
339 if (our_port->connect (destination)) {
340 return -1;
344 setup_bundle ();
345 _session.set_dirty ();
347 return 0;
351 IO::disconnect (void* src)
354 Glib::Mutex::Lock lm (io_lock);
356 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
357 i->disconnect_all ();
360 check_bundles_connected ();
363 changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
365 return 0;
368 /** Caller must hold process lock */
369 bool
370 IO::ensure_ports_locked (ChanCount count, bool clear, void* /*src*/)
372 assert (!AudioEngine::instance()->process_lock().trylock());
374 Port* port = 0;
375 bool changed = false;
377 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
379 const size_t n = count.get(*t);
381 /* remove unused ports */
382 for (size_t i = n_ports().get(*t); i > n; --i) {
383 port = _ports.port(*t, i-1);
385 assert(port);
386 _ports.remove(port);
387 _session.engine().unregister_port (*port);
389 changed = true;
392 /* create any necessary new ports */
393 while (n_ports().get(*t) < n) {
395 string portname = build_legal_port_name (*t);
397 try {
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;
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;
412 catch (AudioEngine::PortRegistrationFailure& err) {
413 /* pass it on */
414 throw;
417 _ports.add (port);
418 changed = true;
422 if (changed) {
423 check_bundles_connected ();
424 PortCountChanged (n_ports()); /* EMIT SIGNAL */
425 _session.set_dirty ();
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 ();
435 return changed;
438 /** Caller must hold process lock */
440 IO::ensure_ports (ChanCount count, bool clear, void* src)
442 assert (!AudioEngine::instance()->process_lock().trylock());
444 bool changed = false;
446 if (count == n_ports() && !clear) {
447 return 0;
450 IOChange change;
452 change.before = _ports.count ();
455 Glib::Mutex::Lock im (io_lock);
456 changed = ensure_ports_locked (count, clear, src);
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 ();
468 return 0;
471 /** Caller must hold process lock */
473 IO::ensure_io (ChanCount count, bool clear, void* src)
475 assert (!AudioEngine::instance()->process_lock().trylock());
477 return ensure_ports (count, clear, src);
480 XMLNode&
481 IO::get_state (void)
483 return state (true);
486 XMLNode&
487 IO::state (bool /*full_state*/)
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);
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());
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);
509 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
511 vector<string> connections;
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());
517 if (i->get_connections (connections)) {
519 for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
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.
528 XMLNode* cnode = new XMLNode (X_("Connection"));
530 cnode->add_property (X_("other"), _session.engine().make_port_name_relative (*ci));
531 pnode->add_child_nocopy (*cnode);
535 node->add_child_nocopy (*pnode);
538 snprintf (buf, sizeof (buf), "%" PRId64, _user_latency);
539 node->add_property (X_("user-latency"), buf);
541 return *node;
545 IO::set_state (const XMLNode& node, int version)
547 /* callers for version < 3000 need to call set_state_2X directly, as A3 IOs
548 * are input OR output, not both, so the direction needs to be specified
549 * by the caller.
551 assert (version >= 3000);
553 const XMLProperty* prop;
554 XMLNodeConstIterator iter;
555 LocaleGuard lg (X_("POSIX"));
557 /* force use of non-localized representation of decimal point,
558 since we use it a lot in XML files and so forth.
561 if (node.name() != state_node_name) {
562 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
563 return -1;
566 if ((prop = node.property ("name")) != 0) {
567 set_name (prop->value());
570 if ((prop = node.property (X_("default-type"))) != 0) {
571 _default_type = DataType(prop->value());
572 assert(_default_type != DataType::NIL);
575 if ((prop = node.property ("id")) != 0) {
576 _id = prop->value ();
579 if ((prop = node.property ("direction")) != 0) {
580 _direction = (Direction) string_2_enum (prop->value(), _direction);
583 if (create_ports (node, version)) {
584 return -1;
587 if (connecting_legal) {
589 if (make_connections (node, version, false)) {
590 return -1;
593 } else {
595 pending_state_node = new XMLNode (node);
596 pending_state_node_version = version;
597 pending_state_node_in = false;
598 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
601 if ((prop = node.property ("user-latency")) != 0) {
602 _user_latency = atoi (prop->value ());
605 return 0;
609 IO::set_state_2X (const XMLNode& node, int version, bool in)
611 const XMLProperty* prop;
612 XMLNodeConstIterator iter;
613 LocaleGuard lg (X_("POSIX"));
615 /* force use of non-localized representation of decimal point,
616 since we use it a lot in XML files and so forth.
619 if (node.name() != state_node_name) {
620 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
621 return -1;
624 if ((prop = node.property ("name")) != 0) {
625 set_name (prop->value());
628 if ((prop = node.property (X_("default-type"))) != 0) {
629 _default_type = DataType(prop->value());
630 assert(_default_type != DataType::NIL);
633 if ((prop = node.property ("id")) != 0) {
634 _id = prop->value ();
637 _direction = in ? Input : Output;
639 if (create_ports (node, version)) {
640 return -1;
643 if (connecting_legal) {
645 if (make_connections_2X (node, version, in)) {
646 return -1;
649 } else {
651 pending_state_node = new XMLNode (node);
652 pending_state_node_version = version;
653 pending_state_node_in = in;
654 ConnectingLegal.connect_same_thread (connection_legal_c, boost::bind (&IO::connecting_became_legal, this));
657 return 0;
661 IO::connecting_became_legal ()
663 int ret;
665 assert (pending_state_node);
667 connection_legal_c.disconnect ();
669 ret = make_connections (*pending_state_node, pending_state_node_version, pending_state_node_in);
671 delete pending_state_node;
672 pending_state_node = 0;
674 return ret;
677 boost::shared_ptr<Bundle>
678 IO::find_possible_bundle (const string &desired_name)
680 static const string digits = "0123456789";
681 const string &default_name = (_direction == Input ? _("in") : _("out"));
682 const string &bundle_type_name = (_direction == Input ? _("input") : _("output"));
684 boost::shared_ptr<Bundle> c = _session.bundle_by_name (desired_name);
686 if (!c) {
687 int bundle_number, mask;
688 string possible_name;
689 bool stereo = false;
690 string::size_type last_non_digit_pos;
692 error << string_compose(_("Unknown bundle \"%1\" listed for %2 of %3"), desired_name, bundle_type_name, _name)
693 << endmsg;
695 // find numeric suffix of desired name
696 bundle_number = 0;
698 last_non_digit_pos = desired_name.find_last_not_of(digits);
700 if (last_non_digit_pos != string::npos) {
701 stringstream s;
702 s << desired_name.substr(last_non_digit_pos);
703 s >> bundle_number;
706 // see if it's a stereo connection e.g. "in 3+4"
708 if (last_non_digit_pos > 1 && desired_name[last_non_digit_pos] == '+') {
709 string::size_type left_last_non_digit_pos;
711 left_last_non_digit_pos = desired_name.find_last_not_of(digits, last_non_digit_pos-1);
713 if (left_last_non_digit_pos != string::npos) {
714 int left_bundle_number = 0;
715 stringstream s;
716 s << desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
717 s >> left_bundle_number;
719 if (left_bundle_number > 0 && left_bundle_number + 1 == bundle_number) {
720 bundle_number--;
721 stereo = true;
726 // make 0-based
727 if (bundle_number)
728 bundle_number--;
730 // find highest set bit
731 mask = 1;
732 while ((mask <= bundle_number) && (mask <<= 1)) {}
734 // "wrap" bundle number into largest possible power of 2
735 // that works...
737 while (mask) {
739 if (bundle_number & mask) {
740 bundle_number &= ~mask;
742 stringstream s;
743 s << default_name << " " << bundle_number + 1;
745 if (stereo) {
746 s << "+" << bundle_number + 2;
749 possible_name = s.str();
751 if ((c = _session.bundle_by_name (possible_name)) != 0) {
752 break;
755 mask >>= 1;
757 if (c) {
758 info << string_compose (_("Bundle %1 was not available - \"%2\" used instead"), desired_name, possible_name)
759 << endmsg;
760 } else {
761 error << string_compose(_("No %1 bundles available as a replacement"), bundle_type_name)
762 << endmsg;
767 return c;
772 IO::get_port_counts_2X (XMLNode const & node, int /*version*/, ChanCount& n, boost::shared_ptr<Bundle>& /*c*/)
774 XMLProperty const * prop;
775 XMLNodeList children = node.children ();
777 uint32_t n_audio = 0;
779 for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
781 if ((prop = node.property ("inputs")) != 0 && _direction == Input) {
782 n_audio = count (prop->value().begin(), prop->value().end(), '{');
783 } else if ((prop = node.property ("input-connection")) != 0 && _direction == Input) {
784 n_audio = 1;
785 } else if ((prop = node.property ("outputs")) != 0 && _direction == Output) {
786 n_audio = count (prop->value().begin(), prop->value().end(), '{');
787 } else if ((prop = node.property ("output-connection")) != 0 && _direction == Output) {
788 n_audio = 2;
792 ChanCount cnt;
793 cnt.set_audio (n_audio);
794 n = ChanCount::max (n, cnt);
796 return 0;
800 IO::get_port_counts (const XMLNode& node, int version, ChanCount& n, boost::shared_ptr<Bundle>& c)
802 if (version < 3000) {
803 return get_port_counts_2X (node, version, n, c);
806 XMLProperty const * prop;
807 XMLNodeConstIterator iter;
808 uint32_t n_audio = 0;
809 uint32_t n_midi = 0;
810 ChanCount cnt;
812 n = n_ports();
814 if ((prop = node.property ("connection")) != 0) {
816 if ((c = find_possible_bundle (prop->value())) != 0) {
817 n = ChanCount::max (n, c->nchannels());
819 return 0;
822 for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
824 if ((*iter)->name() == X_("Bundle")) {
825 if ((c = find_possible_bundle (prop->value())) != 0) {
826 n = ChanCount::max (n, c->nchannels());
827 return 0;
828 } else {
829 return -1;
833 if ((*iter)->name() == X_("Port")) {
834 prop = (*iter)->property (X_("type"));
836 if (!prop) {
837 continue;
840 if (prop->value() == X_("audio")) {
841 cnt.set_audio (++n_audio);
842 } else if (prop->value() == X_("midi")) {
843 cnt.set_midi (++n_midi);
848 n = ChanCount::max (n, cnt);
849 return 0;
853 IO::create_ports (const XMLNode& node, int version)
855 ChanCount n;
856 boost::shared_ptr<Bundle> c;
858 get_port_counts (node, version, n, c);
861 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
863 if (ensure_ports (n, true, this)) {
864 error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
865 return -1;
869 /* XXX use c */
871 return 0;
875 IO::make_connections (const XMLNode& node, int version, bool in)
877 if (version < 3000) {
878 return make_connections_2X (node, version, in);
881 const XMLProperty* prop;
883 for (XMLNodeConstIterator i = node.children().begin(); i != node.children().end(); ++i) {
885 if ((*i)->name() == "Bundle") {
886 XMLProperty const * prop = (*i)->property ("name");
887 if (prop) {
888 boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value());
889 if (b) {
890 connect_ports_to_bundle (b, this);
894 return 0;
897 if ((*i)->name() == "Port") {
899 prop = (*i)->property (X_("name"));
901 if (!prop) {
902 continue;
905 Port* p = port_by_name (prop->value());
907 if (p) {
908 for (XMLNodeConstIterator c = (*i)->children().begin(); c != (*i)->children().end(); ++c) {
910 XMLNode* cnode = (*c);
912 if (cnode->name() != X_("Connection")) {
913 continue;
916 if ((prop = cnode->property (X_("other"))) == 0) {
917 continue;
920 if (prop) {
921 connect (p, prop->value(), this);
928 return 0;
933 IO::make_connections_2X (const XMLNode& node, int /*version*/, bool in)
935 const XMLProperty* prop;
937 /* XXX: bundles ("connections" as was) */
939 if ((prop = node.property ("inputs")) != 0 && in) {
941 string::size_type ostart = 0;
942 string::size_type start = 0;
943 string::size_type end = 0;
944 int i = 0;
945 int n;
946 vector<string> ports;
948 string const str = prop->value ();
950 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
951 start += 1;
953 if ((end = str.find_first_of ('}', start)) == string::npos) {
954 error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
955 return -1;
958 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
959 error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
961 return -1;
963 } else if (n > 0) {
966 for (int x = 0; x < n; ++x) {
967 /* XXX: this is a bit of a hack; need to check if it's always valid */
968 string::size_type const p = ports[x].find ("/out");
969 if (p != string::npos) {
970 ports[x].replace (p, 4, "/audio_out");
972 nth(i)->connect (ports[x]);
976 ostart = end+1;
977 i++;
982 if ((prop = node.property ("outputs")) != 0 && !in) {
984 string::size_type ostart = 0;
985 string::size_type start = 0;
986 string::size_type end = 0;
987 int i = 0;
988 int n;
989 vector<string> ports;
991 string const str = prop->value ();
993 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
994 start += 1;
996 if ((end = str.find_first_of ('}', start)) == string::npos) {
997 error << string_compose(_("IO: badly formed string in XML node for outputs \"%1\""), str) << endmsg;
998 return -1;
1001 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1002 error << string_compose(_("IO: bad output string in XML node \"%1\""), str) << endmsg;
1004 return -1;
1006 } else if (n > 0) {
1008 for (int x = 0; x < n; ++x) {
1009 /* XXX: this is a bit of a hack; need to check if it's always valid */
1010 string::size_type const p = ports[x].find ("/in");
1011 if (p != string::npos) {
1012 ports[x].replace (p, 3, "/audio_in");
1014 nth(i)->connect (ports[x]);
1018 ostart = end+1;
1019 i++;
1023 return 0;
1027 IO::set_ports (const string& str)
1029 vector<string> ports;
1030 int i;
1031 int n;
1032 uint32_t nports;
1034 if ((nports = count (str.begin(), str.end(), '{')) == 0) {
1035 return 0;
1039 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1041 // FIXME: audio-only
1042 if (ensure_ports (ChanCount(DataType::AUDIO, nports), true, this)) {
1043 return -1;
1047 string::size_type start, end, ostart;
1049 ostart = 0;
1050 start = 0;
1051 end = 0;
1052 i = 0;
1054 while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1055 start += 1;
1057 if ((end = str.find_first_of ('}', start)) == string::npos) {
1058 error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1059 return -1;
1062 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1063 error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1065 return -1;
1067 } else if (n > 0) {
1069 for (int x = 0; x < n; ++x) {
1070 connect (nth (i), ports[x], this);
1074 ostart = end+1;
1075 i++;
1078 return 0;
1082 IO::parse_io_string (const string& str, vector<string>& ports)
1084 string::size_type pos, opos;
1086 if (str.length() == 0) {
1087 return 0;
1090 pos = 0;
1091 opos = 0;
1093 ports.clear ();
1095 while ((pos = str.find_first_of (',', opos)) != string::npos) {
1096 ports.push_back (str.substr (opos, pos - opos));
1097 opos = pos + 1;
1100 if (opos < str.length()) {
1101 ports.push_back (str.substr(opos));
1104 return ports.size();
1108 IO::parse_gain_string (const string& str, vector<string>& ports)
1110 string::size_type pos, opos;
1112 pos = 0;
1113 opos = 0;
1114 ports.clear ();
1116 while ((pos = str.find_first_of (',', opos)) != string::npos) {
1117 ports.push_back (str.substr (opos, pos - opos));
1118 opos = pos + 1;
1121 if (opos < str.length()) {
1122 ports.push_back (str.substr(opos));
1125 return ports.size();
1128 bool
1129 IO::set_name (const string& requested_name)
1131 string name = requested_name;
1133 if (_name == name) {
1134 return true;
1137 /* replace all colons in the name. i wish we didn't have to do this */
1139 replace_all (name, ":", "-");
1141 for (PortSet::iterator i = _ports.begin(); i != _ports.end(); ++i) {
1142 string current_name = i->name();
1143 current_name.replace (current_name.find (_name), _name.val().length(), name);
1144 i->set_name (current_name);
1147 bool const r = SessionObject::set_name (name);
1149 setup_bundle ();
1151 return r;
1154 framecnt_t
1155 IO::latency () const
1157 framecnt_t max_latency;
1158 framecnt_t latency;
1160 max_latency = 0;
1162 /* io lock not taken - must be protected by other means */
1164 for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1165 if ((latency = i->private_latency_range (_direction == Output).max) > max_latency) {
1166 DEBUG_TRACE (DEBUG::Latency, string_compose ("port %1 has %2 latency of %3 - use\n",
1167 name(),
1168 ((_direction == Output) ? "PLAYBACK" : "CAPTURE"),
1169 latency));
1170 max_latency = latency;
1174 DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: max %4 latency from %2 ports = %3\n",
1175 name(), _ports.num_ports(), max_latency,
1176 ((_direction == Output) ? "PLAYBACK" : "CAPTURE")));
1177 return max_latency;
1181 IO::connect_ports_to_bundle (boost::shared_ptr<Bundle> c, void* src)
1183 BLOCK_PROCESS_CALLBACK ();
1186 Glib::Mutex::Lock lm2 (io_lock);
1188 c->connect (_bundle, _session.engine());
1190 /* If this is a UserBundle, make a note of what we've done */
1192 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1193 if (ub) {
1195 /* See if we already know about this one */
1196 std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1197 while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1198 ++i;
1201 if (i == _bundles_connected.end()) {
1202 /* We don't, so make a note */
1203 _bundles_connected.push_back (new UserBundleInfo (this, ub));
1208 changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1209 return 0;
1213 IO::disconnect_ports_from_bundle (boost::shared_ptr<Bundle> c, void* src)
1215 BLOCK_PROCESS_CALLBACK ();
1218 Glib::Mutex::Lock lm2 (io_lock);
1220 c->disconnect (_bundle, _session.engine());
1222 /* If this is a UserBundle, make a note of what we've done */
1224 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
1225 if (ub) {
1227 std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin();
1228 while (i != _bundles_connected.end() && (*i)->bundle != ub) {
1229 ++i;
1232 if (i != _bundles_connected.end()) {
1233 delete *i;
1234 _bundles_connected.erase (i);
1239 changed (IOChange (IOChange::ConnectionsChanged), src); /* EMIT SIGNAL */
1240 return 0;
1245 IO::disable_connecting ()
1247 connecting_legal = false;
1248 return 0;
1252 IO::enable_connecting ()
1254 connecting_legal = true;
1255 boost::optional<int> r = ConnectingLegal ();
1256 return r.get_value_or (0);
1259 void
1260 IO::bundle_changed (Bundle::Change /*c*/)
1262 //XXX
1263 // connect_input_ports_to_bundle (_input_bundle, this);
1267 string
1268 IO::build_legal_port_name (DataType type)
1270 const int name_size = jack_port_name_size();
1271 int limit;
1272 string suffix;
1274 if (type == DataType::AUDIO) {
1275 suffix = _("audio");
1276 } else if (type == DataType::MIDI) {
1277 suffix = _("midi");
1278 } else {
1279 throw unknown_type();
1282 /* note that if "in" or "out" are translated it will break a session
1283 across locale switches because a port's connection list will
1284 show (old) translated names, but the current port name will
1285 use the (new) translated name.
1288 if (_direction == Input) {
1289 suffix += X_("_in");
1290 } else {
1291 suffix += X_("_out");
1294 // allow up to 4 digits for the output port number, plus the slash, suffix and extra space
1296 limit = name_size - _session.engine().client_name().length() - (suffix.length() + 5);
1298 char buf1[name_size+1];
1299 char buf2[name_size+1];
1301 snprintf (buf1, name_size+1, ("%.*s/%s"), limit, _name.val().c_str(), suffix.c_str());
1303 int port_number = find_port_hole (buf1);
1304 snprintf (buf2, name_size+1, "%s %d", buf1, port_number);
1306 return string (buf2);
1309 int32_t
1310 IO::find_port_hole (const char* base)
1312 /* CALLER MUST HOLD IO LOCK */
1314 uint32_t n;
1316 if (_ports.empty()) {
1317 return 1;
1320 /* we only allow up to 4 characters for the port number
1323 for (n = 1; n < 9999; ++n) {
1324 char buf[jack_port_name_size()];
1325 PortSet::iterator i = _ports.begin();
1327 snprintf (buf, jack_port_name_size(), _("%s %u"), base, n);
1329 for ( ; i != _ports.end(); ++i) {
1330 if (i->name() == buf) {
1331 break;
1335 if (i == _ports.end()) {
1336 break;
1339 return n;
1343 AudioPort*
1344 IO::audio(uint32_t n) const
1346 return _ports.nth_audio_port (n);
1350 MidiPort*
1351 IO::midi(uint32_t n) const
1353 return _ports.nth_midi_port (n);
1357 * Setup a bundle that describe our inputs or outputs. Also creates the bundle if necessary.
1360 void
1361 IO::setup_bundle ()
1363 char buf[32];
1365 if (!_bundle) {
1366 _bundle.reset (new Bundle (_direction == Input));
1369 _bundle->suspend_signals ();
1371 _bundle->remove_channels ();
1373 if (_direction == Input) {
1374 snprintf(buf, sizeof (buf), _("%s in"), _name.val().c_str());
1375 } else {
1376 snprintf(buf, sizeof (buf), _("%s out"), _name.val().c_str());
1378 _bundle->set_name (buf);
1380 int c = 0;
1381 for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
1383 uint32_t const N = _ports.count().get (*i);
1384 for (uint32_t j = 0; j < N; ++j) {
1385 _bundle->add_channel (bundle_channel_name (j, N, *i), *i);
1386 _bundle->set_port (c, _session.engine().make_port_name_non_relative (_ports.port(*i, j)->name()));
1387 ++c;
1392 _bundle->resume_signals ();
1395 /** @return Bundles connected to our ports */
1396 BundleList
1397 IO::bundles_connected ()
1399 BundleList bundles;
1401 /* User bundles */
1402 for (std::vector<UserBundleInfo*>::iterator i = _bundles_connected.begin(); i != _bundles_connected.end(); ++i) {
1403 bundles.push_back ((*i)->bundle);
1406 /* Session bundles */
1407 boost::shared_ptr<ARDOUR::BundleList> b = _session.bundles ();
1408 for (ARDOUR::BundleList::iterator i = b->begin(); i != b->end(); ++i) {
1409 if ((*i)->connected_to (_bundle, _session.engine())) {
1410 bundles.push_back (*i);
1414 /* Route bundles */
1416 boost::shared_ptr<ARDOUR::RouteList> r = _session.get_routes ();
1418 if (_direction == Input) {
1419 for (ARDOUR::RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1420 if ((*i)->output()->bundle()->connected_to (_bundle, _session.engine())) {
1421 bundles.push_back ((*i)->output()->bundle());
1424 } else {
1425 for (ARDOUR::RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1426 if ((*i)->input()->bundle()->connected_to (_bundle, _session.engine())) {
1427 bundles.push_back ((*i)->input()->bundle());
1432 return bundles;
1436 IO::UserBundleInfo::UserBundleInfo (IO* io, boost::shared_ptr<UserBundle> b)
1438 bundle = b;
1439 b->Changed.connect_same_thread (changed, boost::bind (&IO::bundle_changed, io, _1));
1442 std::string
1443 IO::bundle_channel_name (uint32_t c, uint32_t n, DataType t) const
1445 char buf[32];
1447 if (t == DataType::AUDIO) {
1449 switch (n) {
1450 case 1:
1451 return _("mono");
1452 case 2:
1453 return c == 0 ? _("L") : _("R");
1454 default:
1455 snprintf (buf, sizeof(buf), _("%d"), (c + 1));
1456 return buf;
1459 } else {
1461 snprintf (buf, sizeof(buf), _("%d"), (c + 1));
1462 return buf;
1466 return "";
1469 string
1470 IO::name_from_state (const XMLNode& node)
1472 const XMLProperty* prop;
1474 if ((prop = node.property ("name")) != 0) {
1475 return prop->value();
1478 return string();
1481 void
1482 IO::set_name_in_state (XMLNode& node, const string& new_name)
1484 const XMLProperty* prop;
1486 if ((prop = node.property ("name")) != 0) {
1487 node.add_property ("name", new_name);
1491 bool
1492 IO::connected () const
1494 /* do we have any connections at all? */
1496 for (PortSet::const_iterator p = _ports.begin(); p != _ports.end(); ++p) {
1497 if (p->connected()) {
1498 return true;
1502 return false;
1505 bool
1506 IO::connected_to (boost::shared_ptr<const IO> other) const
1508 if (!other) {
1509 return connected ();
1512 assert (_direction != other->direction());
1514 uint32_t i, j;
1515 uint32_t no = n_ports().n_total();
1516 uint32_t ni = other->n_ports ().n_total();
1518 for (i = 0; i < no; ++i) {
1519 for (j = 0; j < ni; ++j) {
1520 if (nth(i)->connected_to (other->nth(j)->name())) {
1521 return true;
1526 return false;
1529 bool
1530 IO::connected_to (const string& str) const
1532 for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1533 if (i->connected_to (str)) {
1534 return true;
1538 return false;
1541 /** Caller must hold process lock */
1542 void
1543 IO::process_input (boost::shared_ptr<Processor> proc, framepos_t start_frame, framepos_t end_frame, pframes_t nframes)
1545 /* don't read the data into new buffers - just use the port buffers directly */
1547 _buffers.get_jack_port_addresses (_ports, nframes);
1548 proc->run (_buffers, start_frame, end_frame, nframes, true);
1551 void
1552 IO::collect_input (BufferSet& bufs, pframes_t nframes, ChanCount offset)
1554 assert(bufs.available() >= _ports.count());
1556 if (_ports.count() == ChanCount::ZERO) {
1557 return;
1560 bufs.set_count (_ports.count());
1562 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1563 PortSet::iterator i = _ports.begin(*t);
1564 BufferSet::iterator b = bufs.begin(*t);
1566 for (uint32_t off = 0; off < offset.get(*t); ++off, ++b) {
1567 if (b == bufs.end(*t)) {
1568 continue;
1572 for ( ; i != _ports.end(*t); ++i, ++b) {
1573 Buffer& bb (i->get_buffer (nframes));
1574 b->read_from (bb, nframes);
1579 void
1580 IO::copy_to_outputs (BufferSet& bufs, DataType type, pframes_t nframes, framecnt_t offset)
1582 // Copy any buffers 1:1 to outputs
1584 PortSet::iterator o = _ports.begin(type);
1585 BufferSet::iterator i = bufs.begin(type);
1586 BufferSet::iterator prev = i;
1588 while (i != bufs.end(type) && o != _ports.end (type)) {
1589 Buffer& port_buffer (o->get_buffer (nframes));
1590 port_buffer.read_from (*i, nframes, offset);
1591 prev = i;
1592 ++i;
1593 ++o;
1596 // Copy last buffer to any extra outputs
1598 while (o != _ports.end(type)) {
1599 Buffer& port_buffer (o->get_buffer (nframes));
1600 port_buffer.read_from (*prev, nframes, offset);
1601 ++o;
1605 Port*
1606 IO::port_by_name (const std::string& str) const
1608 /* to be called only from ::set_state() - no locking */
1610 for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1612 const Port& p(*i);
1614 if (p.name() == str) {
1615 return const_cast<Port*>(&p);
1619 return 0;
1622 bool
1623 IO::physically_connected () const
1625 for (PortSet::const_iterator i = _ports.begin(); i != _ports.end(); ++i) {
1626 if (i->physically_connected()) {
1627 return true;
1631 return false;
1634 bool
1635 IO::has_port (Port* p) const
1637 Glib::Mutex::Lock lm (io_lock);
1638 return _ports.contains (p);