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