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