a gadzillion changes all over the place. nothing is finished, but all is better than...
[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         cerr << "Adding a processor called " << processor->name() << endl;
656
657         {
658                 Glib::RWLock::WriterLock lm (_processor_lock);
659
660                 boost::shared_ptr<PluginInsert> pi;
661                 boost::shared_ptr<PortInsert> porti;
662
663                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
664
665                 if (processor == _amp || processor == _meter || processor == _main_outs) {
666                         // Ensure only one of these are in the list at any time
667                         if (loc != _processors.end()) {
668                                 if (iter == loc) { // Already in place, do nothing
669                                         return 0;
670                                 } else { // New position given, relocate
671                                         _processors.erase (loc);
672                                 }
673                         }
674
675                 } else {
676                         if (loc != _processors.end()) {
677                                 cerr << "ERROR: Processor added to route twice!" << endl;
678                                 return 1;
679                         }
680
681                         loc = iter;
682                 }
683
684                 cerr << "Adding " << processor->name() << endl;
685
686                 _processors.insert (loc, processor);
687
688                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
689                 // configure redirect ports properly, etc.
690                 
691                 ProcessorStreams rerr;
692
693                 if (configure_processors_unlocked (&rerr)) {
694                         
695                         dump_processors(_name + "bad config", _processors);
696                         if (err) {
697                                 *err = rerr;
698                         }
699                         cerr << "Error at proc " << rerr.index << " with input of " << rerr.count << endl;
700                         ProcessorList::iterator ploc = loc;
701                         --ploc;
702                         _processors.erase(ploc);
703                         configure_processors_unlocked (0); // it worked before we tried to add it ...
704                         cerr << "Bad IO config\n";
705                         return -1;
706                 }
707         
708                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
709                         
710                         if (pi->natural_input_streams() == ChanCount::ZERO) {
711                                 /* generator plugin */
712                                 _have_internal_generator = true;
713                         }
714                         
715                 }
716                 
717                 // Ensure peak vector sizes before the plugin is activated
718                 ChanCount potential_max_streams = ChanCount::max (processor->input_streams(), processor->output_streams());
719
720                 _meter->configure_io (potential_max_streams, potential_max_streams);
721
722                 // XXX: do we want to emit the signal here ? change call order.
723                 processor->activate ();
724                 processor->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
725
726                 _user_latency = 0;
727         }
728         
729         if (processor_max_streams != old_pms || old_pms == ChanCount::ZERO) {
730                 reset_panner ();
731         }
732
733         dump_processors (_name + " added one", _processors);
734         processors_changed (); /* EMIT SIGNAL */
735         
736         return 0;
737 }
738
739 bool
740 Route::add_processor_from_xml (const XMLNode& node, Placement placement)
741 {
742         ProcessorList::iterator loc;
743         if (placement == PreFader) {
744                 /* generic pre-fader: insert immediately before the amp */
745                 loc = find(_processors.begin(), _processors.end(), _amp);
746         } else {
747                 /* generic post-fader: insert at end */
748                 loc = _processors.end();
749         }
750
751         return add_processor_from_xml (node, loc);
752 }
753
754 bool
755 Route::add_processor_from_xml (const XMLNode& node, ProcessorList::iterator iter)
756 {
757         const XMLProperty *prop;
758
759         // legacy sessions use a different node name for sends
760         if (node.name() == "Send") {
761         
762                 try {
763                         boost::shared_ptr<Send> send (new Send (_session, node));
764                         add_processor (send, iter); 
765                         return true;
766                 } 
767                 
768                 catch (failed_constructor &err) {
769                         error << _("Send construction failed") << endmsg;
770                         return false;
771                 }
772                 
773         } else if (node.name() == "Processor") {
774                 
775                 try {
776                         if ((prop = node.property ("type")) != 0) {
777
778                                 boost::shared_ptr<Processor> processor;
779                                 bool have_insert = false;
780
781                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
782                                     prop->value() == "lv2" ||
783                                     prop->value() == "vst" ||
784                                     prop->value() == "audiounit") {
785                                         
786                                         processor.reset (new PluginInsert(_session, node));
787                                         have_insert = true;
788                                         
789                                 } else if (prop->value() == "port") {
790
791                                         processor.reset (new PortInsert (_session, node));
792                                 
793                                 } else if (prop->value() == "send") {
794
795                                         processor.reset (new Send (_session, node));
796                                         have_insert = true;
797                                 
798                                 } else if (prop->value() == "meter") {
799
800                                         processor = _meter;
801                                 
802                                 } else if (prop->value() == "amp") {
803                                         
804                                         processor = _amp;
805                                         
806                                 } else if (prop->value() == "listen" || prop->value() == "deliver") {
807
808                                         /* XXX need to generalize */
809
810                                         processor = _control_outs;
811                                         
812                                 } else if (prop->value() == "main-outs") {
813                                         
814                                         processor = _main_outs;
815                                         
816                                 } else {
817
818                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
819                                 }
820                                 
821                                 if (iter == _processors.end() && processor->visible() && !_processors.empty()) {
822                                         /* check for invisible processors stacked at the end and leave them there */
823                                         ProcessorList::iterator p;
824                                         p = _processors.end();
825                                         --p;
826                                         cerr << "Let's check " << (*p)->name() << " vis ? " << (*p)->visible() << endl;
827                                         while (!(*p)->visible() && p != _processors.begin()) {
828                                                 --p;
829                                         }
830                                         ++p;
831                                         iter = p;
832                                 }
833
834                                 return (add_processor (processor, iter) == 0);
835                                 
836                         } else {
837                                 error << _("Processor XML node has no type property") << endmsg;
838                         }
839                 }
840
841                 catch (failed_constructor &err) {
842                         warning << _("processor could not be created. Ignored.") << endmsg;
843                         return false;
844                 }
845         }
846         return false;
847 }
848
849 int
850 Route::add_processors (const ProcessorList& others, Placement placement, ProcessorStreams* err)
851 {
852         ProcessorList::iterator loc;
853         if (placement == PreFader) {
854                 /* generic pre-fader: insert immediately before the amp */
855                 loc = find(_processors.begin(), _processors.end(), _amp);
856         } else {
857                 /* generic post-fader: insert at end */
858                 loc = _processors.end();
859
860                 if (!_processors.empty()) {
861                         /* check for invisible processors stacked at the end and leave them there */
862                         ProcessorList::iterator p;
863                         p = _processors.end();
864                         --p;
865                         cerr << "Let's check " << (*p)->name() << " vis ? " << (*p)->visible() << endl;
866                         while (!(*p)->visible() && p != _processors.begin()) {
867                                 --p;
868                         }
869                         ++p;
870                         loc = p;
871                 }
872         }
873
874         return add_processors (others, loc, err);
875 }
876
877 int
878 Route::add_processors (const ProcessorList& others, ProcessorList::iterator iter, ProcessorStreams* err)
879 {
880         /* NOTE: this is intended to be used ONLY when copying
881            processors from another Route. Hence the subtle
882            differences between this and ::add_processor()
883         */
884
885         ChanCount old_pms = processor_max_streams;
886
887         if (!_session.engine().connected()) {
888                 return 1;
889         }
890
891         if (others.empty()) {
892                 return 0;
893         }
894
895         {
896                 Glib::RWLock::WriterLock lm (_processor_lock);
897                 ProcessorList::iterator existing_end = _processors.end();
898                 --existing_end;
899
900                 ChanCount potential_max_streams = ChanCount::max (n_inputs(), n_outputs());
901
902                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
903                         
904                         // Ensure meter only appears in the list once
905                         if (*i == _meter) {
906                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
907                                 if (m != _processors.end()) {
908                                         _processors.erase(m);
909                                 }
910                         }
911                         
912                         boost::shared_ptr<PluginInsert> pi;
913                         
914                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
915                                 pi->set_count (1);
916                                 
917                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
918                                 if (m > potential_max_streams)
919                                         potential_max_streams = m;
920                         }
921
922                         // Ensure peak vector sizes before the plugin is activated
923                         _meter->configure_io (potential_max_streams, potential_max_streams);
924                         
925                         _processors.insert (iter, *i);
926                         
927                         if (configure_processors_unlocked (err)) {
928                                 ++existing_end;
929                                 _processors.erase (existing_end, _processors.end());
930                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
931                                 return -1;
932                         }
933                         
934                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
935                 }
936
937                 _user_latency = 0;
938         }
939         
940         if (processor_max_streams != old_pms || old_pms == ChanCount::ZERO) {
941                 reset_panner ();
942         }
943         
944         dump_processors (_name + " added several", _processors);
945         processors_changed (); /* EMIT SIGNAL */
946
947         return 0;
948 }
949
950 void
951 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
952 {
953         if (p == PreFader) {
954                 start = _processors.begin();
955                 end = find(_processors.begin(), _processors.end(), _amp);
956         } else {
957                 start = find(_processors.begin(), _processors.end(), _amp);
958                 ++start;
959                 end = _processors.end();
960         }
961 }
962
963 /** Turn off all processors with a given placement
964  * @param p Placement of processors to disable
965  */
966 void
967 Route::disable_processors (Placement p)
968 {
969         Glib::RWLock::ReaderLock lm (_processor_lock);
970         
971         ProcessorList::iterator start, end;
972         placement_range(p, start, end);
973         
974         for (ProcessorList::iterator i = start; i != end; ++i) {
975                 (*i)->deactivate ();
976         }
977
978         _session.set_dirty ();
979 }
980
981 /** Turn off all redirects 
982  */
983 void
984 Route::disable_processors ()
985 {
986         Glib::RWLock::ReaderLock lm (_processor_lock);
987         
988         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
989                 (*i)->deactivate ();
990         }
991         
992         _session.set_dirty ();
993 }
994
995 /** Turn off all redirects with a given placement
996  * @param p Placement of redirects to disable
997  */
998 void
999 Route::disable_plugins (Placement p)
1000 {
1001         Glib::RWLock::ReaderLock lm (_processor_lock);
1002         
1003         ProcessorList::iterator start, end;
1004         placement_range(p, start, end);
1005         
1006         for (ProcessorList::iterator i = start; i != end; ++i) {
1007                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1008                         (*i)->deactivate ();
1009                 }
1010         }
1011         
1012         _session.set_dirty ();
1013 }
1014
1015 /** Turn off all plugins
1016  */
1017 void
1018 Route::disable_plugins ()
1019 {
1020         Glib::RWLock::ReaderLock lm (_processor_lock);
1021         
1022         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1023                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1024                         (*i)->deactivate ();
1025                 }
1026         }
1027         
1028         _session.set_dirty ();
1029 }
1030
1031
1032 void
1033 Route::ab_plugins (bool forward)
1034 {
1035         Glib::RWLock::ReaderLock lm (_processor_lock);
1036                         
1037         if (forward) {
1038
1039                 /* forward = turn off all active redirects, and mark them so that the next time
1040                    we go the other way, we will revert them
1041                 */
1042
1043                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1044                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1045                                 continue;
1046                         }
1047
1048                         if ((*i)->active()) {
1049                                 (*i)->deactivate ();
1050                                 (*i)->set_next_ab_is_active (true);
1051                         } else {
1052                                 (*i)->set_next_ab_is_active (false);
1053                         }
1054                 }
1055
1056         } else {
1057
1058                 /* backward = if the redirect was marked to go active on the next ab, do so */
1059
1060                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1061
1062                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1063                                 continue;
1064                         }
1065
1066                         if ((*i)->get_next_ab_is_active()) {
1067                                 (*i)->activate ();
1068                         } else {
1069                                 (*i)->deactivate ();
1070                         }
1071                 }
1072         }
1073         
1074         _session.set_dirty ();
1075 }
1076         
1077         
1078 /* Figure out the streams that will feed into PreFader */
1079 ChanCount
1080 Route::pre_fader_streams() const
1081 {
1082         boost::shared_ptr<Processor> processor;
1083
1084         /* Find the last pre-fader redirect that isn't a send; sends don't affect the number
1085          * of streams. */
1086         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1087                 if ((*i) == _amp) {
1088                         break;
1089                 }
1090                 if (boost::dynamic_pointer_cast<Send> (*i) == 0) {
1091                         processor = *i;
1092                 }
1093         }
1094         
1095         if (processor) {
1096                 return processor->output_streams();
1097         } else {
1098                 return n_inputs ();
1099         }
1100 }
1101
1102
1103 /** Remove processors with a given placement.
1104  * @param p Placement of processors to remove.
1105  */
1106 void
1107 Route::clear_processors (Placement p)
1108 {
1109         const ChanCount old_pms = processor_max_streams;
1110
1111         if (!_session.engine().connected()) {
1112                 return;
1113         }
1114         
1115         bool already_deleting = _session.deletion_in_progress();
1116         if (!already_deleting) {
1117                 _session.set_deletion_in_progress();
1118         }
1119
1120         {
1121                 Glib::RWLock::WriterLock lm (_processor_lock);
1122                 ProcessorList new_list;
1123                 ProcessorStreams err;
1124
1125                 ProcessorList::iterator amp_loc = find(_processors.begin(), _processors.end(), _amp);
1126                 if (p == PreFader) {
1127                         // Get rid of PreFader processors
1128                         for (ProcessorList::iterator i = _processors.begin(); i != amp_loc; ++i) {
1129                                 (*i)->drop_references ();
1130                         }
1131                         // Keep the rest
1132                         for (ProcessorList::iterator i = amp_loc; i != _processors.end(); ++i) {
1133                                 new_list.push_back (*i);
1134                         }
1135                 } else {
1136                         // Keep PreFader processors
1137                         for (ProcessorList::iterator i = _processors.begin(); i != amp_loc; ++i) {
1138                                 new_list.push_back (*i);
1139                         }
1140                         new_list.push_back (_amp);
1141                         // Get rid of PostFader processors
1142                         for (ProcessorList::iterator i = amp_loc; i != _processors.end(); ++i) {
1143                                 (*i)->drop_references ();
1144                         }
1145                 }
1146
1147                 _processors = new_list;
1148                 configure_processors_unlocked (&err); // this can't fail
1149         }
1150
1151         if (processor_max_streams != old_pms) {
1152                 reset_panner ();
1153         }
1154         
1155         processor_max_streams.reset();
1156         _have_internal_generator = false;
1157         processors_changed (); /* EMIT SIGNAL */
1158
1159         if (!already_deleting) {
1160                 _session.clear_deletion_in_progress();
1161         }
1162 }
1163
1164 int
1165 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1166 {
1167         /* these can never be removed */
1168
1169         if (processor == _amp || processor == _meter || processor == _main_outs) {
1170                 return 0;
1171         }
1172
1173         ChanCount old_pms = processor_max_streams;
1174
1175         if (!_session.engine().connected()) {
1176                 return 1;
1177         }
1178
1179         processor_max_streams.reset();
1180
1181         {
1182                 Glib::RWLock::WriterLock lm (_processor_lock);
1183                 ProcessorList::iterator i;
1184                 bool removed = false;
1185
1186                 for (i = _processors.begin(); i != _processors.end(); ) {
1187                         if (*i == processor) {
1188
1189                                 /* move along, see failure case for configure_processors()
1190                                    where we may need to reprocessor the processor.
1191                                 */
1192
1193                                 /* stop redirects that send signals to JACK ports
1194                                    from causing noise as a result of no longer being
1195                                    run.
1196                                 */
1197
1198                                 boost::shared_ptr<IOProcessor> redirect;
1199                                 
1200                                 if ((redirect = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1201                                         redirect->io()->disconnect_inputs (this);
1202                                         redirect->io()->disconnect_outputs (this);
1203                                 }
1204                                 
1205                                 i = _processors.erase (i);
1206                                 removed = true;
1207                                 break;
1208
1209                         } else {
1210                                 ++i;
1211                         }
1212
1213                         _user_latency = 0;
1214                 }
1215
1216                 if (!removed) {
1217                         /* what? */
1218                         return 1;
1219                 }
1220
1221                 if (configure_processors_unlocked (err)) {
1222                         /* get back to where we where */
1223                         _processors.insert (i, processor);
1224                         /* we know this will work, because it worked before :) */
1225                         configure_processors_unlocked (0);
1226                         return -1;
1227                 }
1228
1229                 _have_internal_generator = false;
1230
1231                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1232                         boost::shared_ptr<PluginInsert> pi;
1233                         
1234                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1235                                 if (pi->is_generator()) {
1236                                         _have_internal_generator = true;
1237                                         break;
1238                                 }
1239                         }
1240                 }
1241         }
1242
1243         if (old_pms != processor_max_streams) {
1244                 reset_panner ();
1245         }
1246
1247         processor->drop_references ();
1248         
1249         dump_processors (_name + " removed one", _processors);
1250         processors_changed (); /* EMIT SIGNAL */
1251
1252         return 0;
1253 }
1254
1255 int
1256 Route::configure_processors (ProcessorStreams* err)
1257 {
1258         if (!_in_configure_processors) {
1259                 Glib::RWLock::WriterLock lm (_processor_lock);
1260                 return configure_processors_unlocked (err);
1261         }
1262         return 0;
1263 }
1264
1265 /** Configure the input/output configuration of each processor in the processors list.
1266  * Return 0 on success, otherwise configuration is impossible.
1267  */
1268 int
1269 Route::configure_processors_unlocked (ProcessorStreams* err)
1270 {
1271         if (_in_configure_processors) {
1272            return 0;
1273         }
1274
1275         _in_configure_processors = true;
1276
1277         // Check each processor in order to see if we can configure as requested
1278         ChanCount in = n_inputs();
1279         ChanCount out;
1280         list< pair<ChanCount,ChanCount> > configuration;
1281         uint32_t index = 0;
1282         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1283                 cerr << "Can " << (*p)->name() << " support in= " << in << " out= " << out;
1284                 if ((*p)->can_support_io_configuration(in, out)) {
1285                         cerr << " yes\n";
1286                         configuration.push_back(make_pair(in, out));
1287                         in = out;
1288                 } else {
1289                         cerr << " no\n";
1290                         if (err) {
1291                                 err->index = index;
1292                                 err->count = in;
1293                         }
1294                         _in_configure_processors = false;
1295                         return -1;
1296                 }
1297         }
1298         
1299         // We can, so configure everything
1300         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1301         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1302                 (*p)->configure_io(c->first, c->second);
1303                 (*p)->activate();
1304                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1305                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1306                 out = c->second;
1307         }
1308
1309         // Ensure route outputs match last processor's outputs
1310         if (out != n_outputs()) {
1311                 ensure_io (n_inputs(), out, false, this);
1312         }
1313
1314         _in_configure_processors = false;
1315         return 0;
1316 }
1317
1318 void
1319 Route::all_processors_flip ()
1320 {
1321         Glib::RWLock::ReaderLock lm (_processor_lock);
1322
1323         if (_processors.empty()) {
1324                 return;
1325         }
1326
1327         bool first_is_on = _processors.front()->active();
1328         
1329         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1330                 if (first_is_on) {
1331                         (*i)->deactivate ();
1332                 } else {
1333                         (*i)->activate ();
1334                 }
1335         }
1336         
1337         _session.set_dirty ();
1338 }
1339
1340 /** Set all processors with a given placement to a given active state.
1341  * @param p Placement of processors to change.
1342  * @param state New active state for those processors.
1343  */
1344 void
1345 Route::all_processors_active (Placement p, bool state)
1346 {
1347         Glib::RWLock::ReaderLock lm (_processor_lock);
1348
1349         if (_processors.empty()) {
1350                 return;
1351         }
1352         ProcessorList::iterator start, end;
1353         placement_range(p, start, end);
1354
1355         bool before_amp = true;
1356         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1357                 if ((*i) == _amp) {
1358                         before_amp = false;
1359                         continue;
1360                 }
1361                 if (p == PreFader && before_amp) {
1362                         if (state) {
1363                                 (*i)->activate ();
1364                         } else {
1365                                 (*i)->deactivate ();
1366                         }
1367                 }
1368         }
1369         
1370         _session.set_dirty ();
1371 }
1372
1373 int
1374 Route::reorder_processors (const ProcessorList& new_order, Placement placement, ProcessorStreams* err)
1375 {
1376         {
1377                 Glib::RWLock::WriterLock lm (_processor_lock);
1378                 ChanCount old_pms = processor_max_streams;
1379                 ProcessorList::iterator oiter;
1380                 ProcessorList::const_iterator niter;
1381                 ProcessorList as_it_was_before = _processors;
1382                 ProcessorList as_it_will_be;
1383                 ProcessorList::iterator start, end;
1384
1385                 dump_processors (_name + " PreReorder", _processors);
1386                 placement_range (placement, start, end);
1387
1388                 oiter = start;
1389                 niter = new_order.begin(); 
1390
1391                 while (oiter != end && niter !=  new_order.end()) {
1392                         
1393                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1394                            then append it to the temp list. 
1395
1396                            Otherwise, see if the next processor in the old list is in the new list. if not,
1397                            its been deleted. If its there, append it to the temp list.
1398                         */
1399                         
1400                         if (oiter == end) {
1401
1402                                 /* no more elements in the old list, so just stick the rest of 
1403                                    the new order onto the temp list.
1404                                 */
1405
1406                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1407
1408                         } else {
1409                                 
1410                                 if (!(*oiter)->visible()) {
1411
1412                                         as_it_will_be.push_back (*oiter);
1413
1414                                 } else {
1415
1416                                         /* visible processor: check that its in the new order */
1417
1418                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1419                                                 /* deleted: do nothing */
1420                                         } else {
1421                                                 /* ignore this one, and add the next item from the new order instead */
1422                                                 as_it_will_be.push_back (*niter);
1423                                                 ++niter;
1424                                         }
1425                                 }
1426                                 
1427                                 /* now remove from old order - its taken care of no matter what */
1428                                 oiter = _processors.erase (oiter);
1429                         }
1430                 }
1431
1432                 _processors.insert (end, as_it_will_be.begin(), as_it_will_be.end());
1433
1434                 dump_processors (_name + " PostReorder", _processors);
1435
1436                 if (configure_processors_unlocked (err)) {
1437                         _processors = as_it_was_before;
1438                         processor_max_streams = old_pms;
1439                         return -1;
1440                 } 
1441         } 
1442
1443         dump_processors (_name + " sorted", _processors);
1444         /* do we really need to do this every time? */
1445         reset_panner ();
1446         processors_changed (); /* EMIT SIGNAL */
1447
1448         return 0;
1449 }
1450
1451 XMLNode&
1452 Route::get_state()
1453 {
1454         return state(true);
1455 }
1456
1457 XMLNode&
1458 Route::get_template()
1459 {
1460         return state(false);
1461 }
1462
1463 XMLNode&
1464 Route::state(bool full_state)
1465 {
1466         XMLNode *node = new XMLNode("Route");
1467         ProcessorList::iterator i;
1468         char buf[32];
1469
1470         if (_flags) {
1471                 node->add_property("flags", enum_2_string (_flags));
1472         }
1473         
1474         node->add_property("default-type", _default_type.to_string());
1475
1476         node->add_property("active", _active?"yes":"no");
1477         node->add_property("muted", _muted?"yes":"no");
1478         node->add_property("soloed", _soloed?"yes":"no");
1479         node->add_property("phase-invert", _phase_invert?"yes":"no");
1480         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1481         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1482         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1483         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1484         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no");
1485         node->add_property("meter-point", enum_2_string (_meter_point));
1486
1487         if (_edit_group) {
1488                 node->add_property("edit-group", _edit_group->name());
1489         }
1490         if (_mix_group) {
1491                 node->add_property("mix-group", _mix_group->name());
1492         }
1493
1494         string order_string;
1495         OrderKeys::iterator x = order_keys.begin(); 
1496
1497         while (x != order_keys.end()) {
1498                 order_string += string ((*x).first);
1499                 order_string += '=';
1500                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1501                 order_string += buf;
1502                 
1503                 ++x;
1504
1505                 if (x == order_keys.end()) {
1506                         break;
1507                 }
1508
1509                 order_string += ':';
1510         }
1511         node->add_property ("order-keys", order_string);
1512
1513         node->add_child_nocopy (IO::state (full_state));
1514         node->add_child_nocopy (_solo_control->get_state ());
1515         node->add_child_nocopy (_mute_control->get_state ());
1516
1517         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1518         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1519         remote_control_node->add_property (X_("id"), buf);
1520         node->add_child_nocopy (*remote_control_node);
1521
1522         if (_comment.length()) {
1523                 XMLNode *cmt = node->add_child ("Comment");
1524                 cmt->add_content (_comment);
1525         }
1526
1527         for (i = _processors.begin(); i != _processors.end(); ++i) {
1528                 node->add_child_nocopy((*i)->state (full_state));
1529         }
1530
1531         if (_extra_xml){
1532                 node->add_child_copy (*_extra_xml);
1533         }
1534         
1535         return *node;
1536 }
1537
1538 XMLNode&
1539 Route::get_processor_state ()
1540 {
1541         XMLNode* root = new XMLNode (X_("redirects"));
1542         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1543                 root->add_child_nocopy ((*i)->state (true));
1544         }
1545
1546         return *root;
1547 }
1548
1549 int
1550 Route::set_processor_state (const XMLNode& root)
1551 {
1552         if (root.name() != X_("redirects")) {
1553                 return -1;
1554         }
1555
1556         XMLNodeList nlist;
1557         XMLNodeList nnlist;
1558         XMLNodeConstIterator iter;
1559         XMLNodeConstIterator niter;
1560         Glib::RWLock::ReaderLock lm (_processor_lock);
1561
1562         nlist = root.children();
1563         
1564         for (iter = nlist.begin(); iter != nlist.end(); ++iter){
1565
1566                 /* iter now points to a IOProcessor state node */
1567                 
1568                 nnlist = (*iter)->children ();
1569
1570                 for (niter = nnlist.begin(); niter != nnlist.end(); ++niter) {
1571
1572                         /* find the IO child node, since it contains the ID we need */
1573
1574                         /* XXX OOP encapsulation violation, ugh */
1575
1576                         if ((*niter)->name() == IO::state_node_name) {
1577
1578                                 XMLProperty* prop = (*niter)->property (X_("id"));
1579                                 
1580                                 if (!prop) {
1581                                         warning << _("IOProcessor node has no ID, ignored") << endmsg;
1582                                         break;
1583                                 }
1584
1585                                 ID id = prop->value ();
1586
1587                                 /* now look for a processor with that ID */
1588         
1589                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1590                                         if ((*i)->id() == id) {
1591                                                 (*i)->set_state (**iter);
1592                                                 break;
1593                                         }
1594                                 }
1595                                 
1596                                 break;
1597                                 
1598                         }
1599                 }
1600
1601         }
1602
1603         return 0;
1604 }
1605
1606 void
1607 Route::set_deferred_state ()
1608 {
1609         XMLNodeList nlist;
1610         XMLNodeConstIterator niter;
1611
1612         if (!deferred_state) {
1613                 return;
1614         }
1615
1616         nlist = deferred_state->children();
1617
1618         _set_processor_states (nlist);
1619
1620         delete deferred_state;
1621         deferred_state = 0;
1622 }
1623
1624 int
1625 Route::set_state (const XMLNode& node)
1626 {
1627         return _set_state (node, true);
1628 }
1629
1630 int
1631 Route::_set_state (const XMLNode& node, bool call_base)
1632 {
1633         XMLNodeList nlist;
1634         XMLNodeConstIterator niter;
1635         XMLNode *child;
1636         XMLPropertyList plist;
1637         const XMLProperty *prop;
1638
1639         if (node.name() != "Route"){
1640                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1641                 return -1;
1642         }
1643
1644         if ((prop = node.property (X_("flags"))) != 0) {
1645                 _flags = Flag (string_2_enum (prop->value(), _flags));
1646         } else {
1647                 _flags = Flag (0);
1648         }
1649         
1650         if ((prop = node.property (X_("default-type"))) != 0) {
1651                 _default_type = DataType(prop->value());
1652                 assert(_default_type != DataType::NIL);
1653         }
1654
1655         if ((prop = node.property (X_("phase-invert"))) != 0) {
1656                 set_phase_invert (prop->value()=="yes"?true:false, this);
1657         }
1658
1659         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1660                 set_denormal_protection (prop->value()=="yes"?true:false, this);
1661         }
1662         
1663         _active = true;
1664         if ((prop = node.property (X_("active"))) != 0) {
1665                 set_active (prop->value() == "yes");
1666         }
1667
1668         if ((prop = node.property (X_("muted"))) != 0) {
1669                 bool yn = prop->value()=="yes"?true:false; 
1670
1671                 /* force reset of mute status */
1672
1673                 _muted = !yn;
1674                 set_mute(yn, this);
1675                 mute_gain = desired_mute_gain;
1676         }
1677
1678         if ((prop = node.property (X_("soloed"))) != 0) {
1679                 bool yn = prop->value()=="yes"?true:false; 
1680
1681                 /* force reset of solo status */
1682
1683                 _soloed = !yn;
1684                 set_solo (yn, this);
1685                 solo_gain = desired_solo_gain;
1686         }
1687
1688         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1689                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1690         }
1691
1692         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1693                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1694         }
1695
1696         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1697                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1698         }
1699
1700         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1701                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1702         }
1703
1704         if ((prop = node.property (X_("meter-point"))) != 0) {
1705                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1706         }
1707         
1708         if ((prop = node.property (X_("edit-group"))) != 0) {
1709                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1710                 if(edit_group == 0) {
1711                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1712                 } else {
1713                         set_edit_group(edit_group, this);
1714                 }
1715         }
1716
1717         if ((prop = node.property (X_("order-keys"))) != 0) {
1718
1719                 long n;
1720
1721                 string::size_type colon, equal;
1722                 string remaining = prop->value();
1723
1724                 while (remaining.length()) {
1725
1726                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1727                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1728                                       << endmsg;
1729                         } else {
1730                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1731                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1732                                               << endmsg;
1733                                 } else {
1734                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1735                                 }
1736                         }
1737
1738                         colon = remaining.find_first_of (':');
1739
1740                         if (colon != string::npos) {
1741                                 remaining = remaining.substr (colon+1);
1742                         } else {
1743                                 break;
1744                         }
1745                 }
1746         }
1747
1748         nlist = node.children();
1749
1750         delete deferred_state;
1751         deferred_state = new XMLNode(X_("deferred state"));
1752
1753         /* set parent class properties before anything else */
1754
1755         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1756
1757                 child = *niter;
1758
1759                 if (child->name() == IO::state_node_name && call_base) {
1760                         IO::set_state (*child);
1761                         break;
1762                 }
1763         }
1764
1765         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1766                 
1767                 child = *niter;
1768                         
1769                 if (child->name() == X_("Send") || child->name() == X_("Processor")) {
1770                         deferred_state->add_child_copy (*child);
1771                 }
1772         }
1773
1774         if (ports_legal) {
1775                 _set_processor_states (deferred_state->children());
1776                 delete deferred_state;
1777                 deferred_state = 0;
1778         }
1779
1780         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1781                 child = *niter;
1782
1783                 if (child->name() == X_("Automation")) {
1784                         
1785                         if ((prop = child->property (X_("path"))) != 0)  {
1786                                 load_automation (prop->value());
1787                         }
1788
1789                 } else if (child->name() == X_("ControlOuts")) {
1790
1791                         /* ignore this - deprecated */
1792
1793                 } else if (child->name() == X_("Comment")) {
1794
1795                         /* XXX this is a terrible API design in libxml++ */
1796
1797                         XMLNode *cmt = *(child->children().begin());
1798                         _comment = cmt->content();
1799
1800                 } else if (child->name() == X_("Extra")) {
1801
1802                         _extra_xml = new XMLNode (*child);
1803
1804                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1805                         
1806                         if (prop->value() == "solo") {
1807                                 _solo_control->set_state (*child);
1808                                 _session.add_controllable (_solo_control);
1809                         } else if (prop->value() == "mute") {
1810                                 _mute_control->set_state (*child);
1811                                 _session.add_controllable (_mute_control);
1812                         }
1813                 } else if (child->name() == X_("RemoteControl")) {
1814                         if ((prop = child->property (X_("id"))) != 0) {
1815                                 int32_t x;
1816                                 sscanf (prop->value().c_str(), "%d", &x);
1817                                 set_remote_control_id (x);
1818                         }
1819                 }
1820         }
1821
1822         if ((prop = node.property (X_("mix-group"))) != 0) {
1823                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1824                 if (mix_group == 0) {
1825                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1826                 }  else {
1827                         set_mix_group(mix_group, this);
1828                 }
1829         }
1830
1831         return 0;
1832 }
1833
1834 void
1835 Route::_set_processor_states(const XMLNodeList &nlist)
1836 {
1837         XMLNodeConstIterator niter;
1838         bool has_meter_processor = false; // legacy sessions don't
1839         ProcessorList::iterator i, o;
1840
1841         cerr << "Setting processor states with in = " << n_inputs() << endl;
1842
1843         // Iterate through existing processors, remove those which are not in the state list
1844         for (i = _processors.begin(); i != _processors.end(); ) {
1845                 ProcessorList::iterator tmp = i;
1846                 ++tmp;
1847
1848                 bool processorInStateList = false;
1849         
1850                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1851
1852                         XMLProperty* id_prop = (*niter)->property(X_("id"));
1853                         if (id_prop && (*i)->id() == id_prop->value()) {
1854                                 processorInStateList = true;
1855                                 break;
1856                         }
1857                 }
1858                 
1859                 if (!processorInStateList) {
1860                         remove_processor (*i);
1861                 }
1862
1863                 i = tmp;
1864         }
1865
1866         // Iterate through state list and make sure all processors are on the track and in the correct order,
1867         // set the state of existing processors according to the new state on the same go
1868         i = _processors.begin();
1869
1870         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
1871                 
1872                 XMLProperty* prop = (*niter)->property ("type");
1873
1874                 if (prop && prop->value() == "meter")  {
1875                         has_meter_processor = true;
1876                 }
1877
1878                 o = i;
1879
1880                 if (prop->value() != "meter" && prop->value() != "amp" && prop->value() != "main-outs") {
1881
1882                         // Check whether the next processor in the list 
1883                         
1884                         while (o != _processors.end()) {
1885                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
1886                                 if (id_prop && (*o)->id() == id_prop->value()) {
1887                                         break;
1888                                 }
1889                                 
1890                                 ++o;
1891                         }
1892                 }
1893
1894                 // If the processor (*niter) is not on the route,
1895                 // create it and move it to the correct location
1896                 if (o == _processors.end()) {
1897
1898                         if (add_processor_from_xml (**niter, i)) {
1899                                 --i; // move iterator to the newly inserted processor
1900                         } else {
1901                                 cerr << "Error restoring route: unable to restore processor" << endl;
1902                         }
1903
1904                 // Otherwise, the processor already exists; just
1905                 // ensure it is at the location provided in the XML state
1906                 } else {
1907
1908                         if (i != o) {
1909                                 boost::shared_ptr<Processor> tmp = (*o);
1910                                 _processors.erase (o); // remove the old copy
1911                                 _processors.insert (i, tmp); // insert the processor at the correct location
1912                                 --i; // move iterator to the correct processor
1913                         }
1914
1915                         (*i)->set_state (**niter);
1916                 }
1917         }
1918
1919         /* note: there is no configure_processors() call because we figure that
1920            the XML state represents a working signal route.
1921         */
1922
1923         if (!has_meter_processor) {
1924                 set_meter_point (_meter_point, NULL);
1925         }
1926
1927         processors_changed ();
1928
1929         
1930
1931 }
1932
1933 void
1934 Route::curve_reallocate ()
1935 {
1936 //      _gain_automation_curve.finish_resize ();
1937 //      _pan_automation_curve.finish_resize ();
1938 }
1939
1940 void
1941 Route::silence (nframes_t nframes)
1942 {
1943         if (!_silent) {
1944
1945                 IO::silence (nframes);
1946                 
1947                 { 
1948                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
1949                         
1950                         if (lm.locked()) {
1951                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1952                                         boost::shared_ptr<PluginInsert> pi;
1953
1954                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1955                                                 // skip plugins, they don't need anything when we're not active
1956                                                 continue;
1957                                         }
1958                                         
1959                                         (*i)->silence (nframes);
1960                                 }
1961
1962                                 if (nframes == _session.get_block_size()) {
1963                                         // _silent = true;
1964                                 }
1965                         }
1966                 }
1967                 
1968         }
1969 }       
1970
1971 boost::shared_ptr<Delivery>
1972 Route::add_listener (boost::shared_ptr<IO> io, const string& listen_name)
1973 {
1974         string name = _name;
1975         name += '[';
1976         name += listen_name;
1977         name += ']';
1978         
1979         boost::shared_ptr<Delivery> listener (new Delivery (_session, name, Delivery::Listen)); 
1980
1981         /* As an IO, our control outs need as many IO outputs as we have outputs
1982          *   (we track the changes in ::output_change_handler()).
1983          * As a processor, the listener is an identity processor
1984          *   (i.e. it does not modify its input buffers whatsoever)
1985          */
1986
1987         if (listener->io()->ensure_io (ChanCount::ZERO, n_outputs(), true, this)) {
1988                 return boost::shared_ptr<Delivery>();
1989         }
1990         
1991         add_processor (listener, PostFader);
1992
1993         return listener;
1994 }
1995
1996 int
1997 Route::listen_via (boost::shared_ptr<IO> io, const string& listen_name)
1998 {
1999         vector<string> ports;
2000         vector<string>::const_iterator i;
2001
2002         {
2003                 Glib::RWLock::ReaderLock rm (_processor_lock);
2004                 
2005                 for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2006                         boost::shared_ptr<const Delivery> d = boost::dynamic_pointer_cast<const Delivery>(*x);
2007
2008                         if (d && d->io() == io) {
2009                                 /* already listening via the specified IO: do nothing */
2010                                 return 0;
2011                         }
2012                 }
2013         }
2014
2015         uint32_t ni = io->n_inputs().n_total();
2016
2017         for (uint32_t n = 0; n < ni; ++n) {
2018                 ports.push_back (io->input(n)->name());
2019         }
2020
2021         if (ports.empty()) {
2022                 return 0;
2023         }
2024         
2025         boost::shared_ptr<Delivery> listen_point = add_listener (io, listen_name);
2026         
2027         /* XXX hack for now .... until we can generalize listen points */
2028
2029         _control_outs = listen_point;
2030
2031         /* now connect to the named ports */
2032         
2033         ni = listen_point->io()->n_outputs().n_total();
2034         size_t psize = ports.size();
2035
2036         for (size_t n = 0; n < ni; ++n) {
2037                 if (listen_point->io()->connect_output (listen_point->io()->output (n), ports[n % psize], this)) {
2038                         error << string_compose (_("could not connect %1 to %2"),
2039                                                  listen_point->io()->output(n)->name(), ports[n % psize]) << endmsg;
2040                         return -1;
2041                 }
2042         }
2043
2044         
2045         return 0;
2046 }       
2047
2048 void
2049 Route::drop_listen (boost::shared_ptr<IO> io)
2050 {
2051         ProcessorStreams err;
2052         ProcessorList::iterator tmp;
2053
2054         Glib::RWLock::ReaderLock rm (_processor_lock);
2055         
2056         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
2057                 
2058                 tmp = x;
2059                 ++tmp;
2060                 
2061                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*x);
2062                 
2063                 if (d && d->io() == io) {
2064                         /* already listening via the specified IO: do nothing */
2065                         remove_processor (*x, &err);
2066                         
2067                 } 
2068                 
2069                 x = tmp;
2070         }
2071 }
2072
2073 void
2074 Route::set_edit_group (RouteGroup *eg, void *src)
2075
2076 {
2077         if (eg == _edit_group) {
2078                 return;
2079         }
2080
2081         if (_edit_group) {
2082                 _edit_group->remove (this);
2083         }
2084
2085         if ((_edit_group = eg) != 0) {
2086                 _edit_group->add (this);
2087         }
2088
2089         _session.set_dirty ();
2090         edit_group_changed (src); /* EMIT SIGNAL */
2091 }
2092
2093 void
2094 Route::drop_edit_group (void *src)
2095 {
2096         _edit_group = 0;
2097         _session.set_dirty ();
2098         edit_group_changed (src); /* EMIT SIGNAL */
2099 }
2100
2101 void
2102 Route::set_mix_group (RouteGroup *mg, void *src)
2103
2104 {
2105         if (mg == _mix_group) {
2106                 return;
2107         }
2108
2109         if (_mix_group) {
2110                 _mix_group->remove (this);
2111         }
2112
2113         if ((_mix_group = mg) != 0) {
2114                 _mix_group->add (this);
2115         }
2116
2117         _session.set_dirty ();
2118         mix_group_changed (src); /* EMIT SIGNAL */
2119 }
2120
2121 void
2122 Route::drop_mix_group (void *src)
2123 {
2124         _mix_group = 0;
2125         _session.set_dirty ();
2126         mix_group_changed (src); /* EMIT SIGNAL */
2127 }
2128
2129 void
2130 Route::set_comment (string cmt, void *src)
2131 {
2132         _comment = cmt;
2133         comment_changed (src);
2134         _session.set_dirty ();
2135 }
2136
2137 bool
2138 Route::feeds (boost::shared_ptr<Route> other)
2139 {
2140         uint32_t i, j;
2141
2142         IO& self = *this;
2143         uint32_t no = self.n_outputs().n_total();
2144         uint32_t ni = other->n_inputs ().n_total();
2145
2146         for (i = 0; i < no; ++i) {
2147                 for (j = 0; j < ni; ++j) {
2148                         if (self.output(i)->connected_to (other->input(j)->name())) {
2149                                 return true;
2150                         }
2151                 }
2152         }
2153
2154         /* check IOProcessors which may also interconnect Routes */
2155
2156         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2157
2158                 boost::shared_ptr<IOProcessor> proc = boost::dynamic_pointer_cast<IOProcessor>(*r);
2159                 
2160                 if (!proc) {
2161                         continue;
2162                 }
2163                 
2164                 no = proc->io()->n_outputs().n_total();
2165                 
2166                 for (i = 0; i < no; ++i) {
2167                         for (j = 0; j < ni; ++j) {
2168                                 if (proc->io()->output(i)->connected_to (other->input (j)->name())) {
2169                                         return true;
2170                                 }
2171                         }
2172                 }
2173         }
2174
2175         return false;
2176 }
2177
2178 void
2179 Route::set_mute_config (mute_type t, bool onoff, void *src)
2180 {
2181         switch (t) {
2182         case PRE_FADER:
2183                 _mute_affects_pre_fader = onoff;
2184                 pre_fader_changed(src); /* EMIT SIGNAL */
2185                 break;
2186
2187         case POST_FADER:
2188                 _mute_affects_post_fader = onoff;
2189                 post_fader_changed(src); /* EMIT SIGNAL */
2190                 break;
2191
2192         case CONTROL_OUTS:
2193                 _mute_affects_control_outs = onoff;
2194                 control_outs_changed(src); /* EMIT SIGNAL */
2195                 break;
2196
2197         case MAIN_OUTS:
2198                 _mute_affects_main_outs = onoff;
2199                 main_outs_changed(src); /* EMIT SIGNAL */
2200                 break;
2201         }
2202 }
2203
2204 bool
2205 Route::get_mute_config (mute_type t)
2206 {
2207         bool onoff = false;
2208         
2209         switch (t){
2210         case PRE_FADER:
2211                 onoff = _mute_affects_pre_fader; 
2212                 break;
2213         case POST_FADER:
2214                 onoff = _mute_affects_post_fader;
2215                 break;
2216         case CONTROL_OUTS:
2217                 onoff = _mute_affects_control_outs;
2218                 break;
2219         case MAIN_OUTS:
2220                 onoff = _mute_affects_main_outs;
2221                 break;
2222         }
2223         
2224         return onoff;
2225 }
2226
2227 void
2228 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
2229 {
2230         nframes_t now = _session.transport_frame();
2231
2232         {
2233                 Glib::RWLock::ReaderLock lm (_processor_lock);
2234
2235                 if (!did_locate) {
2236                         automation_snapshot (now, true);
2237                 }
2238
2239                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2240                         
2241                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2242                                 (*i)->deactivate ();
2243                                 (*i)->activate ();
2244                         }
2245                         
2246                         (*i)->transport_stopped (now);
2247                 }
2248         }
2249
2250         IO::transport_stopped (now);
2251  
2252         _roll_delay = _initial_delay;
2253 }
2254
2255 void
2256 Route::input_change_handler (IOChange change, void *src)
2257 {
2258         if ((change & ConfigurationChanged)) {
2259                 configure_processors (0);
2260         }
2261 }
2262
2263 void
2264 Route::output_change_handler (IOChange change, void *src)
2265 {
2266         if ((change & ConfigurationChanged)) {
2267                 if (_control_outs) {
2268                         _control_outs->io()->ensure_io (ChanCount::ZERO, n_outputs(), true, this);
2269                 }
2270                 
2271                 configure_processors (0);
2272         }
2273 }
2274
2275 uint32_t
2276 Route::pans_required () const
2277 {
2278         if (n_outputs().n_audio() < 2) {
2279                 return 0;
2280         }
2281         
2282         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2283 }
2284
2285 int 
2286 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,  
2287                 bool session_state_changing, bool can_record, bool rec_monitors_input)
2288 {
2289         if (n_outputs().n_total() == 0) {
2290                 return 0;
2291         }
2292
2293         if (session_state_changing || !_active)  {
2294                 silence (nframes);
2295                 return 0;
2296         }
2297
2298         _amp->apply_gain_automation(false);
2299         
2300         if (n_inputs() != ChanCount::ZERO) {
2301                 passthru (start_frame, end_frame, nframes, 0);
2302         } else {
2303                 silence (nframes);
2304         }
2305
2306         return 0;
2307 }
2308
2309 nframes_t
2310 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2311 {
2312         if (_roll_delay > nframes) {
2313
2314                 _roll_delay -= nframes;
2315                 silence (nframes);
2316                 /* transport frame is not legal for caller to use */
2317                 return 0;
2318
2319         } else if (_roll_delay > 0) {
2320
2321                 nframes -= _roll_delay;
2322                 silence (_roll_delay);
2323                 /* we've written _roll_delay of samples into the 
2324                    output ports, so make a note of that for
2325                    future reference.
2326                 */
2327                 increment_output_offset (_roll_delay);
2328                 transport_frame += _roll_delay;
2329
2330                 _roll_delay = 0;
2331         }
2332
2333         return nframes;
2334 }
2335
2336 int
2337 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2338              bool can_record, bool rec_monitors_input)
2339 {
2340         {
2341                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2342                 if (lm.locked()) {
2343                         // automation snapshot can also be called from the non-rt context
2344                         // and it uses the processor list, so we take the lock out here
2345                         automation_snapshot (_session.transport_frame(), false);
2346                 }
2347         }
2348
2349         if ((n_outputs().n_total() == 0 && _processors.empty()) || n_inputs().n_total() == 0 || !_active) {
2350                 silence (nframes);
2351                 return 0;
2352         }
2353         
2354         nframes_t unused = 0;
2355
2356         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2357                 return 0;
2358         }
2359
2360         _silent = false;
2361
2362         _amp->apply_gain_automation(false);
2363
2364         { 
2365                 Glib::Mutex::Lock am (data().control_lock(), Glib::TRY_LOCK);
2366                 
2367                 if (am.locked() && _session.transport_rolling()) {
2368                         
2369                         if (_gain_control->automation_playback()) {
2370                                 _amp->apply_gain_automation(
2371                                                 _gain_control->list()->curve().rt_safe_get_vector (
2372                                                         start_frame, end_frame, _session.gain_automation_buffer(), nframes));
2373                         }
2374                 }
2375         }
2376
2377         passthru (start_frame, end_frame, nframes, declick);
2378
2379         return 0;
2380 }
2381
2382 int
2383 Route::silent_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, 
2384                     bool can_record, bool rec_monitors_input)
2385 {
2386         silence (nframes);
2387         return 0;
2388 }
2389
2390 void
2391 Route::toggle_monitor_input ()
2392 {
2393         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2394                 i->ensure_monitor_input( ! i->monitoring_input());
2395         }
2396 }
2397
2398 bool
2399 Route::has_external_redirects () const
2400 {
2401         // FIXME: what about sends?
2402
2403         boost::shared_ptr<const PortInsert> pi;
2404         
2405         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2406                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2407
2408                         for (PortSet::const_iterator port = pi->io()->outputs().begin();
2409                                         port != pi->io()->outputs().end(); ++port) {
2410                                 
2411                                 string port_name = port->name();
2412                                 string client_name = port_name.substr (0, port_name.find(':'));
2413
2414                                 /* only say "yes" if the redirect is actually in use */
2415                                 
2416                                 if (client_name != "ardour" && pi->active()) {
2417                                         return true;
2418                                 }
2419                         }
2420                 }
2421         }
2422
2423         return false;
2424 }
2425
2426 void
2427 Route::flush_processors ()
2428 {
2429         /* XXX shouldn't really try to take this lock, since
2430            this is called from the RT audio thread.
2431         */
2432
2433         Glib::RWLock::ReaderLock lm (_processor_lock);
2434
2435         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2436                 (*i)->deactivate ();
2437                 (*i)->activate ();
2438         }
2439 }
2440
2441 void
2442 Route::set_meter_point (MeterPoint p, void *src)
2443 {
2444         if (_meter_point != p) {
2445                 _meter_point = p;
2446
2447                 // Move meter in the processors list
2448                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _meter);
2449                 _processors.erase(loc);
2450                 switch (p) {
2451                 case MeterInput:
2452                         loc = _processors.begin();
2453                         break;
2454                 case MeterPreFader:
2455                         loc = find(_processors.begin(), _processors.end(), _amp);
2456                         break;
2457                 case MeterPostFader:
2458                         loc = _processors.end();
2459                         break;
2460                 }
2461                 _processors.insert(loc, _meter);
2462                 
2463                  meter_change (src); /* EMIT SIGNAL */
2464                 processors_changed (); /* EMIT SIGNAL */
2465                 _session.set_dirty ();
2466         }
2467 }
2468
2469 nframes_t
2470 Route::update_total_latency ()
2471 {
2472         nframes_t old = _own_latency;
2473
2474         if (_user_latency) {
2475                 _own_latency = _user_latency;
2476         } else {
2477                 _own_latency = 0;
2478
2479                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2480                         if ((*i)->active ()) {
2481                                 _own_latency += (*i)->signal_latency ();
2482                         }
2483                 }
2484         }
2485
2486 #undef DEBUG_LATENCY
2487 #ifdef DEBUG_LATENCY
2488         cerr << _name << ": internal redirect latency = " << _own_latency << endl;
2489 #endif
2490
2491         set_port_latency (_own_latency);
2492         
2493         if (!_user_latency) {
2494                 /* this (virtual) function is used for pure Routes,
2495                    not derived classes like AudioTrack.  this means
2496                    that the data processed here comes from an input
2497                    port, not prerecorded material, and therefore we
2498                    have to take into account any input latency.
2499                 */
2500
2501
2502                 _own_latency += input_latency ();
2503         }
2504
2505         if (old != _own_latency) {
2506                 signal_latency_changed (); /* EMIT SIGNAL */
2507         }
2508         
2509 #ifdef DEBUG_LATENCY
2510         cerr << _name << ": input latency = " << input_latency() << " total = "
2511              << _own_latency << endl;
2512 #endif
2513
2514         return _own_latency;
2515 }
2516
2517 void
2518 Route::set_user_latency (nframes_t nframes)
2519 {
2520         Latent::set_user_latency (nframes);
2521         _session.update_latency_compensation (false, false);
2522 }
2523
2524 void
2525 Route::set_latency_delay (nframes_t longest_session_latency)
2526 {
2527         nframes_t old = _initial_delay;
2528
2529         if (_own_latency < longest_session_latency) {
2530                 _initial_delay = longest_session_latency - _own_latency;
2531         } else {
2532                 _initial_delay = 0;
2533         }
2534
2535         if (_initial_delay != old) {
2536                 initial_delay_changed (); /* EMIT SIGNAL */
2537         }
2538
2539         if (_session.transport_stopped()) {
2540                 _roll_delay = _initial_delay;
2541         }
2542 }
2543
2544 void
2545 Route::automation_snapshot (nframes_t now, bool force)
2546 {
2547         if (!force && !should_snapshot(now)) {
2548                 return;
2549         }
2550
2551         IO::automation_snapshot (now, force);
2552
2553         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2554                 (*i)->automation_snapshot (now, force);
2555         }
2556 }
2557
2558 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2559         : Controllable (name), route (s), type(tp)
2560 {
2561         
2562 }
2563
2564 void
2565 Route::ToggleControllable::set_value (float val)
2566 {
2567         bool bval = ((val >= 0.5f) ? true: false);
2568         
2569         switch (type) {
2570         case MuteControl:
2571                 route.set_mute (bval, this);
2572                 break;
2573         case SoloControl:
2574                 route.set_solo (bval, this);
2575                 break;
2576         default:
2577                 break;
2578         }
2579 }
2580
2581 float
2582 Route::ToggleControllable::get_value (void) const
2583 {
2584         float val = 0.0f;
2585         
2586         switch (type) {
2587         case MuteControl:
2588                 val = route.muted() ? 1.0f : 0.0f;
2589                 break;
2590         case SoloControl:
2591                 val = route.soloed() ? 1.0f : 0.0f;
2592                 break;
2593         default:
2594                 break;
2595         }
2596
2597         return val;
2598 }
2599
2600 void 
2601 Route::set_block_size (nframes_t nframes)
2602 {
2603         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2604                 (*i)->set_block_size (nframes);
2605         }
2606         _session.ensure_buffers(processor_max_streams);
2607 }
2608
2609 void
2610 Route::protect_automation ()
2611 {
2612         Automatable::protect_automation();
2613         
2614         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2615                 (*i)->protect_automation();
2616 }
2617
2618 void
2619 Route::set_pending_declick (int declick)
2620 {
2621         if (_declickable) {
2622                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2623                 if (declick) {
2624                         _pending_declick = declick;
2625                 }
2626                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2627         } else {
2628                 _pending_declick = 0;
2629         }
2630
2631 }
2632
2633 /** Shift automation forwards from a particular place, thereby inserting time.
2634  *  Adds undo commands for any shifts that are performed.
2635  *
2636  * @param pos Position to start shifting from.
2637  * @param frames Amount to shift forwards by.
2638  */
2639
2640 void
2641 Route::shift (nframes64_t pos, nframes64_t frames)
2642 {
2643 #ifdef THIS_NEEDS_FIXING_FOR_V3
2644
2645         /* gain automation */
2646         XMLNode &before = _gain_control->get_state ();
2647         _gain_control->shift (pos, frames);
2648         XMLNode &after = _gain_control->get_state ();
2649         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
2650
2651         /* pan automation */
2652         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
2653                 Curve & c = (*i)->automation ();
2654                 XMLNode &before = c.get_state ();
2655                 c.shift (pos, frames);
2656                 XMLNode &after = c.get_state ();
2657                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
2658         }
2659
2660         /* redirect automation */
2661         {
2662                 Glib::RWLock::ReaderLock lm (redirect_lock);
2663                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
2664                         
2665                         set<uint32_t> a;
2666                         (*i)->what_has_automation (a);
2667                         
2668                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
2669                                 AutomationList & al = (*i)->automation_list (*j);
2670                                 XMLNode &before = al.get_state ();
2671                                 al.shift (pos, frames);
2672                                 XMLNode &after = al.get_state ();
2673                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
2674                         }
2675                 }
2676         }
2677 #endif
2678
2679 }
2680
2681
2682 int
2683 Route::save_as_template (const string& path, const string& name)
2684 {
2685         XMLNode& node (state (false));
2686         XMLTree tree;
2687         
2688         IO::set_name_in_state (*node.children().front(), name);
2689         
2690         tree.set_root (&node);
2691         return tree.write (path.c_str());
2692 }
2693
2694
2695 bool
2696 Route::set_name (const string& str)
2697 {
2698         bool ret;
2699         string ioproc_name;
2700
2701         if ((ret = IO::set_name (str)) == true) {
2702                 Glib::RWLock::ReaderLock lm (_processor_lock);
2703                 
2704                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2705                         
2706                         /* rename all delivery objects to reflect our new name */
2707
2708                         boost::shared_ptr<Delivery> dp = boost::dynamic_pointer_cast<Delivery> (*i);
2709
2710                         if (dp) {
2711                                 string dp_name = str;
2712                                 dp_name += '[';
2713                                 dp_name += "XXX FIX ME XXX";
2714                                 dp_name += ']';
2715                                 
2716                                 if (!dp->set_name (dp_name)) {
2717                                         ret = false;
2718                                 }
2719                         }
2720                 }
2721
2722         }
2723
2724         return ret;
2725 }