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