one more send zipper fix
[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
24 #include <sigc++/bind.h>
25 #include <pbd/xml++.h>
26
27 #include <ardour/timestamps.h>
28 #include <ardour/audioengine.h>
29 #include <ardour/route.h>
30 #include <ardour/insert.h>
31 #include <ardour/send.h>
32 #include <ardour/session.h>
33 #include <ardour/utils.h>
34 #include <ardour/configuration.h>
35 #include <ardour/cycle_timer.h>
36 #include <ardour/route_group.h>
37 #include <ardour/port.h>
38 #include <ardour/ladspa_plugin.h>
39 #include <ardour/panner.h>
40 #include <ardour/dB.h>
41 #include <ardour/mix.h>
42
43 #include "i18n.h"
44
45 using namespace std;
46 using namespace ARDOUR;
47 //using namespace sigc;
48
49
50 uint32_t Route::order_key_cnt = 0;
51
52
53 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg)
54         : IO (sess, name, input_min, input_max, output_min, output_max),
55           _flags (flg),
56           _midi_solo_control (*this, MIDIToggleControl::SoloControl, _session.midi_port()),
57           _midi_mute_control (*this, MIDIToggleControl::MuteControl, _session.midi_port())
58 {
59         init ();
60 }
61
62 Route::Route (Session& sess, const XMLNode& node)
63         : IO (sess, "route"),
64           _midi_solo_control (*this, MIDIToggleControl::SoloControl, _session.midi_port()),
65           _midi_mute_control (*this, MIDIToggleControl::MuteControl, _session.midi_port())
66 {
67         init ();
68         set_state (node);
69 }
70
71 void
72 Route::init ()
73 {
74         redirect_max_outs = 0;
75         _muted = false;
76         _soloed = false;
77         _solo_safe = false;
78         _phase_invert = false;
79         order_keys[N_("signal")] = order_key_cnt++;
80         _active = true;
81         _silent = false;
82         _meter_point = MeterPostFader;
83         _initial_delay = 0;
84         _roll_delay = 0;
85         _own_latency = 0;
86         _have_internal_generator = false;
87         _declickable = false;
88         _pending_declick = true;
89         _remote_control_id = 0;
90
91         _edit_group = 0;
92         _mix_group = 0;
93
94         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
95         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
96         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
97         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
98         
99         solo_gain = 1.0;
100         desired_solo_gain = 1.0;
101         mute_gain = 1.0;
102         desired_mute_gain = 1.0;
103
104         _control_outs = 0;
105
106         input_changed.connect (mem_fun (this, &Route::input_change_handler));
107         output_changed.connect (mem_fun (this, &Route::output_change_handler));
108
109         reset_midi_control (_session.midi_port(), _session.get_midi_control());
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                 TentativeLockMonitor cm (control_outs_lock, __LINE__, __FILE__);
239                 
240                 if (cm.locked()) {
241                         co = _control_outs;
242                 } else {
243                         co = 0;
244                 }
245         }
246         
247         { 
248                 TentativeLockMonitor dm (declick_lock, __LINE__, __FILE__);
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                 TentativeRWLockMonitor rm (redirect_lock, false, __LINE__, __FILE__);
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()) {
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                 TentativeRWLockMonitor rm (redirect_lock, false, __LINE__, __FILE__);
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                                 if (!_panner->empty() &&
626                                     (_panner->automation_state() & Play ||
627                                      ((_panner->automation_state() & Touch) && !_panner->touching()))) {
628                                         pan_automated (bufs, nbufs, start_frame, end_frame, nframes, offset);
629                                 } else {
630                                         pan (bufs, nbufs, nframes, offset, 1.0); 
631                                 }
632                         }
633                 }
634
635         }
636
637         /* ----------------------------------------------------------------------------------------------------
638            POST-FADER METERING
639            -------------------------------------------------------------------------------------------------- */
640
641         if (meter && (_meter_point == MeterPostFader)) {
642 //              cerr << "meter post" << endl;
643
644                 if ((_gain == 0 && !apply_gain_automation) || dmg == 0) {
645                         uint32_t no = n_outputs();
646                         for (n = 0; n < no; ++n) {
647                                 _peak_power[n] = 0;
648                         } 
649                 } else {
650                         uint32_t no = n_outputs();
651                         for (n = 0; n < no; ++n) {
652                                 _peak_power[n] = Session::compute_peak (output(n)->get_buffer (nframes) + offset, nframes, _peak_power[n]);
653                         }
654                 }
655         }
656 }
657
658 uint32_t
659 Route::n_process_buffers ()
660 {
661         return max (n_inputs(), redirect_max_outs);
662 }
663
664 void
665
666 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)
667 {
668         vector<Sample*>& bufs = _session.get_passthru_buffers();
669         uint32_t limit = n_process_buffers ();
670
671         _silent = false;
672
673         collect_input (bufs, limit, nframes, offset);
674
675 #define meter_stream meter_first
676
677         if (meter_first) {
678                 for (uint32_t n = 0; n < limit; ++n) {
679                         _peak_power[n] = Session::compute_peak (bufs[n], nframes, _peak_power[n]);
680                 }
681                 meter_stream = false;
682         } else {
683                 meter_stream = true;
684         }
685                 
686         process_output_buffers (bufs, limit, start_frame, end_frame, nframes, offset, true, declick, meter_stream);
687
688 #undef meter_stream
689 }
690
691 void
692 Route::set_phase_invert (bool yn, void *src)
693 {
694         if (_phase_invert != yn) {
695                 _phase_invert = yn;
696         }
697         //  phase_invert_changed (src); /* EMIT SIGNAL */
698 }
699
700 void
701 Route::set_solo (bool yn, void *src)
702 {
703         if (_solo_safe) {
704                 return;
705         }
706
707         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
708                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
709                 return;
710         }
711
712         if (_soloed != yn) {
713                 _soloed = yn;
714                  solo_changed (src); /* EMIT SIGNAL */
715
716                  if (_session.get_midi_feedback()) {
717                          _midi_solo_control.send_feedback (_soloed);
718                  }
719         }
720 }
721
722 void
723 Route::set_solo_mute (bool yn)
724 {
725         LockMonitor lm (declick_lock, __LINE__, __FILE__);
726
727         /* Called by Session in response to another Route being soloed.
728          */
729            
730         desired_solo_gain = (yn?0.0:1.0);
731 }
732
733 void
734 Route::set_solo_safe (bool yn, void *src)
735 {
736         if (_solo_safe != yn) {
737                 _solo_safe = yn;
738                  solo_safe_changed (src); /* EMIT SIGNAL */
739         }
740 }
741
742 void
743 Route::set_mute (bool yn, void *src)
744
745 {
746         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
747                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
748                 return;
749         }
750
751         if (_muted != yn) {
752                 _muted = yn;
753                 mute_changed (src); /* EMIT SIGNAL */
754                 
755                 if (_session.get_midi_feedback()) {
756                         _midi_mute_control.send_feedback (_muted);
757                 }
758                 
759                 LockMonitor lm (declick_lock, __LINE__, __FILE__);
760                 desired_mute_gain = (yn?0.0f:1.0f);
761         }
762 }
763
764 int
765 Route::add_redirect (Redirect *redirect, void *src, uint32_t* err_streams)
766 {
767         uint32_t old_rmo = redirect_max_outs;
768
769         if (!_session.engine().connected()) {
770                 return 1;
771         }
772
773         {
774                 RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
775
776                 PluginInsert* pi;
777                 PortInsert* porti;
778
779                 uint32_t potential_max_streams = 0;
780
781                 if ((pi = dynamic_cast<PluginInsert*>(redirect)) != 0) {
782                         pi->set_count (1);
783
784                         if (pi->input_streams() == 0) {
785                                 /* instrument plugin */
786                                 _have_internal_generator = true;
787                         }
788
789                         potential_max_streams = max(pi->input_streams(), pi->output_streams());
790
791                 } else if ((porti = dynamic_cast<PortInsert*>(redirect)) != 0) {
792
793                         /* force new port inserts to start out with an i/o configuration
794                            that matches this route's i/o configuration.
795
796                            the "inputs" for the port are supposed to match the output
797                            of this route.
798
799                            the "outputs" of the route should match the inputs of this
800                            route. XXX shouldn't they match the number of active signal
801                            streams at the point of insertion?
802                            
803                         */
804
805                         porti->ensure_io (n_outputs (), n_inputs(), false, this);
806                 }
807
808                 // Ensure peak vector sizes before the plugin is activated
809                 while (_peak_power.size() < potential_max_streams) {
810                         _peak_power.push_back(0);
811                 }
812                 while (_stored_peak_power.size() < potential_max_streams) {
813                         _stored_peak_power.push_back(0);
814                 }
815
816                 _redirects.push_back (redirect);
817
818                 if (_reset_plugin_counts (err_streams)) {
819                         _redirects.pop_back ();
820                         _reset_plugin_counts (0); // it worked before we tried to add it ...
821                         return -1;
822                 }
823
824                 redirect->activate ();
825                 redirect->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
826         }
827         
828         if (redirect_max_outs != old_rmo || old_rmo == 0) {
829                 reset_panner ();
830         }
831
832
833         redirects_changed (src); /* EMIT SIGNAL */
834         return 0;
835 }
836
837 int
838 Route::add_redirects (const RedirectList& others, void *src, uint32_t* err_streams)
839 {
840         uint32_t old_rmo = redirect_max_outs;
841
842         if (!_session.engine().connected()) {
843                 return 1;
844         }
845
846         {
847                 RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
848
849                 RedirectList::iterator existing_end = _redirects.end();
850                 --existing_end;
851
852                 uint32_t potential_max_streams = 0;
853
854                 for (RedirectList::const_iterator i = others.begin(); i != others.end(); ++i) {
855                         
856                         PluginInsert* pi;
857                         
858                         if ((pi = dynamic_cast<PluginInsert*>(*i)) != 0) {
859                                 pi->set_count (1);
860                                 
861                                 uint32_t m = max(pi->input_streams(), pi->output_streams());
862                                 if (m > potential_max_streams)
863                                         potential_max_streams = m;
864                         }
865
866                         // Ensure peak vector sizes before the plugin is activated
867                         while (_peak_power.size() < potential_max_streams) {
868                                 _peak_power.push_back(0);
869                         }
870                         while (_stored_peak_power.size() < potential_max_streams) {
871                                 _stored_peak_power.push_back(0);
872                         }
873
874                         _redirects.push_back (*i);
875                         
876                         if (_reset_plugin_counts (err_streams)) {
877                                 ++existing_end;
878                                 _redirects.erase (existing_end, _redirects.end());
879                                 _reset_plugin_counts (0); // it worked before we tried to add it ...
880                                 return -1;
881                         }
882                         
883                         (*i)->activate ();
884                         (*i)->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
885                 }
886         }
887         
888         if (redirect_max_outs != old_rmo || old_rmo == 0) {
889                 reset_panner ();
890         }
891
892         redirects_changed (src); /* EMIT SIGNAL */
893         return 0;
894 }
895
896 void
897 Route::clear_redirects (void *src)
898 {
899         uint32_t old_rmo = redirect_max_outs;
900
901         if (!_session.engine().connected()) {
902                 return;
903         }
904
905         {
906                 RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
907
908                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
909                         delete *i;
910                 }
911
912                 _redirects.clear ();
913         }
914
915         if (redirect_max_outs != old_rmo) {
916                 reset_panner ();
917         }
918         
919         redirect_max_outs = 0;
920         _have_internal_generator = false;
921         redirects_changed (src); /* EMIT SIGNAL */
922 }
923
924 int
925 Route::remove_redirect (Redirect *redirect, void *src, uint32_t* err_streams)
926 {
927         uint32_t old_rmo = redirect_max_outs;
928
929         if (!_session.engine().connected()) {
930                 return 1;
931         }
932
933         redirect_max_outs = 0;
934
935         {
936                 RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
937                 RedirectList::iterator i;
938                 bool removed = false;
939
940                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
941                         if (*i == redirect) {
942
943                                 RedirectList::iterator tmp;
944
945                                 /* move along, see failure case for reset_plugin_counts()
946                                    where we may need to reinsert the redirect.
947                                 */
948
949                                 tmp = i;
950                                 ++tmp;
951
952                                 /* stop redirects that send signals to JACK ports
953                                    from causing noise as a result of no longer being
954                                    run.
955                                 */
956
957                                 Send* send;
958                                 PortInsert* port_insert;
959                                 
960                                 if ((send = dynamic_cast<Send*> (*i)) != 0) {
961                                         send->disconnect_inputs (this);
962                                         send->disconnect_outputs (this);
963                                 } else if ((port_insert = dynamic_cast<PortInsert*> (*i)) != 0) {
964                                         port_insert->disconnect_inputs (this);
965                                         port_insert->disconnect_outputs (this);
966                                 }
967
968                                 _redirects.erase (i);
969
970                                 i = tmp;
971                                 removed = true;
972                                 break;
973                         }
974                 }
975
976                 if (!removed) {
977                         /* what? */
978                         return 1;
979                 }
980
981                 if (_reset_plugin_counts (err_streams)) {
982                         /* get back to where we where */
983                         _redirects.insert (i, redirect);
984                         /* we know this will work, because it worked before :) */
985                         _reset_plugin_counts (0);
986                         return -1;
987                 }
988
989                 bool foo = false;
990
991                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
992                         PluginInsert* pi;
993
994                         if ((pi = dynamic_cast<PluginInsert*>(*i)) != 0) {
995                                 if (pi->is_generator()) {
996                                         foo = true;
997                                 }
998                         }
999                 }
1000
1001                 _have_internal_generator = foo;
1002         }
1003
1004         if (old_rmo != redirect_max_outs) {
1005                 reset_panner ();
1006         }
1007
1008         redirects_changed (src); /* EMIT SIGNAL */
1009         return 0;
1010 }
1011
1012 int
1013 Route::reset_plugin_counts (uint32_t* lpc)
1014 {
1015         RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
1016         return _reset_plugin_counts (lpc);
1017 }
1018
1019
1020 int
1021 Route::_reset_plugin_counts (uint32_t* err_streams)
1022 {
1023         RedirectList::iterator r;
1024         uint32_t i_cnt;
1025         uint32_t s_cnt;
1026         map<Placement,list<InsertCount> > insert_map;
1027         jack_nframes_t initial_streams;
1028
1029         redirect_max_outs = 0;
1030         i_cnt = 0;
1031         s_cnt = 0;
1032
1033         /* divide inserts up by placement so we get the signal flow
1034            properly modelled. we need to do this because the _redirects
1035            list is not sorted by placement, and because other reasons may 
1036            exist now or in the future for this separate treatment.
1037         */
1038         
1039         for (r = _redirects.begin(); r != _redirects.end(); ++r) {
1040
1041                 Insert *insert;
1042
1043                 /* do this here in case we bomb out before we get to the end of
1044                    this function.
1045                 */
1046
1047                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1048
1049                 if ((insert = dynamic_cast<Insert*>(*r)) != 0) {
1050                         ++i_cnt;
1051                         insert_map[insert->placement()].push_back (InsertCount (*insert));
1052
1053                         /* reset plugin counts back to one for now so
1054                            that we have a predictable, controlled
1055                            state to try to configure.
1056                         */
1057
1058                         PluginInsert* pi;
1059                 
1060                         if ((pi = dynamic_cast<PluginInsert*>(insert)) != 0) {
1061                                 pi->set_count (1);
1062                         }
1063
1064                 } else if (dynamic_cast<Send*> (*r) != 0) {
1065                         ++s_cnt;
1066                 }
1067         }
1068         
1069         if (i_cnt == 0) {
1070                 if (s_cnt) {
1071                         goto recompute;
1072                 } else {
1073                         return 0;
1074                 }
1075         }
1076
1077         /* Now process each placement in order, checking to see if we 
1078            can really do what has been requested.
1079         */
1080
1081         /* A: PreFader */
1082         
1083         if (check_some_plugin_counts (insert_map[PreFader], n_inputs (), err_streams)) {
1084                 return -1;
1085         }
1086
1087         /* figure out the streams that will feed into PreFader */
1088
1089         if (!insert_map[PreFader].empty()) {
1090                 InsertCount& ic (insert_map[PreFader].back());
1091                 initial_streams = ic.insert.compute_output_streams (ic.cnt);
1092         } else {
1093                 initial_streams = n_inputs ();
1094         }
1095
1096         /* B: PostFader */
1097
1098         if (check_some_plugin_counts (insert_map[PostFader], initial_streams, err_streams)) {
1099                 return -1;
1100         }
1101
1102         /* OK, everything can be set up correctly, so lets do it */
1103
1104         apply_some_plugin_counts (insert_map[PreFader]);
1105         apply_some_plugin_counts (insert_map[PostFader]);
1106
1107         /* recompute max outs of any redirect */
1108
1109   recompute:
1110
1111         redirect_max_outs = 0;
1112         RedirectList::iterator prev = _redirects.end();
1113
1114         for (r = _redirects.begin(); r != _redirects.end(); prev = r, ++r) {
1115                 Send* s;
1116
1117                 if ((s = dynamic_cast<Send*> (*r)) != 0) {
1118                         if (r == _redirects.begin()) {
1119                                 s->expect_inputs (n_inputs());
1120                         } else {
1121                                 s->expect_inputs ((*prev)->output_streams());
1122                         }
1123                 }
1124
1125                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1126         }
1127
1128         /* we're done */
1129
1130         return 0;
1131 }                                  
1132
1133 int32_t
1134 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1135 {
1136         list<InsertCount>::iterator i;
1137
1138         for (i = iclist.begin(); i != iclist.end(); ++i) {
1139                 
1140                 if ((*i).insert.configure_io ((*i).cnt, (*i).in, (*i).out)) {
1141                         return -1;
1142                 }
1143                 /* make sure that however many we have, they are all active */
1144                 (*i).insert.activate ();
1145         }
1146
1147         return 0;
1148 }
1149
1150 int32_t
1151 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1152 {
1153         list<InsertCount>::iterator i;
1154         
1155         for (i = iclist.begin(); i != iclist.end(); ++i) {
1156
1157                 if (((*i).cnt = (*i).insert.can_support_input_configuration (required_inputs)) < 0) {
1158                         if (err_streams) {
1159                                 *err_streams = required_inputs;
1160                         }
1161                         return -1;
1162                 }
1163                 
1164                 (*i).in = required_inputs;
1165                 (*i).out = (*i).insert.compute_output_streams ((*i).cnt);
1166
1167                 required_inputs = (*i).out;
1168         }
1169
1170         return 0;
1171 }
1172
1173 int
1174 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1175 {
1176         uint32_t old_rmo = redirect_max_outs;
1177
1178         if (err_streams) {
1179                 *err_streams = 0;
1180         }
1181
1182         RedirectList to_be_deleted;
1183
1184         {
1185                 RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
1186                 RedirectList::iterator tmp;
1187                 RedirectList the_copy;
1188
1189                 the_copy = _redirects;
1190                 
1191                 /* remove all relevant redirects */
1192
1193                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1194                         tmp = i;
1195                         ++tmp;
1196
1197                         if ((*i)->placement() == placement) {
1198                                 to_be_deleted.push_back (*i);
1199                                 _redirects.erase (i);
1200                         }
1201
1202                         i = tmp;
1203                 }
1204
1205                 /* now copy the relevant ones from "other" */
1206                 
1207                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1208                         if ((*i)->placement() == placement) {
1209                                 _redirects.push_back (Redirect::clone (**i));
1210                         }
1211                 }
1212
1213                 /* reset plugin stream handling */
1214
1215                 if (_reset_plugin_counts (err_streams)) {
1216
1217                         /* FAILED COPY ATTEMPT: we have to restore order */
1218
1219                         /* delete all cloned redirects */
1220
1221                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1222
1223                                 tmp = i;
1224                                 ++tmp;
1225
1226                                 if ((*i)->placement() == placement) {
1227                                         delete *i;
1228                                         _redirects.erase (i);
1229                                 }
1230                                 
1231                                 i = tmp;
1232                         }
1233
1234                         /* restore the natural order */
1235
1236                         _redirects = the_copy;
1237                         redirect_max_outs = old_rmo;
1238
1239                         /* we failed, even though things are OK again */
1240
1241                         return -1;
1242
1243                 } else {
1244                         
1245                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1246
1247                         for (RedirectList::iterator i = to_be_deleted.begin(); i != to_be_deleted.end(); ++i) {
1248                                 delete *i;
1249                         }
1250                 }
1251         }
1252
1253         if (redirect_max_outs != old_rmo || old_rmo == 0) {
1254                 reset_panner ();
1255         }
1256
1257         redirects_changed (this); /* EMIT SIGNAL */
1258         return 0;
1259 }
1260
1261 void
1262 Route::all_redirects_flip ()
1263 {
1264         RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
1265
1266         if (_redirects.empty()) {
1267                 return;
1268         }
1269
1270         bool first_is_on = _redirects.front()->active();
1271         
1272         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1273                 (*i)->set_active (!first_is_on, this);
1274         }
1275 }
1276
1277 void
1278 Route::all_redirects_active (bool state)
1279 {
1280         RWLockMonitor lm (redirect_lock, false,  __LINE__, __FILE__);
1281
1282         if (_redirects.empty()) {
1283                 return;
1284         }
1285
1286         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1287                 (*i)->set_active (state, this);
1288         }
1289 }
1290
1291 struct RedirectSorter {
1292     bool operator() (const Redirect *a, const Redirect *b) {
1293             return a->sort_key() < b->sort_key();
1294     }
1295 };
1296
1297 int
1298 Route::sort_redirects (uint32_t* err_streams)
1299 {
1300         {
1301                 RedirectSorter comparator;
1302                 RWLockMonitor lm (redirect_lock, true, __LINE__, __FILE__);
1303                 uint32_t old_rmo = redirect_max_outs;
1304
1305                 /* the sweet power of C++ ... */
1306
1307                 RedirectList as_it_was_before = _redirects;
1308
1309                 _redirects.sort (comparator);
1310         
1311                 if (_reset_plugin_counts (err_streams)) {
1312                         _redirects = as_it_was_before;
1313                         redirect_max_outs = old_rmo;
1314                         return -1;
1315                 } 
1316         } 
1317
1318         reset_panner ();
1319         redirects_changed (this); /* EMIT SIGNAL */
1320
1321         return 0;
1322 }
1323
1324 XMLNode&
1325 Route::get_state()
1326 {
1327         return state(true);
1328 }
1329
1330 XMLNode&
1331 Route::get_template()
1332 {
1333         return state(false);
1334 }
1335
1336 XMLNode&
1337 Route::state(bool full_state)
1338 {
1339         XMLNode *node = new XMLNode("Route");
1340         XMLNode *aevents;
1341         RedirectList:: iterator i;
1342         char buf[32];
1343
1344         if (_flags) {
1345                 snprintf (buf, sizeof (buf), "0x%x", _flags);
1346                 node->add_property("flags", buf);
1347         }
1348         node->add_property("active", _active?"yes":"no");
1349         node->add_property("muted", _muted?"yes":"no");
1350         node->add_property("soloed", _soloed?"yes":"no");
1351         node->add_property("phase-invert", _phase_invert?"yes":"no");
1352         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1353         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1354         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1355         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1356
1357         if (_edit_group) {
1358                 node->add_property("edit-group", _edit_group->name());
1359         }
1360         if (_mix_group) {
1361                 node->add_property("mix-group", _mix_group->name());
1362         }
1363
1364         /* MIDI control */
1365
1366         MIDI::channel_t chn;
1367         MIDI::eventType ev;
1368         MIDI::byte      additional;
1369         XMLNode*        midi_node = 0;
1370         XMLNode*        child;
1371
1372         midi_node = node->add_child ("MIDI");
1373         
1374         if (_midi_mute_control.get_control_info (chn, ev, additional)) {
1375                 child = midi_node->add_child ("mute");
1376                 set_midi_node_info (child, ev, chn, additional);
1377         }
1378         if (_midi_solo_control.get_control_info (chn, ev, additional)) {
1379                 child = midi_node->add_child ("solo");
1380                 set_midi_node_info (child, ev, chn, additional);
1381         }
1382
1383         
1384         string order_string;
1385         OrderKeys::iterator x = order_keys.begin(); 
1386
1387         while (x != order_keys.end()) {
1388                 order_string += (*x).first;
1389                 order_string += '=';
1390                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1391                 order_string += buf;
1392                 
1393                 ++x;
1394
1395                 if (x == order_keys.end()) {
1396                         break;
1397                 }
1398
1399                 order_string += ':';
1400         }
1401         node->add_property ("order-keys", order_string);
1402
1403         node->add_child_nocopy (IO::state (full_state));
1404
1405         if (_control_outs) {
1406                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1407                 cnode->add_child_nocopy (_control_outs->state (full_state));
1408                 node->add_child_nocopy (*cnode);
1409         }
1410
1411         if (_comment.length()) {
1412                 XMLNode *cmt = node->add_child ("Comment");
1413                 cmt->add_content (_comment);
1414         }
1415
1416         if (full_state) {
1417                 string path;
1418
1419                 path = _session.snap_name();
1420                 path += "-gain-";
1421                 path += legalize_for_path (_name);
1422                 path += ".automation";
1423
1424                 /* XXX we didn't ask for a state save, we asked for the current state.
1425                    FIX ME!
1426                 */
1427
1428                 if (save_automation (path)) {
1429                         error << _("Could not get state of route.  Problem with save_automation") << endmsg;
1430                 }
1431
1432                 aevents = node->add_child ("Automation");
1433                 aevents->add_property ("path", path);
1434         }       
1435
1436         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1437                 node->add_child_nocopy((*i)->state (full_state));
1438         }
1439
1440         if (_extra_xml){
1441                 node->add_child_copy (*_extra_xml);
1442         }
1443         
1444         return *node;
1445 }
1446
1447 void
1448 Route::set_deferred_state ()
1449 {
1450         XMLNodeList nlist;
1451         XMLNodeConstIterator niter;
1452
1453         if (!deferred_state) {
1454                 return;
1455         }
1456
1457         nlist = deferred_state->children();
1458
1459         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1460                 add_redirect_from_xml (**niter);
1461         }
1462
1463         delete deferred_state;
1464         deferred_state = 0;
1465 }
1466
1467 void
1468 Route::add_redirect_from_xml (const XMLNode& node)
1469 {
1470         const XMLProperty *prop;
1471         Insert *insert = 0;
1472         Send *send = 0;
1473
1474         if (node.name() == "Send") {
1475                 
1476                 try {
1477                         send = new Send (_session, node);
1478                 } 
1479                 
1480                 catch (failed_constructor &err) {
1481                         error << _("Send construction failed") << endmsg;
1482                         return;
1483                 }
1484                 
1485                 add_redirect (send, this);
1486                 
1487         } else if (node.name() == "Insert") {
1488                 
1489                 try {
1490                         if ((prop = node.property ("type")) != 0) {
1491
1492                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1493
1494                                         insert = new PluginInsert(_session, node);
1495                                         
1496                                 } else if (prop->value() == "port") {
1497
1498
1499                                         insert = new PortInsert (_session, node);
1500
1501                                 } else {
1502
1503                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1504                                 }
1505
1506                                 add_redirect (insert, this);
1507                                 
1508                         } else {
1509                                 error << _("Insert XML node has no type property") << endmsg;
1510                         }
1511                 }
1512                 
1513                 catch (failed_constructor &err) {
1514                         warning << _("insert could not be created. Ignored.") << endmsg;
1515                         return;
1516                 }
1517         }
1518 }
1519
1520 int
1521 Route::set_state (const XMLNode& node)
1522 {
1523         XMLNodeList nlist;
1524         XMLNodeConstIterator niter;
1525         XMLNode *child;
1526         XMLPropertyList plist;
1527         const XMLProperty *prop;
1528         XMLNodeList midi_kids;
1529
1530
1531         if (node.name() != "Route"){
1532                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1533                 return -1;
1534         }
1535
1536         if ((prop = node.property ("flags")) != 0) {
1537                 int x;
1538                 sscanf (prop->value().c_str(), "0x%x", &x);
1539                 _flags = Flag (x);
1540         } else {
1541                 _flags = Flag (0);
1542         }
1543
1544         if ((prop = node.property ("phase-invert")) != 0) {
1545                 set_phase_invert(prop->value()=="yes"?true:false, this);
1546         }
1547
1548         if ((prop = node.property ("active")) != 0) {
1549                 set_active (prop->value() == "yes");
1550         }
1551
1552         if ((prop = node.property ("muted")) != 0) {
1553                 bool yn = prop->value()=="yes"?true:false; 
1554
1555                 /* force reset of mute status */
1556
1557                 _muted = !yn;
1558                 set_mute(yn, this);
1559                 mute_gain = desired_mute_gain;
1560         }
1561
1562         if ((prop = node.property ("soloed")) != 0) {
1563                 bool yn = prop->value()=="yes"?true:false; 
1564
1565                 /* force reset of solo status */
1566
1567                 _soloed = !yn;
1568                 set_solo (yn, this);
1569                 solo_gain = desired_solo_gain;
1570         }
1571
1572         if ((prop = node.property ("mute-affects-pre-fader")) != 0) {
1573                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1574         }
1575
1576         if ((prop = node.property ("mute-affects-post-fader")) != 0) {
1577                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1578         }
1579
1580         if ((prop = node.property ("mute-affects-control-outs")) != 0) {
1581                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1582         }
1583
1584         if ((prop = node.property ("mute-affects-main-outs")) != 0) {
1585                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1586         }
1587
1588         if ((prop = node.property ("edit-group")) != 0) {
1589                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1590                 if(edit_group == 0) {
1591                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1592                 } else {
1593                         set_edit_group(edit_group, this);
1594                 }
1595         }
1596
1597         if ((prop = node.property ("order-keys")) != 0) {
1598
1599                 long n;
1600
1601                 string::size_type colon, equal;
1602                 string remaining = prop->value();
1603
1604                 while (remaining.length()) {
1605
1606                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1607                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1608                                       << endmsg;
1609                         } else {
1610                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1611                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1612                                               << endmsg;
1613                                 } else {
1614                                         set_order_key (remaining.substr (0, equal), n);
1615                                 }
1616                         }
1617
1618                         colon = remaining.find_first_of (':');
1619
1620                         if (colon != string::npos) {
1621                                 remaining = remaining.substr (colon+1);
1622                         } else {
1623                                 break;
1624                         }
1625                 }
1626         }
1627
1628         nlist = node.children();
1629
1630         if (deferred_state) {
1631                 delete deferred_state;
1632         }
1633
1634         deferred_state = new XMLNode("deferred state");
1635
1636         /* set parent class properties before anything else */
1637
1638         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1639
1640                 child = *niter;
1641
1642                 if (child->name() == IO::state_node_name) {
1643
1644                         IO::set_state (*child);
1645                         break;
1646                 }
1647         }
1648                         
1649         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1650
1651                 child = *niter;
1652                         
1653                 if (child->name() == "Send") {
1654
1655
1656                         if (!IO::ports_legal) {
1657
1658                                 deferred_state->add_child_copy (*child);
1659
1660                         } else {
1661                                 add_redirect_from_xml (*child);
1662                         }
1663
1664                 } else if (child->name() == "Insert") {
1665                         
1666                         if (!IO::ports_legal) {
1667                                 
1668                                 deferred_state->add_child_copy (*child);
1669
1670                         } else {
1671                                 
1672                                 add_redirect_from_xml (*child);
1673                         }
1674
1675                 } else if (child->name() == "Automation") {
1676
1677                         XMLPropertyList plist;
1678                         XMLPropertyConstIterator piter;
1679                         XMLProperty *prop;
1680                         
1681                         plist = child->properties();
1682                         for (piter = plist.begin(); piter != plist.end(); ++piter) {
1683                                 prop = *piter;
1684                                 if (prop->name() == "path") {
1685                                         load_automation (prop->value());
1686                                 }
1687                         }
1688
1689                 } else if (child->name() == "ControlOuts") {
1690                         
1691                         string coutname = _name;
1692                         coutname += _("[control]");
1693
1694                         _control_outs = new IO (_session, coutname);
1695                         _control_outs->set_state (**(child->children().begin()));
1696
1697                 } else if (child->name() == "Comment") {
1698
1699                         /* XXX this is a terrible API design in libxml++ */
1700
1701                         XMLNode *cmt = *(child->children().begin());
1702                         _comment = cmt->content();
1703
1704                 } else if (child->name() == "extra") {
1705                         _extra_xml = new XMLNode (*child);
1706                 }
1707         }
1708
1709         if ((prop = node.property ("mix-group")) != 0) {
1710                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1711                 if (mix_group == 0) {
1712                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1713                 }  else {
1714                         set_mix_group(mix_group, this);
1715                 }
1716         }
1717
1718         midi_kids = node.children ("MIDI");
1719         
1720         for (niter = midi_kids.begin(); niter != midi_kids.end(); ++niter) {
1721         
1722                 XMLNodeList kids;
1723                 XMLNodeConstIterator miter;
1724                 XMLNode*    child;
1725
1726                 kids = (*niter)->children ();
1727
1728                 for (miter = kids.begin(); miter != kids.end(); ++miter) {
1729
1730                         child =* miter;
1731
1732                         MIDI::eventType ev = MIDI::on; /* initialize to keep gcc happy */
1733                         MIDI::byte additional = 0;  /* ditto */
1734                         MIDI::channel_t chn = 0;    /* ditto */
1735                         
1736                         if (child->name() == "mute") {
1737                         
1738                                 if (get_midi_node_info (child, ev, chn, additional)) {
1739                                         _midi_mute_control.set_control_type (chn, ev, additional);
1740                                 } else {
1741                                         error << string_compose(_("MIDI mute control specification for %1 is incomplete, so it has been ignored"), _name) << endmsg;
1742                                 }
1743                         }
1744                         else if (child->name() == "solo") {
1745                         
1746                                 if (get_midi_node_info (child, ev, chn, additional)) {
1747                                         _midi_solo_control.set_control_type (chn, ev, additional);
1748                                 } else {
1749                                         error << string_compose(_("MIDI mute control specification for %1 is incomplete, so it has been ignored"), _name) << endmsg;
1750                                 }
1751                         }
1752
1753                 }
1754         }
1755
1756         
1757         return 0;
1758 }
1759
1760 void
1761 Route::curve_reallocate ()
1762 {
1763 //      _gain_automation_curve.finish_resize ();
1764 //      _pan_automation_curve.finish_resize ();
1765 }
1766
1767 void
1768 Route::silence (jack_nframes_t nframes, jack_nframes_t offset)
1769 {
1770         if (!_silent) {
1771
1772                 // reset_peak_meters ();
1773                 
1774                 IO::silence (nframes, offset);
1775
1776                 if (_control_outs) {
1777                         _control_outs->silence (nframes, offset);
1778                 }
1779
1780                 { 
1781                         TentativeRWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
1782                         
1783                         if (lm.locked()) {
1784                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1785                                         PluginInsert* pi;
1786                                         if (!_active && (pi = dynamic_cast<PluginInsert*> (*i)) != 0) {
1787                                                 // skip plugins, they don't need anything when we're not active
1788                                                 continue;
1789                                         }
1790
1791                                         (*i)->silence (nframes, offset);
1792                                 }
1793
1794                                 if (nframes == _session.get_block_size() && offset == 0) {
1795                                         // _silent = true;
1796                                 }
1797                         }
1798                 }
1799                 
1800         }
1801 }       
1802
1803 int
1804 Route::set_control_outs (const vector<string>& ports)
1805 {
1806         LockMonitor lm (control_outs_lock, __LINE__, __FILE__);
1807         vector<string>::const_iterator i;
1808
1809         if (_control_outs) {
1810                 delete _control_outs;
1811                 _control_outs = 0;
1812         }
1813         
1814         if (ports.empty()) {
1815                 return 0;
1816         }
1817  
1818         string coutname = _name;
1819         coutname += _("[control]");
1820         
1821         _control_outs = new IO (_session, coutname);
1822
1823         /* our control outs need as many outputs as we
1824            have outputs. we track the changes in ::output_change_handler().
1825         */
1826
1827         _control_outs->ensure_io (0, n_outputs(), true, this);
1828  
1829         return 0;
1830 }       
1831
1832 void
1833 Route::set_edit_group (RouteGroup *eg, void *src)
1834
1835 {
1836         if (_edit_group) {
1837                 _edit_group->remove (this);
1838         }
1839
1840         if ((_edit_group = eg)) {
1841                 _edit_group->add (this);
1842         }
1843
1844         _session.set_dirty ();
1845
1846         edit_group_changed (src); /* EMIT SIGNAL */
1847 }
1848
1849 void
1850 Route::set_mix_group (RouteGroup *mg, void *src)
1851
1852 {
1853         if (_mix_group) {
1854                 _mix_group->remove (this);
1855         }
1856
1857         if ((_mix_group = mg)) {
1858                 _mix_group->add (this);
1859         }
1860
1861         _session.set_dirty ();
1862         
1863         mix_group_changed (src); /* EMIT SIGNAL */
1864 }
1865
1866 void
1867 Route::set_comment (string cmt, void *src)
1868 {
1869         _comment = cmt;
1870         comment_changed (src);
1871         _session.set_dirty ();
1872 }
1873
1874 bool
1875 Route::feeds (Route *o)
1876 {
1877         uint32_t i, j;
1878
1879         IO& other = *o;
1880         IO& self = *this;
1881         uint32_t no = self.n_outputs();
1882         uint32_t ni = other.n_inputs ();
1883
1884         for (i = 0; i < no; ++i) {
1885                 for (j = 0; j < ni; ++j) {
1886                         if (self.output(i)->connected_to (other.input(j)->name())) {
1887                                 return true;
1888                         }
1889                 }
1890         }
1891
1892         /* check Redirects which may also interconnect Routes */
1893
1894         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1895
1896                 no = (*r)->n_outputs();
1897
1898                 for (i = 0; i < no; ++i) {
1899                         for (j = 0; j < ni; ++j) {
1900                                 if ((*r)->output(i)->connected_to (other.input (j)->name())) {
1901                                         return true;
1902                                 }
1903                         }
1904                 }
1905         }
1906
1907         /* check for control room outputs which may also interconnect Routes */
1908
1909         if (_control_outs) {
1910
1911                 no = _control_outs->n_outputs();
1912                 
1913                 for (i = 0; i < no; ++i) {
1914                         for (j = 0; j < ni; ++j) {
1915                                 if (_control_outs->output(i)->connected_to (other.input (j)->name())) {
1916                                         return true;
1917                                 }
1918                         }
1919                 }
1920         }
1921
1922         return false;
1923 }
1924
1925 void
1926 Route::set_mute_config (mute_type t, bool onoff, void *src)
1927 {
1928         switch (t) {
1929         case PRE_FADER:
1930                 _mute_affects_pre_fader = onoff;
1931                  pre_fader_changed(src); /* EMIT SIGNAL */
1932                 break;
1933
1934         case POST_FADER:
1935                 _mute_affects_post_fader = onoff;
1936                  post_fader_changed(src); /* EMIT SIGNAL */
1937                 break;
1938
1939         case CONTROL_OUTS:
1940                 _mute_affects_control_outs = onoff;
1941                  control_outs_changed(src); /* EMIT SIGNAL */
1942                 break;
1943
1944         case MAIN_OUTS:
1945                 _mute_affects_main_outs = onoff;
1946                  main_outs_changed(src); /* EMIT SIGNAL */
1947                 break;
1948         }
1949 }
1950
1951 bool
1952 Route::get_mute_config (mute_type t)
1953 {
1954         bool onoff = false;
1955         
1956         switch (t){
1957         case PRE_FADER:
1958                 onoff = _mute_affects_pre_fader; 
1959                 break;
1960         case POST_FADER:
1961                 onoff = _mute_affects_post_fader;
1962                 break;
1963         case CONTROL_OUTS:
1964                 onoff = _mute_affects_control_outs;
1965                 break;
1966         case MAIN_OUTS:
1967                 onoff = _mute_affects_main_outs;
1968                 break;
1969         }
1970         
1971         return onoff;
1972 }
1973
1974 void
1975 Route::set_active (bool yn)
1976 {
1977         _active = yn; 
1978          active_changed(); /* EMIT SIGNAL */
1979 }
1980
1981 void
1982 Route::transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1983 {
1984         jack_nframes_t now = _session.transport_frame();
1985
1986         {
1987                 RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
1988
1989                 if (!did_locate) {
1990                         automation_snapshot (now);
1991                 }
1992
1993                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1994                         
1995                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1996                                 (*i)->deactivate ();
1997                                 (*i)->activate ();
1998                         }
1999                         
2000                         (*i)->transport_stopped (now);
2001                 }
2002         }
2003
2004         IO::transport_stopped (now);
2005  
2006         _roll_delay = _initial_delay;
2007 }
2008
2009 UndoAction
2010 Route::get_memento() const
2011 {
2012         void (Route::*pmf)(state_id_t) = &Route::set_state;
2013         return sigc::bind (mem_fun (*(const_cast<Route *>(this)), pmf), _current_state_id);
2014 }
2015
2016 void
2017 Route::set_state (state_id_t id)
2018 {
2019         return;
2020 }
2021
2022 void
2023 Route::input_change_handler (IOChange change, void *ignored)
2024 {
2025         if (change & ConfigurationChanged) {
2026                 reset_plugin_counts (0);
2027         }
2028 }
2029
2030 void
2031 Route::output_change_handler (IOChange change, void *ignored)
2032 {
2033         if (change & ConfigurationChanged) {
2034                 if (_control_outs) {
2035                         _control_outs->ensure_io (0, n_outputs(), true, this);
2036                 }
2037                 
2038                 reset_plugin_counts (0);
2039         }
2040 }
2041
2042 uint32_t
2043 Route::pans_required () const
2044 {
2045         if (n_outputs() < 2) {
2046                 return 0;
2047         }
2048         
2049         return max (n_inputs (), redirect_max_outs);
2050 }
2051
2052 int 
2053 Route::no_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2054                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2055 {
2056         if (n_outputs() == 0) {
2057                 return 0;
2058         }
2059
2060         if (session_state_changing || !_active)  {
2061                 silence (nframes, offset);
2062                 return 0;
2063         }
2064
2065         apply_gain_automation = false;
2066         
2067         if (n_inputs()) {
2068                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2069         } else {
2070                 silence (nframes, offset);
2071         }
2072
2073         return 0;
2074 }
2075
2076 jack_nframes_t
2077 Route::check_initial_delay (jack_nframes_t nframes, jack_nframes_t& offset, jack_nframes_t& transport_frame)
2078 {
2079         if (_roll_delay > nframes) {
2080
2081                 _roll_delay -= nframes;
2082                 silence (nframes, offset);
2083                 /* transport frame is not legal for caller to use */
2084                 return 0;
2085
2086         } else if (_roll_delay > 0) {
2087
2088                 nframes -= _roll_delay;
2089
2090                 silence (_roll_delay, offset);
2091
2092                 offset += _roll_delay;
2093                 transport_frame += _roll_delay;
2094
2095                 _roll_delay = 0;
2096         }
2097
2098         return nframes;
2099 }
2100
2101 int
2102 Route::roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, int declick,
2103              bool can_record, bool rec_monitors_input)
2104 {
2105         {
2106                 TentativeRWLockMonitor lm(redirect_lock, false, __LINE__, __FILE__);
2107                 if (lm.locked()) {
2108                         // automation snapshot can also be called from the non-rt context
2109                         // and it uses the redirect list, so we take the lock out here
2110                         automation_snapshot (_session.transport_frame());
2111                 }
2112         }
2113                 
2114         if ((n_outputs() == 0 && _redirects.empty()) || n_inputs() == 0 || !_active) {
2115                 silence (nframes, offset);
2116                 return 0;
2117         }
2118         
2119         jack_nframes_t unused = 0;
2120
2121         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2122                 return 0;
2123         }
2124
2125         _silent = false;
2126
2127         apply_gain_automation = false;
2128
2129         { 
2130                 TentativeLockMonitor am (automation_lock, __LINE__, __FILE__);
2131                 
2132                 if (am.locked() && _session.transport_rolling()) {
2133                         
2134                         jack_nframes_t start_frame = end_frame - nframes;
2135                         
2136                         if (gain_automation_playback()) {
2137                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2138                         }
2139                 }
2140         }
2141
2142         passthru (start_frame, end_frame, nframes, offset, declick, false);
2143
2144         return 0;
2145 }
2146
2147 int
2148 Route::silent_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2149                     bool can_record, bool rec_monitors_input)
2150 {
2151         silence (nframes, offset);
2152         return 0;
2153 }
2154
2155 void
2156 Route::toggle_monitor_input ()
2157 {
2158         for (vector<Port*>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2159                 (*i)->request_monitor_input(!(*i)->monitoring_input());
2160         }
2161 }
2162
2163 bool
2164 Route::has_external_redirects () const
2165 {
2166         const PortInsert* pi;
2167         
2168         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2169                 if ((pi = dynamic_cast<const PortInsert*>(*i)) != 0) {
2170
2171                         uint32_t no = pi->n_outputs();
2172
2173                         for (uint32_t n = 0; n < no; ++n) {
2174                                 
2175                                 string port_name = pi->output(n)->name();
2176                                 string client_name = port_name.substr (0, port_name.find(':'));
2177
2178                                 /* only say "yes" if the redirect is actually in use */
2179                                 
2180                                 if (client_name != "ardour" && pi->active()) {
2181                                         return true;
2182                                 }
2183                         }
2184                 }
2185         }
2186
2187         return false;
2188 }
2189
2190 void
2191 Route::reset_midi_control (MIDI::Port* port, bool on)
2192 {
2193         MIDI::channel_t chn;
2194         MIDI::eventType ev;
2195         MIDI::byte extra;
2196
2197         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2198                         (*i)->reset_midi_control (port, on);
2199         }
2200
2201         IO::reset_midi_control (port, on);
2202         
2203         _midi_solo_control.get_control_info (chn, ev, extra);
2204         if (!on) {
2205                 chn = -1;
2206         }
2207         _midi_solo_control.midi_rebind (port, chn);
2208         
2209         _midi_mute_control.get_control_info (chn, ev, extra);
2210         if (!on) {
2211                 chn = -1;
2212         }
2213         _midi_mute_control.midi_rebind (port, chn);
2214 }
2215
2216 void
2217 Route::send_all_midi_feedback ()
2218 {
2219         if (_session.get_midi_feedback()) {
2220
2221                 {
2222                         RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
2223                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2224                                 (*i)->send_all_midi_feedback ();
2225                         }
2226                 }
2227
2228                 IO::send_all_midi_feedback();
2229
2230                 _midi_solo_control.send_feedback (_soloed);
2231                 _midi_mute_control.send_feedback (_muted);
2232         }
2233 }
2234
2235 MIDI::byte*
2236 Route::write_midi_feedback (MIDI::byte* buf, int32_t& bufsize)
2237 {
2238         buf = _midi_solo_control.write_feedback (buf, bufsize, _soloed);
2239         buf = _midi_mute_control.write_feedback (buf, bufsize, _muted);
2240
2241         {
2242                 RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
2243                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2244                         buf = (*i)->write_midi_feedback (buf, bufsize);
2245                 }
2246         }
2247
2248         return IO::write_midi_feedback (buf, bufsize);
2249 }
2250
2251 void
2252 Route::flush_redirects ()
2253 {
2254         /* XXX shouldn't really try to take this lock, since
2255            this is called from the RT audio thread.
2256         */
2257
2258         RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
2259
2260         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2261                 (*i)->deactivate ();
2262                 (*i)->activate ();
2263         }
2264 }
2265
2266 void
2267 Route::set_meter_point (MeterPoint p, void *src)
2268 {
2269         if (_meter_point != p) {
2270                 _meter_point = p;
2271                  meter_change (src); /* EMIT SIGNAL */
2272                 _session.set_dirty ();
2273         }
2274 }
2275
2276 jack_nframes_t
2277 Route::update_total_latency ()
2278 {
2279         _own_latency = 0;
2280
2281         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2282                 if ((*i)->active ()) {
2283                         _own_latency += (*i)->latency ();
2284                 }
2285         }
2286
2287         set_port_latency (_own_latency);
2288
2289         /* this (virtual) function is used for pure Routes,
2290            not derived classes like AudioTrack.  this means
2291            that the data processed here comes from an input
2292            port, not prerecorded material, and therefore we
2293            have to take into account any input latency.
2294         */
2295
2296         _own_latency += input_latency ();
2297
2298         return _own_latency;
2299 }
2300
2301 void
2302 Route::set_latency_delay (jack_nframes_t longest_session_latency)
2303 {
2304         _initial_delay = longest_session_latency - _own_latency;
2305
2306         if (_session.transport_stopped()) {
2307                 _roll_delay = _initial_delay;
2308         }
2309 }
2310
2311 void
2312 Route::automation_snapshot (jack_nframes_t now)
2313 {
2314         IO::automation_snapshot (now);
2315
2316         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2317                 (*i)->automation_snapshot (now);
2318         }
2319 }
2320
2321 Route::MIDIToggleControl::MIDIToggleControl (Route& s, ToggleType tp, MIDI::Port* port)
2322         : MIDI::Controllable (port, true), route (s), type(tp), setting(false)
2323 {
2324         last_written = false; /* XXX need a good out-of-bound-value */
2325 }
2326
2327 void
2328 Route::MIDIToggleControl::set_value (float val)
2329 {
2330         MIDI::eventType et;
2331         MIDI::channel_t chn;
2332         MIDI::byte additional;
2333
2334         get_control_info (chn, et, additional);
2335
2336         setting = true;
2337
2338 #ifdef HOLD_TOGGLE_VALUES
2339         if (et == MIDI::off || et == MIDI::on) {
2340
2341                 /* literal toggle */
2342
2343                 switch (type) {
2344                 case MuteControl:
2345                         route.set_mute (!route.muted(), this);
2346                         break;
2347                 case SoloControl:
2348                         route.set_solo (!route.soloed(), this);
2349                         break;
2350                 default:
2351                         break;
2352                 }
2353
2354         } else {
2355 #endif
2356
2357                 /* map full control range to a boolean */
2358
2359                 bool bval = ((val >= 0.5f) ? true: false);
2360                 
2361                 switch (type) {
2362                 case MuteControl:
2363                         route.set_mute (bval, this);
2364                         break;
2365                 case SoloControl:
2366                         route.set_solo (bval, this);
2367                         break;
2368                 default:
2369                         break;
2370                 }
2371
2372 #ifdef HOLD_TOGGLE_VALUES
2373         }
2374 #endif
2375
2376         setting = false;
2377 }
2378
2379 void
2380 Route::MIDIToggleControl::send_feedback (bool value)
2381 {
2382
2383         if (!setting && get_midi_feedback()) {
2384                 MIDI::byte val = (MIDI::byte) (value ? 127: 0);
2385                 MIDI::channel_t ch = 0;
2386                 MIDI::eventType ev = MIDI::none;
2387                 MIDI::byte additional = 0;
2388                 MIDI::EventTwoBytes data;
2389             
2390                 if (get_control_info (ch, ev, additional)) {
2391                         data.controller_number = additional;
2392                         data.value = val;
2393                         last_written = value;
2394                         
2395                         route._session.send_midi_message (get_port(), ev, ch, data);
2396                 }
2397         }
2398         
2399 }
2400
2401 MIDI::byte*
2402 Route::MIDIToggleControl::write_feedback (MIDI::byte* buf, int32_t& bufsize, bool val, bool force)
2403 {
2404         if (get_midi_feedback() && bufsize > 2) {
2405                 MIDI::channel_t ch = 0;
2406                 MIDI::eventType ev = MIDI::none;
2407                 MIDI::byte additional = 0;
2408
2409                 if (get_control_info (ch, ev, additional)) {
2410                         if (val != last_written || force) {
2411                                 *buf++ = (0xF0 & ev) | (0xF & ch);
2412                                 *buf++ = additional; /* controller number */
2413                                 *buf++ = (MIDI::byte) (val ? 127 : 0);
2414                                 bufsize -= 3;
2415                                 last_written = val;
2416                         }
2417                 }
2418         }
2419
2420         return buf;
2421 }
2422
2423 void 
2424 Route::set_block_size (jack_nframes_t nframes)
2425 {
2426         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2427                 (*i)->set_block_size (nframes);
2428         }
2429 }
2430
2431 void
2432 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2433 {
2434         _session.update_latency_compensation (false, false);
2435 }
2436
2437 void
2438 Route::protect_automation ()
2439 {
2440         switch (gain_automation_state()) {
2441         case Write:
2442         case Touch:
2443                 set_gain_automation_state (Off);
2444                 break;
2445         default:
2446                 break;
2447         }
2448
2449         switch (panner().automation_state ()) {
2450         case Write:
2451         case Touch:
2452                 panner().set_automation_state (Off);
2453                 break;
2454         default:
2455                 break;
2456         }
2457         
2458         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2459                 PluginInsert* pi;
2460                 if ((pi = dynamic_cast<PluginInsert*> (*i)) != 0) {
2461                         pi->protect_automation ();
2462                 }
2463         }
2464 }
2465
2466 void
2467 Route::set_pending_declick (int declick)
2468 {
2469         if (_declickable) {
2470                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2471                 if (declick) {
2472                         _pending_declick = declick;
2473                 }
2474                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2475         } else {
2476                 _pending_declick = 0;
2477         }
2478
2479 }