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