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