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