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