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