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