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