Moved DataType into it's own class (resolved a name clash on ARDOUR::MIDI
[ardour.git] / libs / ardour / route.cc
1 /*
2     Copyright (C) 2000 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     $Id$
19 */
20
21 #include <cmath>
22 #include <fstream>
23 #include <cassert>
24
25 #include <sigc++/bind.h>
26 #include <pbd/xml++.h>
27
28 #include <ardour/timestamps.h>
29 #include <ardour/buffer.h>
30 #include <ardour/audioengine.h>
31 #include <ardour/route.h>
32 #include <ardour/insert.h>
33 #include <ardour/send.h>
34 #include <ardour/session.h>
35 #include <ardour/utils.h>
36 #include <ardour/configuration.h>
37 #include <ardour/cycle_timer.h>
38 #include <ardour/route_group.h>
39 #include <ardour/port.h>
40 #include <ardour/ladspa_plugin.h>
41 #include <ardour/panner.h>
42 #include <ardour/dB.h>
43 #include <ardour/mix.h>
44
45 #include "i18n.h"
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace PBD;
50
51
52 uint32_t Route::order_key_cnt = 0;
53
54
55 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg, DataType default_type)
56         : IO (sess, name, input_min, input_max, output_min, output_max, default_type),
57           _flags (flg),
58           _solo_control (*this, ToggleControllable::SoloControl),
59           _mute_control (*this, ToggleControllable::MuteControl)
60 {
61         init ();
62 }
63
64 Route::Route (Session& sess, const XMLNode& node)
65         : IO (sess, "route"),
66           _solo_control (*this, ToggleControllable::SoloControl),
67           _mute_control (*this, ToggleControllable::MuteControl)
68 {
69         init ();
70         set_state (node);
71 }
72
73 void
74 Route::init ()
75 {
76         redirect_max_outs = 0;
77         _muted = false;
78         _soloed = false;
79         _solo_safe = false;
80         _phase_invert = false;
81         order_keys[N_("signal")] = order_key_cnt++;
82         _active = true;
83         _silent = false;
84         _meter_point = MeterPostFader;
85         _initial_delay = 0;
86         _roll_delay = 0;
87         _own_latency = 0;
88         _have_internal_generator = false;
89         _declickable = false;
90         _pending_declick = true;
91         _remote_control_id = 0;
92
93         _edit_group = 0;
94         _mix_group = 0;
95
96         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
97         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
98         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
99         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
100         
101         solo_gain = 1.0;
102         desired_solo_gain = 1.0;
103         mute_gain = 1.0;
104         desired_mute_gain = 1.0;
105
106         _control_outs = 0;
107
108         input_changed.connect (mem_fun (this, &Route::input_change_handler));
109         output_changed.connect (mem_fun (this, &Route::output_change_handler));
110 }
111
112 Route::~Route ()
113 {
114         GoingAway (); /* EMIT SIGNAL */
115         clear_redirects (this);
116
117         if (_control_outs) {
118                 delete _control_outs;
119         }
120 }
121
122 void
123 Route::set_remote_control_id (uint32_t id)
124 {
125         if (id != _remote_control_id) {
126                 _remote_control_id = id;
127                 RemoteControlIDChanged ();
128         }
129 }
130
131 uint32_t
132 Route::remote_control_id() const
133 {
134         return _remote_control_id;
135 }
136
137 long
138 Route::order_key (string name) const
139 {
140         OrderKeys::const_iterator i;
141         
142         if ((i = order_keys.find (name)) == order_keys.end()) {
143                 return -1;
144         }
145
146         return (*i).second;
147 }
148
149 void
150 Route::set_order_key (string name, long n)
151 {
152         order_keys[name] = n;
153         _session.set_dirty ();
154 }
155
156 void
157 Route::inc_gain (gain_t fraction, void *src)
158 {
159         IO::inc_gain (fraction, src);
160 }
161
162 void
163 Route::set_gain (gain_t val, void *src)
164 {
165         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
166                 
167                 if (_mix_group->is_relative()) {
168                         
169                         
170                         gain_t usable_gain  = gain();
171                         if (usable_gain < 0.000001f) {
172                                 usable_gain=0.000001f;
173                         }
174                                                 
175                         gain_t delta = val;
176                         if (delta < 0.000001f) {
177                                 delta=0.000001f;
178                         }
179
180                         delta -= usable_gain;
181
182                         if (delta == 0.0f) return;
183
184                         gain_t factor = delta / usable_gain;
185
186                         if (factor > 0.0f) {
187                                 factor = _mix_group->get_max_factor(factor);
188                                 if (factor == 0.0f) {
189                                         gain_changed (src);
190                                         return;
191                                 }
192                         } else {
193                                 factor = _mix_group->get_min_factor(factor);
194                                 if (factor == 0.0f) {
195                                         gain_changed (src);
196                                         return;
197                                 }
198                         }
199                                         
200                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
201
202                 } else {
203                         
204                         _mix_group->apply (&Route::set_gain, val, _mix_group);
205                 }
206
207                 return;
208         } 
209
210         if (val == gain()) {
211                 return;
212         }
213
214         IO::set_gain (val, src);
215 }
216
217 void
218 Route::process_output_buffers (vector<Sample*>& bufs, uint32_t nbufs,
219                                jack_nframes_t start_frame, jack_nframes_t end_frame, 
220                                jack_nframes_t nframes, jack_nframes_t offset, bool with_redirects, int declick,
221                                bool meter)
222 {
223         uint32_t n;
224         RedirectList::iterator i;
225         bool post_fader_work = false;
226         bool mute_declick_applied = false;
227         gain_t dmg, dsg, dg;
228         vector<Sample*>::iterator bufiter;
229         IO *co;
230         bool mute_audible;
231         bool solo_audible;
232         bool no_monitor = (Config->get_use_hardware_monitoring() || !Config->get_use_sw_monitoring ());
233         gain_t* gab = _session.gain_automation_buffer();
234
235         declick = _pending_declick;
236
237         {
238                 Glib::Mutex::Lock cm (control_outs_lock, Glib::TRY_LOCK);
239                 
240                 if (cm.locked()) {
241                         co = _control_outs;
242                 } else {
243                         co = 0;
244                 }
245         }
246         
247         { 
248                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
249                 
250                 if (dm.locked()) {
251                         dmg = desired_mute_gain;
252                         dsg = desired_solo_gain;
253                         dg = _desired_gain;
254                 } else {
255                         dmg = mute_gain;
256                         dsg = solo_gain;
257                         dg = _gain;
258                 }
259         }
260
261         /* ----------------------------------------------------------------------------------------------------
262            GLOBAL DECLICK (for transport changes etc.)
263            -------------------------------------------------------------------------------------------------- */
264
265         if (declick > 0) {
266                 apply_declick (bufs, nbufs, nframes, 0.0, 1.0, _phase_invert);
267                 _pending_declick = 0;
268         } else if (declick < 0) {
269                 apply_declick (bufs, nbufs, nframes, 1.0, 0.0, _phase_invert);
270                 _pending_declick = 0;
271         } else {
272
273                 /* no global declick */
274
275                 if (solo_gain != dsg) {
276                         apply_declick (bufs, nbufs, nframes, solo_gain, dsg, _phase_invert);
277                         solo_gain = dsg;
278                 }
279         }
280
281
282         /* ----------------------------------------------------------------------------------------------------
283            INPUT METERING & MONITORING
284            -------------------------------------------------------------------------------------------------- */
285
286         if (meter && (_meter_point == MeterInput)) {
287                 for (n = 0; n < nbufs; ++n) {
288                         _peak_power[n] = Session::compute_peak (bufs[n], nframes, _peak_power[n]); 
289                 }
290         }
291
292         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
293                 apply_declick (bufs, nbufs, nframes, mute_gain, dmg, _phase_invert);
294                 mute_gain = dmg;
295                 mute_declick_applied = true;
296         }
297
298         if ((_meter_point == MeterInput) && co) {
299                 
300                 solo_audible = dsg > 0;
301                 mute_audible = dmg > 0;// || !_mute_affects_pre_fader;
302                 
303                 if (    // muted by solo of another track
304                         
305                         !solo_audible || 
306                         
307                         // muted by mute of this track 
308                         
309                         !mute_audible ||
310                         
311                         // rec-enabled but not s/w monitoring 
312                         
313                         // TODO: this is probably wrong
314
315                         (no_monitor && record_enabled() && (!_session.get_auto_input() || _session.actively_recording()))
316
317                         ) {
318                         
319                         co->silence (nframes, offset);
320                         
321                 } else {
322
323                         co->deliver_output (bufs, nbufs, nframes, offset);
324                         
325                 } 
326         } 
327
328         /* ----------------------------------------------------------------------------------------------------
329            PRE-FADER REDIRECTS
330            -------------------------------------------------------------------------------------------------- */
331
332         if (with_redirects) {
333                 Glib::RWLock::ReaderLock rm (redirect_lock, Glib::TRY_LOCK);
334                 if (rm.locked()) {
335                         if (mute_gain > 0 || !_mute_affects_pre_fader) {
336                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
337                                         switch ((*i)->placement()) {
338                                         case PreFader:
339                                                 (*i)->run (bufs, nbufs, nframes, offset);
340                                                 break;
341                                         case PostFader:
342                                                 post_fader_work = true;
343                                                 break;
344                                         }
345                                 }
346                         } else {
347                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
348                                         switch ((*i)->placement()) {
349                                         case PreFader:
350                                                 (*i)->silence (nframes, offset);
351                                                 break;
352                                         case PostFader:
353                                                 post_fader_work = true;
354                                                 break;
355                                         }
356                                 }
357                         }
358                 } 
359         }
360
361
362         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_post_fader) {
363                 apply_declick (bufs, nbufs, nframes, mute_gain, dmg, _phase_invert);
364                 mute_gain = dmg;
365                 mute_declick_applied = true;
366         }
367
368         /* ----------------------------------------------------------------------------------------------------
369            PRE-FADER METERING & MONITORING
370            -------------------------------------------------------------------------------------------------- */
371
372         if (meter && (_meter_point == MeterPreFader)) {
373                 for (n = 0; n < nbufs; ++n) {
374                         _peak_power[n] = Session::compute_peak (bufs[n], nframes, _peak_power[n]);
375                 }
376         }
377
378         
379         if ((_meter_point == MeterPreFader) && co) {
380                 
381                 solo_audible = dsg > 0;
382                 mute_audible = dmg > 0 || !_mute_affects_pre_fader;
383                 
384                 if ( // muted by solo of another track
385                         
386                         !solo_audible || 
387                         
388                         // muted by mute of this track 
389                         
390                         !mute_audible ||
391                         
392                         // rec-enabled but not s/w monitoring 
393                         
394                         (no_monitor && record_enabled() && (!_session.get_auto_input() || _session.actively_recording()))
395
396                         ) {
397                         
398                         co->silence (nframes, offset);
399                         
400                 } else {
401
402                         co->deliver_output (bufs, nbufs, nframes, offset);
403                         
404                 } 
405         } 
406         
407         /* ----------------------------------------------------------------------------------------------------
408            GAIN STAGE
409            -------------------------------------------------------------------------------------------------- */
410
411         /* if not recording or recording and requiring any monitor signal, then apply gain */
412
413         if ( // not recording 
414
415                 !(record_enabled() && _session.actively_recording()) || 
416                 
417             // OR recording 
418                 
419                 // h/w monitoring not in use 
420                 
421                 (!Config->get_use_hardware_monitoring() && 
422
423                  // AND software monitoring required
424
425                  Config->get_use_sw_monitoring())) { 
426                 
427                 if (apply_gain_automation) {
428                         
429                         if (_phase_invert) {
430                                 for (n = 0; n < nbufs; ++n)  {
431                                         Sample *sp = bufs[n];
432                                         
433                                         for (jack_nframes_t nx = 0; nx < nframes; ++nx) {
434                                                 sp[nx] *= -gab[nx];
435                                         }
436                                 }
437                         } else {
438                                 for (n = 0; n < nbufs; ++n) {
439                                         Sample *sp = bufs[n];
440                                         
441                                         for (jack_nframes_t nx = 0; nx < nframes; ++nx) {
442                                                 sp[nx] *= gab[nx];
443                                         }
444                                 }
445                         }
446                         
447                         if (apply_gain_automation && _session.transport_rolling() && nframes > 0) {
448                                 _effective_gain = gab[nframes-1];
449                         }
450                         
451                 } else {
452                         
453                         /* manual (scalar) gain */
454                         
455                         if (_gain != dg) {
456                                 
457                                 apply_declick (bufs, nbufs, nframes, _gain, dg, _phase_invert);
458                                 _gain = dg;
459                                 
460                         } else if (_gain != 0 && (_phase_invert || _gain != 1.0)) {
461                                 
462                                 /* no need to interpolate current gain value,
463                                    but its non-unity, so apply it. if the gain
464                                    is zero, do nothing because we'll ship silence
465                                    below.
466                                 */
467
468                                 gain_t this_gain;
469                                 
470                                 if (_phase_invert) {
471                                         this_gain = -_gain;
472                                 } else {
473                                         this_gain = _gain;
474                                 }
475                                 
476                                 for (n = 0; n < nbufs; ++n) {
477                                         Sample *sp = bufs[n];
478                                         apply_gain_to_buffer(sp,nframes,this_gain);
479                                 }
480
481                         } else if (_gain == 0) {
482                                 for (n = 0; n < nbufs; ++n) {
483                                         memset (bufs[n], 0, sizeof (Sample) * nframes);
484                                 }
485                         }
486                 }
487
488         } else {
489
490                 /* actively recording, no monitoring required; leave buffers as-is to save CPU cycles */
491
492         }
493
494         /* ----------------------------------------------------------------------------------------------------
495            POST-FADER REDIRECTS
496            -------------------------------------------------------------------------------------------------- */
497
498         /* note that post_fader_work cannot be true unless with_redirects was also true, so don't test both */
499
500         if (post_fader_work) {
501
502                 Glib::RWLock::ReaderLock rm (redirect_lock, Glib::TRY_LOCK);
503                 if (rm.locked()) {
504                         if (mute_gain > 0 || !_mute_affects_post_fader) {
505                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
506                                         switch ((*i)->placement()) {
507                                         case PreFader:
508                                                 break;
509                                         case PostFader:
510                                                 (*i)->run (bufs, nbufs, nframes, offset);
511                                                 break;
512                                         }
513                                 }
514                         } else {
515                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
516                                         switch ((*i)->placement()) {
517                                         case PreFader:
518                                                 break;
519                                         case PostFader:
520                                                 (*i)->silence (nframes, offset);
521                                                 break;
522                                         }
523                                 }
524                         }
525                 } 
526         }
527
528         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_control_outs) {
529                 apply_declick (bufs, nbufs, nframes, mute_gain, dmg, _phase_invert);
530                 mute_gain = dmg;
531                 mute_declick_applied = true;
532         }
533
534         /* ----------------------------------------------------------------------------------------------------
535            CONTROL OUTPUT STAGE
536            -------------------------------------------------------------------------------------------------- */
537
538         if ((_meter_point == MeterPostFader) && co) {
539                 
540                 solo_audible = solo_gain > 0;
541                 mute_audible = dmg > 0 || !_mute_affects_control_outs;
542
543                 if ( // silent anyway
544
545                         (_gain == 0 && !apply_gain_automation) || 
546                     
547                      // muted by solo of another track
548
549                         !solo_audible || 
550                     
551                      // muted by mute of this track 
552
553                         !mute_audible ||
554
555                     // recording but not s/w monitoring 
556                         
557                         (no_monitor && record_enabled() && (!_session.get_auto_input() || _session.actively_recording()))
558
559                         ) {
560
561                         co->silence (nframes, offset);
562                         
563                 } else {
564
565                         co->deliver_output_no_pan (bufs, nbufs, nframes, offset);
566                 } 
567         } 
568
569         /* ----------------------------------------------------------------------
570            GLOBAL MUTE 
571            ----------------------------------------------------------------------*/
572
573         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_main_outs) {
574                 apply_declick (bufs, nbufs, nframes, mute_gain, dmg, _phase_invert);
575                 mute_gain = dmg;
576                 mute_declick_applied = true;
577         }
578         
579         /* ----------------------------------------------------------------------------------------------------
580            MAIN OUTPUT STAGE
581            -------------------------------------------------------------------------------------------------- */
582
583         solo_audible = dsg > 0;
584         mute_audible = dmg > 0 || !_mute_affects_main_outs;
585         
586         if (n_outputs() == 0) {
587             
588             /* relax */
589
590         } else if (no_monitor && record_enabled() && (!_session.get_auto_input() || _session.actively_recording())) {
591                 
592                 IO::silence (nframes, offset);
593                 
594         } else {
595
596                 if ( // silent anyway
597
598                     (_gain == 0 && !apply_gain_automation) ||
599                     
600                     // muted by solo of another track, but not using control outs for solo
601
602                     (!solo_audible && (_session.solo_model() != Session::SoloBus)) ||
603                     
604                     // muted by mute of this track
605
606                     !mute_audible
607
608                         ) {
609
610                         /* don't use Route::silence() here, because that causes
611                            all outputs (sends, port inserts, etc. to be silent).
612                         */
613                         
614                         if (_meter_point == MeterPostFader) {
615                                 reset_peak_meters ();
616                         }
617                         
618                         IO::silence (nframes, offset);
619                         
620                 } else {
621                         
622                         if (_session.transport_speed() > 1.5f || _session.transport_speed() < -1.5f) {
623                                 pan (bufs, nbufs, nframes, offset, speed_quietning); 
624                         } else {
625                                 // cerr << _name << " panner state = " << _panner->automation_state() << endl;
626                                 if (!_panner->empty() &&
627                                     (_panner->automation_state() & Play ||
628                                      ((_panner->automation_state() & Touch) && !_panner->touching()))) {
629                                         pan_automated (bufs, nbufs, start_frame, end_frame, nframes, offset);
630                                 } else {
631                                         pan (bufs, nbufs, nframes, offset, 1.0); 
632                                 }
633                         }
634                 }
635
636         }
637
638         /* ----------------------------------------------------------------------------------------------------
639            POST-FADER METERING
640            -------------------------------------------------------------------------------------------------- */
641
642         if (meter && (_meter_point == MeterPostFader)) {
643 //              cerr << "meter post" << endl;
644
645                 if ((_gain == 0 && !apply_gain_automation) || dmg == 0) {
646                         uint32_t no = n_outputs();
647                         for (n = 0; n < no; ++n) {
648                                 _peak_power[n] = 0;
649                         } 
650                 } else {
651                         uint32_t no = n_outputs();
652                         for (n = 0; n < no; ++n) {
653                                 _peak_power[n] = Session::compute_peak (output(n)->get_buffer (nframes) + offset, nframes, _peak_power[n]);
654                         }
655                 }
656         }
657 }
658
659 uint32_t
660 Route::n_process_buffers ()
661 {
662         return max (n_inputs(), redirect_max_outs);
663 }
664
665 void
666
667 Route::passthru (jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t nframes, jack_nframes_t offset, int declick, bool meter_first)
668 {
669         vector<Sample*>& bufs = _session.get_passthru_buffers();
670         uint32_t limit = n_process_buffers ();
671
672         _silent = false;
673
674         collect_input (bufs, limit, nframes, offset);
675
676 #define meter_stream meter_first
677
678         if (meter_first) {
679                 for (uint32_t n = 0; n < limit; ++n) {
680                         _peak_power[n] = Session::compute_peak (bufs[n], nframes, _peak_power[n]);
681                 }
682                 meter_stream = false;
683         } else {
684                 meter_stream = true;
685         }
686                 
687         process_output_buffers (bufs, limit, start_frame, end_frame, nframes, offset, true, declick, meter_stream);
688
689 #undef meter_stream
690 }
691
692 void
693 Route::set_phase_invert (bool yn, void *src)
694 {
695         if (_phase_invert != yn) {
696                 _phase_invert = yn;
697         }
698         //  phase_invert_changed (src); /* EMIT SIGNAL */
699 }
700
701 void
702 Route::set_solo (bool yn, void *src)
703 {
704         if (_solo_safe) {
705                 return;
706         }
707
708         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
709                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
710                 return;
711         }
712
713         if (_soloed != yn) {
714                 _soloed = yn;
715                 solo_changed (src); /* EMIT SIGNAL */
716                 _solo_control.Changed (); /* EMIT SIGNAL */
717         }
718 }
719
720 void
721 Route::set_solo_mute (bool yn)
722 {
723         Glib::Mutex::Lock lm (declick_lock);
724
725         /* Called by Session in response to another Route being soloed.
726          */
727            
728         desired_solo_gain = (yn?0.0:1.0);
729 }
730
731 void
732 Route::set_solo_safe (bool yn, void *src)
733 {
734         if (_solo_safe != yn) {
735                 _solo_safe = yn;
736                  solo_safe_changed (src); /* EMIT SIGNAL */
737         }
738 }
739
740 void
741 Route::set_mute (bool yn, void *src)
742
743 {
744         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
745                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
746                 return;
747         }
748
749         if (_muted != yn) {
750                 _muted = yn;
751                 mute_changed (src); /* EMIT SIGNAL */
752                 
753                 _mute_control.Changed (); /* EMIT SIGNAL */
754                 
755                 Glib::Mutex::Lock lm (declick_lock);
756                 desired_mute_gain = (yn?0.0f:1.0f);
757         }
758 }
759
760 int
761 Route::add_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
762 {
763         uint32_t old_rmo = redirect_max_outs;
764
765         if (!_session.engine().connected()) {
766                 return 1;
767         }
768
769         {
770                 Glib::RWLock::WriterLock lm (redirect_lock);
771
772                 boost::shared_ptr<PluginInsert> pi;
773                 boost::shared_ptr<PortInsert> porti;
774
775                 uint32_t potential_max_streams = 0;
776
777                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(redirect)) != 0) {
778                         pi->set_count (1);
779
780                         if (pi->input_streams() == 0) {
781                                 /* instrument plugin */
782                                 _have_internal_generator = true;
783                         }
784
785                         potential_max_streams = max(pi->input_streams(), pi->output_streams());
786                         
787                 } else if ((porti = boost::dynamic_pointer_cast<PortInsert>(redirect)) != 0) {
788
789                         /* force new port inserts to start out with an i/o configuration
790                            that matches this route's i/o configuration.
791
792                            the "inputs" for the port are supposed to match the output
793                            of this route.
794
795                            the "outputs" of the route should match the inputs of this
796                            route. XXX shouldn't they match the number of active signal
797                            streams at the point of insertion?
798                            
799                         */
800
801                         porti->ensure_io (n_outputs (), n_inputs(), false, this);
802                 }
803
804                 // Ensure peak vector sizes before the plugin is activated
805                 while (_peak_power.size() < potential_max_streams) {
806                         _peak_power.push_back(0);
807                 }
808                 while (_visible_peak_power.size() < potential_max_streams) {
809                         _visible_peak_power.push_back(0);
810                 }
811
812                 _redirects.push_back (redirect);
813
814                 if (_reset_plugin_counts (err_streams)) {
815                         _redirects.pop_back ();
816                         _reset_plugin_counts (0); // it worked before we tried to add it ...
817                         return -1;
818                 }
819
820                 redirect->activate ();
821                 redirect->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
822         }
823         
824         if (redirect_max_outs != old_rmo || old_rmo == 0) {
825                 reset_panner ();
826         }
827
828
829         redirects_changed (src); /* EMIT SIGNAL */
830         return 0;
831 }
832
833 int
834 Route::add_redirects (const RedirectList& others, void *src, uint32_t* err_streams)
835 {
836         uint32_t old_rmo = redirect_max_outs;
837
838         if (!_session.engine().connected()) {
839                 return 1;
840         }
841
842         {
843                 Glib::RWLock::WriterLock lm (redirect_lock);
844
845                 RedirectList::iterator existing_end = _redirects.end();
846                 --existing_end;
847
848                 uint32_t potential_max_streams = 0;
849
850                 for (RedirectList::const_iterator i = others.begin(); i != others.end(); ++i) {
851                         
852                         boost::shared_ptr<PluginInsert> pi;
853                         
854                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
855                                 pi->set_count (1);
856                                 
857                                 uint32_t m = max(pi->input_streams(), pi->output_streams());
858                                 if (m > potential_max_streams)
859                                         potential_max_streams = m;
860                         }
861
862                         // Ensure peak vector sizes before the plugin is activated
863                         while (_peak_power.size() < potential_max_streams) {
864                                 _peak_power.push_back(0);
865                         }
866                         while (_visible_peak_power.size() < potential_max_streams) {
867                                 _visible_peak_power.push_back(0);
868                         }
869
870                         _redirects.push_back (*i);
871                         
872                         if (_reset_plugin_counts (err_streams)) {
873                                 ++existing_end;
874                                 _redirects.erase (existing_end, _redirects.end());
875                                 _reset_plugin_counts (0); // it worked before we tried to add it ...
876                                 return -1;
877                         }
878                         
879                         (*i)->activate ();
880                         (*i)->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
881                 }
882         }
883         
884         if (redirect_max_outs != old_rmo || old_rmo == 0) {
885                 reset_panner ();
886         }
887
888         redirects_changed (src); /* EMIT SIGNAL */
889         return 0;
890 }
891
892 void
893 Route::clear_redirects (void *src)
894 {
895         uint32_t old_rmo = redirect_max_outs;
896
897         if (!_session.engine().connected()) {
898                 return;
899         }
900
901         {
902                 Glib::RWLock::WriterLock lm (redirect_lock);
903                 _redirects.clear ();
904         }
905
906         if (redirect_max_outs != old_rmo) {
907                 reset_panner ();
908         }
909         
910         redirect_max_outs = 0;
911         _have_internal_generator = false;
912         redirects_changed (src); /* EMIT SIGNAL */
913 }
914
915 int
916 Route::remove_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
917 {
918         uint32_t old_rmo = redirect_max_outs;
919
920         if (!_session.engine().connected()) {
921                 return 1;
922         }
923
924         redirect_max_outs = 0;
925
926         {
927                 Glib::RWLock::WriterLock lm (redirect_lock);
928                 RedirectList::iterator i;
929                 bool removed = false;
930
931                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
932                         if (*i == redirect) {
933
934                                 RedirectList::iterator tmp;
935
936                                 /* move along, see failure case for reset_plugin_counts()
937                                    where we may need to reinsert the redirect.
938                                 */
939
940                                 tmp = i;
941                                 ++tmp;
942
943                                 /* stop redirects that send signals to JACK ports
944                                    from causing noise as a result of no longer being
945                                    run.
946                                 */
947
948                                 boost::shared_ptr<Send> send;
949                                 boost::shared_ptr<PortInsert> port_insert;
950                                 
951                                 if ((send = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
952                                         send->disconnect_inputs (this);
953                                         send->disconnect_outputs (this);
954                                 } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (*i)) != 0) {
955                                         port_insert->disconnect_inputs (this);
956                                         port_insert->disconnect_outputs (this);
957                                 }
958
959                                 _redirects.erase (i);
960
961                                 i = tmp;
962                                 removed = true;
963                                 break;
964                         }
965                 }
966
967                 if (!removed) {
968                         /* what? */
969                         return 1;
970                 }
971
972                 if (_reset_plugin_counts (err_streams)) {
973                         /* get back to where we where */
974                         _redirects.insert (i, redirect);
975                         /* we know this will work, because it worked before :) */
976                         _reset_plugin_counts (0);
977                         return -1;
978                 }
979
980                 bool foo = false;
981
982                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
983                         boost::shared_ptr<PluginInsert> pi;
984                         
985                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
986                                 if (pi->is_generator()) {
987                                         foo = true;
988                                 }
989                         }
990                 }
991
992                 _have_internal_generator = foo;
993         }
994
995         if (old_rmo != redirect_max_outs) {
996                 reset_panner ();
997         }
998
999         redirects_changed (src); /* EMIT SIGNAL */
1000         return 0;
1001 }
1002
1003 int
1004 Route::reset_plugin_counts (uint32_t* lpc)
1005 {
1006         Glib::RWLock::WriterLock lm (redirect_lock);
1007         return _reset_plugin_counts (lpc);
1008 }
1009
1010
1011 int
1012 Route::_reset_plugin_counts (uint32_t* err_streams)
1013 {
1014         RedirectList::iterator r;
1015         uint32_t i_cnt;
1016         uint32_t s_cnt;
1017         map<Placement,list<InsertCount> > insert_map;
1018         jack_nframes_t initial_streams;
1019
1020         redirect_max_outs = 0;
1021         i_cnt = 0;
1022         s_cnt = 0;
1023
1024         /* divide inserts up by placement so we get the signal flow
1025            properly modelled. we need to do this because the _redirects
1026            list is not sorted by placement, and because other reasons may 
1027            exist now or in the future for this separate treatment.
1028         */
1029         
1030         for (r = _redirects.begin(); r != _redirects.end(); ++r) {
1031
1032                 boost::shared_ptr<Insert> insert;
1033
1034                 /* do this here in case we bomb out before we get to the end of
1035                    this function.
1036                 */
1037
1038                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1039
1040                 if ((insert = boost::dynamic_pointer_cast<Insert>(*r)) != 0) {
1041                         ++i_cnt;
1042                         insert_map[insert->placement()].push_back (InsertCount (insert));
1043
1044                         /* reset plugin counts back to one for now so
1045                            that we have a predictable, controlled
1046                            state to try to configure.
1047                         */
1048
1049                         boost::shared_ptr<PluginInsert> pi;
1050                 
1051                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(insert)) != 0) {
1052                                 pi->set_count (1);
1053                         }
1054
1055                 } else if (boost::dynamic_pointer_cast<Send> (*r) != 0) {
1056                         ++s_cnt;
1057                 }
1058         }
1059         
1060         if (i_cnt == 0) {
1061                 if (s_cnt) {
1062                         goto recompute;
1063                 } else {
1064                         return 0;
1065                 }
1066         }
1067
1068         /* Now process each placement in order, checking to see if we 
1069            can really do what has been requested.
1070         */
1071
1072         /* A: PreFader */
1073         
1074         if (check_some_plugin_counts (insert_map[PreFader], n_inputs (), err_streams)) {
1075                 return -1;
1076         }
1077
1078         /* figure out the streams that will feed into PreFader */
1079
1080         if (!insert_map[PreFader].empty()) {
1081                 InsertCount& ic (insert_map[PreFader].back());
1082                 initial_streams = ic.insert->compute_output_streams (ic.cnt);
1083         } else {
1084                 initial_streams = n_inputs ();
1085         }
1086
1087         /* B: PostFader */
1088
1089         if (check_some_plugin_counts (insert_map[PostFader], initial_streams, err_streams)) {
1090                 return -1;
1091         }
1092
1093         /* OK, everything can be set up correctly, so lets do it */
1094
1095         apply_some_plugin_counts (insert_map[PreFader]);
1096         apply_some_plugin_counts (insert_map[PostFader]);
1097
1098         /* recompute max outs of any redirect */
1099
1100   recompute:
1101
1102         redirect_max_outs = 0;
1103         RedirectList::iterator prev = _redirects.end();
1104
1105         for (r = _redirects.begin(); r != _redirects.end(); prev = r, ++r) {
1106                 boost::shared_ptr<Send> s;
1107
1108                 if ((s = boost::dynamic_pointer_cast<Send> (*r)) != 0) {
1109                         if (r == _redirects.begin()) {
1110                                 s->expect_inputs (n_inputs());
1111                         } else {
1112                                 s->expect_inputs ((*prev)->output_streams());
1113                         }
1114                 }
1115
1116                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1117         }
1118
1119         /* we're done */
1120
1121         return 0;
1122 }                                  
1123
1124 int32_t
1125 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1126 {
1127         list<InsertCount>::iterator i;
1128
1129         for (i = iclist.begin(); i != iclist.end(); ++i) {
1130                 
1131                 if ((*i).insert->configure_io ((*i).cnt, (*i).in, (*i).out)) {
1132                         return -1;
1133                 }
1134                 /* make sure that however many we have, they are all active */
1135                 (*i).insert->activate ();
1136         }
1137
1138         return 0;
1139 }
1140
1141 int32_t
1142 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1143 {
1144         list<InsertCount>::iterator i;
1145         
1146         for (i = iclist.begin(); i != iclist.end(); ++i) {
1147
1148                 if (((*i).cnt = (*i).insert->can_support_input_configuration (required_inputs)) < 0) {
1149                         if (err_streams) {
1150                                 *err_streams = required_inputs;
1151                         }
1152                         return -1;
1153                 }
1154                 
1155                 (*i).in = required_inputs;
1156                 (*i).out = (*i).insert->compute_output_streams ((*i).cnt);
1157
1158                 required_inputs = (*i).out;
1159         }
1160
1161         return 0;
1162 }
1163
1164 int
1165 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1166 {
1167         uint32_t old_rmo = redirect_max_outs;
1168
1169         if (err_streams) {
1170                 *err_streams = 0;
1171         }
1172
1173         RedirectList to_be_deleted;
1174
1175         {
1176                 Glib::RWLock::WriterLock lm (redirect_lock);
1177                 RedirectList::iterator tmp;
1178                 RedirectList the_copy;
1179
1180                 the_copy = _redirects;
1181                 
1182                 /* remove all relevant redirects */
1183
1184                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1185                         tmp = i;
1186                         ++tmp;
1187
1188                         if ((*i)->placement() == placement) {
1189                                 to_be_deleted.push_back (*i);
1190                                 _redirects.erase (i);
1191                         }
1192
1193                         i = tmp;
1194                 }
1195
1196                 /* now copy the relevant ones from "other" */
1197                 
1198                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1199                         if ((*i)->placement() == placement) {
1200                                 _redirects.push_back (Redirect::clone (*i));
1201                         }
1202                 }
1203
1204                 /* reset plugin stream handling */
1205
1206                 if (_reset_plugin_counts (err_streams)) {
1207
1208                         /* FAILED COPY ATTEMPT: we have to restore order */
1209
1210                         /* delete all cloned redirects */
1211
1212                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1213
1214                                 tmp = i;
1215                                 ++tmp;
1216
1217                                 if ((*i)->placement() == placement) {
1218                                         _redirects.erase (i);
1219                                 }
1220                                 
1221                                 i = tmp;
1222                         }
1223
1224                         /* restore the natural order */
1225
1226                         _redirects = the_copy;
1227                         redirect_max_outs = old_rmo;
1228
1229                         /* we failed, even though things are OK again */
1230
1231                         return -1;
1232
1233                 } else {
1234                         
1235                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1236                         to_be_deleted.clear ();
1237                 }
1238         }
1239
1240         if (redirect_max_outs != old_rmo || old_rmo == 0) {
1241                 reset_panner ();
1242         }
1243
1244         redirects_changed (this); /* EMIT SIGNAL */
1245         return 0;
1246 }
1247
1248 void
1249 Route::all_redirects_flip ()
1250 {
1251         Glib::RWLock::ReaderLock lm (redirect_lock);
1252
1253         if (_redirects.empty()) {
1254                 return;
1255         }
1256
1257         bool first_is_on = _redirects.front()->active();
1258         
1259         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1260                 (*i)->set_active (!first_is_on, this);
1261         }
1262 }
1263
1264 void
1265 Route::all_redirects_active (bool state)
1266 {
1267         Glib::RWLock::ReaderLock lm (redirect_lock);
1268
1269         if (_redirects.empty()) {
1270                 return;
1271         }
1272
1273         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1274                 (*i)->set_active (state, this);
1275         }
1276 }
1277
1278 struct RedirectSorter {
1279     bool operator() (boost::shared_ptr<const Redirect> a, boost::shared_ptr<const Redirect> b) {
1280             return a->sort_key() < b->sort_key();
1281     }
1282 };
1283
1284 int
1285 Route::sort_redirects (uint32_t* err_streams)
1286 {
1287         {
1288                 RedirectSorter comparator;
1289                 Glib::RWLock::WriterLock lm (redirect_lock);
1290                 uint32_t old_rmo = redirect_max_outs;
1291
1292                 /* the sweet power of C++ ... */
1293
1294                 RedirectList as_it_was_before = _redirects;
1295
1296                 _redirects.sort (comparator);
1297         
1298                 if (_reset_plugin_counts (err_streams)) {
1299                         _redirects = as_it_was_before;
1300                         redirect_max_outs = old_rmo;
1301                         return -1;
1302                 } 
1303         } 
1304
1305         reset_panner ();
1306         redirects_changed (this); /* EMIT SIGNAL */
1307
1308         return 0;
1309 }
1310
1311 XMLNode&
1312 Route::get_state()
1313 {
1314         return state(true);
1315 }
1316
1317 XMLNode&
1318 Route::get_template()
1319 {
1320         return state(false);
1321 }
1322
1323 XMLNode&
1324 Route::state(bool full_state)
1325 {
1326         XMLNode *node = new XMLNode("Route");
1327         XMLNode *aevents;
1328         RedirectList:: iterator i;
1329         char buf[32];
1330
1331         if (_flags) {
1332                 snprintf (buf, sizeof (buf), "0x%x", _flags);
1333                 node->add_property("flags", buf);
1334         }
1335         
1336         node->add_property("default-type", _default_type.to_string());
1337
1338         node->add_property("active", _active?"yes":"no");
1339         node->add_property("muted", _muted?"yes":"no");
1340         node->add_property("soloed", _soloed?"yes":"no");
1341         node->add_property("phase-invert", _phase_invert?"yes":"no");
1342         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1343         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1344         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1345         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1346
1347         if (_edit_group) {
1348                 node->add_property("edit-group", _edit_group->name());
1349         }
1350         if (_mix_group) {
1351                 node->add_property("mix-group", _mix_group->name());
1352         }
1353
1354         string order_string;
1355         OrderKeys::iterator x = order_keys.begin(); 
1356
1357         while (x != order_keys.end()) {
1358                 order_string += (*x).first;
1359                 order_string += '=';
1360                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1361                 order_string += buf;
1362                 
1363                 ++x;
1364
1365                 if (x == order_keys.end()) {
1366                         break;
1367                 }
1368
1369                 order_string += ':';
1370         }
1371         node->add_property ("order-keys", order_string);
1372
1373         node->add_child_nocopy (IO::state (full_state));
1374
1375         if (_control_outs) {
1376                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1377                 cnode->add_child_nocopy (_control_outs->state (full_state));
1378                 node->add_child_nocopy (*cnode);
1379         }
1380
1381         if (_comment.length()) {
1382                 XMLNode *cmt = node->add_child ("Comment");
1383                 cmt->add_content (_comment);
1384         }
1385
1386         if (full_state) {
1387                 string path;
1388
1389                 path = _session.snap_name();
1390                 path += "-gain-";
1391                 path += legalize_for_path (_name);
1392                 path += ".automation";
1393
1394                 /* XXX we didn't ask for a state save, we asked for the current state.
1395                    FIX ME!
1396                 */
1397
1398                 if (save_automation (path)) {
1399                         error << _("Could not get state of route.  Problem with save_automation") << endmsg;
1400                 }
1401
1402                 aevents = node->add_child ("Automation");
1403                 aevents->add_property ("path", path);
1404         }       
1405
1406         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1407                 node->add_child_nocopy((*i)->state (full_state));
1408         }
1409
1410         if (_extra_xml){
1411                 node->add_child_copy (*_extra_xml);
1412         }
1413         
1414         return *node;
1415 }
1416
1417 void
1418 Route::set_deferred_state ()
1419 {
1420         XMLNodeList nlist;
1421         XMLNodeConstIterator niter;
1422
1423         if (!deferred_state) {
1424                 return;
1425         }
1426
1427         nlist = deferred_state->children();
1428
1429         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1430                 add_redirect_from_xml (**niter);
1431         }
1432
1433         delete deferred_state;
1434         deferred_state = 0;
1435 }
1436
1437 void
1438 Route::add_redirect_from_xml (const XMLNode& node)
1439 {
1440         const XMLProperty *prop;
1441
1442         if (node.name() == "Send") {
1443                 
1444
1445                 try {
1446                         boost::shared_ptr<Send> send (new Send (_session, node));
1447                         add_redirect (send, this);
1448                 } 
1449                 
1450                 catch (failed_constructor &err) {
1451                         error << _("Send construction failed") << endmsg;
1452                         return;
1453                 }
1454                 
1455         } else if (node.name() == "Insert") {
1456                 
1457                 try {
1458                         if ((prop = node.property ("type")) != 0) {
1459
1460                                 boost::shared_ptr<Insert> insert;
1461
1462                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1463
1464                                         insert.reset (new PluginInsert(_session, node));
1465                                         
1466                                 } else if (prop->value() == "port") {
1467
1468
1469                                         insert.reset (new PortInsert (_session, node));
1470
1471                                 } else {
1472
1473                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1474                                 }
1475
1476                                 add_redirect (insert, this);
1477                                 
1478                         } else {
1479                                 error << _("Insert XML node has no type property") << endmsg;
1480                         }
1481                 }
1482                 
1483                 catch (failed_constructor &err) {
1484                         warning << _("insert could not be created. Ignored.") << endmsg;
1485                         return;
1486                 }
1487         }
1488 }
1489
1490 int
1491 Route::set_state (const XMLNode& node)
1492 {
1493         XMLNodeList nlist;
1494         XMLNodeConstIterator niter;
1495         XMLNode *child;
1496         XMLPropertyList plist;
1497         const XMLProperty *prop;
1498
1499         if (node.name() != "Route"){
1500                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1501                 return -1;
1502         }
1503
1504         if ((prop = node.property ("flags")) != 0) {
1505                 int x;
1506                 sscanf (prop->value().c_str(), "0x%x", &x);
1507                 _flags = Flag (x);
1508         } else {
1509                 _flags = Flag (0);
1510         }
1511         
1512         if ((prop = node.property ("default-type")) != 0) {
1513                 _default_type = DataType(prop->value());
1514                 assert(_default_type != DataType::NIL);
1515         }
1516
1517         if ((prop = node.property ("phase-invert")) != 0) {
1518                 set_phase_invert(prop->value()=="yes"?true:false, this);
1519         }
1520
1521         if ((prop = node.property ("active")) != 0) {
1522                 set_active (prop->value() == "yes");
1523         }
1524
1525         if ((prop = node.property ("muted")) != 0) {
1526                 bool yn = prop->value()=="yes"?true:false; 
1527
1528                 /* force reset of mute status */
1529
1530                 _muted = !yn;
1531                 set_mute(yn, this);
1532                 mute_gain = desired_mute_gain;
1533         }
1534
1535         if ((prop = node.property ("soloed")) != 0) {
1536                 bool yn = prop->value()=="yes"?true:false; 
1537
1538                 /* force reset of solo status */
1539
1540                 _soloed = !yn;
1541                 set_solo (yn, this);
1542                 solo_gain = desired_solo_gain;
1543         }
1544
1545         if ((prop = node.property ("mute-affects-pre-fader")) != 0) {
1546                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1547         }
1548
1549         if ((prop = node.property ("mute-affects-post-fader")) != 0) {
1550                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1551         }
1552
1553         if ((prop = node.property ("mute-affects-control-outs")) != 0) {
1554                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1555         }
1556
1557         if ((prop = node.property ("mute-affects-main-outs")) != 0) {
1558                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1559         }
1560
1561         if ((prop = node.property ("edit-group")) != 0) {
1562                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1563                 if(edit_group == 0) {
1564                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1565                 } else {
1566                         set_edit_group(edit_group, this);
1567                 }
1568         }
1569
1570         if ((prop = node.property ("order-keys")) != 0) {
1571
1572                 long n;
1573
1574                 string::size_type colon, equal;
1575                 string remaining = prop->value();
1576
1577                 while (remaining.length()) {
1578
1579                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1580                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1581                                       << endmsg;
1582                         } else {
1583                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1584                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1585                                               << endmsg;
1586                                 } else {
1587                                         set_order_key (remaining.substr (0, equal), n);
1588                                 }
1589                         }
1590
1591                         colon = remaining.find_first_of (':');
1592
1593                         if (colon != string::npos) {
1594                                 remaining = remaining.substr (colon+1);
1595                         } else {
1596                                 break;
1597                         }
1598                 }
1599         }
1600
1601         nlist = node.children();
1602
1603         if (deferred_state) {
1604                 delete deferred_state;
1605         }
1606
1607         deferred_state = new XMLNode("deferred state");
1608
1609         /* set parent class properties before anything else */
1610
1611         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1612
1613                 child = *niter;
1614
1615                 if (child->name() == IO::state_node_name) {
1616
1617                         IO::set_state (*child);
1618                         break;
1619                 }
1620         }
1621                         
1622         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1623
1624                 child = *niter;
1625                         
1626                 if (child->name() == "Send") {
1627
1628
1629                         if (!IO::ports_legal) {
1630
1631                                 deferred_state->add_child_copy (*child);
1632
1633                         } else {
1634                                 add_redirect_from_xml (*child);
1635                         }
1636
1637                 } else if (child->name() == "Insert") {
1638                         
1639                         if (!IO::ports_legal) {
1640                                 
1641                                 deferred_state->add_child_copy (*child);
1642
1643                         } else {
1644                                 
1645                                 add_redirect_from_xml (*child);
1646                         }
1647
1648                 } else if (child->name() == "Automation") {
1649
1650                         XMLPropertyList plist;
1651                         XMLPropertyConstIterator piter;
1652                         XMLProperty *prop;
1653                         
1654                         plist = child->properties();
1655                         for (piter = plist.begin(); piter != plist.end(); ++piter) {
1656                                 prop = *piter;
1657                                 if (prop->name() == "path") {
1658                                         load_automation (prop->value());
1659                                 }
1660                         }
1661
1662                 } else if (child->name() == "ControlOuts") {
1663                         
1664                         string coutname = _name;
1665                         coutname += _("[control]");
1666
1667                         _control_outs = new IO (_session, coutname);
1668                         _control_outs->set_state (**(child->children().begin()));
1669
1670                 } else if (child->name() == "Comment") {
1671
1672                         /* XXX this is a terrible API design in libxml++ */
1673
1674                         XMLNode *cmt = *(child->children().begin());
1675                         _comment = cmt->content();
1676
1677                 } else if (child->name() == "extra") {
1678                         _extra_xml = new XMLNode (*child);
1679                 }
1680         }
1681
1682         if ((prop = node.property ("mix-group")) != 0) {
1683                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1684                 if (mix_group == 0) {
1685                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1686                 }  else {
1687                         set_mix_group(mix_group, this);
1688                 }
1689         }
1690
1691         return 0;
1692 }
1693
1694 void
1695 Route::curve_reallocate ()
1696 {
1697 //      _gain_automation_curve.finish_resize ();
1698 //      _pan_automation_curve.finish_resize ();
1699 }
1700
1701 void
1702 Route::silence (jack_nframes_t nframes, jack_nframes_t offset)
1703 {
1704         if (!_silent) {
1705
1706                 // reset_peak_meters ();
1707                 
1708                 IO::silence (nframes, offset);
1709
1710                 if (_control_outs) {
1711                         _control_outs->silence (nframes, offset);
1712                 }
1713
1714                 { 
1715                         Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
1716                         
1717                         if (lm.locked()) {
1718                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1719                                         boost::shared_ptr<PluginInsert> pi;
1720                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1721                                                 // skip plugins, they don't need anything when we're not active
1722                                                 continue;
1723                                         }
1724
1725                                         (*i)->silence (nframes, offset);
1726                                 }
1727
1728                                 if (nframes == _session.get_block_size() && offset == 0) {
1729                                         // _silent = true;
1730                                 }
1731                         }
1732                 }
1733                 
1734         }
1735 }       
1736
1737 int
1738 Route::set_control_outs (const vector<string>& ports)
1739 {
1740         Glib::Mutex::Lock lm (control_outs_lock);
1741         vector<string>::const_iterator i;
1742
1743         if (_control_outs) {
1744                 delete _control_outs;
1745                 _control_outs = 0;
1746         }
1747         
1748         if (ports.empty()) {
1749                 return 0;
1750         }
1751  
1752         string coutname = _name;
1753         coutname += _("[control]");
1754         
1755         _control_outs = new IO (_session, coutname);
1756
1757         /* our control outs need as many outputs as we
1758            have outputs. we track the changes in ::output_change_handler().
1759         */
1760
1761         _control_outs->ensure_io (0, n_outputs(), true, this);
1762  
1763         return 0;
1764 }       
1765
1766 void
1767 Route::set_edit_group (RouteGroup *eg, void *src)
1768
1769 {
1770         if (eg == _edit_group) {
1771                 return;
1772         }
1773
1774         if (_edit_group) {
1775                 _edit_group->remove (this);
1776         }
1777
1778         if ((_edit_group = eg) != 0) {
1779                 _edit_group->add (this);
1780         }
1781
1782         _session.set_dirty ();
1783         edit_group_changed (src); /* EMIT SIGNAL */
1784 }
1785
1786 void
1787 Route::drop_edit_group (void *src)
1788 {
1789         _edit_group = 0;
1790         _session.set_dirty ();
1791         edit_group_changed (src); /* EMIT SIGNAL */
1792 }
1793
1794 void
1795 Route::set_mix_group (RouteGroup *mg, void *src)
1796
1797 {
1798         if (mg == _mix_group) {
1799                 return;
1800         }
1801
1802         if (_mix_group) {
1803                 _mix_group->remove (this);
1804         }
1805
1806         if ((_mix_group = mg) != 0) {
1807                 _mix_group->add (this);
1808         }
1809
1810         _session.set_dirty ();
1811         mix_group_changed (src); /* EMIT SIGNAL */
1812 }
1813
1814 void
1815 Route::drop_mix_group (void *src)
1816 {
1817         _mix_group = 0;
1818         _session.set_dirty ();
1819         mix_group_changed (src); /* EMIT SIGNAL */
1820 }
1821
1822 void
1823 Route::set_comment (string cmt, void *src)
1824 {
1825         _comment = cmt;
1826         comment_changed (src);
1827         _session.set_dirty ();
1828 }
1829
1830 bool
1831 Route::feeds (boost::shared_ptr<Route> other)
1832 {
1833         uint32_t i, j;
1834
1835         IO& self = *this;
1836         uint32_t no = self.n_outputs();
1837         uint32_t ni = other->n_inputs ();
1838
1839         for (i = 0; i < no; ++i) {
1840                 for (j = 0; j < ni; ++j) {
1841                         if (self.output(i)->connected_to (other->input(j)->name())) {
1842                                 return true;
1843                         }
1844                 }
1845         }
1846
1847         /* check Redirects which may also interconnect Routes */
1848
1849         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1850
1851                 no = (*r)->n_outputs();
1852
1853                 for (i = 0; i < no; ++i) {
1854                         for (j = 0; j < ni; ++j) {
1855                                 if ((*r)->output(i)->connected_to (other->input (j)->name())) {
1856                                         return true;
1857                                 }
1858                         }
1859                 }
1860         }
1861
1862         /* check for control room outputs which may also interconnect Routes */
1863
1864         if (_control_outs) {
1865
1866                 no = _control_outs->n_outputs();
1867                 
1868                 for (i = 0; i < no; ++i) {
1869                         for (j = 0; j < ni; ++j) {
1870                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
1871                                         return true;
1872                                 }
1873                         }
1874                 }
1875         }
1876
1877         return false;
1878 }
1879
1880 void
1881 Route::set_mute_config (mute_type t, bool onoff, void *src)
1882 {
1883         switch (t) {
1884         case PRE_FADER:
1885                 _mute_affects_pre_fader = onoff;
1886                  pre_fader_changed(src); /* EMIT SIGNAL */
1887                 break;
1888
1889         case POST_FADER:
1890                 _mute_affects_post_fader = onoff;
1891                  post_fader_changed(src); /* EMIT SIGNAL */
1892                 break;
1893
1894         case CONTROL_OUTS:
1895                 _mute_affects_control_outs = onoff;
1896                  control_outs_changed(src); /* EMIT SIGNAL */
1897                 break;
1898
1899         case MAIN_OUTS:
1900                 _mute_affects_main_outs = onoff;
1901                  main_outs_changed(src); /* EMIT SIGNAL */
1902                 break;
1903         }
1904 }
1905
1906 bool
1907 Route::get_mute_config (mute_type t)
1908 {
1909         bool onoff = false;
1910         
1911         switch (t){
1912         case PRE_FADER:
1913                 onoff = _mute_affects_pre_fader; 
1914                 break;
1915         case POST_FADER:
1916                 onoff = _mute_affects_post_fader;
1917                 break;
1918         case CONTROL_OUTS:
1919                 onoff = _mute_affects_control_outs;
1920                 break;
1921         case MAIN_OUTS:
1922                 onoff = _mute_affects_main_outs;
1923                 break;
1924         }
1925         
1926         return onoff;
1927 }
1928
1929 void
1930 Route::set_active (bool yn)
1931 {
1932         _active = yn; 
1933          active_changed(); /* EMIT SIGNAL */
1934 }
1935
1936 void
1937 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1938 {
1939         jack_nframes_t now = _session.transport_frame();
1940
1941         {
1942                 Glib::RWLock::ReaderLock lm (redirect_lock);
1943
1944                 if (!did_locate) {
1945                         automation_snapshot (now);
1946                 }
1947
1948                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1949                         
1950                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1951                                 (*i)->deactivate ();
1952                                 (*i)->activate ();
1953                         }
1954                         
1955                         (*i)->transport_stopped (now);
1956                 }
1957         }
1958
1959         IO::transport_stopped (now);
1960  
1961         _roll_delay = _initial_delay;
1962 }
1963
1964 UndoAction
1965 Route::get_memento() const
1966 {
1967         void (Route::*pmf)(state_id_t) = &Route::set_state;
1968         return sigc::bind (mem_fun (*(const_cast<Route *>(this)), pmf), _current_state_id);
1969 }
1970
1971 void
1972 Route::set_state (state_id_t id)
1973 {
1974         return;
1975 }
1976
1977 void
1978 Route::input_change_handler (IOChange change, void *ignored)
1979 {
1980         if (change & ConfigurationChanged) {
1981                 reset_plugin_counts (0);
1982         }
1983 }
1984
1985 void
1986 Route::output_change_handler (IOChange change, void *ignored)
1987 {
1988         if (change & ConfigurationChanged) {
1989                 if (_control_outs) {
1990                         _control_outs->ensure_io (0, n_outputs(), true, this);
1991                 }
1992                 
1993                 reset_plugin_counts (0);
1994         }
1995 }
1996
1997 uint32_t
1998 Route::pans_required () const
1999 {
2000         if (n_outputs() < 2) {
2001                 return 0;
2002         }
2003         
2004         return max (n_inputs (), redirect_max_outs);
2005 }
2006
2007 int 
2008 Route::no_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2009                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2010 {
2011         if (n_outputs() == 0) {
2012                 return 0;
2013         }
2014
2015         if (session_state_changing || !_active)  {
2016                 silence (nframes, offset);
2017                 return 0;
2018         }
2019
2020         apply_gain_automation = false;
2021         
2022         if (n_inputs()) {
2023                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2024         } else {
2025                 silence (nframes, offset);
2026         }
2027
2028         return 0;
2029 }
2030
2031 jack_nframes_t
2032 Route::check_initial_delay (jack_nframes_t nframes, jack_nframes_t& offset, jack_nframes_t& transport_frame)
2033 {
2034         if (_roll_delay > nframes) {
2035
2036                 _roll_delay -= nframes;
2037                 silence (nframes, offset);
2038                 /* transport frame is not legal for caller to use */
2039                 return 0;
2040
2041         } else if (_roll_delay > 0) {
2042
2043                 nframes -= _roll_delay;
2044
2045                 silence (_roll_delay, offset);
2046
2047                 offset += _roll_delay;
2048                 transport_frame += _roll_delay;
2049
2050                 _roll_delay = 0;
2051         }
2052
2053         return nframes;
2054 }
2055
2056 int
2057 Route::roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, int declick,
2058              bool can_record, bool rec_monitors_input)
2059 {
2060         {
2061                 Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
2062                 if (lm.locked()) {
2063                         // automation snapshot can also be called from the non-rt context
2064                         // and it uses the redirect list, so we take the lock out here
2065                         automation_snapshot (_session.transport_frame());
2066                 }
2067         }
2068                 
2069         if ((n_outputs() == 0 && _redirects.empty()) || n_inputs() == 0 || !_active) {
2070                 silence (nframes, offset);
2071                 return 0;
2072         }
2073         
2074         jack_nframes_t unused = 0;
2075
2076         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2077                 return 0;
2078         }
2079
2080         _silent = false;
2081
2082         apply_gain_automation = false;
2083
2084         { 
2085                 Glib::Mutex::Lock am (automation_lock, Glib::TRY_LOCK);
2086                 
2087                 if (am.locked() && _session.transport_rolling()) {
2088                         
2089                         jack_nframes_t start_frame = end_frame - nframes;
2090                         
2091                         if (gain_automation_playback()) {
2092                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2093                         }
2094                 }
2095         }
2096
2097         passthru (start_frame, end_frame, nframes, offset, declick, false);
2098
2099         return 0;
2100 }
2101
2102 int
2103 Route::silent_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2104                     bool can_record, bool rec_monitors_input)
2105 {
2106         silence (nframes, offset);
2107         return 0;
2108 }
2109
2110 void
2111 Route::toggle_monitor_input ()
2112 {
2113         for (vector<Port*>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2114                 (*i)->request_monitor_input(!(*i)->monitoring_input());
2115         }
2116 }
2117
2118 bool
2119 Route::has_external_redirects () const
2120 {
2121         boost::shared_ptr<const PortInsert> pi;
2122         
2123         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2124                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2125
2126                         uint32_t no = pi->n_outputs();
2127
2128                         for (uint32_t n = 0; n < no; ++n) {
2129                                 
2130                                 string port_name = pi->output(n)->name();
2131                                 string client_name = port_name.substr (0, port_name.find(':'));
2132
2133                                 /* only say "yes" if the redirect is actually in use */
2134                                 
2135                                 if (client_name != "ardour" && pi->active()) {
2136                                         return true;
2137                                 }
2138                         }
2139                 }
2140         }
2141
2142         return false;
2143 }
2144
2145 void
2146 Route::flush_redirects ()
2147 {
2148         /* XXX shouldn't really try to take this lock, since
2149            this is called from the RT audio thread.
2150         */
2151
2152         Glib::RWLock::ReaderLock lm (redirect_lock);
2153
2154         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2155                 (*i)->deactivate ();
2156                 (*i)->activate ();
2157         }
2158 }
2159
2160 void
2161 Route::set_meter_point (MeterPoint p, void *src)
2162 {
2163         if (_meter_point != p) {
2164                 _meter_point = p;
2165                  meter_change (src); /* EMIT SIGNAL */
2166                 _session.set_dirty ();
2167         }
2168 }
2169
2170 jack_nframes_t
2171 Route::update_total_latency ()
2172 {
2173         _own_latency = 0;
2174
2175         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2176                 if ((*i)->active ()) {
2177                         _own_latency += (*i)->latency ();
2178                 }
2179         }
2180
2181         set_port_latency (_own_latency);
2182
2183         /* this (virtual) function is used for pure Routes,
2184            not derived classes like AudioTrack.  this means
2185            that the data processed here comes from an input
2186            port, not prerecorded material, and therefore we
2187            have to take into account any input latency.
2188         */
2189
2190         _own_latency += input_latency ();
2191
2192         return _own_latency;
2193 }
2194
2195 void
2196 Route::set_latency_delay (jack_nframes_t longest_session_latency)
2197 {
2198         _initial_delay = longest_session_latency - _own_latency;
2199
2200         if (_session.transport_stopped()) {
2201                 _roll_delay = _initial_delay;
2202         }
2203 }
2204
2205 void
2206 Route::automation_snapshot (jack_nframes_t now)
2207 {
2208         IO::automation_snapshot (now);
2209
2210         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2211                 (*i)->automation_snapshot (now);
2212         }
2213 }
2214
2215 Route::ToggleControllable::ToggleControllable (Route& s, ToggleType tp)
2216         : route (s), type(tp)
2217 {
2218         
2219 }
2220
2221 void
2222 Route::ToggleControllable::set_value (float val)
2223 {
2224         bool bval = ((val >= 0.5f) ? true: false);
2225         
2226         switch (type) {
2227         case MuteControl:
2228                 route.set_mute (bval, this);
2229                 break;
2230         case SoloControl:
2231                 route.set_solo (bval, this);
2232                 break;
2233         default:
2234                 break;
2235         }
2236 }
2237
2238 float
2239 Route::ToggleControllable::get_value (void) const
2240 {
2241         float val = 0.0f;
2242         
2243         switch (type) {
2244         case MuteControl:
2245                 val = route.muted() ? 1.0f : 0.0f;
2246                 break;
2247         case SoloControl:
2248                 val = route.soloed() ? 1.0f : 0.0f;
2249                 break;
2250         default:
2251                 break;
2252         }
2253
2254         return val;
2255 }
2256
2257 void 
2258 Route::set_block_size (jack_nframes_t nframes)
2259 {
2260         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2261                 (*i)->set_block_size (nframes);
2262         }
2263 }
2264
2265 void
2266 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2267 {
2268         _session.update_latency_compensation (false, false);
2269 }
2270
2271 void
2272 Route::protect_automation ()
2273 {
2274         switch (gain_automation_state()) {
2275         case Write:
2276         case Touch:
2277                 set_gain_automation_state (Off);
2278                 break;
2279         default:
2280                 break;
2281         }
2282
2283         switch (panner().automation_state ()) {
2284         case Write:
2285         case Touch:
2286                 panner().set_automation_state (Off);
2287                 break;
2288         default:
2289                 break;
2290         }
2291         
2292         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2293                 boost::shared_ptr<PluginInsert> pi;
2294                 if ((pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2295                         pi->protect_automation ();
2296                 }
2297         }
2298 }
2299
2300 void
2301 Route::set_pending_declick (int declick)
2302 {
2303         if (_declickable) {
2304                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2305                 if (declick) {
2306                         _pending_declick = declick;
2307                 }
2308                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2309         } else {
2310                 _pending_declick = 0;
2311         }
2312
2313 }