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