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