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