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