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