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