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