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