0343545936fcdf07e348c8601cb4427bcc1e5e50
[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 <unistd.h>
22 #include <locale.h>
23 #include <errno.h>
24
25 #include <sigc++/bind.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
34 #include <ardour/audioengine.h>
35 #include <ardour/io.h>
36 #include <ardour/route.h>
37 #include <ardour/port.h>
38 #include <ardour/audio_port.h>
39 #include <ardour/midi_port.h>
40 #include <ardour/auto_bundle.h>
41 #include <ardour/session.h>
42 #include <ardour/cycle_timer.h>
43 #include <ardour/panner.h>
44 #include <ardour/buffer_set.h>
45 #include <ardour/meter.h>
46 #include <ardour/amp.h>
47
48 #include "i18n.h"
49
50 #include <cmath>
51
52 /*
53   A bug in OS X's cmath that causes isnan() and isinf() to be 
54   "undeclared". the following works around that
55 */
56
57 #if defined(__APPLE__) && defined(__MACH__)
58 extern "C" int isnan (double);
59 extern "C" int isinf (double);
60 #endif
61
62 #define BLOCK_PROCESS_CALLBACK() Glib::Mutex::Lock em (_session.engine().process_lock())
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67
68 const string                 IO::state_node_name = "IO";
69 bool                         IO::connecting_legal = false;
70 bool                         IO::ports_legal = false;
71 bool                         IO::panners_legal = false;
72 sigc::signal<void>           IO::Meter;
73 sigc::signal<int>            IO::ConnectingLegal;
74 sigc::signal<int>            IO::PortsLegal;
75 sigc::signal<int>            IO::PannersLegal;
76 sigc::signal<void,ChanCount> IO::PortCountChanged;
77 sigc::signal<int>            IO::PortsCreated;
78
79 Glib::StaticMutex IO::m_meter_signal_lock = GLIBMM_STATIC_MUTEX_INIT;
80
81 /* this is a default mapper of [0 .. 1.0] control values to a gain coefficient.
82    others can be imagined. 
83 */
84
85 #if 0
86 static gain_t direct_control_to_gain (double fract) { 
87         /* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
88         /* this maxes at +6dB */
89         return pow (2.0,(sqrt(sqrt(sqrt(fract)))*198.0-192.0)/6.0);
90 }
91
92 static double direct_gain_to_control (gain_t gain) { 
93         /* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
94         if (gain == 0) return 0.0;
95         
96         return pow((6.0*log(gain)/log(2.0)+192.0)/198.0, 8.0);
97 }
98 #endif
99
100 /** @param default_type The type of port that will be created by ensure_io
101  * and friends if no type is explicitly requested (to avoid breakage).
102  */
103 IO::IO (Session& s, const string& name,
104         int input_min, int input_max, int output_min, int output_max,
105         DataType default_type, bool public_ports)
106         : SessionObject(s, name),
107           AutomatableControls (s),
108           _output_buffers (new BufferSet()),
109           _active(true),
110           _default_type (default_type),
111           _public_ports (public_ports),
112           _input_minimum (ChanCount::ZERO),
113           _input_maximum (ChanCount::INFINITE),
114           _output_minimum (ChanCount::ZERO),
115           _output_maximum (ChanCount::INFINITE)
116 {
117         _panner = new Panner (name, _session);
118         _meter = new PeakMeter (_session);
119
120         if (input_min > 0) {
121                 _input_minimum = ChanCount(_default_type, input_min);
122         }
123         if (input_max >= 0) {
124                 _input_maximum = ChanCount(_default_type, input_max);
125         }
126         if (output_min > 0) {
127                 _output_minimum = ChanCount(_default_type, output_min);
128         }
129         if (output_max >= 0) {
130                 _output_maximum = ChanCount(_default_type, output_max);
131         }
132
133         _gain = 1.0;
134         _desired_gain = 1.0;
135         pending_state_node = 0;
136         no_panner_reset = false;
137         _phase_invert = false;
138         deferred_state = 0;
139
140         boost::shared_ptr<AutomationList> gl(
141                         new AutomationList(Evoral::Parameter(GainAutomation)));
142
143         _gain_control = boost::shared_ptr<GainControl>(
144                         new GainControl(X_("gaincontrol"), *this, gl));
145
146         add_control(_gain_control);
147
148         apply_gain_automation = false;
149         
150         {
151                 // IO::Meter is emitted from another thread so the
152                 // Meter signal must be protected.
153                 Glib::Mutex::Lock guard (m_meter_signal_lock);
154                 m_meter_connection = Meter.connect (mem_fun (*this, &IO::meter));
155         }
156         
157         // Connect to our own PortCountChanged signal to connect output buffers
158         IO::PortCountChanged.connect (mem_fun (*this, &IO::attach_buffers));
159
160         _session.add_controllable (_gain_control);
161
162         create_bundles_for_inputs_and_outputs ();
163 }
164
165 IO::IO (Session& s, const XMLNode& node, DataType dt)
166         : SessionObject(s, "unnamed io"),
167           AutomatableControls (s),
168           _output_buffers (new BufferSet()),
169           _active(true),
170           _default_type (dt)
171 {
172         _meter = new PeakMeter (_session);
173         _public_ports = true; // XXX get this from node
174         _panner = 0;
175         deferred_state = 0;
176         no_panner_reset = false;
177         _desired_gain = 1.0;
178         _gain = 1.0;
179
180         apply_gain_automation = false;
181         
182         boost::shared_ptr<AutomationList> gl(
183                         new AutomationList(Evoral::Parameter(GainAutomation)));
184
185         _gain_control = boost::shared_ptr<GainControl>(
186                         new GainControl(X_("gaincontrol"), *this, gl));
187
188         add_control(_gain_control);
189
190         set_state (node);
191
192         {
193                 // IO::Meter is emitted from another thread so the
194                 // Meter signal must be protected.
195                 Glib::Mutex::Lock guard (m_meter_signal_lock);
196                 m_meter_connection = Meter.connect (mem_fun (*this, &IO::meter));
197         }
198         
199         // Connect to our own PortCountChanged signal to connect output buffers
200         IO::PortCountChanged.connect (mem_fun (*this, &IO::attach_buffers));
201
202         _session.add_controllable (_gain_control);
203
204         create_bundles_for_inputs_and_outputs ();
205 }
206
207 IO::~IO ()
208 {
209         Glib::Mutex::Lock guard (m_meter_signal_lock);
210         Glib::Mutex::Lock lm (io_lock);
211
212         BLOCK_PROCESS_CALLBACK ();
213
214         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
215                 _session.engine().unregister_port (*i);
216         }
217
218         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
219                 _session.engine().unregister_port (*i);
220         }
221
222         m_meter_connection.disconnect();
223
224         delete _meter;
225         delete _panner;
226         delete _output_buffers;
227 }
228
229 void
230 IO::silence (nframes_t nframes, nframes_t offset)
231 {
232         /* io_lock, not taken: function must be called from Session::process() calltree */
233
234         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
235                 i->get_buffer().silence (nframes, offset);
236         }
237 }
238
239 /** Deliver bufs to the IO's output ports
240  *
241  * This function should automatically do whatever it necessary to correctly deliver bufs
242  * to the outputs, eg applying gain or pan or whatever else needs to be done.
243  */
244 void
245 IO::deliver_output (BufferSet& bufs, nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset)
246 {
247         // FIXME: type specific code doesn't actually need to be here, it will go away in time
248
249         /* ********** AUDIO ********** */
250
251         // Apply gain if gain automation isn't playing
252         if ( ! apply_gain_automation) {
253                 
254                 gain_t dg = _gain; // desired gain
255
256                 {
257                         Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
258
259                         if (dm.locked()) {
260                                 dg = _desired_gain;
261                         }
262
263                 }
264
265                 if (dg != _gain || dg != 1.0)
266                         Amp::run_in_place(bufs, nframes, _gain, dg, _phase_invert);
267         }
268         
269         // Use the panner to distribute audio to output port buffers
270         if (_panner && !_panner->empty() && !_panner->bypassed()) {
271                 _panner->distribute (bufs, output_buffers(), start_frame, end_frame, nframes, offset);
272         } else {
273                 const DataType type = DataType::AUDIO;
274                 
275                 // Copy any audio 1:1 to outputs
276                 
277                 BufferSet::iterator o = output_buffers().begin(type);
278                 BufferSet::iterator i = bufs.begin(type);
279                 BufferSet::iterator prev = i;
280                 
281                 while (i != bufs.end(type) && o != output_buffers().end (type)) {
282                         o->read_from(*i, nframes, offset);
283                         prev = i;
284                         ++i;
285                         ++o;
286                 }
287
288                 /* extra outputs get a copy of the last buffer */
289
290                 while (o != output_buffers().end(type)) {
291                         o->read_from(*prev, nframes, offset);
292                         ++o;
293                 }
294         }
295
296         /* ********** MIDI ********** */
297
298         // No MIDI, we're done here
299         if (bufs.count().n_midi() == 0) {
300                 return;
301         }
302
303         const DataType type = DataType::MIDI;
304
305         // Copy any MIDI 1:1 to outputs
306         assert(bufs.count().n_midi() == output_buffers().count().n_midi());
307         BufferSet::iterator o = output_buffers().begin(type);
308         for (BufferSet::iterator i = bufs.begin(type); i != bufs.end(type); ++i, ++o) {
309                 o->read_from(*i, nframes, offset);
310         }
311 }
312
313 void
314 IO::collect_input (BufferSet& outs, nframes_t nframes, nframes_t offset)
315 {
316         assert(outs.available() >= n_inputs());
317         
318         if (n_inputs() == ChanCount::ZERO)
319                 return;
320
321         outs.set_count(n_inputs());
322         
323         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
324                 
325                 BufferSet::iterator o = outs.begin(*t);
326                 for (PortSet::iterator i = _inputs.begin(*t); i != _inputs.end(*t); ++i, ++o) {
327                         (*i).cycle_start (nframes, offset);
328                         o->read_from(i->get_buffer(), nframes, offset);
329                 }
330
331         }
332 }
333
334 void
335 IO::just_meter_input (nframes_t start_frame, nframes_t end_frame, 
336                       nframes_t nframes, nframes_t offset)
337 {
338         BufferSet& bufs = _session.get_scratch_buffers (n_inputs());
339
340         collect_input (bufs, nframes, offset);
341
342         _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
343 }
344
345
346 void
347 IO::check_bundles_connected_to_inputs ()
348 {
349         check_bundles (_bundles_connected_to_inputs, inputs());
350 }
351
352 void
353 IO::check_bundles_connected_to_outputs ()
354 {
355         check_bundles (_bundles_connected_to_outputs, outputs());
356 }
357
358 void
359 IO::check_bundles (std::vector<UserBundleInfo>& list, const PortSet& ports)
360 {
361         std::vector<UserBundleInfo> new_list;
362         
363         for (std::vector<UserBundleInfo>::iterator i = list.begin(); i != list.end(); ++i) {
364
365                 ChanCount const N = i->bundle->nchannels ();
366
367                 if (ports.num_ports (default_type()) < N.get (default_type())) {
368                         continue;
369                 }
370
371                 bool ok = true;
372                 uint32_t n = N.get (default_type());
373
374                 for (uint32_t j = 0; j < n; ++j) {
375                         /* Every port on bundle channel j must be connected to our input j */
376                         PortList const pl = i->bundle->channel_ports (j);
377                         for (uint32_t k = 0; k < pl.size(); ++k) {
378                                 if (ports.port(j)->connected_to (pl[k]) == false) {
379                                         ok = false;
380                                         break;
381                                 }
382                         }
383
384                         if (ok == false) {
385                                 break;
386                         }
387                 }
388
389                 if (ok) {
390                         new_list.push_back (*i);
391                 } else {
392                         i->configuration_will_change.disconnect ();
393                         i->configuration_has_changed.disconnect ();
394                         i->ports_will_change.disconnect ();
395                         i->ports_have_changed.disconnect ();
396                 }
397         }
398
399         list = new_list;
400 }
401
402
403 int
404 IO::disconnect_input (Port* our_port, string other_port, void* src)
405 {
406         if (other_port.length() == 0 || our_port == 0) {
407                 return 0;
408         }
409
410         { 
411                 BLOCK_PROCESS_CALLBACK ();
412                 
413                 {
414                         Glib::Mutex::Lock lm (io_lock);
415                         
416                         /* check that our_port is really one of ours */
417                         
418                         if ( ! _inputs.contains(our_port)) {
419                                 return -1;
420                         }
421                         
422                         /* disconnect it from the source */
423                         
424                         if (_session.engine().disconnect (other_port, our_port->name())) {
425                                 error << string_compose(_("IO: cannot disconnect input port %1 from %2"), our_port->name(), other_port) << endmsg;
426                                 return -1;
427                         }
428
429                         check_bundles_connected_to_inputs ();
430                 }
431         }
432
433         input_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
434         _session.set_dirty ();
435
436         return 0;
437 }
438
439 int
440 IO::connect_input (Port* our_port, string other_port, void* src)
441 {
442         if (other_port.length() == 0 || our_port == 0) {
443                 return 0;
444         }
445
446         {
447                 BLOCK_PROCESS_CALLBACK ();
448                 
449                 {
450                         Glib::Mutex::Lock lm (io_lock);
451                         
452                         /* check that our_port is really one of ours */
453                         
454                         if ( ! _inputs.contains(our_port) ) {
455                                 return -1;
456                         }
457                         
458                         /* connect it to the source */
459
460                         if (_session.engine().connect (other_port, our_port->name())) {
461                                 return -1;
462                         }
463                 }
464         }
465
466         input_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
467         _session.set_dirty ();
468         return 0;
469 }
470
471 int
472 IO::disconnect_output (Port* our_port, string other_port, void* src)
473 {
474         if (other_port.length() == 0 || our_port == 0) {
475                 return 0;
476         }
477
478         {
479                 BLOCK_PROCESS_CALLBACK ();
480                 
481                 {
482                         Glib::Mutex::Lock lm (io_lock);
483                         
484                         /* check that our_port is really one of ours */
485                         
486                         if ( ! _outputs.contains(our_port) ) {
487                                 return -1;
488                         }
489                         
490                         /* disconnect it from the destination */
491                         
492                         if (_session.engine().disconnect (our_port->name(), other_port)) {
493                                 error << string_compose(_("IO: cannot disconnect output port %1 from %2"), our_port->name(), other_port) << endmsg;
494                                 return -1;
495                         }
496
497                         check_bundles_connected_to_outputs ();
498                 }
499         }
500
501         output_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
502         _session.set_dirty ();
503         return 0;
504 }
505
506 int
507 IO::connect_output (Port* our_port, string other_port, void* src)
508 {
509         if (other_port.length() == 0 || our_port == 0) {
510                 return 0;
511         }
512
513         {
514                 BLOCK_PROCESS_CALLBACK ();
515
516                 
517                 {
518                         Glib::Mutex::Lock lm (io_lock);
519                         
520                         /* check that our_port is really one of ours */
521                         
522                         if ( ! _outputs.contains(our_port) ) {
523                                 return -1;
524                         }
525                         
526                         /* connect it to the destination */
527                         
528                         if (_session.engine().connect (our_port->name(), other_port)) {
529                                 return -1;
530                         }
531                 }
532         }
533
534         output_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
535         _session.set_dirty ();
536         return 0;
537 }
538
539 int
540 IO::set_input (Port* other_port, void* src)
541 {
542         /* this removes all but one ports, and connects that one port
543            to the specified source.
544         */
545
546         if (_input_minimum.n_total() > 1) {
547                 /* sorry, you can't do this */
548                 return -1;
549         }
550
551         if (other_port == 0) {
552                 if (_input_minimum == ChanCount::ZERO) {
553                         return ensure_inputs (ChanCount::ZERO, false, true, src);
554                 } else {
555                         return -1;
556                 }
557         }
558
559         if (ensure_inputs (ChanCount(other_port->type(), 1), true, true, src)) {
560                 return -1;
561         }
562
563         return connect_input (_inputs.port(0), other_port->name(), src);
564 }
565
566 int
567 IO::remove_output_port (Port* port, void* src)
568 {
569         IOChange change (NoChange);
570
571         {
572                 BLOCK_PROCESS_CALLBACK ();
573
574                 
575                 {
576                         Glib::Mutex::Lock lm (io_lock);
577
578                         if (n_outputs() <= _output_minimum) {
579                                 /* sorry, you can't do this */
580                                 return -1;
581                         }
582
583                         if (_outputs.remove(port)) {
584                                 change = IOChange (change|ConfigurationChanged);
585
586                                 if (port->connected()) {
587                                         change = IOChange (change|ConnectionsChanged);
588                                 } 
589
590                                 _session.engine().unregister_port (*port);
591                                 check_bundles_connected_to_outputs ();
592                                 
593                                 setup_peak_meters ();
594                                 reset_panner ();
595                         }
596                 }
597
598                 PortCountChanged (n_outputs()); /* EMIT SIGNAL */
599         }
600
601         if (change == ConnectionsChanged) {
602                 setup_bundles_for_inputs_and_outputs ();
603         }
604
605         if (change != NoChange) {
606                 output_changed (change, src);
607                 _session.set_dirty ();
608                 return 0;
609         }
610
611         return -1;
612 }
613
614 /** Add an output port.
615  *
616  * @param destination Name of input port to connect new port to.
617  * @param src Source for emitted ConfigurationChanged signal.
618  * @param type Data type of port.  Default value (NIL) will use this IO's default type.
619  */
620 int
621 IO::add_output_port (string destination, void* src, DataType type)
622 {
623         Port* our_port;
624
625         if (type == DataType::NIL)
626                 type = _default_type;
627
628         {
629                 BLOCK_PROCESS_CALLBACK ();
630
631                 
632                 { 
633                         Glib::Mutex::Lock lm (io_lock);
634                         
635                         if (n_outputs() >= _output_maximum) {
636                                 return -1;
637                         }
638                 
639                         /* Create a new output port */
640                         
641                         string portname = build_legal_port_name (type, false);
642                         
643                         if ((our_port = _session.engine().register_output_port (type, portname, _public_ports)) == 0) {
644                                 error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
645                                 return -1;
646                         }
647                         
648                         _outputs.add (our_port);
649                         setup_peak_meters ();
650                         reset_panner ();
651                 }
652
653                 PortCountChanged (n_outputs()); /* EMIT SIGNAL */
654         }
655
656         if (destination.length()) {
657                 if (_session.engine().connect (our_port->name(), destination)) {
658                         return -1;
659                 }
660         }
661         
662         // pan_changed (src); /* EMIT SIGNAL */
663         output_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
664         setup_bundles_for_inputs_and_outputs ();
665         _session.set_dirty ();
666
667         return 0;
668 }
669
670 int
671 IO::remove_input_port (Port* port, void* src)
672 {
673         IOChange change (NoChange);
674
675         {
676                 BLOCK_PROCESS_CALLBACK ();
677
678                 
679                 {
680                         Glib::Mutex::Lock lm (io_lock);
681
682                         if (n_inputs() <= _input_minimum) {
683                                 /* sorry, you can't do this */
684                                 return -1;
685                         }
686
687                         if (_inputs.remove(port)) {
688                                 change = IOChange (change|ConfigurationChanged);
689
690                                 if (port->connected()) {
691                                         change = IOChange (change|ConnectionsChanged);
692                                 } 
693
694                                 _session.engine().unregister_port (*port);
695                                 check_bundles_connected_to_inputs ();
696                                 
697                                 setup_peak_meters ();
698                                 reset_panner ();
699                         }
700                 }
701                 
702                 PortCountChanged (n_inputs ()); /* EMIT SIGNAL */
703         }
704
705         if (change == ConfigurationChanged) {
706                 setup_bundles_for_inputs_and_outputs ();
707         }
708
709         if (change != NoChange) {
710                 input_changed (change, src);
711                 _session.set_dirty ();
712                 return 0;
713         } 
714         
715         return -1;
716 }
717
718
719 /** Add an input port.
720  *
721  * @param type Data type of port.  The appropriate port type, and @ref Port will be created.
722  * @param destination Name of input port to connect new port to.
723  * @param src Source for emitted ConfigurationChanged signal.
724  */
725 int
726 IO::add_input_port (string source, void* src, DataType type)
727 {
728         Port* our_port;
729         
730         if (type == DataType::NIL)
731                 type = _default_type;
732
733         {
734                 BLOCK_PROCESS_CALLBACK ();
735                 
736                 { 
737                         Glib::Mutex::Lock lm (io_lock);
738
739                         if (_input_maximum.get(type) >= 0 && n_inputs().get (type) >= _input_maximum.get (type)) {
740                                 return -1;
741                         }
742
743                         /* Create a new input port */
744                         
745                         string portname = build_legal_port_name (type, true);
746
747                         if ((our_port = _session.engine().register_input_port (type, portname, _public_ports)) == 0) {
748                                 error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
749                                 return -1;
750                         }
751
752                         _inputs.add (our_port);
753                         setup_peak_meters ();
754                         reset_panner ();
755                 }
756
757                 PortCountChanged (n_inputs()); /* EMIT SIGNAL */
758         }
759
760         if (source.length()) {
761
762                 if (_session.engine().connect (source, our_port->name())) {
763                         return -1;
764                 }
765         } 
766
767         // pan_changed (src); /* EMIT SIGNAL */
768         input_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
769         setup_bundles_for_inputs_and_outputs ();
770         _session.set_dirty ();
771         
772         return 0;
773 }
774
775 int
776 IO::disconnect_inputs (void* src)
777 {
778         { 
779                 BLOCK_PROCESS_CALLBACK ();
780                 
781                 {
782                         Glib::Mutex::Lock lm (io_lock);
783                         
784                         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
785                                 _session.engine().disconnect (*i);
786                         }
787
788                         check_bundles_connected_to_inputs ();
789                 }
790         }
791         
792         input_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
793         
794         return 0;
795 }
796
797 int
798 IO::disconnect_outputs (void* src)
799 {
800         {
801                 BLOCK_PROCESS_CALLBACK ();
802                 
803                 {
804                         Glib::Mutex::Lock lm (io_lock);
805                         
806                         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
807                                 _session.engine().disconnect (*i);
808                         }
809
810                         check_bundles_connected_to_outputs ();
811                 }
812         }
813
814         output_changed (ConnectionsChanged, src); /* EMIT SIGNAL */
815         _session.set_dirty ();
816         
817         return 0;
818 }
819
820 bool
821 IO::ensure_inputs_locked (ChanCount count, bool clear, void* src)
822 {
823         Port* input_port = 0;
824         bool  changed    = false;
825
826
827         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
828                 
829                 const size_t n = count.get(*t);
830         
831                 /* remove unused ports */
832                 for (size_t i = n_inputs().get(*t); i > n; --i) {
833                         input_port = _inputs.port(*t, i-1);
834
835                         assert(input_port);
836                         _inputs.remove(input_port);
837                         _session.engine().unregister_port (*input_port);
838
839                         changed = true;
840                 }
841
842                 /* create any necessary new ports */
843                 while (n_inputs().get(*t) < n) {
844
845                         string portname = build_legal_port_name (*t, true);
846
847                         try {
848
849                                 if ((input_port = _session.engine().register_input_port (*t, portname, _public_ports)) == 0) {
850                                         error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
851                                         return -1;
852                                 }
853                         }
854
855                         catch (AudioEngine::PortRegistrationFailure& err) {
856                                 setup_peak_meters ();
857                                 reset_panner ();
858                                 /* pass it on */
859                                 throw AudioEngine::PortRegistrationFailure();
860                         }
861
862                         _inputs.add (input_port);
863                         changed = true;
864                 }
865         }
866         
867         if (changed) {
868                 check_bundles_connected_to_inputs ();
869                 setup_peak_meters ();
870                 reset_panner ();
871                 PortCountChanged (n_inputs()); /* EMIT SIGNAL */
872                 _session.set_dirty ();
873         }
874         
875         if (clear) {
876                 /* disconnect all existing ports so that we get a fresh start */
877                 for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
878                         _session.engine().disconnect (*i);
879                 }
880         }
881
882         return changed;
883 }
884
885 /** Attach output_buffers to port buffers.
886  * 
887  * Connected to IO's own PortCountChanged signal.
888  */
889 void
890 IO::attach_buffers(ChanCount ignored)
891 {
892         _output_buffers->attach_buffers(_outputs);
893 }
894
895 int
896 IO::ensure_io (ChanCount in, ChanCount out, bool clear, void* src)
897 {
898         bool in_changed     = false;
899         bool out_changed    = false;
900         bool need_pan_reset = false;
901
902         in = min (_input_maximum, in);
903
904         out = min (_output_maximum, out);
905
906         if (in == n_inputs() && out == n_outputs() && !clear) {
907                 return 0;
908         }
909
910         {
911                 BLOCK_PROCESS_CALLBACK ();
912                 Glib::Mutex::Lock lm (io_lock);
913
914                 Port* port;
915                 
916                 if (n_outputs() != out) {
917                         need_pan_reset = true;
918                 }
919                 
920                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
921
922                         const size_t nin = in.get(*t);
923                         const size_t nout = out.get(*t);
924
925                         Port* output_port = 0;
926                         Port* input_port = 0;
927
928                         /* remove unused output ports */
929                         for (size_t i = n_outputs().get(*t); i > nout; --i) {
930                                 output_port = _outputs.port(*t, i-1);
931
932                                 assert(output_port);
933                                 _outputs.remove(output_port);
934                                 _session.engine().unregister_port (*output_port);
935
936                                 out_changed = true;
937                         }
938
939                         /* remove unused input ports */
940                         for (size_t i = n_inputs().get(*t); i > nin; --i) {
941                                 input_port = _inputs.port(*t, i-1);
942
943                                 assert(input_port);
944                                 _inputs.remove(input_port);
945                                 _session.engine().unregister_port (*input_port);
946
947                                 in_changed = true;
948                         }
949
950                         /* create any necessary new input ports */
951
952                         while (n_inputs().get(*t) < nin) {
953
954                                 string portname = build_legal_port_name (*t, true);
955
956                                 try {
957                                         if ((port = _session.engine().register_input_port (*t, portname, _public_ports)) == 0) {
958                                                 error << string_compose(_("IO: cannot register input port %1"), portname) << endmsg;
959                                                 return -1;
960                                         }
961                                 }
962                                 
963                                 catch (AudioEngine::PortRegistrationFailure& err) {
964                                         setup_peak_meters ();
965                                         reset_panner ();
966                                         /* pass it on */
967                                         throw AudioEngine::PortRegistrationFailure();
968                                 }
969
970                                 _inputs.add (port);
971                                 in_changed = true;
972                         }
973
974                         /* create any necessary new output ports */
975
976                         while (n_outputs().get(*t) < nout) {
977
978                                 string portname = build_legal_port_name (*t, false);
979                                 
980                                 try { 
981                                         if ((port = _session.engine().register_output_port (*t, portname, _public_ports)) == 0) {
982                                                 error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
983                                                 return -1;
984                                         }
985                                 }
986
987                                 catch (AudioEngine::PortRegistrationFailure& err) {
988                                         setup_peak_meters ();
989                                         reset_panner ();
990                                         /* pass it on */
991                                         throw AudioEngine::PortRegistrationFailure ();
992                                 }
993
994                                 _outputs.add (port);
995                                 out_changed = true;
996                         }
997                 }
998                 
999                 if (clear) {
1000                         
1001                         /* disconnect all existing ports so that we get a fresh start */
1002                         
1003                         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
1004                                 _session.engine().disconnect (*i);
1005                         }
1006                         
1007                         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
1008                                 _session.engine().disconnect (*i);
1009                         }
1010                 }
1011                 
1012                 if (in_changed || out_changed) {
1013                         setup_peak_meters ();
1014                         reset_panner ();
1015                 }
1016         }
1017
1018         if (out_changed) {
1019                 check_bundles_connected_to_outputs ();
1020                 output_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
1021         }
1022         
1023         if (in_changed) {
1024                 check_bundles_connected_to_inputs ();
1025                 input_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
1026         }
1027
1028         if (in_changed || out_changed) {
1029                 PortCountChanged (max (n_outputs(), n_inputs())); /* EMIT SIGNAL */
1030                 setup_bundles_for_inputs_and_outputs ();
1031                 _session.set_dirty ();
1032         }
1033
1034         return 0;
1035 }
1036
1037 int
1038 IO::ensure_inputs (ChanCount count, bool clear, bool lockit, void* src)
1039 {
1040         bool changed = false;
1041
1042         count = min (_input_maximum, count);
1043
1044         if (count == n_inputs() && !clear) {
1045                 return 0;
1046         }
1047
1048         if (lockit) {
1049                 BLOCK_PROCESS_CALLBACK ();
1050                 Glib::Mutex::Lock im (io_lock);
1051                 changed = ensure_inputs_locked (count, clear, src);
1052         } else {
1053                 changed = ensure_inputs_locked (count, clear, src);
1054         }
1055
1056         if (changed) {
1057                 input_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
1058                 setup_bundles_for_inputs_and_outputs ();
1059                 _session.set_dirty ();
1060         }
1061         return 0;
1062 }
1063
1064 bool
1065 IO::ensure_outputs_locked (ChanCount count, bool clear, void* src)
1066 {
1067         Port* output_port    = 0;
1068         bool  changed        = false;
1069         bool  need_pan_reset = false;
1070
1071         if (n_outputs() != count) {
1072                 need_pan_reset = true;
1073         }
1074         
1075         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1076
1077                 const size_t n = count.get(*t);
1078
1079                 /* remove unused ports */
1080                 for (size_t i = n_outputs().get(*t); i > n; --i) {
1081                         output_port = _outputs.port(*t, i-1);
1082
1083                         assert(output_port);
1084                         _outputs.remove(output_port);
1085                         _session.engine().unregister_port (*output_port);
1086
1087                         changed = true;
1088                 }
1089
1090                 /* create any necessary new ports */
1091                 while (n_outputs().get(*t) < n) {
1092
1093                         string portname = build_legal_port_name (*t, false);
1094
1095                         if ((output_port = _session.engine().register_output_port (*t, portname, _public_ports)) == 0) {
1096                                 error << string_compose(_("IO: cannot register output port %1"), portname) << endmsg;
1097                                 return -1;
1098                         }
1099
1100                         _outputs.add (output_port);
1101                         changed = true;
1102                         setup_peak_meters ();
1103
1104                         if (need_pan_reset) {
1105                                 reset_panner ();
1106                         }
1107                 }
1108         }
1109         
1110         if (changed) {
1111                 check_bundles_connected_to_outputs ();
1112                 PortCountChanged (n_outputs()); /* EMIT SIGNAL */
1113                 _session.set_dirty ();
1114         }
1115         
1116         if (clear) {
1117                 /* disconnect all existing ports so that we get a fresh start */
1118                 for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
1119                         _session.engine().disconnect (*i);
1120                 }
1121         }
1122
1123         return changed;
1124 }
1125
1126 int
1127 IO::ensure_outputs (ChanCount count, bool clear, bool lockit, void* src)
1128 {
1129         bool changed = false;
1130
1131         if (_output_maximum < ChanCount::INFINITE) {
1132                 count = min (_output_maximum, count);
1133                 if (count == n_outputs() && !clear) {
1134                         return 0;
1135                 }
1136         }
1137
1138         /* XXX caller should hold io_lock, but generally doesn't */
1139
1140         if (lockit) {
1141                 BLOCK_PROCESS_CALLBACK ();
1142                 Glib::Mutex::Lock im (io_lock);
1143                 changed = ensure_outputs_locked (count, clear, src);
1144         } else {
1145                 changed = ensure_outputs_locked (count, clear, src);
1146         }
1147
1148         if (changed) {
1149                  output_changed (ConfigurationChanged, src); /* EMIT SIGNAL */
1150                  setup_bundles_for_inputs_and_outputs ();
1151         }
1152
1153         return 0;
1154 }
1155
1156 gain_t
1157 IO::effective_gain () const
1158 {
1159         if (_gain_control->automation_playback()) {
1160                 return _gain_control->get_value();
1161         } else {
1162                 return _desired_gain;
1163         }
1164 }
1165
1166 void
1167 IO::reset_panner ()
1168 {
1169         if (panners_legal) {
1170                 if (!no_panner_reset) {
1171                         _panner->reset (n_outputs().n_audio(), pans_required());
1172                 }
1173         } else {
1174                 panner_legal_c.disconnect ();
1175                 panner_legal_c = PannersLegal.connect (mem_fun (*this, &IO::panners_became_legal));
1176         }
1177 }
1178
1179 int
1180 IO::panners_became_legal ()
1181 {
1182         _panner->reset (n_outputs().n_audio(), pans_required());
1183         _panner->load (); // automation
1184         panner_legal_c.disconnect ();
1185         return 0;
1186 }
1187
1188 void
1189 IO::defer_pan_reset ()
1190 {
1191         no_panner_reset = true;
1192 }
1193
1194 void
1195 IO::allow_pan_reset ()
1196 {
1197         no_panner_reset = false;
1198         reset_panner ();
1199 }
1200
1201
1202 XMLNode&
1203 IO::get_state (void)
1204 {
1205         return state (true);
1206 }
1207
1208 XMLNode&
1209 IO::state (bool full_state)
1210 {
1211         XMLNode* node = new XMLNode (state_node_name);
1212         char buf[64];
1213         string str;
1214         vector<string>::iterator ci;
1215         int n;
1216         LocaleGuard lg (X_("POSIX"));
1217         Glib::Mutex::Lock lm (io_lock);
1218
1219         node->add_property("name", _name);
1220         id().print (buf, sizeof (buf));
1221         node->add_property("id", buf);
1222
1223         for (
1224           std::vector<UserBundleInfo>::iterator i = _bundles_connected_to_inputs.begin();
1225           i != _bundles_connected_to_inputs.end();
1226           ++i
1227           )
1228         {
1229                 XMLNode* n = new XMLNode ("InputBundle");
1230                 n->add_property ("name", i->bundle->name ());
1231                 node->add_child_nocopy (*n);
1232         }
1233
1234         for (
1235           std::vector<UserBundleInfo>::iterator i = _bundles_connected_to_outputs.begin();
1236           i != _bundles_connected_to_outputs.end();
1237           ++i
1238           )
1239         {
1240                 XMLNode* n = new XMLNode ("OutputBundle");
1241                 n->add_property ("name", i->bundle->name ());
1242                 node->add_child_nocopy (*n);
1243         }
1244         
1245         str = "";
1246
1247         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
1248                         
1249                 vector<string> connections;
1250
1251                 if (i->get_connections (connections)) {
1252
1253                         str += '{';
1254                         
1255                         for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
1256                                 if (n) {
1257                                         str += ',';
1258                                 }
1259                                 
1260                                 /* if its a connection to our own port,
1261                                    return only the port name, not the
1262                                    whole thing. this allows connections
1263                                    to be re-established even when our
1264                                    client name is different.
1265                                 */
1266                                 
1267                                 str += _session.engine().make_port_name_relative (*ci);
1268                         }       
1269                         
1270                         str += '}';
1271
1272                 } else {
1273                         str += "{}";
1274                 }
1275         }
1276         
1277         node->add_property ("inputs", str);
1278
1279         str = "";
1280         
1281         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
1282                 
1283                 vector<string> connections;
1284
1285                 if (i->get_connections (connections)) {
1286                         
1287                         str += '{';
1288                         
1289                         for (n = 0, ci = connections.begin(); ci != connections.end(); ++ci, ++n) {
1290                                 if (n) {
1291                                         str += ',';
1292                                 }
1293                                 
1294                                 str += _session.engine().make_port_name_relative (*ci);
1295                         }
1296                         
1297                         str += '}';
1298
1299                 } else {
1300                         str += "{}";
1301                 }
1302         }
1303         
1304         node->add_property ("outputs", str);
1305
1306         node->add_child_nocopy (_panner->state (full_state));
1307         node->add_child_nocopy (_gain_control->get_state ());
1308
1309         snprintf (buf, sizeof(buf), "%2.12f", gain());
1310         node->add_property ("gain", buf);
1311
1312         /* To make backwards compatibility a bit easier, write ChanCount::INFINITE to the session file
1313            as -1.
1314         */
1315
1316         int const in_max = _input_maximum == ChanCount::INFINITE ? -1 : _input_maximum.get(_default_type);
1317         int const out_max = _output_maximum == ChanCount::INFINITE ? -1 : _output_maximum.get(_default_type);
1318
1319         snprintf (buf, sizeof(buf)-1, "%d,%d,%d,%d", _input_minimum.get(_default_type), in_max, _output_minimum.get(_default_type), out_max);
1320
1321         node->add_property ("iolimits", buf);
1322
1323         /* automation */
1324         
1325         if (full_state)
1326                 node->add_child_nocopy (get_automation_state());
1327
1328         return *node;
1329 }
1330
1331 int
1332 IO::set_state (const XMLNode& node)
1333 {
1334         const XMLProperty* prop;
1335         XMLNodeConstIterator iter;
1336         LocaleGuard lg (X_("POSIX"));
1337
1338         /* force use of non-localized representation of decimal point,
1339            since we use it a lot in XML files and so forth.
1340         */
1341
1342         if (node.name() != state_node_name) {
1343                 error << string_compose(_("incorrect XML node \"%1\" passed to IO object"), node.name()) << endmsg;
1344                 return -1;
1345         }
1346
1347         if ((prop = node.property ("name")) != 0) {
1348                 _name = prop->value();
1349                 /* used to set panner name with this, but no more */
1350         } 
1351
1352         if ((prop = node.property ("id")) != 0) {
1353                 _id = prop->value ();
1354         }
1355
1356         int in_min = -1;
1357         int in_max = -1;
1358         int out_min = -1;
1359         int out_max = -1;
1360
1361         if ((prop = node.property ("iolimits")) != 0) {
1362                 sscanf (prop->value().c_str(), "%d,%d,%d,%d",
1363                         &in_min, &in_max, &out_min, &out_max);
1364
1365                 /* Correct for the difference between the way we write things to session files and the
1366                    way things are described by ChanCount; see comments in io.h about what the different
1367                    ChanCount values mean. */
1368
1369                 if (in_min < 0) {
1370                         _input_minimum = ChanCount::ZERO;
1371                 } else {
1372                         _input_minimum = ChanCount (_default_type, in_min);
1373                 }
1374
1375                 if (in_max < 0) {
1376                         _input_maximum = ChanCount::INFINITE;
1377                 } else {
1378                         _input_maximum = ChanCount (_default_type, in_max);
1379                 }
1380
1381                 if (out_min < 0) {
1382                         _output_minimum = ChanCount::ZERO;
1383                 } else {
1384                         _output_minimum = ChanCount (_default_type, out_min);
1385                 }
1386                 
1387                 if (out_max < 0) {
1388                         _output_maximum = ChanCount::INFINITE;
1389                 } else {
1390                         _output_maximum = ChanCount (_default_type, out_max);
1391                 }
1392         }
1393         
1394         if ((prop = node.property ("gain")) != 0) {
1395                 set_gain (atof (prop->value().c_str()), this);
1396                 _gain = _desired_gain;
1397         }
1398
1399         if ((prop = node.property ("automation-state")) != 0 || (prop = node.property ("automation-style")) != 0) {
1400                 /* old school automation handling */
1401         }
1402
1403         for (iter = node.children().begin(); iter != node.children().end(); ++iter) {
1404
1405                 if ((*iter)->name() == "Panner") {
1406                         if (_panner == 0) {
1407                                 _panner = new Panner (_name, _session);
1408                         }
1409                         _panner->set_state (**iter);
1410                 }
1411
1412                 if ((*iter)->name() == X_("Automation")) {
1413
1414                         set_automation_state (*(*iter), Evoral::Parameter(GainAutomation));
1415                 }
1416
1417                 if ((*iter)->name() == X_("controllable")) {
1418                         if ((prop = (*iter)->property("name")) != 0 && prop->value() == "gaincontrol") {
1419                                 _gain_control->set_state (**iter);
1420                         }
1421                 }
1422         }
1423
1424         if (ports_legal) {
1425
1426                 if (create_ports (node)) {
1427                         return -1;
1428                 }
1429
1430         } else {
1431
1432                 port_legal_c = PortsLegal.connect (mem_fun (*this, &IO::ports_became_legal));
1433         }
1434
1435         if (panners_legal) {
1436                 reset_panner ();
1437         } else {
1438                 panner_legal_c = PannersLegal.connect (mem_fun (*this, &IO::panners_became_legal));
1439         }
1440
1441         if (connecting_legal) {
1442
1443                 if (make_connections (node)) {
1444                         return -1;
1445                 }
1446
1447         } else {
1448                 
1449                 connection_legal_c = ConnectingLegal.connect (mem_fun (*this, &IO::connecting_became_legal));
1450         }
1451
1452         if (!ports_legal || !connecting_legal) {
1453                 pending_state_node = new XMLNode (node);
1454         }
1455
1456         return 0;
1457 }
1458
1459 int
1460 IO::load_automation (string path)
1461 {
1462         string fullpath;
1463         ifstream in;
1464         char line[128];
1465         uint32_t linecnt = 0;
1466         float version;
1467         LocaleGuard lg (X_("POSIX"));
1468
1469         fullpath = Glib::build_filename(_session.automation_dir(), path);
1470
1471         in.open (fullpath.c_str());
1472
1473         if (!in) {
1474                 fullpath = Glib::build_filename(_session.automation_dir(), _session.snap_name() + '-' + path);
1475
1476                 in.open (fullpath.c_str());
1477
1478                 if (!in) {
1479                         error << string_compose(_("%1: cannot open automation event file \"%2\""), _name, fullpath) << endmsg;
1480                         return -1;
1481                 }
1482         }
1483
1484         clear_automation ();
1485
1486         while (in.getline (line, sizeof(line), '\n')) {
1487                 char type;
1488                 nframes_t when;
1489                 double value;
1490
1491                 if (++linecnt == 1) {
1492                         if (memcmp (line, "version", 7) == 0) {
1493                                 if (sscanf (line, "version %f", &version) != 1) {
1494                                         error << string_compose(_("badly formed version number in automation event file \"%1\""), path) << endmsg;
1495                                         return -1;
1496                                 }
1497                         } else {
1498                                 error << string_compose(_("no version information in automation event file \"%1\""), path) << endmsg;
1499                                 return -1;
1500                         }
1501
1502                         continue;
1503                 }
1504
1505                 if (sscanf (line, "%c %" PRIu32 " %lf", &type, &when, &value) != 3) {
1506                         warning << string_compose(_("badly formatted automation event record at line %1 of %2 (ignored)"), linecnt, path) << endmsg;
1507                         continue;
1508                 }
1509
1510                 switch (type) {
1511                 case 'g':
1512                         _gain_control->list()->fast_simple_add (when, value);
1513                         break;
1514
1515                 case 's':
1516                         break;
1517
1518                 case 'm':
1519                         break;
1520
1521                 case 'p':
1522                         /* older (pre-1.0) versions of ardour used this */
1523                         break;
1524
1525                 default:
1526                         warning << _("dubious automation event found (and ignored)") << endmsg;
1527                 }
1528         }
1529
1530         return 0;
1531 }
1532
1533 int
1534 IO::connecting_became_legal ()
1535 {
1536         int ret;
1537
1538         if (pending_state_node == 0) {
1539                 fatal << _("IO::connecting_became_legal() called without a pending state node") << endmsg;
1540                 /*NOTREACHED*/
1541                 return -1;
1542         }
1543
1544         connection_legal_c.disconnect ();
1545
1546         ret = make_connections (*pending_state_node);
1547
1548         if (ports_legal) {
1549                 delete pending_state_node;
1550                 pending_state_node = 0;
1551         }
1552
1553         return ret;
1554 }
1555 int
1556 IO::ports_became_legal ()
1557 {
1558         int ret;
1559
1560         if (pending_state_node == 0) {
1561                 fatal << _("IO::ports_became_legal() called without a pending state node") << endmsg;
1562                 /*NOTREACHED*/
1563                 return -1;
1564         }
1565
1566         port_legal_c.disconnect ();
1567
1568         ret = create_ports (*pending_state_node);
1569
1570         if (connecting_legal) {
1571                 delete pending_state_node;
1572                 pending_state_node = 0;
1573         }
1574
1575         return ret;
1576 }
1577
1578 boost::shared_ptr<Bundle>
1579 IO::find_possible_bundle (const string &desired_name, const string &default_name, const string &bundle_type_name) 
1580 {
1581         static const string digits = "0123456789";
1582
1583         boost::shared_ptr<Bundle> c = _session.bundle_by_name (desired_name);
1584
1585         if (!c) {
1586                 int bundle_number, mask;
1587                 string possible_name;
1588                 bool stereo = false;
1589                 string::size_type last_non_digit_pos;
1590
1591                 error << string_compose(_("Unknown bundle \"%1\" listed for %2 of %3"), desired_name, bundle_type_name, _name)
1592                       << endmsg;
1593
1594                 // find numeric suffix of desired name
1595                 bundle_number = 0;
1596                 
1597                 last_non_digit_pos = desired_name.find_last_not_of(digits);
1598
1599                 if (last_non_digit_pos != string::npos) {
1600                         stringstream s;
1601                         s << desired_name.substr(last_non_digit_pos);
1602                         s >> bundle_number;
1603                 }
1604         
1605                 // see if it's a stereo connection e.g. "in 3+4"
1606
1607                 if (last_non_digit_pos > 1 && desired_name[last_non_digit_pos] == '+') {
1608                         int left_bundle_number = 0;
1609                         string::size_type left_last_non_digit_pos;
1610
1611                         left_last_non_digit_pos = desired_name.find_last_not_of(digits, last_non_digit_pos-1);
1612
1613                         if (left_last_non_digit_pos != string::npos) {
1614                                 stringstream s;
1615                                 s << desired_name.substr(left_last_non_digit_pos, last_non_digit_pos-1);
1616                                 s >> left_bundle_number;
1617
1618                                 if (left_bundle_number > 0 && left_bundle_number + 1 == bundle_number) {
1619                                         bundle_number--;
1620                                         stereo = true;
1621                                 }
1622                         }
1623                 }
1624
1625                 // make 0-based
1626                 if (bundle_number)
1627                         bundle_number--;
1628
1629                 // find highest set bit
1630                 mask = 1;
1631                 while ((mask <= bundle_number) && (mask <<= 1));
1632                 
1633                 // "wrap" bundle number into largest possible power of 2 
1634                 // that works...
1635
1636                 while (mask) {
1637
1638                         if (bundle_number & mask) {
1639                                 bundle_number &= ~mask;
1640                                 
1641                                 stringstream s;
1642                                 s << default_name << " " << bundle_number + 1;
1643
1644                                 if (stereo) {
1645                                         s << "+" << bundle_number + 2;
1646                                 }
1647                                 
1648                                 possible_name = s.str();
1649
1650                                 if ((c = _session.bundle_by_name (possible_name)) != 0) {
1651                                         break;
1652                                 }
1653                         }
1654                         mask >>= 1;
1655                 }
1656                 if (c) {
1657                         info << string_compose (_("Bundle %1 was not available - \"%2\" used instead"), desired_name, possible_name)
1658                              << endmsg;
1659                 } else {
1660                         error << string_compose(_("No %1 bundles available as a replacement"), bundle_type_name)
1661                               << endmsg;
1662                 }
1663
1664         }
1665
1666         return c;
1667
1668 }
1669
1670 int
1671 IO::create_ports (const XMLNode& node)
1672 {
1673         XMLProperty const * prop;
1674         ChanCount num_inputs;
1675         ChanCount num_outputs;
1676
1677         if ((prop = node.property ("input-connection")) != 0) {
1678
1679                 boost::shared_ptr<Bundle> c = find_possible_bundle (prop->value(), _("in"), _("input"));
1680                 
1681                 if (!c) {
1682                         return -1;
1683                 } 
1684
1685                 num_inputs = c->nchannels();
1686
1687         } else if ((prop = node.property ("inputs")) != 0) {
1688
1689                 num_inputs.set (default_type(), count (prop->value().begin(), prop->value().end(), '{'));
1690         }
1691         
1692         if ((prop = node.property ("output-connection")) != 0) {
1693
1694                 boost::shared_ptr<Bundle> c = find_possible_bundle(prop->value(), _("out"), _("output"));
1695
1696                 if (!c) {
1697                         return -1;
1698                 } 
1699
1700                 num_outputs = c->nchannels ();
1701                 
1702         } else if ((prop = node.property ("outputs")) != 0) {
1703
1704                 num_outputs.set (default_type(), count (prop->value().begin(), prop->value().end(), '{'));
1705         }
1706
1707         no_panner_reset = true;
1708
1709         if (ensure_io (num_inputs, num_outputs, true, this)) {
1710                 error << string_compose(_("%1: cannot create I/O ports"), _name) << endmsg;
1711                 return -1;
1712         }
1713
1714         no_panner_reset = false;
1715
1716         set_deferred_state ();
1717
1718         PortsCreated();
1719         return 0;
1720 }
1721
1722
1723 int
1724 IO::make_connections (const XMLNode& node)
1725 {
1726
1727         const XMLProperty* prop;
1728
1729         if ((prop = node.property ("input-connection")) != 0) {
1730                 boost::shared_ptr<Bundle> c = find_possible_bundle (prop->value(), _("in"), _("input"));
1731                 
1732                 if (!c) {
1733                         return -1;
1734                 } 
1735
1736                 connect_input_ports_to_bundle (c, this);
1737
1738         } else if ((prop = node.property ("inputs")) != 0) {
1739                 if (set_inputs (prop->value())) {
1740                         error << string_compose(_("improper input channel list in XML node (%1)"), prop->value()) << endmsg;
1741                         return -1;
1742                 }
1743         }
1744
1745         if ((prop = node.property ("output-connection")) != 0) {
1746                 boost::shared_ptr<Bundle> c = find_possible_bundle (prop->value(), _("out"), _("output"));
1747                 
1748                 if (!c) {
1749                         return -1;
1750                 } 
1751                 
1752                 connect_output_ports_to_bundle (c, this);
1753                 
1754         } else if ((prop = node.property ("outputs")) != 0) {
1755                 if (set_outputs (prop->value())) {
1756                         error << string_compose(_("improper output channel list in XML node (%1)"), prop->value()) << endmsg;
1757                         return -1;
1758                 }
1759         }
1760
1761         for (XMLNodeConstIterator i = node.children().begin(); i != node.children().end(); ++i) {
1762
1763                 if ((*i)->name() == "InputBundle") {
1764                         XMLProperty const * prop = (*i)->property ("name");
1765                         if (prop) {
1766                                 boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value(), _("in"), _("input"));
1767                                 if (b) {
1768                                         connect_input_ports_to_bundle (b, this);
1769                                 }
1770                         }
1771                         
1772                 } else if ((*i)->name() == "OutputBundle") {
1773                         XMLProperty const * prop = (*i)->property ("name");
1774                         if (prop) {
1775                                 boost::shared_ptr<Bundle> b = find_possible_bundle (prop->value(), _("out"), _("output"));
1776                                 if (b) {
1777                                         connect_output_ports_to_bundle (b, this);
1778                                 } 
1779                         }
1780                 }
1781         }
1782         
1783         return 0;
1784 }
1785
1786 int
1787 IO::set_inputs (const string& str)
1788 {
1789         vector<string> ports;
1790         int i;
1791         int n;
1792         uint32_t nports;
1793         
1794         if ((nports = count (str.begin(), str.end(), '{')) == 0) {
1795                 return 0;
1796         }
1797
1798         // FIXME: audio-only
1799         if (ensure_inputs (ChanCount(DataType::AUDIO, nports), true, true, this)) {
1800                 return -1;
1801         }
1802
1803         string::size_type start, end, ostart;
1804
1805         ostart = 0;
1806         start = 0;
1807         end = 0;
1808         i = 0;
1809
1810         while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1811                 start += 1;
1812
1813                 if ((end = str.find_first_of ('}', start)) == string::npos) {
1814                         error << string_compose(_("IO: badly formed string in XML node for inputs \"%1\""), str) << endmsg;
1815                         return -1;
1816                 }
1817
1818                 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1819                         error << string_compose(_("bad input string in XML node \"%1\""), str) << endmsg;
1820
1821                         return -1;
1822                         
1823                 } else if (n > 0) {
1824
1825                         for (int x = 0; x < n; ++x) {
1826                                 connect_input (input (i), ports[x], this);
1827                         }
1828                 }
1829
1830                 ostart = end+1;
1831                 i++;
1832         }
1833
1834         return 0;
1835 }
1836
1837 int
1838 IO::set_outputs (const string& str)
1839 {
1840         vector<string> ports;
1841         int i;
1842         int n;
1843         uint32_t nports;
1844         
1845         if ((nports = count (str.begin(), str.end(), '{')) == 0) {
1846                 return 0;
1847         }
1848
1849         // FIXME: audio-only
1850         if (ensure_outputs (ChanCount(DataType::AUDIO, nports), true, true, this)) {
1851                 return -1;
1852         }
1853
1854         string::size_type start, end, ostart;
1855
1856         ostart = 0;
1857         start = 0;
1858         end = 0;
1859         i = 0;
1860
1861         while ((start = str.find_first_of ('{', ostart)) != string::npos) {
1862                 start += 1;
1863
1864                 if ((end = str.find_first_of ('}', start)) == string::npos) {
1865                         error << string_compose(_("IO: badly formed string in XML node for outputs \"%1\""), str) << endmsg;
1866                         return -1;
1867                 }
1868
1869                 if ((n = parse_io_string (str.substr (start, end - start), ports)) < 0) {
1870                         error << string_compose(_("IO: bad output string in XML node \"%1\""), str) << endmsg;
1871
1872                         return -1;
1873                         
1874                 } else if (n > 0) {
1875
1876                         for (int x = 0; x < n; ++x) {
1877                                 connect_output (output (i), ports[x], this);
1878                         }
1879                 }
1880
1881                 ostart = end+1;
1882                 i++;
1883         }
1884
1885         return 0;
1886 }
1887
1888 int
1889 IO::parse_io_string (const string& str, vector<string>& ports)
1890 {
1891         string::size_type pos, opos;
1892
1893         if (str.length() == 0) {
1894                 return 0;
1895         }
1896
1897         pos = 0;
1898         opos = 0;
1899
1900         ports.clear ();
1901
1902         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1903                 ports.push_back (str.substr (opos, pos - opos));
1904                 opos = pos + 1;
1905         }
1906         
1907         if (opos < str.length()) {
1908                 ports.push_back (str.substr(opos));
1909         }
1910
1911         return ports.size();
1912 }
1913
1914 int
1915 IO::parse_gain_string (const string& str, vector<string>& ports)
1916 {
1917         string::size_type pos, opos;
1918
1919         pos = 0;
1920         opos = 0;
1921         ports.clear ();
1922
1923         while ((pos = str.find_first_of (',', opos)) != string::npos) {
1924                 ports.push_back (str.substr (opos, pos - opos));
1925                 opos = pos + 1;
1926         }
1927         
1928         if (opos < str.length()) {
1929                 ports.push_back (str.substr(opos));
1930         }
1931
1932         return ports.size();
1933 }
1934
1935 bool
1936 IO::set_name (const string& requested_name)
1937 {
1938         if (requested_name == _name) {
1939                 return true;
1940         }
1941         
1942         string name;
1943         Route *rt;
1944         if ( (rt = dynamic_cast<Route *>(this))) {
1945                 name = Route::ensure_track_or_route_name(requested_name, _session);
1946         } else {
1947                 name = requested_name;
1948         }
1949
1950
1951         /* replace all colons in the name. i wish we didn't have to do this */
1952
1953         if (replace_all (name, ":", "-")) {
1954                 warning << _("you cannot use colons to name objects with I/O connections") << endmsg;
1955         }
1956
1957         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
1958                 string current_name = i->short_name();
1959                 current_name.replace (current_name.find (_name), _name.length(), name);
1960                 i->set_name (current_name);
1961         }
1962
1963         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
1964                 string current_name = i->short_name();
1965                 current_name.replace (current_name.find (_name), _name.length(), name);
1966                 i->set_name (current_name);
1967         }
1968
1969         bool const r = SessionObject::set_name(name);
1970
1971         setup_bundles_for_inputs_and_outputs ();
1972
1973         return r;
1974 }
1975
1976 void
1977 IO::set_input_minimum (ChanCount n)
1978 {
1979         _input_minimum = n;
1980 }
1981
1982 void
1983 IO::set_input_maximum (ChanCount n)
1984 {
1985         _input_maximum = n;
1986 }
1987
1988 void
1989 IO::set_output_minimum (ChanCount n)
1990 {
1991         _output_minimum = n;
1992 }
1993
1994 void
1995 IO::set_output_maximum (ChanCount n)
1996 {
1997         _output_maximum = n;
1998 }
1999
2000 void
2001 IO::set_port_latency (nframes_t nframes)
2002 {
2003         Glib::Mutex::Lock lm (io_lock);
2004
2005         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
2006                 i->set_latency (nframes);
2007         }
2008 }
2009
2010 nframes_t
2011 IO::output_latency () const
2012 {
2013         nframes_t max_latency;
2014         nframes_t latency;
2015
2016         max_latency = 0;
2017
2018         /* io lock not taken - must be protected by other means */
2019
2020         for (PortSet::const_iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
2021                 if ((latency = _session.engine().get_port_total_latency (*i)) > max_latency) {
2022                         max_latency = latency;
2023                 }
2024         }
2025
2026         return max_latency;
2027 }
2028
2029 nframes_t
2030 IO::input_latency () const
2031 {
2032         nframes_t max_latency;
2033         nframes_t latency;
2034
2035         max_latency = 0;
2036
2037         /* io lock not taken - must be protected by other means */
2038
2039         for (PortSet::const_iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2040                 if ((latency = _session.engine().get_port_total_latency (*i)) > max_latency) {
2041                         max_latency = latency;
2042                 } 
2043         }
2044
2045         return max_latency;
2046 }
2047
2048 int
2049 IO::connect_input_ports_to_bundle (boost::shared_ptr<Bundle> c, void* src)
2050 {
2051         {
2052                 BLOCK_PROCESS_CALLBACK ();
2053                 Glib::Mutex::Lock lm2 (io_lock);
2054
2055                 /* Connect to the bundle, not worrying about any connections
2056                    that are already made. */
2057
2058                 ChanCount const channels = c->nchannels ();
2059                 uint32_t cnt = channels.get (default_type());
2060
2061                 for (uint32_t n = 0; n < cnt; ++n) {
2062                         const PortList& pl = c->channel_ports (n);
2063
2064                         for (PortList::const_iterator i = pl.begin(); i != pl.end(); ++i) {
2065
2066                           if (!_inputs.port(n)->connected_to (*i)) {
2067                                         
2068                                         if (_session.engine().connect (*i, _inputs.port(n)->name())) {
2069                                                 return -1;
2070                                         }
2071                                 }
2072                                 
2073                         }
2074                 }
2075
2076                 /* If this is a UserBundle, make a note of what we've done */
2077
2078                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
2079                 if (ub) {
2080
2081                         /* See if we already know about this one */
2082                         std::vector<UserBundleInfo>::iterator i = _bundles_connected_to_inputs.begin();
2083                         while (i != _bundles_connected_to_inputs.end() && i->bundle != ub) {
2084                                 ++i;
2085                         }
2086
2087                         if (i == _bundles_connected_to_inputs.end()) {
2088                                 /* We don't, so make a note */
2089                                 _bundles_connected_to_inputs.push_back (UserBundleInfo (this, ub));
2090                         }
2091                 }
2092         }
2093
2094         input_changed (IOChange (ConfigurationChanged|ConnectionsChanged), src); /* EMIT SIGNAL */
2095         return 0;
2096 }
2097
2098 int
2099 IO::connect_output_ports_to_bundle (boost::shared_ptr<Bundle> c, void* src)
2100 {
2101         {
2102                 BLOCK_PROCESS_CALLBACK ();
2103                 Glib::Mutex::Lock lm2 (io_lock);
2104
2105                 /* Connect to the bundle, not worrying about any connections
2106                    that are already made. */
2107
2108                 ChanCount const channels = c->nchannels ();
2109                 uint32_t cnt = channels.get (default_type());
2110
2111                 for (uint32_t n = 0; n < cnt; ++n) {
2112
2113                         const PortList& pl = c->channel_ports (n);
2114
2115                         for (PortList::const_iterator i = pl.begin(); i != pl.end(); ++i) {
2116
2117                                 if (!_outputs.port(n)->connected_to (*i)) {
2118                                                 
2119                                         if (_session.engine().connect (_outputs.port(n)->name(), *i)) {
2120                                                 return -1;
2121                                         }
2122                                 }
2123                         }
2124                 }
2125
2126                 /* If this is a UserBundle, make a note of what we've done */
2127
2128                 boost::shared_ptr<UserBundle> ub = boost::dynamic_pointer_cast<UserBundle> (c);
2129                 if (ub) {
2130
2131                         /* See if we already know about this one */
2132                         std::vector<UserBundleInfo>::iterator i = _bundles_connected_to_outputs.begin();
2133                         while (i != _bundles_connected_to_outputs.end() && i->bundle != ub) {
2134                                 ++i;
2135                         }
2136
2137                         if (i == _bundles_connected_to_outputs.end()) {
2138                                 /* We don't, so make a note */
2139                                 _bundles_connected_to_outputs.push_back (UserBundleInfo (this, ub));
2140                         }
2141                 }
2142         }
2143
2144         output_changed (IOChange (ConnectionsChanged|ConfigurationChanged), src); /* EMIT SIGNAL */
2145
2146         return 0;
2147 }
2148
2149 int
2150 IO::disable_connecting ()
2151 {
2152         connecting_legal = false;
2153         return 0;
2154 }
2155
2156 int
2157 IO::enable_connecting ()
2158 {
2159         connecting_legal = true;
2160         return ConnectingLegal ();
2161 }
2162
2163 int
2164 IO::disable_ports ()
2165 {
2166         ports_legal = false;
2167         return 0;
2168 }
2169
2170 int
2171 IO::enable_ports ()
2172 {
2173         ports_legal = true;
2174         return PortsLegal ();
2175 }
2176
2177 int
2178 IO::disable_panners (void)
2179 {
2180         panners_legal = false;
2181         return 0;
2182 }
2183
2184 int
2185 IO::reset_panners ()
2186 {
2187         panners_legal = true;
2188         return PannersLegal ();
2189 }
2190
2191 void
2192 IO::bundle_configuration_will_change ()
2193 {
2194         //XXX
2195 //      connect_input_ports_to_bundle (_input_bundle, this);
2196 }
2197
2198 void
2199 IO::bundle_configuration_has_changed ()
2200 {
2201         //XXX
2202 //      connect_input_ports_to_bundle (_input_bundle, this);
2203 }
2204
2205 void
2206 IO::bundle_ports_will_change (int ignored)
2207 {
2208 //XXX
2209 //      connect_output_ports_to_bundle (_output_bundle, this);
2210 }
2211
2212 void
2213 IO::bundle_ports_have_changed (int ignored)
2214 {
2215         //XXX
2216 //      connect_output_ports_to_bundle (_output_bundle, this);
2217 }
2218
2219 void
2220 IO::GainControl::set_value (float val)
2221 {
2222         // max gain at about +6dB (10.0 ^ ( 6 dB * 0.05))
2223         if (val > 1.99526231f)
2224                 val = 1.99526231f;
2225
2226         _user_value = val;
2227         _io.set_gain (val, this);
2228         
2229         Changed(); /* EMIT SIGNAL */
2230 }
2231
2232 float
2233 IO::GainControl::get_value (void) const
2234 {
2235         return AutomationControl::get_value();
2236 }
2237
2238 void
2239 IO::setup_peak_meters()
2240 {
2241         ChanCount max_streams = std::max (_inputs.count(), _outputs.count());
2242         _meter->configure_io (max_streams, max_streams);
2243 }
2244
2245 /**
2246     Update the peak meters.
2247
2248     The meter signal lock is taken to prevent modification of the 
2249     Meter signal while updating the meters, taking the meter signal
2250     lock prior to taking the io_lock ensures that all IO will remain 
2251     valid while metering.
2252 */   
2253 void
2254 IO::update_meters()
2255 {
2256         Glib::Mutex::Lock guard (m_meter_signal_lock);
2257         Meter(); /* EMIT SIGNAL */
2258 }
2259
2260 void
2261 IO::meter ()
2262 {
2263         // FIXME: Ugly.  Meter should manage the lock, if it's necessary
2264         
2265         Glib::Mutex::Lock lm (io_lock); // READER: meter thread.
2266         _meter->meter();
2267 }
2268
2269 void
2270 IO::clear_automation ()
2271 {
2272         data().clear (); // clears gain automation
2273         _panner->clear_automation ();
2274 }
2275
2276 void
2277 IO::set_parameter_automation_state (Evoral::Parameter param, AutoState state)
2278 {
2279         // XXX: would be nice to get rid of this special hack
2280
2281         if (param.type() == GainAutomation) {
2282
2283                 bool changed = false;
2284
2285                 { 
2286                         Glib::Mutex::Lock lm (control_lock());
2287
2288                         boost::shared_ptr<AutomationList> gain_auto
2289                                 = boost::dynamic_pointer_cast<AutomationList>(_gain_control->list());
2290
2291                         if (state != gain_auto->automation_state()) {
2292                                 changed = true;
2293                                 _last_automation_snapshot = 0;
2294                                 gain_auto->set_automation_state (state);
2295
2296                                 if (state != Off) {
2297                                         // FIXME: shouldn't this use Curve?
2298                                         set_gain (gain_auto->eval (_session.transport_frame()), this);
2299                                 }
2300                         }
2301                 }
2302
2303                 if (changed) {
2304                         _session.set_dirty ();
2305                 }
2306
2307         } else {
2308                 AutomatableControls::set_parameter_automation_state(param, state);
2309         }
2310 }
2311
2312 void
2313 IO::inc_gain (gain_t factor, void *src)
2314 {
2315         if (_desired_gain == 0.0f)
2316                 set_gain (0.000001f + (0.000001f * factor), src);
2317         else
2318                 set_gain (_desired_gain + (_desired_gain * factor), src);
2319 }
2320
2321 void
2322 IO::set_gain (gain_t val, void *src)
2323 {
2324         // max gain at about +6dB (10.0 ^ ( 6 dB * 0.05))
2325         if (val > 1.99526231f)
2326                 val = 1.99526231f;
2327
2328         if (src != _gain_control.get()) {
2329                 _gain_control->set_value(val);
2330                 // bit twisty, this will come back and call us again
2331                 // (this keeps control in sync with reality)
2332                 return;
2333         }
2334
2335         {
2336                 Glib::Mutex::Lock dm (declick_lock);
2337                 _desired_gain = val;
2338         }
2339
2340         if (_session.transport_stopped()) {
2341                 _gain = val;
2342         }
2343         
2344         if (_session.transport_stopped() && src != 0 && src != this && _gain_control->automation_write()) {
2345                 _gain_control->list()->add (_session.transport_frame(), val);
2346                 
2347         }
2348
2349         _session.set_dirty();
2350 }
2351
2352 void
2353 IO::start_pan_touch (uint32_t which)
2354 {
2355         if (which < _panner->size()) {
2356                 (*_panner)[which]->pan_control()->start_touch();
2357         }
2358 }
2359
2360 void
2361 IO::end_pan_touch (uint32_t which)
2362 {
2363         if (which < _panner->size()) {
2364                 (*_panner)[which]->pan_control()->stop_touch();
2365         }
2366
2367 }
2368
2369 void
2370 IO::automation_snapshot (nframes_t now, bool force)
2371 {
2372         AutomatableControls::automation_snapshot (now, force);
2373
2374         if (_last_automation_snapshot > now || (now - _last_automation_snapshot) > _automation_interval) {
2375                 _panner->snapshot (now);
2376         }
2377         
2378         _panner->snapshot (now);
2379         _last_automation_snapshot = now;
2380 }
2381
2382 void
2383 IO::transport_stopped (nframes_t frame)
2384 {
2385         _gain_control->list()->reposition_for_rt_add (frame);
2386
2387         if (_gain_control->automation_state() != Off) {
2388                 
2389                 /* the src=0 condition is a special signal to not propagate 
2390                    automation gain changes into the mix group when locating.
2391                 */
2392
2393                 // FIXME: shouldn't this use Curve?
2394                 set_gain (_gain_control->list()->eval (frame), 0);
2395         }
2396
2397         _panner->transport_stopped (frame);
2398 }
2399
2400 string
2401 IO::build_legal_port_name (DataType type, bool in)
2402 {
2403         const int name_size = jack_port_name_size();
2404         int limit;
2405         string suffix;
2406         int maxports;
2407
2408         if (type == DataType::AUDIO) {
2409                 suffix = _("audio");
2410         } else if (type == DataType::MIDI) {
2411                 suffix = _("midi");
2412         } else {
2413                 throw unknown_type();
2414         }
2415         
2416         if (in) {
2417                 suffix += _("_in");
2418                 maxports = _input_maximum.get(type);
2419         } else {
2420                 suffix += _("_out");
2421                 maxports = _output_maximum.get(type);
2422         }
2423         
2424         if (maxports == 1) {
2425                 // allow space for the slash + the suffix
2426                 limit = name_size - _session.engine().client_name().length() - (suffix.length() + 1);
2427                 char buf[name_size+1];
2428                 snprintf (buf, name_size+1, ("%.*s/%s"), limit, _name.c_str(), suffix.c_str());
2429                 return string (buf);
2430         } 
2431         
2432         // allow up to 4 digits for the output port number, plus the slash, suffix and extra space
2433
2434         limit = name_size - _session.engine().client_name().length() - (suffix.length() + 5);
2435
2436         char buf1[name_size+1];
2437         char buf2[name_size+1];
2438         
2439         snprintf (buf1, name_size+1, ("%.*s/%s"), limit, _name.c_str(), suffix.c_str());
2440         
2441         int port_number;
2442         
2443         if (in) {
2444                 port_number = find_input_port_hole (buf1);
2445         } else {
2446                 port_number = find_output_port_hole (buf1);
2447         }
2448         
2449         snprintf (buf2, name_size+1, "%s %d", buf1, port_number);
2450         
2451         return string (buf2);
2452 }
2453
2454 int32_t
2455 IO::find_input_port_hole (const char* base)
2456 {
2457         /* CALLER MUST HOLD IO LOCK */
2458
2459         uint32_t n;
2460
2461         if (_inputs.empty()) {
2462                 return 1;
2463         }
2464
2465         /* we only allow up to 4 characters for the port number
2466          */
2467
2468         for (n = 1; n < 9999; ++n) {
2469                 char buf[jack_port_name_size()];
2470                 PortSet::iterator i = _inputs.begin();
2471
2472                 snprintf (buf, jack_port_name_size(), _("%s %u"), base, n);
2473
2474                 for ( ; i != _inputs.end(); ++i) {
2475                         if (i->short_name() == buf) {
2476                                 break;
2477                         }
2478                 }
2479
2480                 if (i == _inputs.end()) {
2481                         break;
2482                 }
2483         }
2484         return n;
2485 }
2486
2487 int32_t
2488 IO::find_output_port_hole (const char* base)
2489 {
2490         /* CALLER MUST HOLD IO LOCK */
2491
2492         uint32_t n;
2493
2494         if (_outputs.empty()) {
2495                 return 1;
2496         }
2497
2498         /* we only allow up to 4 characters for the port number
2499          */
2500
2501         for (n = 1; n < 9999; ++n) {
2502                 char buf[jack_port_name_size()];
2503                 PortSet::iterator i = _outputs.begin();
2504
2505                 snprintf (buf, jack_port_name_size(), _("%s %u"), base, n);
2506
2507                 for ( ; i != _outputs.end(); ++i) {
2508                         if (i->short_name() == buf) {
2509                                 break;
2510                         }
2511                 }
2512
2513                 if (i == _outputs.end()) {
2514                         break;
2515                 }
2516         }
2517         
2518         return n;
2519 }
2520
2521 void
2522 IO::set_active (bool yn)
2523 {
2524         _active = yn; 
2525          active_changed(); /* EMIT SIGNAL */
2526 }
2527
2528
2529 AudioPort*
2530 IO::audio_input(uint32_t n) const
2531 {
2532         return dynamic_cast<AudioPort*>(input(n));
2533 }
2534
2535 AudioPort*
2536 IO::audio_output(uint32_t n) const
2537 {
2538         return dynamic_cast<AudioPort*>(output(n));
2539 }
2540
2541 MidiPort*
2542 IO::midi_input(uint32_t n) const
2543 {
2544         return dynamic_cast<MidiPort*>(input(n));
2545 }
2546
2547 MidiPort*
2548 IO::midi_output(uint32_t n) const
2549 {
2550         return dynamic_cast<MidiPort*>(output(n));
2551 }
2552
2553 void
2554 IO::set_phase_invert (bool yn, void *src)
2555 {
2556         if (_phase_invert != yn) {
2557                 _phase_invert = yn;
2558                 //  phase_invert_changed (src); /* EMIT SIGNAL */
2559         }
2560 }
2561
2562 void
2563 IO::set_denormal_protection (bool yn, void *src)
2564 {
2565         if (_denormal_protection != yn) {
2566                 _denormal_protection = yn;
2567                 //  denormal_protection_changed (src); /* EMIT SIGNAL */
2568         }
2569 }
2570
2571 void
2572 IO::update_port_total_latencies ()
2573 {
2574         /* io_lock, not taken: function must be called from Session::process() calltree */
2575
2576         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2577                 _session.engine().update_total_latency (*i);
2578         }
2579
2580         for (PortSet::iterator i = _outputs.begin(); i != _outputs.end(); ++i) {
2581                 _session.engine().update_total_latency (*i);
2582         }
2583 }
2584
2585
2586 /**
2587  *  Setup bundles that describe our inputs and outputs.
2588  */
2589
2590 void
2591 IO::setup_bundles_for_inputs_and_outputs ()
2592 {
2593         char buf[32];
2594
2595         snprintf(buf, sizeof (buf), _("%s in"), _name.c_str());
2596         _bundle_for_inputs->set_name (buf);
2597         uint32_t const ni = inputs().num_ports();
2598         _bundle_for_inputs->set_channels (ni);
2599         for (uint32_t i = 0; i < ni; ++i) {
2600                 _bundle_for_inputs->set_port (i, inputs().port(i)->name());
2601         }
2602
2603         snprintf(buf, sizeof (buf), _("%s out"), _name.c_str());
2604         _bundle_for_outputs->set_name (buf);
2605         uint32_t const no = outputs().num_ports();
2606         _bundle_for_outputs->set_channels (no);
2607         for (uint32_t i = 0; i < no; ++i) {
2608                 _bundle_for_outputs->set_port (i, outputs().port(i)->name());
2609         }
2610 }
2611
2612
2613 /**
2614  *  Create and setup bundles that describe our inputs and outputs.
2615  */
2616
2617 void
2618 IO::create_bundles_for_inputs_and_outputs ()
2619 {
2620         _bundle_for_inputs = boost::shared_ptr<AutoBundle> (new AutoBundle (true));
2621         _bundle_for_outputs = boost::shared_ptr<AutoBundle> (new AutoBundle (false));
2622         setup_bundles_for_inputs_and_outputs ();
2623 }
2624
2625 /** Add a bundle to a list if is connected to our inputs.
2626  *  @param b Bundle to check.
2627  *  @param bundles List to add to.
2628  */
2629 void
2630 IO::maybe_add_input_bundle_to_list (boost::shared_ptr<Bundle> b, std::vector<boost::shared_ptr<Bundle> >* bundles)
2631 {
2632         boost::shared_ptr<AutoBundle> ab = boost::dynamic_pointer_cast<AutoBundle, Bundle> (b);
2633
2634         if (ab == 0 || ab->ports_are_outputs() == false) {
2635                 return;
2636         }
2637         
2638         if (ab->nchannels().get (default_type()) != n_inputs().n_total ()) {
2639                 return;
2640         }
2641
2642         for (uint32_t i = 0; i < n_inputs().n_total (); ++i) {
2643
2644                 PortList const & pl = b->channel_ports (i);
2645
2646                 if (pl.empty()) {
2647                         return;
2648                 }
2649
2650                 if (!input(i)->connected_to (pl[0])) {
2651                         return;
2652                 }
2653         }
2654
2655         bundles->push_back (b);
2656 }
2657
2658 /** @return Bundles connected to our inputs */
2659 std::vector<boost::shared_ptr<Bundle> >
2660 IO::bundles_connected_to_inputs ()
2661 {
2662         std::vector<boost::shared_ptr<Bundle> > bundles;
2663         
2664         /* User bundles */
2665         for (std::vector<UserBundleInfo>::iterator i = _bundles_connected_to_inputs.begin(); i != _bundles_connected_to_inputs.end(); ++i) {
2666                 bundles.push_back (i->bundle);
2667         }
2668
2669         /* Auto bundles */
2670         _session.foreach_bundle (
2671                 sigc::bind (sigc::mem_fun (*this, &IO::maybe_add_input_bundle_to_list), &bundles)
2672                 );
2673
2674         return bundles;
2675 }
2676
2677
2678 /** Add a bundle to a list if is connected to our outputs.
2679  *  @param b Bundle to check.
2680  *  @param bundles List to add to.
2681  */
2682 void
2683 IO::maybe_add_output_bundle_to_list (boost::shared_ptr<Bundle> b, std::vector<boost::shared_ptr<Bundle> >* bundles)
2684 {
2685         boost::shared_ptr<AutoBundle> ab = boost::dynamic_pointer_cast<AutoBundle, Bundle> (b);
2686         if (ab == 0 || ab->ports_are_inputs() == false) {
2687                 return;
2688         }
2689
2690         if (ab->nchannels ().get (default_type()) != n_outputs().n_total ()) {
2691                 return;
2692         }
2693
2694         for (uint32_t i = 0; i < n_outputs().n_total (); ++i) {
2695
2696                 PortList const & pl = b->channel_ports (i);
2697
2698                 if (pl.empty()) {
2699                         return;
2700                 }
2701
2702                 if (!output(i)->connected_to (pl[0])) {
2703                         return;
2704                 }
2705         }
2706
2707         bundles->push_back (b);
2708 }
2709
2710
2711 /* @return Bundles connected to our outputs */
2712 std::vector<boost::shared_ptr<Bundle> >
2713 IO::bundles_connected_to_outputs ()
2714 {
2715         std::vector<boost::shared_ptr<Bundle> > bundles;
2716
2717         /* User bundles */
2718         for (std::vector<UserBundleInfo>::iterator i = _bundles_connected_to_outputs.begin(); i != _bundles_connected_to_outputs.end(); ++i) {
2719                 bundles.push_back (i->bundle);
2720         }
2721
2722         /* Auto bundles */
2723         _session.foreach_bundle (
2724                 sigc::bind (sigc::mem_fun (*this, &IO::maybe_add_output_bundle_to_list), &bundles)
2725                 );
2726
2727         return bundles; 
2728 }
2729
2730
2731 IO::UserBundleInfo::UserBundleInfo (IO* io, boost::shared_ptr<UserBundle> b)
2732 {
2733         bundle = b;
2734         configuration_will_change = b->ConfigurationWillChange.connect (
2735                 sigc::mem_fun (*io, &IO::bundle_configuration_will_change)
2736                 );
2737         configuration_has_changed = b->ConfigurationHasChanged.connect (
2738                 sigc::mem_fun (*io, &IO::bundle_configuration_has_changed)
2739                 );
2740         ports_will_change = b->PortsWillChange.connect (
2741                 sigc::mem_fun (*io, &IO::bundle_ports_will_change)
2742                 );
2743         ports_have_changed = b->PortsHaveChanged.connect (
2744                 sigc::mem_fun (*io, &IO::bundle_ports_have_changed)
2745                 );
2746 }
2747
2748 void
2749 IO::prepare_inputs (nframes_t nframes, nframes_t offset)
2750 {
2751         /* io_lock, not taken: function must be called from Session::process() calltree */
2752
2753         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2754                 (*i).cycle_start (nframes, offset);
2755         }
2756 }