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